Project 3.01 Blink an LED with a button

In the last project we learned how to read the state of a button. In this project we will learn how to make a decision based on the buttons state that we read. The goal of this project is to turn on an LED when the button is pressed!

Project Code:

///////////////////////////////////////////////////////
// 3.01 - Blink an LED with button press

byte SW1 = 1;
byte LED1 = 13;
bool pressed = 0; 

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

void loop() {
  bool buttonState = digitalRead(SW1);

  //digitalWrite(LED1, !buttonState); 

  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.

The pressed variable makes the code easier to read. A good programmer makes their code easier for others and themselves to read. By adding the pressed variable, it is easy to see when is going on in the code.

bool pressed = 0; 

Here we are using an if-statement to make a decision. If the button is pressed, turn the LED on. Else, turn the LED off. The “==” is used to make a comparison to see if something is equal. Using the “=” operator will assign a value to the variable. This is a very common mistake in programming!

if (buttonState == pressed) {
   digitalWrite(LED1, HIGH);
 }
else {
   digitalWrite(LED1, LOW);
}

Like most things in programming, there is more than one way to do it! Below is a “one liner” that can be used to do the same thing. It digitalWrites the opposite of what was read from the digitalRead funciton. “!” is the NOT operator. When applied, this operator will turn a 1 into a 0 and a 0 into a 1. This inversion is because the button reads a 0 when pressed and a 1 when not pressed. So, when the button is pressed LED1 is written a 1, and when the button is not pressed LED1 is written a 0 with the inversion.

digitalWrite(LED1, !buttonState); 

Try to make a different LED turn on with SW2!

Previous
Previous

Project 3.02 AND Logic

Next
Next

Project 3.00 Read Input