6. Microcontroller Peripherals and Interrupt SystemsIntroduction and ContextA microcontroller becomes useful not merely because it contains a processor core, but because the core is integrated with peripherals that allow it to sense, control, communicate, and respond to physical events. General-purpose input/output (GPIO), timers, counters, watchdogs, pulse-width modulation (PWM), real-time clocks (RTC), analog-to-digital converters (ADC), digital-to-analog converters (DAC), and capture/compare units together form the interface between software and the electromechanical or electronic system being controlled. In a simple application, the processor may poll an input, execute an algorithm, and write an output. In a deterministic control application, however, this approach is often inadequate. Events may occur faster than the software polling loop, timing jitter may affect control quality, and a software fault may leave an actuator in an unsafe state. Interrupt systems address these limitations by allowing hardware events to request processor attention. Properly designed interrupt handling permits the processor to respond within a predictable time while continuing other computation. This chapter examines the architecture, configuration, and application of common microcontroller peripherals. Although register names and implementation details differ among families such as ARM Cortex-M, AVR, PIC, MSP430, and 8051 derivatives, the underlying principles are widely transferable. Learning ObjectivesAfter studying this chapter, the reader should be able to: 1. Explain the operating principles and configuration requirements of major microcontroller peripherals. 2. Distinguish GPIO, timer, counter, capture, compare, PWM, ADC, DAC, and RTC functions. 3. Design interrupt-driven firmware using priorities, masking, nesting, and safe data exchange. 4. Select peripheral operating modes for deterministic control applications. 5. Analyse timing, resolution, latency, jitter, overflow, and quantisation effects. 6. Apply watchdogs and fault-handling mechanisms without creating unsafe recovery behaviour. 7. Integrate peripherals into practical embedded-control systems and evaluate design risks. The Peripheral Subsystem as a Deterministic Control FabricA peripheral is a hardware block that performs a specialised function with limited intervention from the central processing unit. A timer can count clock cycles while the CPU executes unrelated code; an ADC can sample a sensor at a specified instant; and a PWM unit can maintain an output waveform after its duty-cycle register has been configured. This hardware autonomy is particularly important in real-time systems. Three timing quantities are central to peripheral design. Resolution is the smallest measurable or controllable increment, such as one timer tick or one ADC code. Latency is the time between an event and the corresponding processor or output response. Jitter is variation in that response time from one event to another. A control loop may tolerate a fixed latency but perform poorly when jitter is unpredictable. Peripheral operation is generally controlled through registers. Configuration registers select modes and clock sources; status registers report events; data registers hold measured or generated values; and control registers enable, disable, clear, or acknowledge conditions. A common source of faults is incorrect sequencing—for example, enabling an ADC before its reference has stabilised, or clearing an interrupt flag in a way that unintentionally loses a pending event. GPIO: The Fundamental Digital InterfaceGPIO pins are configurable as inputs or outputs and are usually associated with direction, data, pull-up or pull-down, alternate-function, and interrupt configuration registers. An output driver may be push-pull, in which the pin is actively driven high or low, or open-drain/open-collector, in which an external resistor is required to establish the high level. Open-drain interfaces are useful for shared buses such as I²C. Input pins may use internal pull resistors to prevent a floating logic level. A mechanical switch connected to a GPIO commonly requires debouncing because contact bounce can produce several transitions within a few milliseconds. Debouncing may be implemented in hardware with an RC network and Schmitt trigger, or in software using a timer, state machine, or repeated-sample filter. A GPIO interrupt may be triggered by a rising edge, falling edge, either edge, or a level. Edge-triggered interrupts are suitable for discrete events, whereas level-sensitive interrupts require the source to be removed or acknowledged; otherwise the processor may repeatedly re-enter the handler. When a pin is multiplexed with a timer, ADC, serial port, or capture channel, the alternate-function selection must be configured correctly and conflicting functions must be avoided. GPIO design also involves electrical considerations. Maximum source and sink currents, total port current, voltage thresholds, slew rate, electromagnetic compatibility, and protection against overvoltage must be respected. A microcontroller pin should not directly drive a relay coil, motor winding, or high-power lamp; an appropriate transistor, driver, flyback diode, or isolated interface is required. Timers, Counters, and Time BasesA timer increments or decrements according to a clock, while a counter generally counts external transitions. Many microcontrollers use the same hardware block for both functions. A prescaler divides the peripheral clock before it reaches the counting element. If the timer clock is \(f_t\), the prescaler is \(N\), and the timer period is \(P\) counts, the event frequency is \[f_e = \frac{f_t}{NP}\] and the interval is \(T_e=NP/f_t\). For an n-bit up-counter, the maximum count is normally \(2^n-1\), although a programmable period register may define a shorter cycle. Timers support several modes. In periodic or overflow mode, an interrupt is generated when the counter wraps. In clear-on-compare mode, the counter resets when it reaches a compare value, producing accurate periodic events. In one-shot mode, the timer stops after a specified interval. External clock mode converts the block into an event counter, useful for measuring shaft speed, flow pulses, or production counts. A timer used as a software time base should be configured so that its period is compatible with the longest expected interrupt latency and the required scheduling granularity. Long interrupt periods simplify processing but reduce responsiveness; short periods increase overhead. Reading a multi-byte timer requires care on processors where the value cannot be transferred atomically. Hardware latching or a read-high/read-low/read-high verification sequence may be necessary. Timer overflow is not inherently an error. If time differences are calculated using unsigned arithmetic, modulo counting can correctly handle wraparound provided that the maximum interval being measured is less than one complete timer cycle. This principle is important in operating-system ticks and timeout services. Watchdog Timers and Fault RecoveryA watchdog timer resets the microcontroller if software fails to service it within a defined interval. It is a safety mechanism, not a substitute for program validation. The watchdog may be independent of the main CPU clock, improving protection against clock or software failures. Some devices provide a windowed watchdog: servicing too early or too late causes a reset, thereby detecting both stalled execution and runaway loops. A robust design services the watchdog only after essential tasks have completed successfully. A single statement in an unrestricted background loop may conceal the failure of a critical control task. A supervisory task can instead collect health indications from multiple activities and refresh the watchdog only when the system is demonstrably operating correctly. After reset, firmware should read the reset-cause register and record whether the event was a watchdog timeout, brownout, external reset, or power-on reset. Repeated watchdog resets require a controlled safe state and diagnostic logging rather than an endless cycle of blind restarts. Outputs should assume safe values during reset, and actuators should not be enabled until clock, power, and sensor conditions have been verified. PWM and Compare-Based Output GenerationPulse-width modulation represents an average output level by varying the proportion of time that a periodic signal remains active. The duty ratio is \[D=\frac{t_{on}}{T}\] where \(T\) is the PWM period. For an ideal low-pass load, the average output is approximately proportional to duty ratio, although switching losses, dead time, nonlinear loads, and ripple affect the actual result. A timer compare unit changes an output when the counter reaches a programmed compare value. This permits PWM generation without software toggling. The PWM frequency must be selected according to load dynamics, switching losses, acoustic constraints, and electromagnetic compatibility. A motor drive may require complementary outputs and dead time to prevent simultaneous conduction in a half bridge. Updating the duty register near a cycle boundary can create a distorted pulse; buffered or double-buffered registers allow a new value to take effect at a defined update event. PWM is used for motor speed control, LED dimming, switched-mode power conversion, actuator control, and digital-to-analog approximation. In closed-loop control, the duty command is normally bounded, rate-limited, and disabled when overcurrent, overspeed, or sensor faults occur. Capture and Compare UnitsA capture unit copies the current timer value into a capture register when an external edge occurs. The difference between successive captures gives the period of an input signal. If the timer frequency is \(f_t\), and the measured count difference is \(\Delta C\), then the input frequency is approximately \(f_t/\Delta C\), subject to prescaling and timer wraparound. Measuring several periods and averaging can reduce quantisation noise, but averaging increases response time. Capture is useful for frequency, pulse-width, duty-cycle, and time-of-flight measurement. Rising and falling edges can be captured in separate channels or by reconfiguring the edge detector. Input filtering is valuable where electrical noise could create false transitions. A compare unit performs the reverse operation: it produces an action when the timer reaches a programmed value. Actions may include setting or clearing a pin, generating an interrupt, resetting the timer, or triggering an ADC conversion. Hardware compare is preferable to software delay loops because it maintains timing accuracy even when CPU workload changes. Real-Time ClocksAn RTC maintains calendar time or long-duration elapsed time, commonly using a low-frequency crystal or a low-power oscillator. It typically contains seconds, minutes, hours, date, alarm, and periodic-wakeup registers. The RTC may continue operating in a low-power mode while the main processor is stopped. Calendar correctness requires attention to leap years, month lengths, daylight-saving policy, and battery backup. In many control products, monotonic elapsed time and civil calendar time should be treated as separate concepts. RTC alarms can wake a sleeping controller, while periodic interrupts support scheduled maintenance or data logging. The oscillator’s tolerance produces drift; calibration or synchronization with an external time source may be required when accurate timestamps are important. ADC and DAC in Measurement and ControlAn ADC converts an input voltage into a digital code. For an ideal ADC with n bits and reference voltage \(V_{ref}\), the nominal voltage increment is approximately \[q=\frac{V_{ref}}{2^n}\] The actual error also includes offset, gain error, integral and differential nonlinearity, noise, reference instability, and input acquisition limitations. The source impedance must be low enough for the sample-and-hold capacitor to charge within the acquisition interval. If not, a buffer amplifier or longer acquisition time is needed. ADC configuration includes channel selection, reference selection, resolution, sampling time, trigger source, conversion clock, averaging, and end-of-conversion interrupt or DMA operation. A timer-triggered ADC is generally superior to software-triggered sampling in a control loop because it establishes a stable sampling instant. Analog grounding, reference decoupling, input filtering, shielding, and separation of high-current return paths strongly influence measurement quality. Aliasing occurs when a signal contains frequency components above half the sampling frequency. An analogue anti-aliasing filter should therefore precede the ADC. Digital filtering cannot reconstruct information that was already aliased. Oversampling and averaging can improve effective resolution for suitable noise conditions, but they do not remove systematic nonlinearity. A DAC generates an analogue voltage or current from a digital code. It may use a resistor-string, current-steering, or integrated buffered architecture. Important specifications include resolution, settling time, monotonicity, output range, reference accuracy, and glitch energy. DACs are used for actuator commands, waveform generation, calibration, bias control, and test signals. Where no DAC exists, filtered PWM can provide an approximate analogue output, but ripple and load dependence must be considered. Interrupt Architecture and Nested ResponseAn interrupt is a hardware or software request that causes the processor to suspend its current execution and enter an interrupt service routine (ISR). The processor typically saves a context, obtains a vector address, executes the handler, clears or acknowledges the source, and restores the interrupted context. Interrupt latency includes recognition, instruction completion, context stacking, vector fetch, and any architectural synchronization. Interrupt sources may be maskable or non-maskable. A maskable source can be disabled globally or individually; a non-maskable source is reserved for severe events such as hardware failure. An interrupt controller commonly provides pending, active, enable, priority, and vector registers. Priority determines which pending interrupt is serviced first and, in systems supporting nesting, which handler may pre-empt another. Nested interrupts improve responsiveness but increase complexity. A high-priority emergency shutdown may interrupt a lower-priority communication handler, whereas a low-priority periodic tick should not interrupt a time-critical current-limit response. Priority inversion can occur when a high-priority activity waits for a resource held by a lower-priority activity. Short critical sections, priority-aware locking, or priority inheritance may be required. An ISR should execute only the work that must occur immediately. A typical pattern is to capture hardware data, clear the source, update a time-critical variable, and signal a deferred task. Lengthy calculations, formatted output, blocking calls, and dynamic memory allocation are generally inappropriate in an ISR. Variables shared between an ISR and foreground code should be declared with suitable volatility semantics, and multi-byte data must be protected against partial updates. A ring buffer, atomic flag, sequence counter, or briefly masked critical section can provide safe communication. Interrupt flags require device-specific handling. Some are cleared by writing a one, some by writing a zero, and some by reading a status register followed by reading or writing a data register. Clearing a flag before identifying the source may lose an event; clearing it too late may cause immediate re-entry. If multiple events can occur before service, status bits or event counters should be used rather than a single Boolean flag. A Configuration Method for Integrated Control SystemsA disciplined peripheral configuration process begins with system requirements: signal ranges, timing accuracy, response deadlines, power modes, fault behaviour, and safety constraints. The designer then assigns pins and peripheral resources, selects clocks and prescalers, calculates timer periods and ADC rates, configures event routing, and defines interrupt priorities. Initialization should normally proceed from clocks and power domains to GPIO electrical modes, peripheral registers, interrupt vectors, and finally global interrupt enable. Peripheral status flags should be cleared deliberately before enabling their interrupts. The design should distinguish startup configuration from runtime reconfiguration, since changing a timer period or ADC channel while it is active may produce transient outputs or invalid data. For a motor-control loop, for example, a PWM timer can trigger ADC sampling at the centre of a switching interval. The ADC end-of-conversion event can invoke a high-priority control ISR, which reads current and voltage, executes a bounded control calculation, updates a buffered compare register, and records diagnostic status. A lower-priority task can handle communications and data logging. A watchdog supervisor verifies that the control ISR, ADC service, and communication task are all alive. Illustrative Case Study: Protected DC Motor ControllerBackgroundConsider an illustrative 32-bit microcontroller controlling a permanent-magnet DC motor in a laboratory actuator. The system must regulate speed, measure current, respond to an emergency input, and enter a safe state after software failure. Situation and ProblemAn initial prototype used a foreground loop to sample an analogue current sensor and toggle a GPIO-based PWM signal. Under communication load, the sampling interval varied significantly. Occasional overcurrent events were not detected quickly enough, and a stalled software loop left the power stage enabled. AnalysisThe principal defects were software-generated timing, absence of hardware capture of emergency events, and a watchdog serviced unconditionally in the main loop. The design also changed the PWM compare value immediately, allowing a duty update during an active pulse. These defects produced latency, jitter, and unsafe recovery behaviour. Approach and SolutionA centre-aligned PWM timer was selected as the master time base. A compare event triggered the ADC at a repeatable point in each PWM cycle, reducing switching-noise sensitivity. The ADC completion interrupt executed the speed/current control calculation and wrote a double-buffered duty command. A GPIO emergency input was connected to a high-priority edge/level interrupt that disabled the PWM output through both the timer’s fault input and a software state machine. A capture channel measured encoder pulse intervals for speed estimation. The timer overflow logic handled wraparound using unsigned differences. The watchdog was refreshed only by a supervisor after receiving health tokens from the control ISR and communication task. On reset, the firmware inspected the reset cause, kept the gate-driver enable inactive, and required explicit fault clearance before restarting. OutcomeThe revised architecture made the sampling event, control calculation, and duty update predictable. Emergency shutdown no longer depended solely on CPU execution, and a stalled task resulted in a controlled reset with the power stage disabled. The case illustrates that deterministic control is obtained through coordinated hardware and software—not through interrupt use alone. Learning PointsThe most important lessons are to assign timing-critical work to hardware where possible, use interrupt priority according to hazard and deadline, separate immediate protection from deferred diagnostics, and design watchdog recovery as a safety function rather than a convenience. Challenges, Risks, and Common Design ErrorsPeripheral systems fail frequently at their boundaries. Typical errors include selecting an unsuitable clock source, overlooking prescaler effects, assuming an ADC has ideal resolution, leaving inputs floating, failing to debounce switches, and using a timer overflow period shorter than the maximum measurement interval. Another common mistake is enabling an interrupt before its pending flag has been cleared. Excessive ISR duration can cause missed events and priority inversion. Polling a flag that is cleared by an ISR without atomic protection can create race conditions. Reconfiguring a peripheral while an output is active can generate an unintended pulse. Watchdog timeouts may be caused by a deadlock, stack overflow, clock failure, or incorrect service window, so diagnosis should not assume a single software cause. Validation should include worst-case interrupt load, simultaneous events, clock tolerance, voltage and temperature extremes, power-on and brownout behaviour, timer wraparound, noisy inputs, ADC reference variation, and recovery after communication loss. Logic analysers, oscilloscopes, trace units, cycle counters, and fault-injection tests are valuable tools for measuring latency and jitter rather than merely assuming them. Professional, Safety, and Governance ConsiderationsIn industrial, automotive, medical, and energy applications, peripheral configuration is part of a larger safety case. Requirements should be traceable to design decisions, and protection functions should not rely on undocumented device behaviour. Datasheet limits, errata, compiler assumptions, and interrupt-controller rules must be reviewed. Safety-related outputs may require independent shutdown paths, diagnostic feedback, redundancy, or a defined de-energised state. Security also matters. Unauthorised firmware or peripheral reconfiguration can alter PWM outputs, disable watchdogs, or falsify sensor values. Secure boot, access control, debug-port management, authenticated updates, and audit records may therefore be necessary. Engineers should document calibration data, timing assumptions, interrupt priorities, reset causes, and known limitations so that maintenance personnel can reproduce and diagnose faults. Emerging Directions and Best PracticesModern microcontrollers increasingly provide event systems that connect timers, ADCs, comparators, DMA, and communication peripherals without CPU intervention. This reduces latency and power consumption. Peripheral-to-peripheral triggering, timestamp units, configurable logic cells, high-resolution PWM, sigma-delta ADC interfaces, and hardware safety monitors support more autonomous control architectures. Data-driven diagnostics are also becoming practical. Runtime measurements of ISR duration, ADC health, watchdog history, and event rates can reveal degradation before failure. Such analytics should supplement, not replace, deterministic protection mechanisms. Machine-learning algorithms may assist condition monitoring, but safety-critical trip decisions should remain bounded, explainable, and independently verifiable. Best practice is to calculate timing before coding, use hardware-triggered sampling and output updates, keep ISRs short and bounded, document every shared variable, test wraparound and simultaneous events, use safe defaults during reset, and measure actual latency with instruments. Peripheral abstraction layers improve portability, but they must not conceal timing or error behaviour from the engineer responsible for real-time performance. Chapter SummaryMicrocontroller peripherals provide the hardware mechanisms required to connect computation with the physical world. GPIO supports digital interfacing, timers and counters establish time bases and event counts, watchdogs support fault recovery, PWM and compare units generate controlled waveforms, capture units measure timing, RTCs maintain long-duration time, and ADC/DAC blocks connect digital algorithms with analogue signals. Interrupt controllers coordinate these functions by assigning priorities and enabling prompt response to asynchronous events. Deterministic systems depend on resolution, latency, jitter, correct register sequencing, safe data sharing, and appropriate division of work between hardware and software. Nested interrupts can improve response but require bounded ISRs, carefully selected priorities, and protection against race conditions and priority inversion. A complete design also considers electrical limits, aliasing, watchdog strategy, reset behaviour, safety, security, verification, and maintainability. Key TermsGPIO: A configurable microcontroller pin used for digital input or output. Alternate function: A peripheral function multiplexed onto a physical microcontroller pin. Prescaler: A circuit that divides a clock frequency before it reaches a peripheral. Timer: A clock-driven counter used to generate or measure time intervals. Counter: A hardware block that counts external events or transitions. Watchdog timer: A supervisory timer that resets the system when software fails to service it correctly. PWM: Pulse-width modulation, in which duty ratio controls the average delivered energy or signal level. Duty ratio: The fraction of one period for which a PWM signal is active. Capture: The transfer of a timer value into a register when an external event occurs. Compare: A hardware action generated when a timer reaches a programmed value. RTC: Real-time clock used for calendar time or long-duration timekeeping. ADC: Analogue-to-digital converter that maps an analogue quantity to a digital code. DAC: Digital-to-analogue converter that produces an analogue output from a digital code. Quantisation: Representation of a continuous value by discrete digital levels. Aliasing: Misrepresentation of frequency components caused by insufficient sampling rate. Interrupt latency: Time between an interrupt-causing event and execution of its handler. Interrupt nesting: Allowing a higher-priority interrupt to pre-empt a lower-priority ISR. Jitter: Variation in the timing of an otherwise repeated event or response. ISR: Interrupt service routine executed in response to an interrupt request. Critical section: Code region that must execute without conflicting concurrent access. Review QuestionsShort Answer Questions1. Distinguish a timer from an externally clocked counter. 2. Why are internal pull-up or pull-down resistors used on GPIO inputs? 3. Define interrupt latency and jitter. 4. State two reasons for using a hardware-triggered ADC conversion. 5. What is the purpose of a watchdog reset-cause register? Long Answer Questions1. Explain timer operation, prescaling, overflow, compare mode, and the calculation of a periodic interrupt interval. 2. Describe the complete signal path and design considerations in a PWM-based motor-control application. 3. Explain ADC errors, acquisition time, aliasing, reference quality, and analogue front-end design. 4. Discuss interrupt priorities, nesting, ISR design, shared data, and priority inversion. 5. Compare capture and compare units and explain their applications in measurement and waveform generation. Analytical / Application Questions1. A 48 MHz timer clock is divided by a prescaler of 16. What period register value is required for a 1 kHz event, assuming the counter resets after the programmed period and the register represents the number of counts minus one? Explain your assumption. 2. Design an interrupt priority scheme for a controller containing an emergency shutdown input, a current-control loop, a communication interface, and a data-logging task. Justify the ordering and identify work that should be deferred. 3. A motor controller occasionally produces a longer PWM pulse when its duty command changes. Analyse the likely register-update cause and propose a hardware and software correction. 22. Multiple Choice Questions with AnswersQuestion 1A timer clock is 32 MHz, the prescaler is 8, and the timer period is 4000 counts. What event frequency is produced? A. 100 Hz B. 1 kHz C. 4 kHz D. 32 kHz Correct Answer: B. 1 kHz Question 2Which method best provides a stable sampling instant for a control-loop ADC? A. Starting conversion from an arbitrary foreground instruction B. Triggering conversion from a timer event C. Polling the ADC continuously without a timer D. Changing the ADC clock during conversion Correct Answer: B. Triggering conversion from a timer event Question 3Why is a double-buffered PWM compare register useful? A. It increases ADC resolution B. It prevents all interrupt requests C. It allows duty updates to take effect at a defined cycle boundary D. It converts PWM directly into a calendar time Correct Answer: C. It allows duty updates to take effect at a defined cycle boundary Question 4A capture unit records timer values on successive encoder edges. Which quantity is most directly obtained from their difference? A. Signal period in timer ticks B. ADC reference voltage C. PWM transistor current D. RTC calendar date Correct Answer: A. Signal period in timer ticks Question 5Which watchdog strategy provides the strongest evidence that critical software is functioning? A. Refresh the watchdog in every infinite loop B. Disable the watchdog during communication C. Refresh it only after required tasks report healthy completion D. Refresh it immediately after reset Correct Answer: C. Refresh it only after required tasks report healthy completion Question 6What is the principal danger of performing lengthy calculations inside a high-frequency ISR? A. It necessarily increases ADC resolution B. It can delay other interrupts and cause missed events C. It removes timer prescaling D. It guarantees priority inversion cannot occur Correct Answer: B. It can delay other interrupts and cause missed events Question 7For an ideal 12-bit ADC with a 3.3 V reference, the nominal quantisation interval is closest to: A. 0.805 mV B. 8.06 mV C. 80.5 mV D. 805 mV Correct Answer: A. 0.805 mV Question 8Which design is most appropriate for an emergency motor shutdown? A. A low-priority logging task only B. A software delay followed by GPIO polling C. A high-priority interrupt combined with a hardware timer fault path D. An RTC alarm scheduled several seconds later Correct Answer: C. A high-priority interrupt combined with a hardware timer fault path Question 9What problem does an anti-aliasing filter primarily address? A. Timer overflow B. Frequencies above the sampling limit entering the ADC C. Watchdog early servicing D. GPIO output drive current Correct Answer: B. Frequencies above the sampling limit entering the ADC Question 10A level-sensitive interrupt remains asserted after its ISR returns. What is the likely consequence? A. The interrupt may immediately recur B. The timer automatically changes its prescaler C. The ADC becomes lossless D. The RTC stops permanently Correct Answer: A. The interrupt may immediately recur
|