简体   繁体   English

python 3和pyserial 2.7

[英]python 3 and pyserial 2.7

I'm trying to communicate with a serial device in Python, the device needs a sync byte which in this case is 255 then varying other bytes which as said "vary" my code has this and works well 我正在尝试与Python中的串行设备通信,该设备需要一个同步字节,在这种情况下为255,然后更改其他字节,正如所说的“变化”,我的代码具有此功能并且运行良好

serial.write(b '255')
serial.write(b '55')
serial.write(b '69')

This works great but I cannot seem to substitute the last two numbers for variables as in 这很好用,但是我似乎无法用变量的最后两个数字代替

serial.write(b '255')
serial.write(b varA)
serial.write(b varB)

It seems as though this option is not available. 似乎此选项不可用。

Please please Help me out 请帮帮我

b'255' is actually a binary representation of ascii string "255". b'255'实际上是ASCII字符串“ 255”的二进制表示。 If you want to pass exactly byte 255 you can simply write serial.write(255) . 如果您想精确传递字节255,则只需编写serial.write(255) And in this case variables must be assigned with byte (just int in range from 0 to 255). 并且在这种情况下,必须为变量分配字节(在0到255之间的整数范围内)。

serial.write(255)
serial.write(55)
serial.write(69)

varA = 55
varB = 69
serial.write(255)
serial.write(varA)
serial.write(varB)

If its actually need a binary representation of ascii string (why?) and varA\\varB is a string, you can convert it to a byte array. 如果它实际上需要ascii字符串的二进制表示形式(为什么?),而varA \\ varB是一个字符串,则可以将其转换为字节数组。 varA = '255'; varA.encode('ascii') varA = '255'; varA.encode('ascii') the same as b'255' . varA = '255'; varA.encode('ascii')b'255'相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM