← Back to the chapter · Previous detail · Next detail →
Technical detail · Microcontroller Programming: Setup and GPIO
Shared state and interrupt strategies
Suppose the shared counter a starts at 10. The loop reads 10 and plans to add one. Before it writes, an interrupt reads 10, subtracts one, and writes 9. The loop then resumes with its old copy and writes 11. The handler’s update is lost. Each C statement can take several machine steps, so the two updates can interleave like this. Protect the shared update or use an appropriate atomic operation.
Latency is the time from an event to its response. Concurrency means that work in the loop and handler can make progress during the same period, even if one interrupts the other. For the shared counter above, an atomic update or a short protected section can prevent a lost update; pausing interrupts for longer increases response delay. The three strategies make different tradeoffs:
- Spin and wait. Main-line code polls a pending flag, burning cycles while it waits. Polling alone does not make shared read-modify-write updates atomic or guarantee that every interrupt event is counted; use an appropriate atomic operation or short critical section for shared state.
- Disable interrupts around the critical section. On a single-core board, a brief
noInterrupts()/interrupts()region can protect a shared value from ordinary interrupt handlers on that core. A long region delays those handlers, so keep the work short. On a dual-core ESP32, masking interrupts on one core does not stop the other core from accessing shared data; use the platform’s cross-core critical section or another suitable synchronization method. - Do almost nothing in the handler, and defer the real work. The handler sets a Boolean pending flag or copies one small value, then returns; that flag records that at least one event occurred, while a counter or queue is needed when every event matters.
loop()picks the state up on its next pass and does the actual processing. This defers processing until the next loop pass; measure that delay rather than assuming it is bounded.
The short-handler strategy can be combined with a brief protected copy-and-clear in the loop. That combines strategies two and three: defer the processing, but protect the shared handoff. Part 2 develops the interrupt example.