E. Interrupts
Depending on your age you might remember interrupts from your PC. They were always
important to get your sound card to play beautiful music. The ESP8266 can also be controlled
by interrupts. In the previous exercises we were checking regularly for the state of a GPIO pin.
This is fine if you are not doing anything else in the main loop. But you might miss a change
in a state if it is very short, and that is were the interrupts can help. With an interrupt handler
you can tell the processor that you are interested in a specific type of change and a given pin.
This is how it works:
void buttonPressed() {
...
}
void setup()
{ pinMode(PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(PIN), buttonPressed, CHANGE);
}
buttonPressed()
is a method without parameters that gets called when there is a change on
PIN. Instead of CHANGE you can also use RISING which triggers the callback when the pin
changes from LOW to HIGH, or FALLING for a change in the opposite direction. Please do
not execute long tasks in the callback method. The ESP's watchdog will reset the processor if
calling the interrupt takes too much time. You should not do much more than changing a
flag.
Exercise 04.05: I don't want to miss a thing!
In this exercise we will setup an interrupt and turn an LED on and off with every press to the
button. See what happens when you use different interrupt modes like RISING, FALLING and
CHANGE.
Need help?
Do you have a question about the ESP8266 and is the answer not in the manual?