Interrupt Button Counter
An interrupt toggles the LED the instant you press the button, even while loop() is busy waiting.
- Intermediate
- Input & Controls
- 5 parts
Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.
How it works
Normally a sketch only notices a button when loop() gets round to reading it. Here loop() sleeps for a full second between reports, so a short press could be missed entirely. An interrupt solves that: the button is on pin 2, one of the Uno’s two interrupt-capable pins, and attachInterrupt() tells the chip to drop what it is doing and run a function the instant the pin goes from low to high.
onPress() is that function. It adds one to presses, flips the ledOn flag and writes it to the LED on pin 13. The variables are declared volatile because they change behind the main program’s back and the compiler must not cache them. Meanwhile loop() just prints “Presses so far: ” and the count once a second. Press the button while the Serial tab is quiet: the LED reacts at once. Real buttons bounce, giving several quick edges for one press, so real code adds debouncing; and interrupt functions should stay short and never use delay().
Parts
- Arduino Uno
- Push Button
- Resistor
- LED
- GND
Wiring
- Arduino Uno 5V → Push Button A
- Push Button B → Arduino Uno D2
- Arduino Uno D13 → Resistor A
- Resistor B → LED Anode (+)
- LED Cathode (-) → GND
Arduino code
// Interrupt Button Counter
// loop() sleeps for a full second between reports, but the button is handled
// by an interrupt, so the LED reacts instantly and no press is ever missed.
volatile int presses = 0;
volatile bool ledOn = false;
void onPress() {
presses++;
ledOn = !ledOn;
digitalWrite(13, ledOn ? HIGH : LOW);
}
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(13, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), onPress, RISING);
}
void loop() {
Serial.print("Presses so far: ");
Serial.println(presses);
delay(1000);
}
Try changing it
- Count when the button is released instead of pressed: change RISING to FALLING.
- Report five times a second by changing delay(1000) to delay(200). The count still never misses a press.
Next challenge
More projects in Input & Controls
- Button Controlled LEDPress a button to turn on an LED.
- Potentiometer ReadingRead a potentiometer and display its value on the serial monitor.
- Buzzer AlarmPress and hold the button to sound the alarm buzzer.
- Keypad Code LockType a 4-digit code on a keypad and press # to unlock: a servo opens the latch and an…