Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Digital I/O

digitalRead and Buttons

Read buttons and switches with digitalRead: floating inputs, wiring a button, edge detection, toggling an LED on each press and counting presses without errors.

Outputs make things happen; inputs tell your sketch what is going on. The simplest input is a button, and reading one correctly teaches three lessons that apply to every sensor: inputs must never be left floating, you often care about the change rather than the level, and real contacts are messy. This lesson covers the first two and sets up debouncing for the next.

digitalRead

C++
int value = digitalRead(pin);   // returns HIGH or LOW

The pin should be configured as INPUT (or INPUT_PULLUP). The function returns HIGH if the pin is above about 3 V (on a 5 V board), LOW if it is below about 1.5 V, and an unpredictable value in between.

The floating input problem

If a pin is set as INPUT and nothing is connected, it acts like an antenna: it picks up noise from your hand, the mains hum or nearby wires, and digitalRead() flickers between HIGH and LOW. A button that connects the pin to 5 V when pressed leaves the pin floating when released. To fix this, the pin needs a resistor that pulls it to a known level whenever the button is open. A pull-down resistor ties it to GND, a pull-up resistor to 5 V. The Arduino has pull-ups built in, enabled with INPUT_PULLUP.

The easiest wiring: INPUT_PULLUP

Connect one side of the button to the pin and the other side to GND. No external resistor is needed:

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

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(buttonPin) == LOW) {   // pressed pulls the pin to GND
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

Note the inverted logic: with a pull-up, pressed = LOW and released = HIGH. Hide that inversion behind a named helper so the rest of your code reads naturally:

C++
bool isPressed() { return digitalRead(buttonPin) == LOW; }
flowchart LR
    V["5 V"] --> R["Internal pull-up ~20-50 kohm"]
    R --> P["Pin 2"]
    P --> S["Button"]
    S --> G["GND"]

Figure: with INPUT_PULLUP the pin reads HIGH until the button connects it to GND.

Level versus edge

The sketch above reacts to the level: the LED follows the button. Often you want an event: "the button was just pressed", to toggle something or count a press. Detecting that means remembering the previous reading and comparing:

TEXT
previous = HIGH, current = LOW  -> pressed (falling edge)
previous = LOW,  current = HIGH -> released (rising edge)
C Stand-in: edge detection on a recorded button signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The level stayed LOW for four samples but counted as one press. That is exactly what you want when loop() runs thousands of times while a finger is still down.

Toggle an LED on each press

Real sketch, read-only:

C++
const int buttonPin = 2;
const int ledPin = 13;
bool ledOn = false;
int lastState = HIGH;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int state = digitalRead(buttonPin);
  if (lastState == HIGH && state == LOW) {   // falling edge = press
    ledOn = !ledOn;
    digitalWrite(ledPin, ledOn);
  }
  lastState = state;
}

Stand-in with the same logic running over a scripted series of button samples:

C Stand-in: toggle on each press

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Counting and long presses

Edge detection extends naturally. To count presses, increment a counter on each falling edge. To detect a long press, record the time when the press starts (using millis(), introduced in Using millis() Instead of delay()) and compare it on release or while held. Two buttons can be read the same way with two lastState variables, or you can keep the state in arrays and loop over them.

Tips

  • Prefer INPUT_PULLUP and wire buttons to GND; it needs no extra parts and is robust.
  • Do not use delay() in the main loop to "wait out" a press: it blocks everything else.
  • Test with the Serial Monitor: print the raw value to see what the pin does.
  • Keep wires short; long wires pick up noise.
  • Expect some presses to count twice with a real button. That is contact bounce, the subject of the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With INPUT_PULLUP and a button to GND, what does digitalRead return when the button is pressed?

    The pull-up holds the pin HIGH; pressing connects it to GND, so it reads LOW.
  2. 2. Why does an unconnected INPUT pin give random readings?

    Without a defined level, the high-impedance input acts as an antenna.
  3. 3. To detect the moment a button is pressed (not held), you compare:

    A change from HIGH to LOW between two reads is a falling edge, meaning a new press.
  4. 4. Which line correctly toggles a boolean ledOn?

    The assignment ledOn = !ledOn flips the value.

Summary

  • digitalRead() returns HIGH or LOW; unconnected inputs float and must be pulled to a known level.
  • INPUT_PULLUP plus a button to GND gives pressed = LOW without extra parts.
  • Compare the current and previous reading to detect press and release events.
  • Toggle and count on edges, not levels.

Next: Pull-Up Resistors and Debouncing