Embedded Systems
Timers and Interrupts
A pacemaker fires a 1ms pulse every 800ms to keep a heart beating. The pulse timing must be accurate to within 50 microseconds over years of operation. A brushless motor for a drone must update commutation 16,000 times per second. An industrial servo must respond to a position command within 1 millisecond. None of these are possible without hardware timers and interrupts - the two mechanisms that give embedded systems precise control over time. Every motor driver, every RC servo, every real-time controller depends on exactly what this lesson covers.
- **Drone ESCs (Electronic Speed Controllers)**: use 32 kHz PWM and timer interrupts for BLDC motor commutation; the interrupt latency (under 1 µs on STM32F4) determines maximum motor RPM and torque response bandwidth
- **Automotive ECU injection timing**: fuel injectors on modern engines are triggered by timer output compare events synchronized to crankshaft position; timing accuracy of ±1 crankshaft degree requires sub-microsecond timer resolution at 6000 RPM
- **Medical infusion pumps**: stepper motor timing via PWM and encoder input capture ensures drug delivery accuracy; FDA 510(k) requires pump delivery error < 5% at all flow rates, achieved through hardware timer precision
Hardware Interrupts
A microcontroller running at 72 MHz can execute 72 million instructions per second. An external button press lasts perhaps 50 milliseconds - 3.6 million cycles. Polling the button in a loop wastes all those cycles checking a pin that changes state once. **Hardware interrupts** solve this: the peripheral signals the CPU asynchronously when an event occurs, the CPU suspends its current task, handles the event, and resumes. The result: zero wasted cycles, and response times measured in microseconds.
**Interrupt sources on STM32 (common ARM Cortex-M MCU):** - External pins (EXTI): rising edge, falling edge, or both - Timers: overflow, compare match, capture events - Communication peripherals: UART receive, SPI transfer complete, I2C address match - ADC: conversion complete - DMA: transfer complete - System: SysTick (RTOS tick), HardFault, NMI Each interrupt has a **priority** (0 = highest). Higher-priority interrupts can preempt lower-priority ISRs (nested interrupts).
**Contact bounce**: mechanical buttons generate 5-50 ms of rapid transitions when pressed. A single press can trigger 10-100 interrupts. Solutions: hardware RC filter (1kΩ + 100nF), or software debounce (ignore interrupts within 20ms of the first). Most production keyboards and HMI panels use hardware debounce.
Why is polling a button pin less efficient than using an interrupt, even if the polling loop is fast?
Interrupt Service Routines (ISR)
When an interrupt fires, the CPU: saves registers (context), jumps to the **Interrupt Service Routine** (ISR) address from the vector table, executes the ISR, restores registers, and resumes the interrupted code. The entire process takes ~12-20 cycles on ARM Cortex-M (latency ~170 ns at 72 MHz). ISR design follows strict rules: short execution time, no blocking calls, no dynamic memory allocation, no lengthy computations.
**ISR best practices:** 1. Set a flag or write to a queue - do minimal work 2. Let the main loop process data from the flag/queue 3. Never call HAL_Delay(), osDelay(), or any blocking function 4. Use `volatile` for variables shared between ISR and main loop 5. Keep ISR under 1-2 microseconds to avoid missing subsequent interrupts 6. Disable interrupts when reading multi-byte values updated in ISRs
**Interrupt latency matters in motor control**: a BLDC motor controller at 20,000 RPM needs commutation updates every 1 ms. If the ISR takes 500 µs, only half the CPU time is available for control. TI's C2000 series (used in industrial motor drives) has dedicated hardware interrupt controllers with 2-cycle latency and zero-overhead loops specifically for this use case.
Why must variables shared between an ISR and the main loop be declared `volatile` in C?
Timer Modes
Hardware timers are programmable counters that tick at a configurable frequency derived from the system clock. They are the backbone of embedded time-critical operations: generating precise time delays, measuring pulse widths, creating PWM signals, and triggering ADC conversions at exact intervals. STM32 has 14+ timers; modern automotive MCUs have 32+. Understanding timer modes is essential for any real-time application.
| Mode | What It Does | Typical Use |
|---|---|---|
| Up-counting | Count from 0 to ARR, overflow interrupt | Periodic tasks, timebase |
| Down-counting | Count from ARR to 0, underflow interrupt | Same as up-counting with phase offset |
| Up-down (center) | Count 0→ARR→0, interrupt at 0 | Symmetric PWM for motor drives |
| Input Capture | Record timer value when external edge occurs | Frequency/period measurement, encoder |
| Output Compare | Toggle/set/clear output when counter matches CCR | Precise pulse generation |
| PWM Mode 1/2 | Output high/low based on counter vs CCR | Motor speed, LED brightness, servo |
A timer has PSC=84-1 and ARR=1000-1 on a 84 MHz system. What interrupt frequency does it produce?
Pulse Width Modulation (PWM)
**PWM** encodes an analog value as the duty cycle of a digital square wave: the fraction of time the signal is high. A 50% duty cycle on a 5V GPIO averages 2.5V. Low-pass filter the signal and you have a DAC. Without filtering: motor control, servo positioning, LED brightness, switching power supply regulation. PWM is perhaps the most widely used timer mode - found in every servo motor, DC motor driver, and LED dimmer on the planet.
**PWM parameters:** - **Frequency**: how fast the duty cycle repeats (50 Hz for hobby servos, 10-100 kHz for motor drivers, 1 MHz+ for switching regulators) - **Duty cycle**: on-time / period × 100% (0% = always off, 100% = always on) - **Resolution**: how finely duty cycle can be set (12-bit = 4096 steps; 16-bit = 65536 steps) - **Alignment**: edge-aligned (simple) vs center-aligned (for 3-phase motor drives to reduce EMI)
**Dead time** is mandatory in H-bridge motor drivers: when switching between high-side and low-side FETs, both must not conduct simultaneously or the power supply short-circuits. STM32 Advanced timers (TIM1, TIM8) have built-in dead-time insertion registers. Texas Instruments' DRV8323 motor gate driver requires minimum 100 ns dead time; most designs use 200-500 ns.
PWM outputs analog voltage directly and can drive analog circuits without modification
PWM is a digital signal with transitions between 0V and VCC; an analog value is produced only after low-pass filtering; unfiltered PWM drives motors and LEDs through switching, not through analog voltage level
A motor averages the PWM voltage mechanically (its inductance acts as a filter). An LED averages the brightness optically (persistence of vision). But a precision DAC application, audio output, or analog sensor reference needs an RC or LC filter to smooth the PWM into a DC level. Connecting raw PWM to a sensitive analog input causes switching noise and measurement errors.
A servo motor requires 50 Hz PWM with 1-2 ms pulse width for 0-180 degree range. What timer ARR value achieves this with a 1 MHz timer clock?
Key ideas
- **Hardware interrupts** allow the CPU to respond to events asynchronously without polling; the CPU saves context, executes the ISR, and resumes - total overhead ~12-20 cycles (~170 ns at 72 MHz)
- **ISR design rules**: keep short (< 2 µs), no blocking calls, set flags for main loop processing, use `volatile` for shared variables, disable interrupts when accessing multi-byte shared data
- **Timer modes**: up/down counting for periodic interrupts; input capture for frequency measurement; output compare for precise pulse generation; PWM mode for motor control and LED dimming
- **PWM** encodes analog values as digital duty cycles; frequency and resolution are set by PSC and ARR; center-aligned PWM reduces EMI in 3-phase motor drives; dead time insertion prevents H-bridge shoot-through
Related topics
Timers and interrupts underpin all time-critical embedded subsystems:
- ADC and Analog Interfaces — Timer triggers are the standard way to trigger ADC conversions at precise intervals; DMA transfers the results without CPU intervention
- RTOS and Task Scheduling — RTOS tick is generated by SysTick timer interrupt; preemptive scheduling relies on the timer to switch tasks at fixed intervals
- Communication Protocols (UART, SPI, I2C) — All serial peripherals use interrupt or DMA to signal transfer completion; understanding ISR patterns from this lesson is prerequisite for protocol implementation
Вопросы для размышления
- A button ISR fires 50 times during a 50ms press due to contact bounce. What is the most robust debounce strategy that works with interrupts rather than replacing them - and how does it interact with interrupt priority?
- A motor control system needs a 20 kHz PWM update and a 1 kHz sensor read interrupt. Both use the same priority. What happens when they arrive simultaneously - and how should priorities be set to prevent control instability?
- A medical device's ISR takes 500 µs but the specification requires 1 ms interrupt period. Is this system safe? What is the risk, and what architectural changes would fix it?