pySerial write() 不会接受我的字符串 [英] pySerial write() won't take my string
问题描述
使用 Python 3.3 和 pySerial 进行串行通信.
我正在尝试将命令写入我的 COM 端口,但 write 方法不会接受我的字符串.(大部分代码来自这里使用pySerial包的完整示例>
怎么回事?
导入时间导入序列ser = serial.Serial(端口='\\\\.\\COM4',波特率=115200,奇偶校验=串行.PARITY_ODD,stopbits=serial.STOPBITS_ONE,字节大小=串行.EIGHTBITS)如果 ser.isOpen():ser.close()ser.open()ser.isOpen()ser.write("%01#RDD0010000107**\r")出来 = ''# 让我们在读取输出之前等待一秒钟(让我们给设备时间来回答)时间.睡眠(1)而 ser.inWaiting() >0:out += ser.read(40)如果出来!= '':打印(>>"+输出)ser.close()
错误位于 ser.write("%01#RDD0010000107**\r") 那里回溯是这样的数据 = to_bytes(data)b.附加(项目)类型错误:需要一个整数.
原来需要将字符串转换为字节数组,为此我将代码编辑为
ser.write("%01#RDD0010000107**\r".encode())
解决了这个问题
Using Python 3.3 and pySerial for serial communications.
I'm trying to write a command to my COM PORT but the write method won't take my string. (Most of the code is from here Full examples of using pySerial package
What's going on?
import time
import serial
ser = serial.Serial(
port='\\\\.\\COM4',
baudrate=115200,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write("%01#RDD0010000107**\r")
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(40)
if out != '':
print(">>" + out)
ser.close()
Error is at ser.write("%01#RDD0010000107**\r") where it gets Traceback is like this data = to_bytes(data) b.append(item) TypeError: an integer is required.
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to
ser.write("%01#RDD0010000107**\r".encode())
This solved the problem
这篇关于pySerial write() 不会接受我的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!