Sub topic 13
Extending the pattern: long press and repeat
A debounced button gives you a clean press and a clean release. Once you have those two events with reliable timestamps, you can build richer behavior on top of them. This chapter adds two patterns: a long press, which triggers a different action when you hold the button, and auto-repeat, which fires an action over and over while the button stays down.
This chapter assumes you have read the earlier chapters on INPUT_PULLUP, timestamp-based debouncing, edge detection, and non-blocking timing with millis(). You should be comfortable with unsigned long subtraction and with the debounce sketch that tracks lastReading, stableState and lastChangeTime.
What changes when you care about duration
A plain debounced button answers one question: did the stable state change? Long press and repeat ask a second one: how long has it been in this state?
You answer it with one more timestamp. When the stable state becomes pressed, record millis() in a variable such as pressStart. While the button stays pressed, compare millis() - pressStart against a threshold on every pass through loop(). The pattern is the same as non-blocking interval timing. The only new idea is that the timer starts on a button event instead of free-running.
Use the stable (debounced) state for all of this, never the raw reading. The raw pin can flicker for a few milliseconds at the start and end of a press. If a long-press timer were reset by those flickers, it would restart repeatedly and might never fire.
Long press versus short press
Telling a short press from a long press has one design consequence. You cannot know a press is short until the button is released, because the user might still be holding it. So the short-press action has to run on release, not on press.
The sketch below reports a short press when the button is released before 800 ms. It reports a long press as soon as 800 ms is reached, without waiting for release. A flag, longFired, stops the release from also counting as a short press.
const uint8_t BUTTON_PIN = 2;
const unsigned long DEBOUNCE_MS = 30;
const unsigned long LONG_PRESS_MS = 800;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
unsigned long pressStart = 0;
bool longFired = false;
void onShortPress() {
Serial.println(F("short press"));
}
void onLongPress() {
Serial.println(F("long press"));
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChangeTime = now;
lastReading = reading;
}
if ((now - lastChangeTime >= DEBOUNCE_MS) && (reading != stableState)) {
stableState = reading;
if (stableState == LOW) { // pressed
pressStart = now;
longFired = false;
} else if (!longFired) { // released without a long press
onShortPress();
}
}
if (stableState == LOW && !longFired && (now - pressStart >= LONG_PRESS_MS)) {
longFired = true;
onLongPress();
}
}Open the Serial Monitor at 9600 baud to see the output. A quick tap prints short press when you let go. A hold prints long press while the button is still down, and nothing more on release.
Choosing the threshold
Human perception sets a practical range. Most interfaces use a threshold between about 500 ms and 1000 ms. Shorter values cause accidental long presses. Longer ones feel broken, because the user holds the button and sees no response.
The long-press timer starts when the debounced press is accepted, which is DEBOUNCE_MS after the physical contact. With a 30 ms debounce this error is small. It is worth knowing about when you tune the threshold.
Why the short press is delayed
Moving the short-press action to release adds a small delay. For a menu or a mode switch this feels natural. For an action that must react instantly, such as a trigger or an emergency stop, do not combine it with a long-press meaning on the same button. Use a separate button, or fire on press and give the long press an extra, additive effect.
Auto-repeat while held
Auto-repeat is how a keyboard behaves. The key acts once on press, pauses briefly, then acts repeatedly at a steady rate. It suits "increase value" buttons, where you want one tap to add 1 and a hold to scroll quickly.
The pattern needs three numbers:
- The initial delay before repeating starts, for example 500 ms.
- The repeat interval, for example 120 ms.
- A timestamp of the last action.
The sketch below keeps a counter. One tap adds 1. Holding the button adds 1 immediately, waits 500 ms, then adds 1 every 120 ms. It also blinks the built-in LED without delay(), to show the two tasks sharing the loop.
const uint8_t BUTTON_PIN = 2;
const unsigned long DEBOUNCE_MS = 30;
const unsigned long REPEAT_DELAY_MS = 500;
const unsigned long REPEAT_INTERVAL_MS = 120;
const unsigned long BLINK_MS = 500;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
unsigned long lastActionTime = 0;
unsigned long waitMs = REPEAT_DELAY_MS;
int counter = 0;
unsigned long previousBlink = 0;
bool blinkState = LOW;
void step() {
counter++;
Serial.println(counter);
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChangeTime = now;
lastReading = reading;
}
if ((now - lastChangeTime >= DEBOUNCE_MS) && (reading != stableState)) {
stableState = reading;
if (stableState == LOW) { // pressed: act once, then arm the repeat
step();
lastActionTime = now;
waitMs = REPEAT_DELAY_MS;
}
}
if (stableState == LOW && (now - lastActionTime >= waitMs)) {
step();
lastActionTime = now;
waitMs = REPEAT_INTERVAL_MS; // after the first repeat, use the fast rate
}
if (now - previousBlink >= BLINK_MS) {
previousBlink = now;
blinkState = !blinkState;
digitalWrite(LED_BUILTIN, blinkState);
}
}The variable waitMs is the key detail. It holds the time that must pass since the last action before the next one. It starts as the long initial delay and drops to the short repeat interval after the first repeat. This avoids a second timestamp and a second state flag.
Drift and catch-up
The sketch sets lastActionTime = now, so each repeat is measured from when it actually ran. If loop() is occasionally slow, repeats stretch slightly and never bunch together. That is the right behavior for a human-facing control.
If you instead used lastActionTime += waitMs, the average rate would be exact, but a long stall in loop() would cause a burst of catch-up repeats. Use that form only when the average rate matters more than even spacing, such as generating a pulse train.
Common mistakes
| Mistake | What you see | Fix |
|---|---|---|
| Timing from the raw reading instead of the stable state | Long press fires late, or never fires on a noisy button | Start `pressStart` only in the debounced press branch |
| Running the short-press action on press | Every long press also triggers a short press | Run the short action on release and check `longFired` |
| Forgetting to reset `longFired` on each new press | Only the first long press works | Set `longFired = false` when a press is accepted |
| Comparing against a precomputed deadline such as `now >= pressStart + LONG_PRESS_MS` | Wrong behavior near `millis()` rollover | Use `now - pressStart >= LONG_PRESS_MS` |
| Calling `delay()` inside the repeat action | Button release is missed or noticed late | Keep the action short and non-blocking |
| Not resetting `waitMs` on a new press | A second hold repeats immediately at the fast rate | Set `waitMs = REPEAT_DELAY_MS` on every accepted press |
Edge cases to plan for
- Button held at power-up.
stableStatestarts asHIGH, so a button held at boot looks like a fresh press after the debounce time. If that is not acceptable, read the pin once insetup()and initializelastReadingandstableStatefrom it. - Several buttons. Each button needs its own set of variables. When you have more than two, group them in a
structand write one update function that takes a reference to it, rather than copying the globals. - Long actions. If the long-press action takes noticeable time, such as writing to EEPROM, run it once and return. The
longFiredflag guarantees it will not run again until the next press. - Double-tap. A double-tap is a third pattern in the same family. You record the time of the last short press and check whether the next press arrives within a window. It needs one more timestamp and one more flag, and the rest of the structure is unchanged.
Choosing a pattern
| Pattern | Fires | Best for | Cost |
|---|---|---|---|
| Short press on release | When the button is released | Buttons that also have a long-press meaning | Slight delay before the action |
| Long press | When the hold threshold is reached | Rare or risky actions, such as reset or mode change | User must know to hold |
| Auto-repeat | On press, then at intervals while held | Increment and decrement controls | Needs two timing values |
Exercise
In the long-press sketch, a user holds the button for 300 ms and releases. Which function runs, and at what moment? What would go wrong if onShortPress() were called in the branch where stableState == LOW instead?
Show answer
onShortPress() runs at the moment of release, because 300 ms is below LONG_PRESS_MS and longFired is still false. If it ran on press, every long press would also trigger a short press first, since the program cannot know at press time how long the hold will last.
Exercise
Change the repeat sketch so that the repeat interval gets shorter the longer the button is held. It should start at 200 ms, drop to 100 ms after five repeats, and never go below 50 ms. Which variables do you add, and where do you update them?
Show answer
Add a repeatCount integer and make the interval a variable, for example repeatInterval, initialized to 200. Reset repeatCount = 0 and repeatInterval = 200 in the press branch. Inside the repeat branch, after step(), increment repeatCount, set waitMs = repeatInterval, and when repeatCount % 5 == 0 set repeatInterval = max(50UL, repeatInterval / 2). Because 200 halves to 100 and then 50, the floor holds. Update the variables only in the press and repeat branches so they stay tied to the stable state.