Search code examples
arduinobit-manipulationbyte

Arduino Invert byte


I`m using a I2C i/o expander to read up to 8 inputs.

The i/o expander provide a 8 bit output.... 1 byte. Because the e/o expander has internal pull-ups, all 8 bit are 1 when all port are not connected to GND.

So the output is then 255 ... B11111111

when all port are connected to GND.. all 8 bit become 0.

So the output then is 0 ... B00000000

All good, but I could like to invert the signals, when all port are not connected to GND the output should be: 0 ... B00000000.

And when all port are connected to GND the output should be 255 ... B11111111

The usage of Bitwise NOT does not really what i want.

from 255 to -1

Which is logical because they mentioned it on their website:

Link

The code I have does not really work...

byte OutputI2C;
byte OutputI2CInvert;
byte InputModbus;
void setup() {
    Serial.begin(9600);
}

void loop() {
    Wire.requestFrom(B0111000, 1); //connect to i/o expander
    OutputI2C = Wire.read(); // Read data
    OutputI2CInvert = OutputI2C; // make copy
    delay(250);
    Serial.print(~OutputI2CInvert); // invert
}

So I hope someone know how to invert the byte without negative output.


Solution

  • As your type byte is unsigned, normally the bitwise not should work… Can you try to cast your output to this type before printing?

    Something like Serial.print((byte) ~OutputI2CInvert);

    This should force Arduino not to consider the first bit as a sign bit.