使用 Python 3.3 和 pySerial 进行串行通信。
我正在尝试向我的 COM PORT 写入命令,但 write 方法不会获取我的字符串。 (大部分代码来自这里Full examples of using pySerial package
发生了什么事?
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()
错误出现在 ser.write("%01#RDD0010000107**\r") 处 Traceback 是这样的 数据 = to_bytes(数据) b.附加(项目) TypeError:需要一个整数。
最佳答案
事实证明,需要将字符串转换为字节数组,为此我将代码编辑为
ser.write("%01#RDD0010000107**\r".encode())
这样就解决了问题
关于python - pySerial write() 不会接受我的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275079/