How can I create byte values ββfrom integers in Python?
Background: I need to send a numeric value as a byte to an external device, but I am facing a problem. My code:
ser=serial.Serial("COM3",9600, timeout=0)
ser.write(value)
where "value" is the int I read, read. The problem is, when I post this, it sends the character value, not the actual value (it sends byte value 31 for number 5, since that's the unicode position for it, I believe)
In fact, I want to be able to send it the character "\ x05", for example. I guess my question is how would I convert both int 5 to char "\ x05", or 37 to "\ x37"
source to share
Use the built-in function chr()
.
If you have a list of such integers that you need to send, you can use bytearray()
.
Alternatively, in newer versions of Python, you can simply use type byte
.
source to share