将字节串发送到串行设备

joe*_*bee 4 python pyserial python-3.x raspberry-pi

我正在使用在Raspberry上运行的Python3.我有一个串口设备(max232/PiC16F84)通过USB转串口适配器连接到Raspberry.我尝试向设备发送两个字节(例如0000 0011),然后PIC将其解释为命令.USB - 串行适配器配置正确,参数如bauderate应该没问题.我猜我的代码没有将正确的字节发送到串口.

import serial

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=1200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    xonxoff=serial.XOFF,
    rtscts=False,
    dsrdtr=False
)

ser.open()
ser.isOpen()

print("Initializing the device ..")

ser.write(bytes(0x00))

print("Write command")
ser.write (bytes(0x04))

print('Done')
Run Code Online (Sandbox Code Playgroud)

ale*_*xis 10

您正在bytes错误地使用构造函数.当你用intas参数调用它时,你得到:

bytes(int) - >由null字节初始化的参数给出的字节对象大小

所以bytes(0x00)(这只是bytes(0))是空字符串,并且bytes(0x04)是四个零字节:

>>> bytes(0x00)
b''
>>> bytes(0x04)
b'\x00\x00\x00\x00'
Run Code Online (Sandbox Code Playgroud)

你想要的是什么bytes([ 0x00 ]),或者只是一个包含所有字节值的数组:

>>> bytes([0, 4])
b'\x00\x04'
Run Code Online (Sandbox Code Playgroud)

如果字符串很短,您可以简单地将其写为常量:b'\x00\x04'例如.有关bytes()更多选项,请参阅文档.