Using digitalWrite(x, !digitalRead(x)) to toggle a pin in OUTPUT mode

Hello mttr

Take a view into Arduino.h file and you will find the following definition of datatypes used.

void digitalWrite(uint8_t pin, uint8_t val);
int digitalRead(uint8_t pin);

and

#define HIGH 0x1
#define LOW  0x0

The unary prefix ! operator computes logical negation of its operand and isn´t "suitable" for the datatype uint8_t.

The correct coding as already mentioned:

digitalWrite(x, digitalRead(x)==HIGH?LOW:HIGH) ;

to toggle a pin in OUTPUT mode.

HTH

Have a nice day and enjoy coding in C++.

1 Like