Interrupts and Timers in Microcontrollers
1. Definition and Purpose of Interrupts
Definition and Purpose of Interrupts
An interrupt is a hardware or software signal that temporarily halts the normal execution of a microcontroller to handle a higher-priority event. Unlike polling, where the processor continuously checks for events, interrupts allow asynchronous event handling, improving efficiency and real-time responsiveness.
Interrupt Mechanism
When an interrupt occurs, the microcontroller:
- Saves the current program counter and CPU state to the stack.
- Jumps to the Interrupt Service Routine (ISR), a predefined function that handles the event.
- Restores the saved state and resumes normal execution after the ISR completes.
Where tresponse is the total latency, tdetect is the interrupt detection time, tsave is the context-saving time, and tISR is the ISR execution time.
Types of Interrupts
Hardware Interrupts: Triggered by external signals (e.g., GPIO pin changes, timer overflows, ADC conversions). For example, a UART receive interrupt fires when new data arrives.
Software Interrupts: Generated by executing specific instructions (e.g., SWI
in ARM Cortex-M). Often used for system calls or debugging.
Prioritization and Nesting
Microcontrollers implement interrupt priority levels to resolve conflicts. Higher-priority interrupts can preempt lower-priority ISRs (nesting). The Nested Vectored Interrupt Controller (NVIC) in ARM Cortex-M cores allows dynamic priority assignment:
// ARM Cortex-M NVIC priority configuration example
NVIC_SetPriority(USART1_IRQn, 1); // Set USART1 interrupt priority to 1
NVIC_EnableIRQ(USART1_IRQn); // Enable the interrupt
Practical Applications
- Real-time systems: Motor control loops use timer interrupts for precise PWM generation.
- Power management: Wake-up interrupts allow sleep mode exit on external events.
- Communication protocols: I2C and SPI rely on interrupts for efficient data transfer.
1.2 Types of Interrupts: Hardware vs. Software
Hardware Interrupts
Hardware interrupts are generated by external peripheral signals or internal microcontroller events, such as:
- GPIO pin state changes (e.g., rising/falling edge triggers)
- Timer/counter overflow or capture events
- Analog-to-digital conversion completion
- Communication interface events (UART, SPI, I²C)
These interrupts are asynchronous to the program flow and typically have dedicated hardware support. The interrupt service routine (ISR) execution latency is critical and depends on the microcontroller's interrupt controller architecture (e.g., nested vectored interrupt controllers in ARM Cortex-M).
Software Interrupts
Software interrupts are triggered programmatically via specific instructions (e.g., SWI
in ARM, INT
in x86). Key characteristics include:
- Synchronous execution relative to the program flow
- Used for system calls, debugging, or context switching
- No hardware event dependency
In embedded systems, software interrupts often facilitate privileged mode transitions or real-time operating system (RTOS) scheduler invocations.
Comparative Analysis
Attribute | Hardware Interrupts | Software Interrupts |
---|---|---|
Trigger Source | External/internal hardware | Program instruction |
Latency | Determined by hardware priority | Immediate (synchronous) |
Use Case | Real-time event handling | Controlled system calls |
Mathematical Model of Interrupt Latency
The worst-case interrupt latency (L) for hardware interrupts is given by:
where tinstruction is the longest-running atomic instruction, tcontext_save is the register preservation time, and tvector is the ISR lookup time.
Practical Considerations
In mixed-signal systems (e.g., sensor arrays), hardware interrupts may require:
- Debouncing circuits for mechanical switches
- Priority escalation for time-critical peripherals
- Watchdog timers to detect ISR hangs
1.3 Interrupt Service Routines (ISRs) and Their Execution
An Interrupt Service Routine (ISR) is a specialized function that executes in response to a hardware or software interrupt. Unlike regular functions, ISRs operate under strict timing constraints and must adhere to specific architectural rules to ensure deterministic behavior. When an interrupt occurs, the microcontroller's hardware automatically saves the current program counter and status registers, then jumps to the ISR's memory address defined in the interrupt vector table.
ISR Execution Flow
The execution sequence of an ISR follows a well-defined pipeline:
- Interrupt Trigger: A peripheral or external event sets an interrupt flag.
- Priority Resolution: The interrupt controller compares priorities if multiple interrupts occur simultaneously.
- Context Saving: The processor pushes critical registers (PC, SR, etc.) onto the stack.
- ISR Invocation: The CPU fetches the ISR address from the vector table and begins execution.
- Context Restoration: Upon completion, the saved registers are popped from the stack.
Latency Analysis
Interrupt latency (tlatency) is the time between interrupt trigger and ISR execution start. It consists of:
Where:
- tsync = Clock synchronization delay (1-3 cycles)
- texec = Pipeline completion time for current instruction
- tcontext = Register saving overhead (varies by architecture)
Best Practices for ISR Design
Optimal ISR implementation requires balancing responsiveness and system stability:
- Minimal Processing: Keep ISRs short; defer complex tasks to main loop via flags.
- Atomic Operations: Use volatile variables and disable interrupts during critical sections.
- Priority Management: Assign higher priorities to time-critical interrupts (e.g., USB SOF).
- Stack Management: Ensure sufficient stack space for worst-case nesting scenarios.
Advanced Techniques
Modern microcontrollers employ several optimizations for ISR handling:
- Tail-Chaining: Back-to-back interrupt execution without full context restore.
- Late Arrival: Higher priority interrupts can preempt during context saving.
- Banked Registers: Dedicated register sets for ISRs to reduce context switch overhead.
ARM Cortex-M Example
The ARM Cortex-M series implements the NVIC (Nested Vectored Interrupt Controller) which provides:
// Example of an efficient ISR in Cortex-M
void TIM2_IRQHandler(void) __attribute__((interrupt));
void TIM2_IRQHandler(void) {
if(TIM2->SR & TIM_SR_UIF) { // Check update interrupt flag
TIM2->SR &= ~TIM_SR_UIF; // Clear flag
counter++; // Minimal processing
}
}
Real-World Considerations
In high-reliability systems, ISRs must account for:
- Watchdog Timers: Ensure ISRs don't starve the main loop.
- EMI Resilience: Implement signature checks for critical ISRs.
- Debugging: Use trace buffers or GPIO toggles for timing analysis.
2. Interrupt Priority and Nesting
2.1 Interrupt Priority and Nesting
Interrupt Priority Mechanisms
In real-time embedded systems, multiple interrupts may occur simultaneously or nearly simultaneously. To manage such scenarios, microcontrollers implement priority-based interrupt handling, where each interrupt source is assigned a unique priority level. When multiple interrupts are pending, the highest-priority interrupt is serviced first.
The priority level is typically configured via dedicated registers, such as the Interrupt Priority Register (IPR) in ARM Cortex-M or the IP bit in 8051 architectures. The priority can be numerical (e.g., 0–15), where a lower number may indicate higher priority or vice versa, depending on the architecture.
Nested Interrupt Handling
Nested interrupts allow a higher-priority interrupt to preempt an already executing lower-priority interrupt service routine (ISR). This mechanism is critical for time-sensitive tasks, such as motor control or communication protocols, where delays are unacceptable.
To enable nesting:
- The microcontroller must support stack-based context saving (e.g., ARM Cortex-M’s automatic stacking).
- The global interrupt flag must be re-enabled inside the ISR (e.g., via
__enable_irq()
in Cortex-M). - The priority of the interrupting source must be higher than the currently executing ISR.
Priority Inversion and Mitigation
Priority inversion occurs when a low-priority task holds a resource needed by a high-priority task, effectively delaying the latter. This is common in shared resource scenarios (e.g., mutexes). Solutions include:
- Priority inheritance: Temporarily elevates the low-priority task’s priority.
- Priority ceiling protocol: Assigns a predefined maximum priority to shared resources.
Practical Implementation in ARM Cortex-M
Cortex-M microcontrollers use the Nested Vectored Interrupt Controller (NVIC), which supports up to 256 priority levels (8-bit). The priority is split into preemption priority (for nesting) and subpriority (for same-level arbitration).
// Example: Setting interrupt priority in Cortex-M
NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority);
Case Study: Automotive ECU
In automotive engine control units (ECUs), interrupt nesting ensures critical tasks (e.g., fuel injection timing) preempt less urgent ones (e.g., dashboard updates). Misconfigured priorities can lead to engine misfires or communication failures, emphasizing the need for rigorous priority assignment.
2.2 Enabling and Disabling Interrupts
Interrupts in microcontrollers are controlled through dedicated registers that manage their enabling, disabling, and prioritization. The Global Interrupt Enable (GIE) flag, often located in the status register, acts as a master switch for all interrupts. When GIE is cleared, no interrupts are serviced, regardless of individual interrupt enable bits. Conversely, setting GIE allows interrupts to trigger if their specific enable flags are also set.
Interrupt Control Registers
Most microcontrollers feature interrupt mask registers (e.g., IEN0, IEN1) that control individual interrupt sources. For example, enabling a timer interrupt requires setting the corresponding bit in the interrupt enable register:
Disabling interrupts is critical in time-sensitive code sections where atomic operations are necessary. For instance, disabling interrupts during a multi-byte read from a peripheral ensures data consistency.
Atomicity and Critical Sections
When modifying shared resources accessed by interrupts, disabling interrupts temporarily prevents race conditions. The sequence involves:
- Saving the current interrupt state (enabled/disabled).
- Disabling interrupts via the GIE flag.
- Performing the critical operation.
- Restoring the original interrupt state.
In assembly, this is often implemented using push/pop instructions to preserve the status register. In C, compiler intrinsics like __disable_irq()
and __enable_irq()
are used.
Nested Interrupts
Some architectures support nested interrupts, where higher-priority interrupts can preempt lower-priority ones. This requires:
- Configuring interrupt priority levels in dedicated registers (e.g., IP0, IP1).
- Ensuring the stack has sufficient depth to handle multiple interrupt contexts.
Nested interrupts reduce latency for high-priority events but complicate debugging due to non-deterministic execution flows.
Real-World Considerations
In motor control systems, disabling interrupts during PWM updates prevents glitches caused by asynchronous timer modifications. Conversely, communication protocols like UART often rely on uninterrupted interrupt servicing to avoid data loss.
Modern microcontrollers also provide interrupt pending flags, which remain set even if interrupts are disabled, allowing software to poll events when interrupts are impractical.
2.3 Common Interrupt Sources and Their Handling
Hardware-Generated Interrupts
External hardware interrupts are triggered by peripheral devices or physical signal changes on dedicated microcontroller pins. These include:
- GPIO edge/level detection: Configurable as rising, falling, or both edges (e.g., STM32 EXTI controller)
- Analog comparators: Trigger when input crosses reference voltage
- Power management events: Brown-out detection, voltage monitoring
The interrupt latency for hardware events is given by:
where tsync accounts for clock domain crossing synchronization (typically 2-3 clock cycles).
Timer-Based Interrupts
Microcontroller timers generate precise periodic interrupts through:
- Counter overflow/underflow: When timer reaches maximum or zero value
- Compare match: When counter matches predefined register value
- Input capture: On external signal edge detection
The interrupt period for timer overflow is calculated as:
where n is the timer bit-width and the prescaler divides the clock frequency.
Communication Interface Interrupts
Serial protocols generate interrupts for efficient data handling:
- UART: RX buffer full, TX buffer empty, framing errors
- SPI/I2C: Transfer complete, arbitration loss, stop condition
- CAN: Message received, transmit mailbox empty
For high-speed interfaces like USB, controllers typically use double-buffering with DMA to minimize ISR overhead while maintaining data throughput.
Exception-Type Interrupts
Processor core exceptions require immediate handling:
- Divide-by-zero: Arithmetic operation error
- Illegal opcode: Invalid instruction execution
- Memory faults: Access violations or MPU/MMU triggers
These often escalate to non-maskable interrupts (NMI) with fixed priority levels in ARM Cortex-M architectures.
Interrupt Priority Handling
Modern microcontrollers implement priority schemes through:
- Static priority: Fixed in hardware (e.g., ARM NVIC)
- Dynamic priority: Software-configurable levels
- Preemption: Higher priority interrupts can suspend lower ones
The priority resolution time tresolve affects worst-case latency:
where n represents the maximum possible nested interrupts.
Interrupt Service Routine Best Practices
Optimal ISR design follows these principles:
- Minimize duration: Defer processing to main loop when possible
- Atomic operations: Use volatile for shared variables
- Priority-aware design: Prevent priority inversion
- Deterministic timing: Avoid branching where possible
For ARM Cortex-M, the tail-chaining optimization reduces context switching overhead between back-to-back interrupts by up to 12 clock cycles.
3. Role of Timers in Embedded Systems
3.1 Role of Timers in Embedded Systems
Fundamental Principles of Timer Modules
Timer peripherals in microcontrollers are hardware counters that increment or decrement at a fixed clock rate, independent of the CPU. The counting frequency is derived from the system clock, often divided by a prescaler to achieve longer intervals. For a timer with a n-bit counter, the maximum countable value is given by:
where ftimer is the timer clock frequency after prescaling. For instance, a 16-bit timer running at 1 MHz can measure intervals up to 65.535 ms. When the counter overflows, it generates an interrupt, allowing precise timekeeping without CPU polling.
Timer Operating Modes
Modern microcontrollers support multiple timer configurations:
- Periodic Interrupt Mode: The timer reloads a predefined value upon overflow, creating regular interrupts for task scheduling.
- Input Capture: Records the timer value when an external trigger occurs, enabling pulse-width measurement.
- Output Compare: Generates signals or interrupts when the timer matches a set value, used for PWM generation.
- Pulse Accumulation: Counts external events with optional noise filtering.
Clock Synchronization and Jitter Reduction
Timer modules often include synchronization circuits to align the counter with the system clock, minimizing jitter. The synchronization delay tsync for an asynchronous input signal is bounded by:
Advanced implementations use clock domain crossing (CDC) techniques with metastability-hardened flip-flops to achieve sub-nanosecond alignment precision.
Real-World Applications
In motor control systems, timers generate the precise PWM waveforms needed for commutation, with dead-time insertion handled by hardware to prevent shoot-through. For example, a brushless DC motor controller might use:
- One timer for the 20 kHz PWM carrier
- A second timer for Hall sensor edge detection
- A third timer for speed measurement via input capture
Wireless protocols like Bluetooth Low Energy rely on timer-generated wake-up intervals to maintain synchronization while minimizing power consumption. The radio's 1.25 µs slot timing requirement demands timer resolutions below 100 ns, achievable through peripheral triggering without CPU intervention.
Advanced Features in Modern MCUs
Recent microcontroller architectures incorporate:
- Timer concatenation: Combining multiple timers for extended resolution (e.g., two 32-bit timers forming a 64-bit counter)
- Event chaining: Direct hardware links between timers and other peripherals (ADCs, DACs) for latency-free triggering
- Clock recovery: Using timers to extract clock signals from data streams in communication interfaces
The STM32 series implements a timer synchronization matrix that allows any timer to trigger or gate another, enabling complex waveform generation entirely in hardware. Similarly, the ESP32's LEDC peripheral uses fractional prescalers to achieve sub-Hertz PWM frequencies with 16-bit resolution.
3.2 Timer Modes: Polling vs. Interrupt-Driven
Microcontrollers implement timer functionality through two fundamental approaches: polling and interrupt-driven modes. The choice between these methods significantly impacts system responsiveness, power efficiency, and computational overhead.
Polling Mode Operation
In polling mode, the CPU actively monitors the timer's status register at regular intervals to detect overflow or match conditions. The basic workflow follows:
- The timer counter increments with each clock cycle
- Software periodically checks the Timer Overflow Flag (TOV)
- When TOV is set, the application resets the flag and executes the time-critical task
The polling period Tpoll must satisfy the Nyquist criterion relative to the timer period Ttimer:
For a 16-bit timer running at 1MHz (1µs tick), the maximum polling interval before missing an overflow is:
Interrupt-Driven Mode Operation
Interrupt-driven timers leverage hardware automation to eliminate CPU polling. Key components include:
- Timer/Counter Control Register (TCCR) for mode configuration
- Output Compare Register (OCR) for match value storage
- Timer Interrupt Mask Register (TIMSK) for interrupt enable control
When the timer reaches the programmed value, an interrupt sequence occurs:
- Hardware sets the interrupt flag
- CPU completes current instruction
- Program counter jumps to the Interrupt Service Routine (ISR)
- ISR executes and returns via RETI instruction
The interrupt latency tlatency depends on the worst-case instruction completion time:
Where Ncycles represents the maximum instruction cycles for any operation in the instruction set.
Comparative Analysis
The energy consumption difference between modes becomes significant in battery-powered systems. The power ratio Pratio can be modeled as:
Where fpoll is the polling frequency and Einstr is the energy per polling instruction. Modern microcontrollers like ARM Cortex-M series achieve interrupt wake-up times under 20 clock cycles, making interrupt-driven modes 2-3 orders of magnitude more efficient for low-duty-cycle applications.
Real-World Implementation Tradeoffs
Polling remains advantageous when:
- Deterministic response is required (interrupt jitter may reach 10-100µs)
- Handling very high-frequency events (>100kHz) where ISR overhead dominates
- Working with legacy systems lacking nested interrupt controllers
Interrupt-driven designs excel in:
- Power-sensitive applications (IoT sensors, wearables)
- Systems with multiple concurrent timing requirements
- Scenarios requiring precise long-interval timing (hourly data logging)
Advanced microcontrollers often combine both approaches through features like:
- DMA-coupled timers for high-speed data transfers
- Timer output compare auto-toggle modes
- Windowed watchdog timers with interrupt/polling fallback
3.3 Prescalers and Clock Sources for Timers
Clock Sources and Their Impact on Timer Resolution
The accuracy and resolution of a microcontroller's timer module are directly influenced by its clock source. Common clock sources include:
- Internal RC oscillators (typically 1-8% accuracy, low power)
- Crystal oscillators (0.001-0.1% accuracy, higher power)
- Phase-locked loops (PLLs) (multiplied frequency from base clock)
- External clock inputs (for synchronization with other systems)
The timer increment rate (ftimer) relates to the system clock (fsys) through:
where N is the prescaler division factor. Higher fsys enables finer time resolution but increases power consumption.
Prescaler Architecture and Configuration
Prescalers divide the input clock frequency before it reaches the timer counter. They are implemented as binary dividers, offering division ratios of 2n (1, 2, 4, 8...). The effective timer period becomes:
where M is the timer counter width (e.g., 8, 16, or 32 bits). Modern microcontrollers often provide flexible prescaler configurations:
- Fixed prescalers (hardware-configured division ratios)
- Programmable prescalers (software-selectable via control registers)
- Cascaded prescalers (multiple stages for very low frequencies)
Trade-offs in Prescaler Selection
Selecting an appropriate prescaler involves balancing three key parameters:
For PWM applications, the prescaler must be chosen such that:
where TOP is the timer's maximum count value. This often requires iterative selection between resolution requirements and available clock frequencies.
Advanced Clock Synchronization Techniques
In precision timing applications, clock domain synchronization becomes critical. Two common methods are:
- Clock gating: Temporarily halts the timer clock to prevent metastability during prescaler changes
- Shadow registers: Buffers new prescaler values until the next timer cycle boundary
The synchronization delay (tsync) can be calculated as:
where tprop is the propagation delay through the prescaler logic (typically 1-3 clock cycles).
Practical Implementation Example
Consider an ARM Cortex-M4 microcontroller generating a 1 kHz PWM signal with 10-bit resolution from a 16 MHz system clock. The required prescaler value would be:
The nearest integer prescaler value of 16 yields an actual PWM frequency of 976.56 Hz. For exact frequency matching, some microcontrollers offer fractional prescalers or clock modulation techniques.
4. Real-Time Task Scheduling
4.1 Real-Time Task Scheduling
Fundamentals of Real-Time Scheduling
Real-time task scheduling in microcontrollers ensures deterministic execution of time-critical operations. Unlike general-purpose computing, real-time systems require strict adherence to timing constraints, where missing a deadline constitutes system failure. Scheduling algorithms must prioritize tasks based on urgency, computational load, and resource availability.
The schedulability condition for a set of n periodic tasks is derived from Liu & Layland's seminal work:
where Ci is the worst-case execution time (WCET) of task i, Ti is its period, and U(n) is the utilization bound for n tasks. For large n, this bound approaches ln(2) ≈ 0.693.
Common Scheduling Algorithms
- Rate-Monotonic Scheduling (RMS): Assigns static priorities inversely proportional to task periods. Optimal for fixed-priority schemes.
- Earliest Deadline First (EDF): Dynamically prioritizes tasks with the nearest deadlines. Achieves 100% CPU utilization when feasible.
- Time-Triggered Scheduling: Executes tasks at predetermined instants, commonly implemented using timer interrupts.
Practical Implementation Considerations
Microcontroller-specific constraints necessitate careful design:
- Interrupt Latency: The delay between interrupt trigger and ISR execution must be bounded. Modern ARM Cortex-M cores achieve sub-100ns latencies.
- Context Switching Overhead: Saving/restoring register states consumes cycles. RTOS kernels optimize this through dedicated stack frames.
- Timer Resolution: The system tick timer's granularity (e.g., 1ms vs 1μs) determines the minimum schedulable time quantum.
Case Study: Automotive ECU Scheduling
A modern engine control unit (ECU) demonstrates hierarchical scheduling:
- High-frequency tasks (fuel injection timing at 100μs intervals) handled by hardware timers
- Medium-frequency tasks (sensor polling at 10ms) managed by RTOS
- Low-priority tasks (diagnostics) executed during idle periods
where timing jitter must remain below application-specific thresholds (often <50μs for engine control).
Advanced Techniques
Recent research extends classical scheduling theory:
- Mixed-Criticality Scheduling: Allows different assurance levels for tasks (e.g., ASIL-D vs QM in ISO 26262)
- Energy-Aware Scheduling: Dynamically adjusts clock speeds using microcontroller DVS (Dynamic Voltage Scaling)
- Probabilistic Timing Analysis: Uses statistical methods to bound WCET in complex pipelines with cache effects
Modern microcontroller architectures like ARM Cortex-M7 implement dual-issue pipelines and branch prediction, requiring updated WCET analysis techniques that account for instruction-level parallelism.
4.2 Pulse Width Modulation (PWM) Generation
Fundamentals of PWM
Pulse Width Modulation (PWM) is a technique for encoding analog signal levels into digital pulses by varying the duty cycle. The duty cycle (D) is defined as the ratio of the pulse width (τ) to the total period (T):
For a microcontroller, PWM generation relies on timer peripherals configured in compare mode. A counter increments until it matches a predefined value in a capture/compare register (CCR), toggling the output pin state.
Hardware Implementation
Microcontrollers like ARM Cortex-M or AVR use dedicated timer blocks (e.g., TIMx in STM32, Timer1 in ATmega) with PWM-specific features:
- Edge-aligned mode: Counter counts up to the auto-reload value (ARR), resetting after overflow.
- Center-aligned mode: Counter counts up and down, generating symmetric pulses.
- Pre-scalers: Adjust timer clock frequency to achieve desired PWM resolution.
Mathematical Derivation of PWM Parameters
The PWM frequency (fPWM) is determined by the timer clock (fCLK), pre-scaler (PSC), and auto-reload value (ARR):
For a 16-bit timer (ARRmax = 65535) and fCLK = 72 MHz, achieving 1 kHz PWM requires:
Code Implementation (STM32 HAL)
// Configure Timer2 for PWM (Channel 1, 1 kHz, 50% duty)
TIM_HandleTypeDef htim2;
htim2.Instance = TIM2;
htim2.Init.Prescaler = 71; // 72 MHz / (71 + 1) = 1 MHz
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 999; // 1 MHz / (999 + 1) = 1 kHz
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_PWM_Init(&htim2);
TIM_OC_InitTypeDef sConfigOC;
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 500; // 50% duty (500/1000)
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
Applications
PWM is critical in:
- Motor control: Varying duty cycle adjusts average voltage to DC motors.
- LED dimming: Perceived brightness scales with duty cycle due to persistence of vision.
- Power converters: Buck/boost regulators use PWM to regulate output voltage.
Advanced Techniques
For high-resolution applications (e.g., audio class-D amplifiers), dead-time insertion prevents shoot-through in H-bridges. Microcontrollers like STM32F334 include high-resolution timers (217 ps resolution) for such use cases.
4.3 Debouncing Switches Using Interrupts
Mechanical switches exhibit contact bounce—a rapid opening and closing of electrical contacts before settling into a stable state. This phenomenon introduces noise, causing erroneous multiple triggers if processed naively by a microcontroller. Interrupt-based debouncing mitigates this by combining hardware and software techniques to filter transient signals.
Physical Basis of Contact Bounce
When a switch is actuated, the metal contacts do not make or break cleanly due to mechanical elasticity and kinetic energy. The resulting bounce produces a series of voltage spikes lasting typically 1–10 ms, depending on switch construction. The bouncing waveform can be modeled as a damped oscillation:
where τ is the time constant of the contact material and ωd is the damped oscillation frequency. For debouncing, we care primarily about the settling time ts, defined as the duration until |V(t) - Vcc| < δ, where δ is the logic-level threshold.
Interrupt-Driven Debouncing Algorithm
An edge-triggered interrupt captures the initial switch transition, but subsequent bounces must be ignored until the signal stabilizes. The algorithm proceeds as follows:
- Configure the GPIO pin for interrupt-on-change, triggering on either rising or falling edges.
- Upon interrupt, disable further interrupts from the same pin and start a timer.
- When the timer expires (after a conservative bounce period, e.g., 20 ms), read the pin state to determine the settled logic level.
- Re-enable interrupts for subsequent detection.
Timer Period Calculation
The timer delay must exceed the worst-case bounce duration. For a switch with a maximum bounce time Tb, the timer period Td should satisfy:
where σ is the observed bounce time standard deviation and k is a safety factor (typically 3–5). Empirical measurements show most tactile switches exhibit Tb < 5 ms, but industrial switches may require Td = 50 ms.
Hardware Considerations
While software debouncing suffices for many applications, combining it with an RC low-pass filter improves robustness. The filter's cutoff frequency fc should be set below the bounce frequency spectrum:
A typical implementation uses R = 10 kΩ and C = 100 nF (fc ≈ 160 Hz), attenuating high-frequency transients while preserving the clean edge for interrupt detection.
Code Implementation
// STM32 HAL example with timer-based debouncing
volatile uint8_t debounce_flag = 0;
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
if (GPIO_Pin == SWITCH_PIN) {
HAL_TIM_Base_Stop_IT(&htim3);
debounce_flag = 1;
HAL_TIM_Base_Start_IT(&htim3); // Start 20ms debounce timer
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
if (htim == &htim3 && debounce_flag) {
HAL_TIM_Base_Stop_IT(&htim3);
uint8_t state = HAL_GPIO_ReadPin(SWITCH_GPIO_Port, SWITCH_Pin);
process_switch_state(state); // Handle debounced state
debounce_flag = 0;
HAL_NVIC_EnableIRQ(EXTIx_IRQn); // Re-enable interrupts
}
}
5. Minimizing Interrupt Latency
5.1 Minimizing Interrupt Latency
Interrupt latency is the time delay between the assertion of an interrupt signal and the execution of the first instruction in the interrupt service routine (ISR). In real-time systems, minimizing this latency is critical to ensure timely responses to high-priority events. The total latency consists of several components:
where thw is the hardware propagation delay, tsw is the software overhead (e.g., pipeline stalls), and tcontext is the context-switching time.
Hardware-Level Optimization
Modern microcontrollers employ several architectural features to reduce thw:
- Nested Vector Interrupt Controllers (NVIC): Prioritize interrupts dynamically, allowing higher-priority ISRs to preempt lower-priority ones without waiting for completion.
- Shadow Registers: Dedicated register banks for ISRs eliminate the need to save/restore CPU registers, reducing tcontext.
- Direct Memory Access (DMA): Offloads data transfer tasks from the CPU, preventing ISR blocking during peripheral operations.
Software-Level Optimization
Efficient ISR design is equally crucial:
- Minimize ISR Complexity: Defer non-critical processing to the main loop using flags or queues.
- Inline Critical Code: Use compiler directives (e.g.,
__attribute__((always_inline))
in GCC) to eliminate function call overhead. - Precompute Lookup Tables: Replace runtime calculations with pre-stored values for time-critical operations (e.g., sensor linearization).
Compiler and Toolchain Adjustments
Toolchain settings significantly impact latency:
- Optimization Flags:
-O2
or-O3
in GCC reduces branch mispredictions and unrolls loops. - Interrupt Attribute Macros: Ensure the compiler preserves registers correctly (e.g.,
__interrupt
in IAR Embedded Workbench).
Real-World Case Study: Motor Control
In brushless DC motor control, latency below 1 µs is often required to prevent torque ripple. A Cortex-M7 microcontroller achieves this by:
- Using a dedicated PWM timer interrupt for commutation.
- Storing phase-current lookup tables in tightly coupled memory (TCM).
- Assigning the ISR to the highest NVIC priority level (Level 0).
where fPWM is the PWM frequency. Exceeding tmax leads to harmonic distortion in motor current.
5.2 Power Consumption Considerations with Timers
Timer peripherals in microcontrollers contribute significantly to power consumption, particularly in low-power applications where energy efficiency is critical. The primary sources of power dissipation include the timer clock source, prescaler logic, counter registers, and interrupt generation circuitry. Understanding these factors enables optimized designs for battery-operated or energy-harvesting systems.
Clock Source Selection and Power Trade-offs
The choice of clock source directly impacts power consumption. High-frequency clocks (e.g., system clock or PLL outputs) enable faster timer operation but increase dynamic power dissipation quadratically due to the relationship:
where α is the activity factor, C is the load capacitance, V is the supply voltage, and f is the clock frequency. Low-power designs often use secondary oscillators (e.g., 32 kHz watches crystals) for timer operations when timing resolution requirements permit.
Prescaler Configuration Impact
Timer prescalers reduce power by dividing the input clock frequency before it reaches the counter. However, the prescaler logic itself consumes power proportional to its input frequency. The optimal prescaler setting minimizes:
where N is the prescaler division factor. Empirical measurements often reveal a "sweet spot" where further prescaling provides diminishing returns due to static power consumption in the digital logic.
Timer Mode Selection
Different timer operating modes exhibit varying power characteristics:
- Periodic mode maintains constant power draw from continuous counter operation
- One-shot mode allows the timer to automatically disable after reaching the compare value, reducing power between events
- PWM generation shows intermediate consumption proportional to the duty cycle
Advanced microcontrollers implement clock gating that automatically disables timer clocks when not in active use, reducing static power consumption by 30-80% depending on the implementation.
Interrupt-Driven vs Polling Approaches
The method of timer event detection affects system-wide power consumption. Interrupt-driven designs allow the CPU to remain in low-power sleep modes between timer events, while polling requires continuous CPU operation. The power savings can be estimated by:
where PINT represents the additional power from interrupt processing. Modern microcontrollers achieve interrupt wake-up times under 5 μs, making this approach favorable for event intervals longer than ~50 μs.
Peripheral Clock Gating Techniques
Advanced power management involves dynamically enabling/disabling timer peripherals through clock gating registers. The power savings follow an exponential decay relationship during inactive periods:
where toff is the disabled duration and RC represents the power supply time constant. Careful measurement is required as frequent gating can increase energy overhead from repeated power cycling.
Voltage Scaling Effects
Reducing supply voltage for timer peripherals (when supported) provides quadratic power savings but affects timing accuracy due to propagation delay variations:
where VT is the threshold voltage and k is a process-dependent constant. Some microcontrollers implement separate voltage domains for timers requiring precise operation.
5.3 Using Timers for Low-Power Modes
Microcontrollers often operate in power-constrained environments, making low-power modes essential for energy efficiency. Timers play a critical role in managing these modes by enabling wake-up events, duty cycling, and precise timing control without continuous CPU intervention.
Timer-Driven Wake-Up Mechanisms
In low-power modes such as Sleep, Standby, or Stop, the CPU core is halted, but peripherals like timers can remain active. A timer configured in Wake-Up Timer (WUT) mode allows the system to exit low-power states after a predefined interval. The wake-up latency and power consumption are governed by:
where tactive is the timer period and tstartup is the oscillator stabilization time. For ultra-low-power designs, internal low-frequency oscillators (e.g., 32 kHz) are preferred over high-speed clocks.
Auto-Wakeup and Duty Cycling
Periodic wake-up via timers enables duty-cycled operation, where the microcontroller alternates between active and sleep states. The duty cycle (D) is calculated as:
For example, a sensor node sampling at 1 Hz with a 10 ms active time achieves a duty cycle of 1%, drastically reducing average power consumption.
Timer Clock Gating and Prescaling
Further power savings are achieved by:
- Clock gating: Disabling timer clocks when inactive.
- Prescaling: Reducing timer clock frequency to minimize switching losses.
The power dissipation of a timer (Ptimer) scales with frequency:
where Ceff is the effective switched capacitance, VDD is the supply voltage, and f is the clock frequency.
Real-World Implementation
Modern microcontrollers like the STM32L4 series integrate Low-Power Timer (LPTIM) peripherals that operate down to 1.8 V and consume less than 1 µA. These timers support:
- PWM generation in Sleep mode.
- External event counting without CPU intervention.
- Clock synchronization for glitch-free operation.
An example configuration for an STM32L4 in Stop mode with LPTIM wake-up:
// Configure LPTIM for wake-up every 1 second
void enter_low_power_mode() {
// Enable LPTIM clock
RCC->APB1ENR1 |= RCC_APB1ENR1_LPTIM1EN;
// Set autoreload value for 1s interval (32 kHz clock)
LPTIM1->ARR = 32768;
// Enable autoreload and start timer
LPTIM1->CR |= LPTIM_CR_ENABLE;
// Enter Stop mode with LPTIM wake-up
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
}
Trade-offs and Optimization
Selecting timer parameters involves balancing:
- Resolution vs. Power: Higher prescalers reduce power but limit timing precision.
- Wake-up Latency: Faster clocks enable quicker responses but increase idle power.
- Peripheral Overhead: Additional features like DMA or capture/compare increase active power.
For battery-powered IoT devices, empirical measurements show that optimizing timer configurations can extend operational lifetime by 20–40% compared to naive implementations.
6. Recommended Books and Datasheets
6.1 Recommended Books and Datasheets
- PDF Mastering Interrupts: A Guide for Embedded Engineers — The Role of Interrupts in Real-Time Systems 5 Types of Interrupts 6 Chapter 2: Setting Up Interrupts 9 Conguring Interrupts on Microcontrollers 9 Common Interrupt Sources 10 Writing Interrupt Service Routines (ISRs) 12 Chapter 3: Ecient Interrupt Handling Techniques 14 Minimizing ISR Execution Time 14 Interrupt Prioritization 15
- PDF 6. Interrupts - cs.iit.edu — interrupt handler) must be invoked to solve the problem that caused the interrupt, and finally the program's state restored and the program restarted. 6.3 Checking for interrupts We have to modify the state-diagram of the Control Unit to check for interrupts; we also have to update the hardware to provide support for interrupts handling.
- PDF 6 Using the MCU Timers - Springer — Using the MCU Timers 6.1 In this Chapter This chapter contains a description of the timer system of microcontrollers, including the general-purpose timer, the PWM timer, and the watchdog. 6.2 The General Structure and Functions of the Timer System Timing is essential for the operation of microcontroller systems, either for generating
- Chapter 6: Interrupts, DAC, and Sound Generation - University of Texas ... — To enable means to allow interrupts at this time. ... For more details see the Startup.s files within the interrupt examples posted on the book web site. ... Table 6.3.1 lists some of the interrupt sources available on the TM4C family of microcontrollers. Interrupt numbers 0 to 15 contain the faults, software interrupt and SysTick; these ...
- Chapter 6: Functions, Interrupts, and Low-Power Modes — They are described here because the MSP430 needs an interrupt to wake it from a low-power mode. In fact we see that no extra effort is usually needed to handle low-power modes in interrupts: The MSP430 automatically goes to active mode when an interrupt is requested, services the interrupt, and resumes its low-power mode afterward.
- PDF Chapter 6: Interrupts and Timers - embedded-knowhow.co.uk — Many microcontroller counters cause an interrupt as the counter overflows; this interrupt can be used to record the overflow, and the count can continue in a useful way. The effective range of the counter has been extended. If the counter is just free-running with a continuous clock signal, then the "interrupt
- Microcontroller Programming[Book] - O'Reilly Media — It then addresses fundamental microcontroller programming techniques and advanced topics such as interfacing and programmable timer operations. Focusing on Motorola 68HC11 microcontroller, numerous flowcharts illustrate step-by-step procedures, and full-length projects provide practical problem solving approaches, with examples that portray ...
- PDF Embedded Systems -Lab 2: Interrupts and Timers - ETH Z — Interrupts Definition: anhardware interrupt is an electronic signal that alerts the microprocessor of an event. An interrupt can be triggered by either an internal peripheral (e.g.timer) or an external device (e.g.button) Marco Giordano 26./29.10.2022
- Any recommended books for someone new to microcontrollers? — Ugh, as much as I hate this reality, this is 100% correct. Learn to use data sheets now and save yourself tons of time sifting through incomplete or inapplicable general resources for any of the millions of devices out there with different required operating conditions and capabilities.
- PDF AN4776 Application note - STMicroelectronics — the TIM1 timer peripheral is shared across the STM32F1 Series, STM32F2 Series and STM32F4 Series, but for the specific case of STM32F30x microcontrollers family, the TIM1 timer peripheral features a bit ri cher features set than the TIM1 present in the other families. The general purpose timers embedded by the STM32 microcontrollers share the same
6.2 Online Resources and Tutorials
- Periodic Interrupts Using Timers Introduction - Texas Instruments — MSP432 microcontroller has four General Purpose Timer Modules called Timer_A. Each timer has one 16-bit timer and seven associated capture/compare registers. In this lab, you will use Timer A0 to create two PWM outputs for the motor that can be used by robot explorer. You will use Timers A2 and A3 later in Module 16 to interface the two ...
- Exceptions and Interrupts | Computation Structures | Electrical ... — 18 Devices and Interrupts 18.1 Annotated Slides 18.2 Topic Videos 18.3 Worksheet 19 Concurrency and Synchronization 19.1 Annotated Slides 19.2 Topic Videos ... Learning Resource Types theaters Lecture Videos. assignment_turned_in Programming Assignments with Examples. notes Lecture Notes. co_present Instructor Insights.
- 1.6 Getting Started with Timers - Microchip Technology — This technical brief provides information about the Timers/Counters present on the PIC18 families of microcontrollers. The document describes the application area, the modes of operation and the hardware and software requirements of the Timers/Counters and configurable output or input for internal or external use with the help of the Peripheral Pin Select (PPS).
- PDF Chapter 6: Interrupts and Timers - embedded-knowhow.co.uk — Many microcontroller counters cause an interrupt as the counter overflows; this interrupt can be used to record the overflow, and the count can continue in a useful way. The effective range of the counter has been extended. If the counter is just free-running with a continuous clock signal, then the "interrupt
- Timing an AVR microcontroller | FabAcademy - Tutorials — Timers generate interrupts which is how they can interact with your program. An interrupt is something that occurs when a particular trigger (either from an internal or external source) happens; the interrupt allows the program to stop what it was doing, perform a short task, and then return to where it left off in the main program.
- Lab 7: PIC Timers and Counters (Part 1) - Embedded Lab — The T0IF bit set can trigger an interrupt (known as Timer0 Interrupt), if enabled. [An interrupt is an asynchronous signal calling for processor attention. It tells the microcontroller to drop whatever it's doing and go to a predefined place (the interrupt service routine or ISR) when a certain event occurs.
- PDF AN4776 Application note - STMicroelectronics — the TIM1 timer peripheral is shared across the STM32F1 Series, STM32F2 Series and STM32F4 Series, but for the specific case of STM32F30x microcontrollers family, the TIM1 timer peripheral features a bit ri cher features set than the TIM1 present in the other families. The general purpose timers embedded by the STM32 microcontrollers share the same
- Chapter 6: Interrupts, DAC, and Sound Generation - University of Texas ... — An interrupt is the automatic transfer of software execution in response to a hardware event that is asynchronous with the current software execution.This hardware event is called a trigger.The hardware event can either be a busy to ready transition in an external I/O device (like the UART input/output) or an internal event (like bus fault, memory fault, or a periodic timer).
- PIC16f877a Timer - Tutorials — Timer Basics. As the name suggests these are used to measure the time or generate the accurate time delay. The microcontroller can also generate/measure the required time delays by running loops, but the timer/counter relieves the CPU from that redundant and repetitive task, allowing it to allocate maximum processing time for other tasks.
- PDF Timers: Timer0 Tutorial (Part 1) - Microchip Technology — Timers Tutorial PIC® MID-RANGE MICROCONTROLLERS TIMER MODULES In the next few labs we will look at three timer/counters that are available in the mid-range PIC microcontroller family. You will notice that each of these timer/counters have unique features but also have some characteristics that are common (see Figure 1-3).
6.3 Community Forums and Discussion Groups
- PDF Lab 3 - Interrupts and Timers - grdc.myintegrator.com.au — Lab 3 - Interrupts and Timers Interrupts. Serial port. Periodic timers. Real-time clock. Flexible timer module. Introduction Interrupts are an essential feature of a microcontroller. They enable the software to respond, in a timely fashion, to internal and external hardware events. For example, the reception and transmission of bytes via the ...
- Periodic Interrupts Using Timers Introduction - Texas Instruments — MSP432 microcontroller has four General Purpose Timer Modules called Timer_A. Each timer has one 16-bit timer and seven associated capture/compare registers. In this lab, you will use Timer A0 to create two PWM outputs for the motor that can be used by robot explorer. You will use Timers A2 and A3 later in Module 16 to interface the two ...
- ARM core timer interrupts - Raspberry Pi Forums — ARM core timer interrupts. Thu Feb 27, 2025 12:57 pm . ... CNTV_ELn How are these other 4 interrupts connected in BCM2711? Regards, Rene Barto. renebarto Posts: 7 Joined: Thu Apr 20, 2023 7:36 pm. Re: ARM core timer interrupts. Thu Feb 27, 2025 1:44 pm . ... Community General discussion Announcements Other languages Deutsch
- c - What are the various ways to disable and re-enable interrupts in ... — The standard technique to enforce atomic access to volatile variables shared with ISRs, via "atomic access guards" or "interrupt guards", in particular when running a bare metal, single-threaded cooperative multi-tasking application with no operating system, is as follows: // 1. save interrupt state // 2. disable only the interrupts necessary // You get atomic access to volatile variables ...
- 1.6 Getting Started with Timers - Microchip Technology — This technical brief provides information about the Timers/Counters present on the PIC18 families of microcontrollers. The document describes the application area, the modes of operation and the hardware and software requirements of the Timers/Counters and configurable output or input for internal or external use with the help of the Peripheral Pin Select (PPS).
- TM4C123GH6PM: Spurious timer interrupt - TI E2E support forums — Somewhere in step 1, the timer peripheral is being partly initialized with the sequence of calls: TimerConfigure(), TimerUpdateMode(), TimerPrescaleSet(), TimerLoadSet(), IntPrioritySet(), TimerIntClear(). Later in step 3, when the superloop is running, an event occurs which shall enable the timer and interrupt.
- PDF Chapter 6: Interrupts and Timers - embedded-knowhow.co.uk — Many microcontroller counters cause an interrupt as the counter overflows; this interrupt can be used to record the overflow, and the count can continue in a useful way. The effective range of the counter has been extended. If the counter is just free-running with a continuous clock signal, then the "interrupt
- PDF AN4776 Application note - STMicroelectronics — the TIM1 timer peripheral is shared across the STM32F1 Series, STM32F2 Series and STM32F4 Series, but for the specific case of STM32F30x microcontrollers family, the TIM1 timer peripheral features a bit ri cher features set than the TIM1 present in the other families. The general purpose timers embedded by the STM32 microcontrollers share the same
- How to implement interrupt flags in C, using a Microcontroller? — I have set up a project using a 16-bit Microcontroller called Thunderbird12, similar to the 9s12/Freescale 68HC12 family. It does a few things but mainly turn on an external water pump. Everything works fine except I need to implement an interrupt. I want to be able to stop the motor using an interrupt through a push button.
- Timer Interrupts question - All About Circuits — A microcontroller has a Timer peripheral that can be configured to generate a hardware interrupt every 10 ms. I need to describe an interrupt service routine that maintains real time I.E. ticks, seconds, minutes and hours based on this interrupt. I also need to explain what happens to the MCU...