CYTHEIA AIOpen the editor

Interrupt Button Counter

An interrupt toggles the LED the instant you press the button, even while loop() is busy waiting.

Open this circuit and run it

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

Wiring

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

Open this circuit and run it

Next challenge

More projects in Input & Controls