Sub topic 13
Interrupts for Button Input: When and Why to Avoid Them
This chapter assumes you can wire a button to INPUT_PULLUP, read it with digitalRead, and debounce it with millis, as covered in the earlier chapters. It also assumes you know the basic sketch structure of setup and loop. Interrupts are an optional technique for button input. For most buttons, the polling approach you already have is the better choice.
What an interrupt does
Polling means your loop asks the pin "are you pressed?" over and over. An interrupt reverses this. The microcontroller hardware watches the pin. When the pin changes in a way you chose, the processor pauses the code it is running, jumps to a function you wrote, runs it, and then resumes where it stopped.
That function is an interrupt service routine (ISR). It takes no arguments and returns nothing. You register it with attachInterrupt.
The trigger mode says which pin change fires the ISR:
| Mode | Fires when |
|---|---|
| `FALLING` | The pin goes from HIGH to LOW. This is a press with `INPUT_PULLUP`. |
| `RISING` | The pin goes from LOW to HIGH. This is a release with `INPUT_PULLUP`. |
| `CHANGE` | The pin changes in either direction. |
| `LOW` | The pin is LOW. The ISR repeats for as long as the pin stays LOW. |
Not every pin supports this. On an Arduino Uno only pins 2 and 3 can trigger external interrupts. Always pass the pin through digitalPinToInterrupt() instead of hard-coding an interrupt number. The interrupt numbers differ between boards, and this function converts a pin number to the right one for your board.
The simplest interrupt button, and its problem
This sketch counts presses with an ISR and prints the count. It uses the internal pull-up, so a press is a falling edge.
const int buttonPin = 2;
volatile unsigned int pressCount = 0;
void onPress() {
pressCount++;
}
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), onPress, FALLING);
}
void loop() {
noInterrupts();
unsigned int copy = pressCount;
interrupts();
Serial.println(copy);
delay(500);
}Run it and press the button once. On many buttons the count jumps by two, three, or more. Contact bounce produces several real falling edges within a millisecond or two, and the hardware catches every one. A polling loop that reads the pin only once per pass can miss some of this chatter by accident. An interrupt cannot, so an interrupt makes bounce more visible, not less.
Two details in this sketch matter for any ISR:
volatiletells the compiler thatpressCountcan change outside the normal flow ofloop. Without it, the compiler may keep a copy of the variable in a register and never see the ISR's updates.pressCountis a 16-bit value, and the Uno's processor is 8-bit. Reading it takes two separate byte reads. If an interrupt fired between those two reads, you would get half of an old value and half of a new one. ThenoInterrupts()andinterrupts()pair makes the copy safe. Reading a singleboolorbytedoes not need this protection.
Why interrupts are a poor default for buttons
The ISR runs under restrictions
While an ISR runs, other interrupts are normally blocked. Several things you rely on in loop behave differently or fail:
delay()does not work inside an ISR, because it depends on timer interrupts that are blocked.millis()can be read, but its value does not advance while the ISR runs.Serial.print()can hang or lose data, because it needs interrupts to drain its buffer.- A long ISR delays everything else, including the timer that keeps
millis()accurate and serial reception. Bytes can be dropped if the ISR is slow.
The rule is to keep an ISR to a few lines. It should set a flag or update a counter and return.
Debouncing becomes harder
In polling code, debouncing is a few lines of state in loop, as in the earlier chapter. In an interrupt, you cannot wait out the bounce, because you cannot call delay. The usual workaround is to remember when the last accepted edge happened and ignore edges that follow too soon.
const int buttonPin = 2;
const int ledPin = LED_BUILTIN;
const unsigned long lockoutMs = 25;
volatile bool pressFlag = false;
volatile unsigned long lastAcceptedTime = 0;
bool ledOn = false;
void onPress() {
unsigned long now = millis();
if (now - lastAcceptedTime >= lockoutMs) {
lastAcceptedTime = now;
pressFlag = true;
}
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(buttonPin), onPress, FALLING);
}
void loop() {
if (pressFlag) {
pressFlag = false;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}The ISR does almost nothing. It compares the time, sets a flag, and returns. The real work, toggling the LED, happens in loop. This is the standard pattern: the ISR records that something happened, and the main code decides what to do about it.
This version still has a flaw. The lockout only blocks edges that arrive within 25 ms of the last accepted press. The button also bounces when you release it. If you hold the button for longer than 25 ms and then release it, the contacts can chatter, and a bounce that briefly closes the contact looks like a new falling edge. That edge arrives after the lockout has expired, so the ISR accepts it as a second press. The result is an occasional double toggle that is hard to reproduce.
You can reduce this by also checking the pin level in loop before acting on the flag, but at that point you have rebuilt part of the polling approach. The state-based debounce from the previous chapter has no such hole, because it tracks the stable state of the pin instead of individual edges.
Shared state brings new bugs
Every variable shared between an ISR and loop must be volatile. Any variable wider than the processor's word size must be read with interrupts disabled. Flags must be cleared in the right order. These bugs appear rarely and do not show up under a simple test. They tend to appear only after hours of running, or when another part of the program changes timing.
Polling is fast enough
The Uno executes your loop many thousands of times per second when loop does not block. A human press lasts tens to hundreds of milliseconds. A polling loop sees every press, as long as loop never stalls for long.
flowchart TDThe diagram below shows the two paths for a single press.
When an interrupt is the right tool
Interrupts earn their complexity when polling cannot do the job. Look for one of these situations:
- Waking from sleep. In a low-power sleep mode the processor is stopped and
loopis not running. A pin interrupt is the way to wake it, and a button is a common wake source. Here the ISR can be empty, and the wake-up itself is the point. - A
loopthat blocks for a long time. If the main code spends a long time in a slow operation, such as a long sensor read or a blocking library call, a button press can arrive and finish while you are not looking. An interrupt records it. - Very short or fast signals. Pulses from a flow meter, a rotary encoder, or a speed sensor can be much shorter than a
looppass. Counting these is the classic use of the counter sketch above. These signals come from clean electronics or optical sensors, not bouncy mechanical contacts, so bounce is less of a concern. - Hard response-time limits. If a safety cutoff must react within microseconds, polling cannot promise that.
If none of these apply, use polling. A button that toggles an LED, steps a menu, or starts a task does not need an interrupt.
A decision checklist
Ask these questions in order:
- Does my
looprun freely, passing many times per second? If yes, poll. - Does the processor sleep between presses? If yes, use an interrupt to wake it.
- Can
loopstall long enough to miss a press? If yes, first try to restructure the code so it does not block, usingmillistiming instead ofdelay. Use an interrupt only if you cannot. - If you do use one, does the ISR only set a flag or change a counter? Is every shared variable
volatile? Is every multi-byte read protected?
Common mistakes
- Calling
Serial.printlnordelayinside an ISR. Set a flag and print fromloop. - Forgetting
volatile. The program compiles and then misses changes. - Using a pin that does not support interrupts. On a Uno, only pins 2 and 3 work.
- Using the
LOWmode with a held button. The ISR fires continuously while the pin stays LOW and starves the main code. - Assuming a lockout timer removes all bounce. Release bounce can still slip through.
- Reading a multi-byte counter without disabling interrupts, which produces rare corrupted readings.
Exercise
A sketch counts button presses with an ISR attached with FALLING on a button using INPUT_PULLUP. Each physical press often adds two or three to the count. Give the cause, and name one change that makes the count accurate while still using the ISR.
Show answer
Contact bounce makes the pin fall several times within a millisecond or two, and each falling edge fires the ISR. To fix it, record the time of the last accepted edge in a volatile unsigned long and ignore edges that arrive within about 25 ms. Alternatively, have the ISR only set a flag and do the debounce in loop. Remember that a lockout alone can still accept a bounce on release.
Exercise
Why does the counter sketch in this chapter copy pressCount inside noInterrupts() and interrupts() before printing it, and would the same protection be needed for a volatile bool?
Show answer
On an 8-bit processor such as the Uno's, reading a 16-bit variable takes two byte reads. An interrupt between them could change the value and give a mixed, wrong result, so interrupts are disabled during the copy. A bool fits in one byte and is read in a single step, so it needs no such protection, though it still needs volatile.
Exercise
You are building a battery-powered device that sleeps most of the time and must do something when a user presses a button. Should you poll or use an interrupt, and what should the ISR contain?
Show answer
Use an interrupt, because the processor is asleep and loop is not running, so only a pin interrupt can wake it. The ISR can be empty or can just set a flag. After waking, the main code continues, handles the flag, and applies debouncing in normal code.