Project 3.04 NOT Logic
What if you wanted to turn on an LED when SW1 was NOT pressed? In this project you’ll learn about using NOT logic with a button to turn on LED1 when SW1 is NOT pressed.
Project Code:
/////////////////////////////////////////////////////// // 3.04 - NOT Logic byte SW1 = 1; bool pressed = 0; byte LED1 = 13; void setup() { pinMode(LED1, OUTPUT); } void loop() { bool buttonState = digitalRead(SW1); if (buttonState != pressed) { digitalWrite(LED1, HIGH); } else { digitalWrite(LED1, LOW); } } ///////////////////////////////////////////////////////
*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.
All if the code up to the if-statement is the same as the last project, so we’ll skip to the difference.
In our project, we're going to use the special symbol “!” instead of “&&” or “||”. This ! symbol is known as the NOT operator. The NOT operator is different from the AND and OR operators becuase it can be used with comparisons and boolean values. When using it, it's like saying “the opposite of” something.
When you put ! in front of a boolean value, it changes that value to its opposite. So, if you have !0 (which can be read as “not 0”), it turns into 1. Similarly, if you have !1 (which is “not 1”), it becomes 0. It's a handy way to switch between these two boolean values in our code.
When using the NOT operator for comparisons, it does essentially the same thing. It inverts the output. In this sketch it can be written in a few different ways:
buttonState != pressed (The NOT is grouped with the “=” operator and is the same as saying “Not equal to”)
or
!(buttonState == pressed) (The expression inside of the parenthesis is evaluated first, then negated)
In this sketch we use the “!=” form. So in english, this line of code reads “If buttonState is not equal to pressed”.
if (buttonState != pressed) {
If the conditional evaluated to true, LED1 is turned on.
digitalWrite(LED1, HIGH); }
Else, if the conditional evaluates to false, LED1 is turned off.
else { digitalWrite(LED1, LOW); }