pythonbitwise-operatorspyserialbitmaskbitwise-and

Test if a given bit is set in a byte


I have an EasyDAQ relay board. To turn on relay 1, you send it one byte, relay 2, two bytes, relay 3, four bytes and relay 4, eight bytes. All the relays on = 15 bytes. To turn off a relay you have to basically subtract its byte number from the total of bytes from the relays that are on. So if all relays are on, the board polls at 15 bytes. If I want to turn off relay 3, I subtract 4 bytes from 15 bytes. All this I have done. What I want to do is tell if a relay is on from the number of bytes polled from the board. For example if the board polls at 11 bytes I know relay 3 (4 bytes) is not turned on. How can I calculate this?


Solution

  • I think your terminology for "byte numbers" and sending a particular number of "bytes" is a little confused. I'm assuming what is going on is that you are reading a value from the board that is a single byte (consisting of 8 bits) where the individual bits represent the state of the relays. Thus if the board returns 15 in decimal (base 10), in binary that is 0b1111, which as you can see has all four bit set indicating that all four relays are on. (The '0b' indicates that the number is in binary)

    Assuming that is true, take a look at pythons's bitwise operators. In particular if you want to test if a particular bit of a int in binary is set, you can bitwise AND it with a bitmask where the bit you care about is set to one and the rest are zeros. So you could test if the third relay is set with something like

    RELAY_3_BITMASK = 0b0100  #Third bit is set to one
    if value_from_board & RELAY_3_BITMASK:
        print("Relay 3 is on")
    else:
        print("Relay 3 is off")