A Press the Loop Misses
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 12 of 18.
A sketch is sometimes busy with a slow job or a long delay(). A loop that reads the button only between jobs misses a press that starts and ends inside one.
An interrupt fixes that: when a pin changes, the board stops what it is doing, runs a function you choose, then carries on. The chip watches the pin itself, even during delay().
void onPress() {
digitalWrite(ledPin, HIGH);
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), onPress, FALLING);
}attachInterrupt() takes three things: the interrupt for the pin (digitalPinToInterrupt(buttonPin) finds it), the function to run, and when. FALLING is the moment the pin goes from HIGH to LOW: with a pull-up, the moment the button goes down.
The function is called an interrupt service routine, or ISR. Keep it short: no delay() and no Serial.
Challenge
EasyThis alarm checks its button only once every 2 seconds, so a quick press is missed. Make a press light the LED at once:
- write an ISR,
onPress(), that turns the LED on - in
setup(), attach it to the button pin withFALLING
Keep the slow job in loop(). The LED stays on after a press, like an alarm. Press Run, tap the button, then Check.
Try it yourself
const int ledPin = 13;
const int buttonPin = 2;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
// attach the interrupt here
}
void loop() {
// the slow job: keep it as it is
Serial.println("working");
delay(2000);
// this only looks at the button once every 2 seconds,
// so a short press is missed
if (digitalRead(buttonPin) == LOW) {
digitalWrite(ledPin, HIGH);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Timing Without Delay
Practice on your own: Arduino playground