Sub topic 8
Reacting to a press once, not continuously
This chapter assumes you can wire a pushbutton to a pin with INPUT_PULLUP, and that you know why a pressed button reads LOW in that wiring. It also assumes you are comfortable with bool variables and if statements. The bounce problem comes in the next chapter. Here the goal is narrower: make one physical press trigger one action.
Level versus edge
digitalRead() reports the level of a pin right now. It does not report that the button was just pressed. A human press lasts roughly 50 to 300 ms, and loop() on an Uno runs thousands of times in that window. If your code acts on the level, it acts on every one of those passes.
Here is the common first attempt. It is meant to toggle the LED once per press, and it does not.
const uint8_t BUTTON_PIN = 2;
bool ledState = LOW;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) { // level check: true on every pass while held
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
}While the button is held, the LED toggles on every pass through loop(). It flickers faster than you can see, and the LED ends up on or off depending on when you let go. The code answers "is the button down?" when the question you want answered is "did the button just go down?"
An edge is the moment a signal changes from one level to the other. With INPUT_PULLUP there are two:
- A falling edge goes from
HIGHtoLOW. This is the press. - A rising edge goes from
LOWtoHIGH. This is the release.
A sketch has no hardware that reports edges to loop(). It finds them by comparing two readings: the one from this pass and the one from the previous pass. If they differ, an edge happened.
The previous-state pattern
Keep a variable that holds the reading from the last pass. On each pass, read the pin once, compare, act, and then store the new reading.
const uint8_t BUTTON_PIN = 2;
bool lastReading = HIGH; // released, because INPUT_PULLUP idles HIGH
bool ledState = LOW;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
bool reading = digitalRead(BUTTON_PIN);
if (lastReading == HIGH && reading == LOW) { // falling edge: pressed
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
lastReading = reading; // always remember this pass for the next one
}The condition is true on exactly one pass per transition. On the next pass lastReading is LOW, so holding the button changes nothing. Releasing and pressing again produces a new HIGH to LOW transition.
The table lists all four combinations of previous and current reading, with the pull-up wiring.
| Previous reading | Current reading | Meaning | Event |
|---|---|---|---|
| HIGH | HIGH | Still released | none |
| HIGH | LOW | Just pressed | falling edge |
| LOW | LOW | Still held | none |
| LOW | HIGH | Just released | rising edge |
The same logic can be drawn as two states with an event on each arrow.
Rules that keep the pattern correct
Three details cause most of the bugs people hit with this pattern.
- Read the pin once per pass and store it in a local variable. If you call
digitalRead()separately for the comparison and for the update, the pin can change between the two calls. The comparison and the stored value then disagree, and you can miss an edge or see one twice. - Update
lastReadingon every pass. If you putlastReading = reading;inside theif, the stored value goes stale. The next pass compares against an old reading, and the logic stops tracking the pin. - Do the update after the comparison. If you move it above the
if,lastReadingalways equalsreadingand no edge is ever found.
Choosing the starting value
lastReading needs a value before the first pass. Initializing it to HIGH assumes the button is released at power-up, which is correct for a pull-up wiring in almost every case.
If the button is held while the board resets, that assumption is wrong. The first pass reads LOW and sees a HIGH to LOW transition that never happened. You get one phantom press at startup. To avoid it, read the real pin in setup():
const uint8_t BUTTON_PIN = 2;
bool lastReading;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
lastReading = digitalRead(BUTTON_PIN); // whatever the button is doing right now
}
void loop() {
// edge detection as before
}Do the read after pinMode(). Before that call the pin is a floating input, and the value is meaningless.
Counting presses and watching the edges
The next sketch counts presses and prints them. It also reports releases, which is useful for seeing the whole cycle.
const uint8_t BUTTON_PIN = 2;
bool lastReading = HIGH;
unsigned int pressCount = 0;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
lastReading = digitalRead(BUTTON_PIN);
}
void loop() {
bool reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
if (reading == LOW) {
pressCount++;
Serial.print("Pressed, count = ");
Serial.println(pressCount);
} else {
Serial.println("Released");
}
}
lastReading = reading;
}The outer if (reading != lastReading) means "any edge happened". The inner if tells the two edges apart. This shape is easy to extend. Code that should run on press goes in the LOW branch, and code that should run on release goes in the other branch.
Open the Serial Monitor at 9600 baud and press the button a few times. On many buttons you will see something like this for a single press:
Pressed, count = 1
Released
Pressed, count = 2
Released
Pressed, count = 3
ReleasedYou pressed once, and the sketch reports three presses. Edge detection did its job. The pin really did go HIGH, LOW, HIGH, LOW within a millisecond or two. The mechanical contacts bounced, and each bounce is a genuine edge. Some presses will report cleanly and others will not, which is typical of bounce.
What this pattern depends on
Edge detection by polling works only if loop() samples the pin often enough to see each level. Two things can break that.
Blocking code
If loop() spends 500 ms inside delay(), the pin is not read during that time. A press and release that both happen inside the delay leave lastReading unchanged, and the sketch never notices them. A press that is still held when the delay ends is detected late. The millis() approach from the earlier chapters is what keeps the sampling rate high.
Slow work in the loop
Any long operation has the same effect, such as a long Serial.print() at a low baud rate or a slow sensor read. A pass that takes 20 ms means the pin is sampled 50 times a second. A quick tap can fall between samples. For typical human presses this is fine until a pass takes more than a few tens of milliseconds. Keep each pass short.
Polling versus interrupts
Polling samples the pin. An interrupt reacts to the edge itself, so it catches presses even while loop() is busy. The last chapters in this tutorial compare that approach with polling, including the extra care interrupts need.
Edge-triggered actions in the loop
Edge detection pairs well with state that persists between passes. The toggle in the second sketch above is an example. The button event flips a stored boolean, and the output follows the stored boolean, not the button level. This separation is useful when the action is more than one pin write:
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 8;
bool lastReading = HIGH;
uint8_t mode = 0; // 0 = off, 1 = dim, 2 = full
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT); // pin 8 is not a PWM pin on an Uno, so "dim" is shown as a half-rate blink
lastReading = digitalRead(BUTTON_PIN);
}
void loop() {
bool reading = digitalRead(BUTTON_PIN);
if (lastReading == HIGH && reading == LOW) {
mode = (mode + 1) % 3; // advance: 0 -> 1 -> 2 -> 0
}
lastReading = reading;
if (mode == 0) {
digitalWrite(LED_PIN, LOW);
} else if (mode == 1) {
digitalWrite(LED_PIN, (millis() / 500) % 2); // slow blink, no delay()
} else {
digitalWrite(LED_PIN, HIGH);
}
}The press changes mode once. The rest of loop() acts on mode on every pass, including the blink in mode 1, which reads millis() directly and never blocks. As written, this sketch can still skip modes when the button bounces, and the next chapter addresses that.
Common mistakes
- Using
if (digitalRead(pin) == LOW)alone for a one-shot action. This is the level bug from the start of the chapter. - Forgetting the inversion. With
INPUT_PULLUP, a press isHIGHtoLOW. Writing the condition aslastReading == LOW && reading == HIGHdetects the release instead, so the action fires when you let go. - Using
intorboolinconsistently.digitalRead()returnsint, and storing it inboolis fine because the values are 0 and 1. Mixing in a third value, such as a "pressed" flag stored in the same variable, makes comparisons unreliable. - Declaring
lastReadingas a local variable insideloop(). It is reinitialized every pass, so it never remembers anything. It must be a global orstatic.
Exercises
Exercise
A sketch uses INPUT_PULLUP and contains this code in loop(): "bool reading = digitalRead(2); if (lastReading == LOW && reading == HIGH) { count++; } lastReading = reading;". Does count increase when the button is pressed or when it is released, and why?
Show answer
It increases when the button is released. With INPUT_PULLUP the pin idles HIGH and goes LOW when pressed. The condition checks for LOW followed by HIGH, which is the rising edge, and that happens at release. To count presses, test lastReading == HIGH && reading == LOW.
Exercise
A student moves "lastReading = reading;" so it runs only inside the if block that detects the falling edge. Describe what goes wrong.
Show answer
lastReading is no longer updated on passes where no press edge occurs. After the first press it stays LOW. While the button is released, reading is HIGH and lastReading is still LOW, so the next press compares LOW to LOW and is never detected. The press logic fires only on the first press, and after that the stored value no longer tracks the pin. The update must run on every pass.