Logical NOT in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Logical NOT is performed using the ! operator. The truth table is given below −

ExpressionOutput
TF
FT

As you can see, the logical NOT inverts the truth value of the expression.

Example

The usage can be understood from the example given below −

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   int i = 10;

   if (!(i > 10)) {
      Serial.println("i is NOT greater than 10");
   }
   else {
      Serial.println("i is greater than 10");
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

The NOT function is often used while waiting for something to become true.

while(!condition){
   //do something
}

For example, if you are waiting for Serial input,

while(!Serial.available()){
   //Wait
}

The above loop will break when Serial.available() returns something greater than 0, i.e., when the serial input is received.

raja
Published on 31-May-2021 14:05:06
Advertisements