Chapter 6
Timing, Interrupts and Embedded Control Models
Diploma in IOT
Embedded Systems for IoT
•
Diploma
Timing, Interrupts and Embedded Control Models
Introduction
An embedded IoT device interacts with the physical world through events that occur at particular times: a sensor sample becomes available, a communication frame arrives, a motor must be switched, or a safety limit is exceeded. Correct functionality therefore depends not only on what the firmware does, but also on when it does it. Timing errors can produce missed sensor readings, communication failures, unstable control loops, corrupted data and unsafe actuator behaviour.
This chapter develops the practical foundations required to configure timers, counters, watchdogs and interrupts. It then examines polling, event-driven firmware, finite-state machines, scheduling and non-blocking design. The emphasis is on deterministic behaviour, bounded response time and maintainable firmware suitable for microcontroller-based IoT systems.
Learning Objectives
By the end of this chapter, a learner should be able to:
distinguish timers, counters, real-time clocks and watchdog timers;
calculate timer periods, tick frequencies and interrupt rates;
explain interrupt entry, latency, priority and service time;
select polling, interrupt-driven or hybrid designs;
model application behaviour using finite-state machines;
implement cooperative scheduling and non-blocking firmware patterns;
analyse deadline, jitter and overload conditions; and
design a reliable embedded control solution for an IoT application.
1. Time in Embedded Systems
A microcontroller normally executes instructions sequentially, but external events are concurrent with that execution. A timer peripheral provides a periodic or delayed event without requiring the processor to count every instruction. A counter records transitions on an external input, such as pulses from a flow meter. A real-time clock maintains calendar time, usually with low power consumption. A watchdog detects software that has failed to execute correctly.
Important timing terms include:
Period (T): time between successive repetitions of an event.
Frequency (f): repetitions per second, measured in hertz (Hz).
Deadline: latest acceptable completion time.
Latency: delay between an event and the beginning of its response.
Execution or service time: time required to handle an event.
Jitter: variation in the timing of an event or response.
Throughput: amount of work completed per unit time.
Determinism: predictability of timing behaviour.
Frequency and period are related by
f = 1/T
where f is in hertz and T is in seconds. This relationship applies to periodic signals and requires consistent units.
A system is hard real-time when missing a deadline is unacceptable, such as in a protection system. It is soft real-time when occasional deadline misses reduce quality but do not cause immediate failure, as in environmental display updates. Many IoT devices contain both types: an over-temperature shutdown may be hard real-time, while cloud reporting is soft real-time.
2. Timers and Counters
2.1 Timer operation
A timer increments a register from a clock source. When the register reaches a terminal value, it may set a flag, generate an interrupt, reset to zero or toggle an output. The clock may be the CPU clock, a divided clock, a low-frequency oscillator or an external signal.
If a timer receives a clock of frequency fclk and divides it by a prescaler N, its timer tick frequency is
ftick = fclk/N
and the tick period is
ttick = N/fclk
For a timer that counts from zero through a reload value R, the overflow period is
Toverflow = (R + 1)N/fclk
The +1 is required because both zero and R are counted. This formula assumes one timer increment per prescaled clock tick, no extra synchronisation delay and an unchanged clock frequency.
For an n-bit up-counter, the maximum count is 2n − 1. If it is allowed to wrap naturally, the overflow period is
Toverflow = 2n N/fclk
Worked Example 1: Timer configuration
A 16-bit timer is clocked at 8 MHz with a prescaler of 64. The desired interrupt period is approximately 10 ms.
The tick frequency is
ftick = 8,000,000/64 = 125,000 Hz.
Thus, each tick lasts 8 μs. The required number of ticks is
10 ms/8 μs = 1,250 ticks.
For a timer that counts from zero to a reload value, choose
R = 1,250 − 1 = 1,249.
The actual period is 1,250 × 8 μs = 10 ms, assuming the hardware uses the stated counting mode. If the timer instead counts upward to a fixed maximum and uses a reload register, the reload convention must be checked in the device manual; different microcontrollers use different representations.
2.2 Timer modes
Common modes include:
Mode
Typical use
Free-running
Timestamping and measuring intervals
Periodic overflow
System tick and sampling
Output compare
Precise waveform or pulse generation
Input capture
Measuring external pulse width or frequency
One-shot
Delayed action or timeout
Pulse-width modulation
Motor, LED and power control
A timer should generally be configured to generate the smallest useful number of interrupts. A very fast interrupt increases overhead and may reduce the time available for application work.
2.3 Counters and measurement
An external-event counter can measure accumulated pulses. If a flow sensor produces P pulses during a gate interval Tg, its measured frequency is
fsignal = P/Tg
If each pulse represents a fixed volume Vp, the estimated flow rate is
Q = P Vp/Tg
where Q is volume per second. Accuracy depends on sensor calibration, gate duration, missed pulses and signal conditioning. Longer gate intervals improve resolution but reduce update speed.
3. Watchdog Timers
A watchdog timer is an independent timer that resets the microcontroller if firmware fails to refresh it within a permitted interval. Failure may result from an infinite loop, deadlock, memory corruption, electrical noise or an unexpected peripheral state.
The watchdog must not be treated as a substitute for correct software. A robust design refreshes it only after essential tasks have completed or after a supervisory task has verified their health. Refreshing it unconditionally inside a fast interrupt can conceal a failed main program.
A useful watchdog design records reset cause, stores a small diagnostic record in retained memory and enters a safe actuator state after reset. The timeout must exceed the worst legitimate execution delay, including communication and flash operations, but remain short enough to recover from faults promptly.
4. Interrupts and Response Time
An interrupt allows hardware to request processor attention. A typical sequence is:
hardware detects an event;
a flag is set;
the processor completes or suspends the current instruction sequence;
context is saved;
the interrupt vector selects an interrupt service routine (ISR);
the ISR handles or records the event; and
context is restored and normal execution resumes.
Interrupt response timeline
Figure: Interrupt response timeline
Figure: Main components of interrupt response time.
4.1 Latency and jitter
Interrupt latency is affected by the current instruction, disabled-interrupt intervals, higher-priority ISRs and hardware synchronisation. A simplified model is
Ltotal = Lhardware + Ldisabled + Lhigher + Lentry
where the terms represent hardware recognition, time spent with interrupts disabled, interference from higher-priority work and entry/context-save time. This is an engineering model, not a universal hardware equation; the exact terms must be measured or obtained from the microcontroller documentation.
If an event arrives every Ta seconds and the ISR requires Ca seconds, a necessary utilisation condition for a single regularly serviced source is
U = Ca/Ta < 1
This condition is necessary but not sufficient for meeting deadlines, because bursts, priorities and blocking can still cause misses. In a system with several independent periodic tasks, a first utilisation estimate is
U = ∑(Ci/Ti)
where Ci is execution time and Ti is period of task i. Cooperative systems normally require margin below 100 percent; the exact schedulability limit depends on the scheduling algorithm and task deadlines.
4.2 ISR design rules
An ISR should be short, bounded and predictable. It should usually read a hardware register, clear the event flag, capture a timestamp or place data into a buffer, and set a flag for deferred processing. It should avoid blocking calls, lengthy calculations, dynamic memory allocation, formatted printing and network transactions.
Shared data between an ISR and ordinary code must be designed carefully. A variable modified by an ISR may need a volatile declaration so the compiler does not incorrectly cache it, but volatile does not make multi-byte access atomic and does not provide mutual exclusion. Atomic operations, critical sections, interrupt-safe queues or a real-time operating system primitive may be required.
5. Polling, Interrupts and Event-Driven Design
Polling repeatedly checks device status. It is simple and easy to debug, but wastes CPU time and may respond slowly if the polling loop is long. Interrupt-driven design allows the processor to perform other work until an event occurs, but introduces concurrency and shared-data complexity. Hybrid design uses interrupts for precise capture and a foreground loop for substantial processing; this is common in resource-constrained IoT devices.
Approach
Strength
Main risk
Polling
Simple control flow
Missed events and variable response time
Interrupts
Fast event response
Race conditions and excessive ISR load
DMA
Low CPU cost for data transfer
Buffer ownership and configuration complexity
RTOS tasks
Structured concurrency
Scheduling overhead and priority errors
Hybrid
Good balance
Requires clear boundaries
An event-driven architecture represents activity as events such as BUTTON_PRESSED, SAMPLE_READY, PACKET_RECEIVED or TIMEOUT. An event queue decouples event detection from event processing. Queue overflow must be handled explicitly through dropping, overwriting, back-pressure or fault reporting.
6. Finite-State Machines
A finite-state machine (FSM) models a system using a finite set of states, inputs and transitions. A transition may also produce an action. The general conceptual form is
(state, event) → (new state, actions)
For an IoT door controller, states might be LOCKED, UNLOCKED, OPEN_ALARM and FAULT. A timer event can cause UNLOCKED → LOCKED after a timeout; a reed-switch event can cause LOCKED → OPEN_ALARM if the physical condition is inconsistent.
An FSM is preferable to scattered Boolean flags when behaviour depends on history. It makes legal and illegal transitions explicit and supports testing by supplying event sequences. Entry actions, exit actions and timeout handling should be defined clearly. A state handler should not wait inside a delay loop; it should record a deadline and return to the main scheduler.
7. Scheduling and Non-Blocking Firmware
A cooperative scheduler repeatedly runs ready tasks. Each task performs a small bounded amount of work and returns. A simple periodic task becomes ready when the current time reaches its next release time. For a task with period T, the next release may be updated using
tnext ← tnext + T.
This preserves the intended schedule, whereas setting tnext ← now + T allows execution delays to accumulate as drift. If a task misses several periods, the design must specify whether to catch up, skip releases or enter a fault state.
A non-blocking delay stores a target time rather than stopping the processor:
if state == WAITING and time_reached(now, deadline):
state = READY
For wrapping unsigned clocks, direct subtraction is safer than comparing absolute times:
if (unsigned_time)(now - start) >= interval:
action()
start = now
This pattern is valid when the interval is less than half the range of the clock and when unsigned arithmetic follows the target language's defined wraparound behaviour. A time_reached helper should be used where portability or clock width is uncertain.
A scheduler table can document timing requirements:
Task
Period
Typical execution
Deadline
Priority
Safety check
1 ms
40 μs
1 ms
Highest
Sensor sample
100 ms
1.2 ms
100 ms
Medium
Display update
500 ms
4 ms
500 ms
Low
Cloud upload
Event-driven
20 ms
Soft
Low
The worst-case execution time, not the average, should be used when checking hard deadlines. Measurements should include compiler optimisation, cache effects where applicable, communication bursts and interrupt interference.
Consider an illustrative battery-powered greenhouse controller with temperature and humidity sensors, a ventilation fan, a water valve, a local display and an MQTT connection. The controller must protect plants from excessive temperature while periodically reporting measurements.
Problem
A first implementation uses long delays: it samples sensors, waits, updates the display and then communicates. During communication, it may fail to detect a door opening or an over-temperature condition. The valve also remains active if a network operation blocks.
Analysis
The safety response is hard real-time relative to cloud reporting. The fan control requires a periodic sensor sample, but the network connection is asynchronous. A watchdog is needed because a peripheral driver could lock the main loop. The design therefore separates urgent detection from slower work.
Approach
A hardware timer generates a 1 ms system tick. The over-temperature input uses an interrupt that records the event and sets thermal_fault. The ISR does not drive the fan directly if that operation is lengthy; the control task performs the safe-state action at the next bounded opportunity. Sensor sampling runs every 100 ms. Display work runs every 500 ms. MQTT processing is event-driven and is never allowed to block the safety task.
An FSM contains NORMAL, WATERING, THERMAL_FAULT and SENSOR_FAULT. In THERMAL_FAULT, the valve is closed, the fan is commanded to a safe state, an alarm is recorded and recovery requires valid sensor readings. Each task returns quickly, and all waiting uses timestamps.
The watchdog is refreshed by a supervisory task only after it confirms that the scheduler tick is advancing, sensor sampling has succeeded recently and the communication task has not exceeded its permitted stall interval. Reset-cause information is stored for diagnosis.
Outcome
The design has bounded safety response, avoids blocking delays and keeps network failures from stopping local control. Testing can inject timer events, lost sensor responses, queue overflow and watchdog resets. Timing logs can measure interrupt latency, task execution time and jitter under maximum communication load.
Learning points
Safety-critical local control should not depend on cloud availability.
ISRs should capture urgent facts, while tasks perform substantial actions.
FSMs make fault and recovery behaviour explicit.
Watchdogs are most useful when refreshed by verified supervision.
Timing claims must be tested under worst credible load, not only normal operation.
9. Challenges, Safety and Professional Practice
Timing bugs are often intermittent because they depend on event order. Common causes include race conditions, uncleared interrupt flags, timer rollover, priority inversion, queue overflow and excessive logging. Mechanical switches require debouncing; this can be implemented with hardware, a timer-based qualification interval or an FSM that accepts a new state only after stable observations.
Safety-related outputs should have defined power-up, reset and communication-loss states. A network command should not be allowed to bypass local interlocks. Time synchronisation from a network must not be confused with monotonic elapsed time: wall-clock corrections can move forwards or backwards, while a monotonic timer is appropriate for deadlines.
Security is also timing-related. An attacker who floods packets or triggers repeated interrupts can consume CPU time and cause missed deadlines. Rate limiting, bounded parsing, queue limits and priority separation reduce this denial-of-service risk. Diagnostic logs should avoid exposing personal data and should not compromise real-time operation.
Contemporary microcontrollers increasingly provide event systems, DMA, hardware timestamping, low-power timers and multi-core processors. These reduce CPU overhead but do not remove the need for ownership rules, deadline analysis and fault handling. Artificial intelligence may be used for anomaly detection in sensor data, but a safety decision should retain a deterministic fallback and bounded execution path.
Best-Practice Checklist
Choose timer resolution from the actual timing requirement, not habit.
Document clock source, prescaler, reload convention and rollover behaviour.
Keep ISRs short and measure their worst-case duration.
Protect shared data with appropriate atomic or synchronisation mechanisms.
Prefer timestamps and state transitions to blocking delays.
Define queue overflow, sensor timeout and communication-loss behaviour.
Separate hard real-time safety functions from soft real-time reporting.
Analyse worst-case execution time, latency, jitter and cumulative load.
Use watchdogs as supervised fault recovery, not as concealment of faults.
Test under maximum interrupt, communication and sensor-event load.
Chapter Summary
Embedded IoT behaviour depends on deterministic timing as well as logical correctness. Timers generate periodic and delayed events; counters measure external transitions; watchdogs recover from software failure. Timer periods follow the clock, prescaler and counting convention, and unit consistency is essential.
Interrupts provide rapid response but introduce latency, jitter and shared-data hazards. Effective ISRs are short and defer substantial work. Polling is simple, interrupts are responsive, and hybrid designs often provide the best practical balance. Finite-state machines clarify event-dependent behaviour, while cooperative scheduling and timestamp-based non-blocking patterns prevent one task from stopping the system. Deadline analysis must consider worst-case execution, interference, queue capacity and fault conditions. The greenhouse case demonstrates how these principles combine into a safe, maintainable IoT controller.
Key Terms
Timer: A peripheral that measures or generates time-based events.
Counter: A peripheral that counts pulses or external transitions.
Prescaler: A divider that reduces a source clock frequency.
Period: Time between repetitions of a periodic event.
Frequency: Number of repetitions per second.
Deadline: Latest acceptable completion time.
Latency: Delay from an event until response begins.
Jitter: Variation in event or response timing.
Interrupt: Hardware or software request for processor service.
ISR: Interrupt service routine that responds to an interrupt.
Watchdog: Timer that resets a system when not refreshed correctly.
Polling: Repeatedly checking device status in program code.
Event-driven system: System that responds to queued or detected events.
Finite-state machine: Model consisting of states, events and transitions.
Scheduler: Mechanism that determines when tasks execute.
Non-blocking firmware: Firmware that returns from operations without waiting indefinitely.
Worst-case execution time: Maximum credible time required by a task.
Monotonic clock: Clock used for elapsed-time measurement that does not run backwards.
Review Questions
Short Answer Questions
Distinguish a timer from an external-event counter.
Why should an ISR usually be short?
Define interrupt latency and jitter.
What is the purpose of a watchdog timer?
Why are timestamps preferable to blocking delays in many embedded applications?
Long Answer Questions
Explain timer configuration using clock frequency, prescaler and reload value, including the assumptions behind the period equation.
Compare polling, interrupt-driven and hybrid firmware architectures.
Describe how a finite-state machine improves the design of an IoT actuator controller.
Explain the causes of interrupt latency and methods for reducing timing uncertainty.
Discuss how watchdog supervision, safe states and fault logging should be integrated into embedded firmware.
Analytical / Application Questions
A 12 MHz timer uses a prescaler of 48. Determine its tick period and the reload value required for a 20 ms interval when counting from zero. State any hardware convention that must be verified.
Design a scheduling approach for a device with a 2 ms safety task, a 100 ms sensor task and an event-driven network task. Identify possible overload and blocking hazards.
Develop an FSM for a water pump with OFF, PRIMING, RUNNING and FAULT states. Specify events, transitions, timeout behaviour and the safe response to sensor failure.
Multiple Choice Questions with Answers
Question 1
A timer clocked at 8 MHz with prescaler 64 has what tick frequency?
A. 125 kHz
B. 512 kHz
C. 8 MHz
D. 64 kHz
Correct Answer: A. 125 kHz
Question 2
Which operation is most appropriate for an interrupt service routine?
A. Perform a lengthy network upload
B. Wait for a peripheral indefinitely
C. Capture event data and set a processing flag
D. Allocate large dynamic memory blocks
Correct Answer: C. Capture event data and set a processing flag
Question 3
What is the principal purpose of a watchdog timer?
A. To increase CPU clock frequency
B. To reset firmware that fails to operate correctly
C. To measure analogue voltage directly
D. To replace all interrupt handlers
Correct Answer: B. To reset firmware that fails to operate correctly
Question 4
Which design is non-blocking?
A. Calling a delay routine while waiting for a timeout
B. Busy-waiting until a sensor responds
C. Recording a deadline and returning to the scheduler
D. Disabling interrupts until an operation completes
Correct Answer: C. Recording a deadline and returning to the scheduler
Question 5
For a periodic task, which value should be used for hard-deadline analysis?
A. Average execution time only
B. Worst-case credible execution time
C. Minimum execution time
D. Time spent in comments
Correct Answer: B. Worst-case credible execution time
Question 6
A finite-state machine primarily represents a system using which elements?
A. States, events and transitions
B. Registers, capacitors and inductors
C. Packets, addresses and encryption keys only
D. Files, folders and processes only
Correct Answer: A. States, events and transitions
Question 7
A counter records 600 pulses in 2 seconds. What is the measured pulse frequency?
A. 30 Hz
B. 300 Hz
C. 600 Hz
D. 1,200 Hz
Correct Answer: B. 300 Hz
Question 8
Why is unconditionally refreshing a watchdog inside a fast ISR unsafe?
A. It always stops the timer peripheral
B. It can conceal failure of the main program
C. It changes the sensor calibration
D. It guarantees a deadlock
Correct Answer: B. It can conceal failure of the main program
Question 9
Which clock is most suitable for measuring elapsed time across network clock corrections?
A. A monotonic clock
B. A wall clock that can be adjusted
C. A display refresh counter only
D. A random-number generator
Correct Answer: A. A monotonic clock
Question 10
If an event source produces events every 10 ms and its handler takes 2 ms, its basic utilisation is: