Sub topic 1
Reading a Button with digitalRead()
This chapter covers how an Arduino sketch reads a pushbutton, why INPUT_PULLUP reverses the logic you might expect, what contact bounce does to the readings, and why delay() stops a sketch from responding to anything else.
Prerequisites
You should be comfortable with the basic setup() and loop() structure, pinMode(), digitalWrite(), if statements, and int variables. You should also have a pushbutton wired to a digital pin and an Arduino board with the IDE installed.
Reading a button with digitalRead()
digitalRead(pin) returns HIGH or LOW for the voltage on a digital pin. Call it in loop() to check the button on every pass.
const uint8_t BUTTON_PIN = 2;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(BUTTON_PIN);
if (reading == LOW) {
Serial.println("Pressed");
} else {
Serial.println("Released");
}
delay(100); // slows the printout; see "The cost of delay()" below
}Wiring with INPUT_PULLUP and inverted logic
Connect one leg of the button to pin 2 and the other leg to GND. INPUT_PULLUP turns on an internal resistor that holds the pin at HIGH while the button is open. Pressing the button connects the pin to GND, so the pin reads LOW. The logic is inverted: pressed means LOW.
> Note: Do not use INPUT alone with a button wired to GND. The pin would float and give random readings.
What contact bounce looks like
A mechanical button's metal contacts bounce for a few milliseconds when they close and open. The pin can switch between HIGH and LOW several times for one press.
Without filtering, a sketch that counts LOW readings can count one press as many.
The cost of delay()
delay(ms) pauses the whole sketch. Nothing else runs during the pause, and digitalRead() is not called. Consider this blinking code:
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}If the button is pressed during either delay, the sketch misses it. A sketch that waits on delay() cannot respond to inputs on time.
Exercise
Why does a button wired with INPUT_PULLUP read LOW when pressed?
Show answer
The internal pull-up holds the pin HIGH while the button is open. Pressing the button connects the pin to GND, which pulls the pin LOW.