Search code examples
pythonpython-3.xraspberry-piraspberry-pi3raspberry-pi2

Byte manipulation (Serial Data) Raspberry Pi


Im trying to establish an RS485 communication system between a raspberry pi and an arduino. Im currently using Nick Gammons arduino 485 library Arduino RS485 Library and would like to port it over to python to run on the raspberry pi.

The transmission side of things is working fine with crc8 and complement error prevention working however Im having difficulty with the receiving side of things. As documented in the pySerial API HERE ser.read() returns a variable of type bytes. The problem with this is that I require bitwise operations to perform error checks as an example:

            in_byte = ser.read()


            if (in_byte >> 4) != ((in_byte & 0x0F) ^ 0x0F):
                return 0

            in_byte >>= 4

This of course throws up an interpretor error saying that the bitwise operator '>>' is not compatible with variables of type int and bytes

I know of the int.from_bytes method however this seems to require multiple bytes plus an endian format

What is the 'correct' or typical way that I should perform bitwise operations on byte by byte serial data?

Im relatively new to python coming from a C / C++ background,

Thanks

Andy


Solution

  • Short answer:

    ord() function works great for single bytes ex:

            temp = ser.read()
            in_byte = ord(temp)
    

    TLDR:

    Using Python struct.unpack with 1-byte variables