python - pySerial write() 不会接受我的字符串

标签 python pyserial

使用 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/

相关文章:

python - 在 xlsxwriter 中交换 X 轴和 Y 轴

python - 使用远程驱动程序设置 chrome 选项

python - 完全相同的 python3 代码在 shell 中工作但不在脚本中工作?

python - Pyserial 持久配置

python - 如何通过 USB 发送一个 gcode 命令?

python - python中写入和监听同一个串口

python - 使用 OpenCV 计算视频文件中的帧数?

python - 如何使用 SWIG 将 Fortran 有序 2d numpy 数组传递到 C++

python - 为什么这个 python 函数返回 None

python - pySerial readline 读取之前写入的数据