Sub topic 11
Detecting a press instead of a held level
This chapter assumes you can wire a button to INPUT_PULLUP and read it with digitalRead. It also assumes you know that a press reads LOW, and that you have a debounced reading, as in the sketch from the previous chapter. Here you will turn that steady reading into events: "the button was just pressed" and "the button was just released".
Level versus event
digitalRead reports a level. With INPUT_PULLUP, LOW means "the button is down right now". It does not tell you when that started.
Most actions you want are events. You want to count one press, switch a mode once, or send one message. A person holds a button for about 100 to 300 ms. At 16 MHz, loop() can run thousands of times in that time. If you act on the level, you act thousands of times per press.
The following sketch shows the mistake:
const int buttonPin = 2;
unsigned long count = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
if (digitalRead(buttonPin) == LOW) {
count++;
Serial.println(count);
}
}One short tap prints many numbers. The count tracks how long you held the button and how fast loop() runs, not how many times you pressed it. A level is the right tool only when you want something to follow the button, such as an LED that is on while the button is held (the first example in this tutorial).
| Question | Use | Example |
|---|---|---|
| Is the button down right now? | Level | LED on while held |
| Did the button just go down? | Press edge | Count presses, toggle a mode |
| Did the button just come up? | Release edge | Measure how long it was held |
The idea: compare with the previous reading
An edge is a change between two samples. To find one, keep the previous state in a variable and compare it with the current state on every pass through loop().
With an active-low button there are two edges:
- Press edge: the previous state was HIGH and the current state is LOW (the falling edge).
- Release edge: the previous state was LOW and the current state is HIGH (the rising edge).
The event is true for exactly one pass through loop(). The next pass compares the new state with itself and sees no change.
Which state do you compare?
The previous chapter produced two variables: the raw reading and the accepted stableState. Edge detection must compare the debounced state, not the raw pin value. If you compare raw readings, every bounce looks like a separate press and edge detection gives you nothing that level detection did not.
The comparison happens at the moment you accept a new stable state. The old value of stableState is the "previous" state, and the new reading is the "current" one. That is the only place a real transition can be seen.
A reusable button update function
Putting the logic in a function keeps loop() readable. The function sets two flags each pass. Both flags are cleared at the start of every call, so each is true for at most one pass.
const int buttonPin = 2;
const unsigned long debounceMs = 25;
int lastReading;
int stableState;
unsigned long lastChangeTime = 0;
bool pressedEvent = false;
bool releasedEvent = false;
unsigned long pressCount = 0;
void updateButton() {
pressedEvent = false;
releasedEvent = false;
int reading = digitalRead(buttonPin);
if (reading != lastReading) {
lastChangeTime = millis();
lastReading = reading;
}
if ((millis() - lastChangeTime) >= debounceMs && reading != stableState) {
stableState = reading;
if (stableState == LOW) {
pressedEvent = true;
} else {
releasedEvent = true;
}
}
}
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
lastReading = digitalRead(buttonPin);
stableState = lastReading;
}
void loop() {
updateButton();
if (pressedEvent) {
pressCount++;
Serial.print("press #");
Serial.println(pressCount);
}
if (releasedEvent) {
Serial.println("released");
}
}Open the Serial Monitor at 9600 baud. One tap now prints one press #n line followed by one released line, however long you hold the button.
How it works
updateButton()is the debounce code from the previous chapter, with one change. WhenstableStatechanges, it records which way it changed.- The flags are plain
boolglobals. The rest of the sketch reads them and never touches the debounce variables. - Nothing in
updateButton()waits. It returns immediately, soloop()stays fast and can serve other work.
Initialize from the real pin state
Notice that setup() reads the pin to set lastReading and stableState. The earlier debounce sketch started them at HIGH. That is fine for a button that is up at power-on, but it has an edge case.
Suppose the board powers up while the button is held, or a stuck button holds the line LOW. With a hard-coded HIGH start, the first loop pass sees LOW, waits 25 ms, then reports a press event that nobody made. Reading the pin once in setup() removes this. The initial state is whatever the button really is, so no event fires until something changes.
Sometimes you want the opposite, for example to detect "held at boot" to enter a service mode. In that case read the pin in setup() on purpose and act on it there.
Measuring how long a button was held
Having both edges lets you time the hold. Save millis() on the press edge. On the release edge, subtract.
unsigned long pressStart = 0;
void loop() {
updateButton();
if (pressedEvent) {
pressStart = millis();
}
if (releasedEvent) {
unsigned long held = millis() - pressStart;
if (held >= 1000) {
Serial.println("long press");
} else {
Serial.println("short press");
}
}
}Place this loop() in the previous sketch in place of its own loop(). The unsigned subtraction millis() - pressStart stays correct even when millis() wraps around after about 49 days. Keep both variables unsigned long. Using int here is a common bug: it overflows at about 32 seconds.
This version reports the long press only on release. If you want it to fire while the button is still down, check stableState == LOW && millis() - pressStart >= 1000 on each pass, and use a flag so it fires once.
Common mistakes
Blocking the loop with delay
Edge detection only works if you sample often. A delay(200) in loop() makes the sketch blind for 200 ms at a time. A quick tap that starts and ends inside one delay is never seen. The 200 ms delay in the INPUT_PULLUP sketch earlier is acceptable for printing the level, but not for catching events. If other work needs timing, use millis() for it as well.
Slow work in the loop
Long Serial.print calls, analogRead in big loops, or display updates can also stretch each pass. A press shorter than one pass can be missed. If the loop takes more than a few milliseconds, keep it short or look at interrupts, which a later chapter covers.
Treating the event as a state
pressedEvent is true for one pass only. Code like if (pressedEvent) digitalWrite(led, HIGH); turns the LED on and leaves it on. That is correct for a "turn on" action. But if you expected the LED to follow the button, you wanted the level. Decide per action whether you want a level or an event.
Forgetting the pull-up polarity
The press edge is HIGH to LOW only for an active-low button. With an external pull-down wiring, the press edge is LOW to HIGH. The easiest defense is to write the polarity once, inside updateButton(), so the rest of the program only sees pressedEvent.
Using the raw reading
If you compare digitalRead values from consecutive passes and skip debouncing, you get an event for every bounce. Edge detection depends on debouncing. One does not replace the other.
Edge detection in short
- Read the pin.
- Debounce it so you have a trusted stable state.
- When the stable state changes, note the direction.
- Expose the direction as a one-pass flag.
- Act on the flag in the rest of your code.
The next chapter uses the press event to flip an LED on and off.
Exercise
A sketch uses INPUT_PULLUP and increments a counter with if (digitalRead(buttonPin) == LOW) count++;. A single quick tap raises the counter by about 3000. Name the cause and describe the minimal change that makes the counter rise by one per press.
Show answer
The code tests a level, so it counts once per loop() pass while the button is down. To count presses, keep the previous debounced state in a variable and increment only on the pass where the state changes from HIGH to LOW. In practice, compute that transition inside a debounce function such as updateButton() and increment count only when pressedEvent is true.
Exercise
You write a hold timer that stores unsigned int pressStart = millis(); and later computes millis() - pressStart. It works for short presses but gives strange values for holds over about a minute. What is wrong, and what is the fix?
Show answer
unsigned int is 16 bits on AVR boards such as the Uno, so it wraps at 65535 ms, and storing millis() in it truncates the value. The fix is to declare pressStart as unsigned long, the same type millis() returns. The unsigned subtraction then stays correct even when millis() itself wraps.