简体   繁体   中英

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

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". If you want to pass exactly byte 255 you can simply write serial.write(255) . And in this case variables must be assigned with byte (just int in range from 0 to 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. varA = '255'; varA.encode('ascii') varA = '255'; varA.encode('ascii') the same as b'255' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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