IO4: Reliable firmware: interrupts, RTOS tasks, watchdogs and safe state
Interrupts: reacting on time
🎯You'll be able to
Use interrupts for events that can't wait, and keep interrupt handlers short and safe.
🏠The everyday picture
A teacher marking books stops when the fire bell rings. They don't finish the page first, but they also don't mark books during the fire drill: they deal with the bell, then go back.
📘What it really is
-
An interrupt makes the chip pause what it's doing and run a short function (a handler) when something happens: a pin changes, a timer fires, a byte arrives on a serial line.
-
Keep handlers short: set a flag, store a timestamp or put a value in a queue, then return. Do the slow work (sending, writing flash) in the main loop or a task.
-
Shared data: a value changed in a handler and read in the main loop can be read half-updated. Disable interrupts briefly, use atomic types, or pass data through a queue.
-
Polling versus interrupts: polling checks regularly and is simple; interrupts react at once and let the chip sleep until something happens.
-
Debouncing: a mechanical switch "bounces" and can fire many interrupts in a few milliseconds; ignore changes within a short time.
📝A worked example
Input: a float switch should wake JalSetu when the tank overflows.
Steps:
- Configure the switch's pin as a wake source and an interrupt on change.
- In the handler, record the time and set
overflow = True; nothing else. - In the main work, see the flag, send an alarm, and clear it. Ignore further changes within 50 ms (bounce).
Expected output: an overflow alarm that arrives within seconds, without waiting for the 15-minute timer.
🌍Where it's used
- Buttons and switches on every device.
- Pulse counters in water and electricity meters.
- Serial data arriving from modems and GPS receivers.
📝Case scenario
A water meter counted pulses in an interrupt handler that also wrote each count to flash. During heavy use, pulses arrived faster than flash writes finished and some were lost. Counting in the handler and saving totals every minute fixed it.
🖱️Try it
For three events (a button press, a sensor reading every 15 minutes, a byte arriving from a GPS module), decide whether to poll or use an interrupt, and why. Success: a choice and a reason for each.
⚠️Common mistakes
- Slow work in a handler. Sign: missed events. Fix: set a flag; do the work later.
- Unprotected shared data. Sign: rare, odd values. Fix: queues or brief critical sections.
- No debouncing. Sign: one press counted as many. Fix: ignore changes for a few milliseconds.
🛠️For your project
JalSetu wakes on a timer; the capstone design notes can add a pin wake for an overflow switch.
✅Quick check
What should an interrupt handler do?
Show the answer
Something short, such as setting a flag or queueing a value, leaving slow work for later.
Why debounce a mechanical switch?
Show the answer
It bounces and can trigger many times for one press.
