Project 3.03 OR Logic

In this project you’ll learn about using OR logic with buttons to turn on LED1 when SW1 OR SW2 are pressed.

What if you wanted to turn on an LED when SW1 was pressed OR SW2 was pressed? AND logic won’t work for this. We need to learn how to use OR logic to do this.

Project Code:

///////////////////////////////////////////////////////
// 3.03 - OR Logic
// "&&" is the logical "and" comparator. See truth table below.

byte SW1 = 1;
byte SW2 = 0;
bool pressed = 0;

byte LED1 = 13;

void setup() {
  pinMode(SW1, INPUT);
  pinMode(SW2, INPUT);
  
  pinMode(LED1, OUTPUT);
}

void loop() {
  bool SW1State = digitalRead(SW1);
  bool SW2State = digitalRead(SW2);

  if (SW1State == pressed || SW2State == 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 of the code up to the if-statement is the same as the last project, so we’ll skip to the difference.

The difference between this project and the last project is instead of having the “&&” symbols in the conditional, we now have the “||” symbols. This is the programmatic way to say OR.

if (SW1State == pressed || SW2State == pressed) {

The conditional will evaluate to be true if what is on the left side of the “||” symbols or what is on the right side of the “||” symbols is true. The left OR right side need to be true for the code to execute.

 If true, it turns LED1 on: 

  digitalWrite(LED1, HIGH);
}

Else, if it is not true, it turns LED1 off:

else {
  digitalWrite(LED1, LOW);
}

OR has a similarly strict definition in programming. Here is the OR logic truth table:

Input A Input B Output
0 0 0
0 1 1
1 0 1
1 1 1

As you can see, the output is 1 if either input is 1. In other words, if input A OR input B is 1, the output is a 1.

Again, for a more familiar example let’s make the table based on our program’s inputs:

SW1State == pressed SW2State == pressed Output
0 0 0
0 1 1
1 0 1
1 1 1

 As you can see, the output is a 1 if SW1State or SW2State equal 1; I.e., either button is pressed.

Previous
Previous

Project 3.04 NOT Logic

Next
Next

Project 3.02 AND Logic