Menu
CoddyTech

Read a Button

Part of the First Circuits section of Coddy's Arduino journey. Lesson 22 of 22.

A pin can also be an input: the board reads whether it is HIGH or LOW.

This button connects pin 2 to ground (0 volts) while you hold it. When it is up, the pin is connected to nothing and would read random values. INPUT_PULLUP turns on a pull-up resistor inside the board, which holds the pin HIGH until the button pulls it LOW:

pinMode(2, INPUT_PULLUP);

digitalRead(2) gives the pin's level. With a pull-up, a pressed button reads LOW:

if (digitalRead(2) == LOW) {
  // the button is pressed
}

The rest is what you know: if and else to choose, digitalWrite() for the LED, Serial.println() to report.

challenge icon

Challenge

Easy

The button is on pin 2 and the LED on pin 13. Make the LED light while the button is held:

  • set pin 2 to INPUT_PULLUP
  • when digitalRead(buttonPin) is LOW, turn the LED on, print Pressed and wait 200 ms (so the monitor is not flooded)
  • else, turn the LED off

Press Run, hold the green button on the board, then Check.

Try it yourself

const int buttonPin = 2;
const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {

}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in First Circuits

Practice on your own: Arduino playground