Python 将字节字符串发送到串行设备
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26224110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending byte strings to serial device
提问by joebee
I'm using Python3 running on a Raspberry. I have a serial device (max232/PiC16F84) connected to the Raspberry via an USB to Serial adapter. I try to send two bytes to the device (e.g 0000 0011) which then will be interpreted as a command by the PIC. The USB - serial adapter is configured correctly and the parameter such as bauderate should be ok. I guess that my code doesn't send the correct bytes to the serial port.
我正在使用在 Raspberry 上运行的 Python3。我有一个串行设备(max232/PiC16F84)通过 USB 到串行适配器连接到 Raspberry。我尝试向设备发送两个字节(例如 0000 0011),然后由 PIC 将其解释为命令。USB-串口适配器配置正确,波特率等参数应该没问题。我猜我的代码没有将正确的字节发送到串行端口。
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')
回答by alexis
You are using the bytesconstructor incorrectly. When you call it with an intas argument, you get:
您bytes错误地使用了构造函数。当你用intas 参数调用它时,你会得到:
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes(int) -> 由用空字节初始化的参数给出的大小的字节对象
So bytes(0x00)(which is just bytes(0)) is the empty string, and bytes(0x04)is four zero bytes:
所以bytes(0x00)(这只是bytes(0))是空字符串,并且bytes(0x04)是四个零字节:
>>> bytes(0x00)
b''
>>> bytes(0x04)
b'\x00\x00\x00\x00'
What you want is bytes([ 0x00 ])etc., or simply an array with all your byte values:
你想要的是bytes([ 0x00 ])等等,或者只是一个包含所有字节值的数组:
>>> bytes([0, 4])
b'\x00\x04'
If the string is short, you could simply write it as a constant: b'\x00\x04', for example. See the documentation of bytes()for more options.
如果字符串很短,您可以简单地将其写为常量:b'\x00\x04'例如。有关bytes()更多选项,请参阅 的文档。
回答by CARLOS DAVID PINTO SOTELO
Use this: bytes[0x00]+bytes([0x04])
使用这个:字节[0x00]+字节([0x04])

