I have some C code running on an embedded processor, which outputs integers (16 bits) over a serial port (stdout) using printf("%d", my_int);. I have some python code running on a PC that reads the serial stream using pyserial and writes it to a file, which I can just achieve using ser.readline(). This works quite happily, although it isn't very efficient.
As the embedded C is sending quite a lot of numbers and I want to cut down on the transfer time, I would like to send the data formatted as binary rather than ascii (i.e. two bytes/chars rather than several bytes/chars.) I tried to do this with:
char msbs = my_int>>8;
char lsbs = my_int;
printf("%c%c\n", msbs, lsbs)
And then in my python code:
chars = ser.readline()
value = ord(chars[0])<<8 + ord(chars[1])
But value seems to be gibberish. Could anyone point out the thing(s) I'm doing wrong?
Try with this:
import struct
chars = ser.readline()[:-1]
value = struct.unpack('>h', chars)
I've assumed that your integer is signed short and please note the presence of '>' for endianness (bytes order).
However the error with you code was because of operator precedence:
value = (ord(chars[0])<<8) + ord(chars[1]) this should work. But it is better to use struct anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With