Software That Lasts
Interrupts & Real-Time
14 minStudent plan
Reacting to an event the instant it happens, and the specific rules that make interrupt code safe.
After this lesson you can
- Say what an interrupt is for
- Write an ISR that obeys the rules
- Explain why a shared multi-byte variable needs protecting
What an interrupt does
Polling means checking repeatedly in loop(). It is simple, but the response time depends on how long a pass takes, and a short event between two checks is missed entirely.
An interrupt inverts that. The hardware watches the pin, and when the event occurs it suspends whatever the processor was doing, runs a short function, and resumes.
attachInterrupt(digitalPinToInterrupt(2), onPulse, RISING);
That calls onPulse the moment pin 2 goes high, within microseconds, whatever loop() was in the middle of. It is the right tool for encoder pulses, emergency stops and anything short and fast enough to slip between polls.
In the full lesson
- What an interrupt does
- The rules for an ISR
- Atomicity
This lesson comes with the Student plan. The first module of Programming is free.