FALLING, RISING and CHANGE
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 13 of 18.
The Uno has two pins that can trigger an interrupt: pin 2 and pin 3. A button that needs an interrupt must be wired to one of them. Inside the chip they are interrupt 0 and interrupt 1, so let digitalPinToInterrupt() turn the pin into its number. attachInterrupt(3, ...) asks for interrupt 3, which the Uno does not have, and nothing happens.
The last part of attachInterrupt() says which change to react to:
FALLING: the pin goes fromHIGHtoLOW(with a pull-up, a press)RISING: the pin goes fromLOWtoHIGH(a release)CHANGE: either one
With CHANGE, the ISR runs on the press and on the release. It reads the pin to find out which one happened:
void onChange() {
if (digitalRead(buttonPin) == LOW) {
// it went down
} else {
// it came up
}
}
attachInterrupt(digitalPinToInterrupt(buttonPin), onChange, CHANGE);Challenge
EasyThe button is on pin 3, and loop() is busy with a slow job. Make the LED on pin 13 follow the button instantly:
- in
onChange(), read the button:LOWlights the LED,HIGHturns it off - attach
onChange()to the button pin withCHANGE
Press Run, hold and release the button, then Check.
Try it yourself
const int ledPin = 13;
const int buttonPin = 3;
// Runs every time the button pin changes.
void onChange() {
// light the LED when the button is down, turn it off when it is up
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
// attach onChange() to the button pin here
}
void loop() {
// the slow job: keep it as it is
Serial.println("working");
delay(2000);
}
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