Read the code

Here is the whole sketch. It does the same job as Arduino’s own Button example3.

l4-button-arduino.ino
// Lesson 4, Arduino version.
// Lights the UNO R3's LED on pin 13 while the button on pin 2 is held.
void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  if (digitalRead(2) == HIGH) {
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW);
  }
}

What each line does

  1. void setup()The lines inside setup run once, when the board starts11.
  2. pinMode(2, INPUT);Makes pin 2 an input: a pin your code reads6.
  3. pinMode(13, OUTPUT);Makes pin 13 an output, as in Lesson 16.
  4. void loop()Runs again and again, so the board checks the button all the time12.
  5. if (digitalRead(2) == HIGH) {If pin 2 reads HIGH, the button is down, so the next line runs8.
  6. digitalWrite(13, HIGH);Turns the light on7.
  7. } else {The lines after else run when the test is false: the button is up9.
  8. digitalWrite(13, LOW);Turns the light off7.

Reading the button

digitalRead(2) reads pin 2. It gives back HIGH or LOW5.

The two equals signs, ==, ask whether the two sides are equal10.

Sources for this page

  1. Arduino example: Button.ino: public domain
  2. Arduino reference: digitalRead
  3. Arduino reference: pinMode
  4. Arduino reference: digitalWrite
  5. Arduino reference: if
  6. Arduino reference: else
  7. Arduino reference: == (equal to)
  8. Arduino reference: setup()
  9. Arduino reference: loop()