ElectronParade

← Back to Academy

Lesson 117: If/Else Logic (Smart Switches)

Programming is essentially teaching a machine how to make decisions. The core tool for decision-making in almost every programming language is the if/else statement.

We briefly saw an if statement when we read our first pushbutton. Now, let’s explore it in depth by creating a smart switch using two buttons.

Two pushbuttons set up on a breadboard Combining inputs allows for more complex control logic.

The Conditional Statement

An if statement checks a condition. If the condition is true, it executes the code inside its curly brackets. If it is false, it skips that code entirely.

if (condition) {
  // Do this if condition is true
}

Common conditions include:

else if and else

You can chain decisions together.

if (temperature > 80) {
  // Turn on AC
} else if (temperature < 60) {
  // Turn on Heater
} else {
  // Do nothing, the weather is fine
}

The Two-Button Circuit

Set up two pushbuttons on your breadboard with pull-down resistors (just like Lesson 114).

The Code: A Logic Gate

Let’s write a program where Button A turns the LED on, Button B turns it off, and if you press BOTH, the LED blinks rapidly.

int buttonA = 2;
int buttonB = 3;
int ledPin = 9;

void setup() {
  pinMode(buttonA, INPUT);
  pinMode(buttonB, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int stateA = digitalRead(buttonA);
  int stateB = digitalRead(buttonB);

  // Logical AND (&&) means BOTH conditions must be true
  if (stateA == HIGH && stateB == HIGH) {
    // Both pressed: Panic Blink!
    digitalWrite(ledPin, HIGH);
    delay(50);
    digitalWrite(ledPin, LOW);
    delay(50);
  } 
  // If not both, check if just A is pressed
  else if (stateA == HIGH) {
    digitalWrite(ledPin, HIGH); // Turn ON
  } 
  // If not A, check if just B is pressed
  else if (stateB == HIGH) {
    digitalWrite(ledPin, LOW);  // Turn OFF
  }
}

Logical Operators

Notice the && in the first if statement. That is the logical AND operator. It joins two conditions together. If you wanted to check if Button A or Button B was pressed, you would use the logical OR operator, which looks like this: ||.

By combining if/else statements and logical operators, your Arduino can navigate incredibly complex scenarios and build true “smart” devices.

[Building a complex control deck? You might need a larger breadboard. Check out this Full-Size Breadboard 3-Pack.]