Interrupts and Timers in Embedded C

Interrupts allow a microcontroller to respond to hardware and software events without continuously polling every peripheral. Timers provide a hardware time base for periodic execution, input capture, output compare, pulse-width modulation (PWM) and timeout measurement.

These features are fundamental to automotive embedded systems. They are used in sensor acquisition, motor control, communication handling, watchdog supervision, actuator control and real-time scheduling. Correct implementation requires bounded response time, carefully designed interrupt service routines (ISRs), safe data exchange and measured timing behavior.

The exact interrupt controller, timer features, register semantics and priority rules depend on the microcontroller. Always confirm implementation details against the target device reference manual and compiler documentation.

1. What happens when an interrupt occurs?

A peripheral raises an interrupt request when an enabled event occurs. The interrupt controller evaluates the request against priority, masking and enable configuration. If the request is eligible, the processor enters the corresponding exception or interrupt handler.

A simplified sequence is:

Rendering diagram...

The interrupt source and interrupt controller have different responsibilities:

  • Peripheral: Detects the event and usually sets a status or interrupt flag.
  • Interrupt controller: Applies enable, masking and priority rules, and selects an eligible request.
  • CPU: Saves the required execution context, enters the handler and later restores the interrupted context.
  • ISR: Performs the required bounded service for that event.

The order in which a status flag must be cleared is peripheral-specific. Some devices use write-one-to-clear registers; others require a read sequence, a data-register access or a particular acknowledgement order. A wrong sequence can cause repeated interrupts or lost events.

1.1 Pending, masked and disabled interrupts

These terms are related but not interchangeable:

  • Enabled: The relevant peripheral or interrupt-controller enable permits the request to be considered.
  • Masked: A global or priority-specific mask prevents the CPU from servicing the request at that time.
  • Pending: The request has occurred and is awaiting service, subject to the device's interrupt semantics.
  • Cleared: The peripheral/controller state indicating the request has been serviced or withdrawn has been cleared.

A masked interrupt may remain pending and execute after unmasking. Some peripherals instead coalesce repeated events into one status bit. Others have FIFOs or counters that preserve more event information. Check the device documentation rather than assuming every occurrence is queued.

1.2 Priority and nesting

When multiple interrupt requests are eligible, the interrupt controller applies its configured priority rules. Depending on the architecture and configuration, a higher-priority interrupt may pre-empt a lower-priority ISR. Equal-priority requests may be handled according to controller-specific arbitration.

Nested interrupts can improve response to urgent events, but they also increase complexity:

  • Stack and context-save requirements increase.
  • Shared data may be accessed by multiple interrupt contexts.
  • A lower-priority ISR can be interrupted at points that were not expected by its author.
  • Excessive high-priority activity can starve lower-priority handlers or tasks.

Priority numbering is architecture-specific: on some controllers a lower numeric value represents a higher priority. Never infer priority meaning from the number alone.

2. Interrupt service routine design

An ISR should perform only the work that must happen immediately in interrupt context. Longer processing should normally be deferred to a task or main-loop context.

A typical ISR may:

  1. Identify and acknowledge the interrupt source using the documented sequence.
  2. Capture essential data, such as a timer value or received byte.
  3. Update a bounded counter or publish an event.
  4. Move data into a preallocated queue or ring buffer, if the design supports it.
  5. Notify a task using an RTOS API explicitly documented as safe from ISR context.

Avoid the following inside an ISR unless the platform explicitly provides a bounded and safe mechanism:

  • Blocking calls, sleeps or waits.
  • Dynamic memory allocation.
  • Long loops or complex calculations.
  • Formatted logging or slow peripheral output.
  • Waiting for another interrupt or task.
  • Calling ordinary RTOS APIs that are not ISR-safe.
  • Taking a mutex that can block.

Long ISRs increase interrupt latency for other sources and make worst-case response-time analysis harder. A short ISR is not automatically safe, however: its execution time, nesting behavior and shared-data accesses still need to be analyzed.

2.1 Example: capture an event and defer processing

The following is illustrative C. It assumes the device-specific handler has a valid way to read the ADC result and acknowledge the interrupt. The hardware-specific operations are represented by comments.

#include <stdint.h>

static volatile uint16_t g_latest_sample;
static volatile uint8_t  g_sample_ready;

void ADC_IRQHandler(void)
{
    uint16_t sample;

    /* Read the conversion result and acknowledge the source
       using the sequence required by the target MCU. */
    sample = ADC_ReadResult();
    ADC_AcknowledgeInterrupt();

    g_latest_sample = sample;
    g_sample_ready = 1U;
}

void application_task(void)
{
    uint16_t sample;

    if (g_sample_ready != 0U)
    {
        /* Protect this exchange if the target cannot guarantee
           an atomic read/clear sequence for the shared state. */
        sample = g_latest_sample;
        g_sample_ready = 0U;

        process_sample(sample);
    }
}

This is a latest-value notification pattern, not a lossless event queue. If another ADC interrupt occurs before the task consumes the previous sample, the new value can replace the old one. The flag can indicate that data is available, but it does not count how many conversions occurred.

If every sample must be retained, use a properly designed queue, ring buffer or DMA-backed buffer with explicit producer/consumer ownership and overflow handling.

3. Shared data, volatile and atomicity

A variable accessed by both an ISR and foreground code may require volatile so that the compiler performs the observable accesses according to the implementation's rules. However, volatile is not a general synchronization primitive.

It does not, by itself:

  • Make a multi-byte read or write atomic.
  • Prevent a read-modify-write race.
  • Provide mutual exclusion.
  • Create a general inter-thread happens-before relationship.
  • Guarantee that a multi-field data structure is observed consistently.

The correct approach depends on the processor, compiler, C language version and execution model.

3.1 Common exchange patterns

PatternSuitable useImportant condition
Single naturally atomic flagCoalesced notificationConfirm access atomicity and accept that events may merge
CounterCount occurrencesProtect against concurrent read-modify-write and overflow
Short critical sectionSnapshot or update shared stateKeep interrupt-disabled time bounded
Atomic operationSupported lock-free shared stateConfirm the operation is lock-free and ISR-safe on the target
Single-producer/single-consumer ring bufferPreserve a stream of events or samplesDefine ownership, index atomicity and full/empty behavior
DMA buffer with ownership handoffHigh-rate data transferHandle cache coherency, alignment and buffer lifetime where relevant

For an RTOS, use the documented ISR-safe queue, semaphore or notification mechanism. Do not call a task-context API from an ISR merely because it appears to work in a simple test.

3.2 Event coalescing and lost notifications

A one-bit flag represents “one or more events occurred,” not necessarily “exactly one event occurred.” If the producer sets the flag several times before the consumer clears it, those occurrences collapse into one pending indication.

Use a counter when the number of events matters, and a queue when each event carries data or order matters. Both approaches still require overflow/full-buffer behavior to be defined and tested.

4. Hardware timer fundamentals

A hardware timer is a counter driven by a clock source. It may count upward, downward or in both directions. When the counter reaches a configured value or another timer event occurs, the peripheral can set a flag, request an interrupt, capture a value or change an output pin.

Common timer features include:

  • Prescaler or clock divider.
  • Counter register.
  • Auto-reload or period register.
  • Compare registers.
  • Capture registers.
  • Update, overflow and capture flags.
  • PWM output channels.
  • One-shot or continuous operating modes.

The available features and their interactions vary across microcontrollers.

4.1 Timer operating modes

ModeTypical useKey considerations
Periodic updateScheduler tick or periodic samplingClock source, prescaler, reload and interrupt service time
Input capturePulse width, period or speed measurementEdge selection, capture register and overflow handling
Output compareSchedule an output transition at a timer countCompare update timing and counter rollover
PWMMotor, valve, pump or actuator controlPeriod, duty cycle, polarity, dead time and output routing
One-shotTimeout or pulse generationStart, expiry, re-arm and cancellation behavior

4.2 Timer period calculation

For a common edge-aligned up-counter, a simplified timer period is:

T=P×NftimerT = \frac{P \times N}{f_{\text{timer}}}

where:

  • TT is the timer period in seconds.
  • PP is the prescaler division factor.
  • NN is the number of timer ticks in one period.
  • ftimerf_{\text{timer}} is the timer input clock in hertz.

The actual register formula may use prescaler-register value plus one and auto-reload-register value plus one. Center-aligned counting, clock multipliers, timer chaining and synchronization can change the calculation. Use the exact formula from the target reference manual.

5. Deriving a periodic timer interrupt

Consider an illustrative timer with:

  • Timer input clock: 80 MHz.
  • Prescaler division factor: 80.
  • Desired interrupt frequency: 1 kHz.

The counter clock is:

fcounter=80 000 00080=1 000 000 Hzf_{\text{counter}} = \frac{80\,000\,000}{80} = 1\,000\,000\ \text{Hz}

The counter tick is therefore 1 microsecond. A 1 kHz interrupt has a 1 millisecond period, requiring 1000 timer ticks.

If the timer counts from zero through the auto-reload value inclusively, the reload value is 999.

/* Illustrative register-level pseudocode.
   Adapt to the target MCU and its timer driver. */

timer_set_prescaler(TIMER1, 79U);       /* Divide by 80 if register is P - 1 */
timer_set_auto_reload(TIMER1, 999U);    /* 1000 counts: 0 through 999 */
timer_clear_update_flag(TIMER1);
timer_enable_update_interrupt(TIMER1);
timer_start(TIMER1);

This configuration is only correct if the device uses the assumed register semantics and the timer input really is 80 MHz. On some MCUs, the timer clock differs from the peripheral bus clock or changes with clock-tree configuration.

Verify the result by measuring a timer output or toggling a GPIO at a controlled point in the handler. Consider clock tolerance, synchronization and measurement-tool resolution.

6. Input capture: measuring an external signal

Input capture stores the timer count when a configured input edge occurs. It is useful for measuring pulse width, period, frequency and rotational speed.

For two captured rising-edge timestamps C1C_1 and C2C_2, the elapsed timer ticks can be calculated using unsigned modular subtraction, provided the measurement interval is shorter than one complete counter wrap:

ΔC=(C2−C1) mod 2W\Delta C = (C_2 - C_1) \bmod 2^W

where WW is the counter width.

The measured period is:

Tsignal=ΔCfcounterT_{\text{signal}} = \frac{\Delta C}{f_{\text{counter}}}

For example, if a 1 MHz timer records a difference of 2500 ticks, the measured period is 2.5 ms, corresponding to 400 Hz.

For a rotating target with a known number of pulses per revolution, frequency can be converted to rotational speed. The conversion must account for the sensor's pulse count and the system's mechanical reference.

Input capture avoids the software timing uncertainty of reading a timer after an ISR begins. However, capture-register overrun, edge noise, timer rollover and input synchronization still need to be considered.

7. Output compare and PWM

7.1 Output compare

In output-compare mode, the timer compares its current count with a configured compare value. A match can set a flag, request an interrupt or change an output pin, depending on the peripheral.

Output compare is useful for scheduling an action relative to a timer time base. For periodic scheduling, software may advance the compare value by a fixed interval rather than scheduling relative to the time at which the ISR happens. This can reduce accumulated drift from variable ISR latency, provided missed compare events and counter rollover are handled correctly.

7.2 Pulse-width modulation

PWM controls the proportion of each period for which an output is active. The duty cycle is:

D=TonTperiod×100%D = \frac{T_{\text{on}}}{T_{\text{period}}} \times 100\%

For example, a 25% duty cycle means the output is active for one quarter of the PWM period, assuming active-high polarity.

Automotive uses include motor and pump control, valve actuation, thermal management and other actuator interfaces. The relationship between duty cycle and physical output is application-specific; it should not be assumed to be linear.

For power electronics and motor control, also consider complementary outputs, dead time, safe shutdown states, synchronization, update-at-boundary behavior and protection mechanisms. These features are MCU- and application-specific.

8. Interrupt latency, execution time, jitter and deadlines

These timing terms describe different parts of real-time behavior:

  • Interrupt latency: Time from the interrupt event to the start of ISR execution.
  • ISR execution time: Time spent executing the handler.
  • Response time: Time from the event to the required response or completion.
  • Jitter: Variation in the timing of an event, task start or output relative to its intended schedule.
  • Deadline: The latest time by which an operation must complete.
  • Worst-case execution time (WCET): A defensible upper bound on execution time under the defined conditions and assumptions.

A periodic 1 ms timer event does not guarantee that the associated task completes within 1 ms. The event may be delayed by interrupt masking, higher-priority handlers, exception-entry overhead or other platform effects. The task may then wait for CPU time or shared resources.

8.1 Sources of latency and jitter

Depending on the MCU and software architecture, relevant sources include:

  • Interrupts disabled by critical sections.
  • Higher-priority ISR execution and nesting.
  • Pending requests and controller arbitration.
  • CPU load and scheduling delays.
  • Memory, bus or peripheral contention.
  • Cache and flash wait-state effects, where applicable.
  • DMA activity and shared-resource access.
  • RTOS scheduling and synchronization overhead.
  • Variable execution paths in the ISR or task.

8.2 Measuring timing

For a periodic control function, capture timestamps at meaningful points:

  1. Hardware event or timer trigger.
  2. ISR entry.
  3. Completion of the ISR's immediate work.
  4. Task start, if processing is deferred.
  5. Output update or actuator command.

Use a timer capture channel, trace facility or GPIO measurement as appropriate. GPIO toggling is useful but adds instrumentation overhead and may not reveal all internal timing.

Measure under representative worst-case CPU and communication load. Record minimum, maximum and distribution where useful, but do not treat a finite set of observations as proof of WCET unless the analysis method supports that conclusion.

9. Automotive example: periodic sensor acquisition

Consider an ECU that samples a sensor every millisecond and uses the latest value in a control task.

A possible design is:

  1. A hardware timer triggers the ADC conversion at the required sampling interval.
  2. The ADC raises an interrupt when conversion completes.
  3. The ADC ISR reads or acknowledges the result using the documented peripheral sequence.
  4. The ISR publishes the sample into a bounded buffer or updates a latest-value record.
  5. A periodic task consumes the sample, performs plausibility checks and calculates the control response.
  6. The task updates the actuator command before its deadline.

The design must define what happens if:

  • An ADC conversion completes while the previous sample is still being processed.
  • The task is delayed and multiple samples accumulate.
  • The ADC reports an overrun.
  • A sensor value is outside the valid range.
  • The timer or ADC interrupt is delayed.
  • The control task misses its deadline.

The correct response depends on the safety concept and system requirements. For some signals, the latest value may be sufficient; for others, every sample or its timestamp must be retained. A missed deadline may require a diagnostic, degraded mode or safe-state response defined by the system design.

10. Counter overflow and elapsed-time measurement

A timer counter eventually wraps around. Software that measures elapsed time must account for this behavior.

For an unsigned WW-bit counter, subtraction naturally wraps modulo 2W2^W in C. For example:

#include <stdint.h>

uint32_t elapsed_ticks(uint32_t start, uint32_t now)
{
    return (uint32_t)(now - start);
}

This technique is valid when the elapsed interval is known to be less than one full counter wrap and the values are read consistently. It does not distinguish an interval of zero from an interval of one or more complete wraps.

For a 32-bit timer running at 1 MHz, one full wrap takes approximately 4294.97 seconds, or about 71.6 minutes. If intervals can exceed one wrap, extend the time base with an overflow counter or use a wider hardware/software time source with a correctly synchronized read procedure.

When a timer overflow interrupt and a counter read can occur concurrently, a simple read of the counter and overflow flag may produce an inconsistent timestamp. Use a target-specific coherent-read method.

11. Common defects and diagnosis

DefectTypical symptomPrevention or test
Incorrect flag-clear sequenceISR repeats or an event is lostFollow the peripheral reference manual; test back-to-back events
Excessive ISR processingJitter or delayed response elsewhereDefer work and measure ISR execution time
Non-atomic shared accessIntermittent corrupted valuesUse atomic or protected exchange appropriate to the target
Event flag used for a lossless streamMissing samples or eventsUse a counter or queue with overflow handling
Timer clock miscalculationIncorrect period or driftVerify the clock tree and register semantics
Counter rollover ignoredIncorrect elapsed-time resultUse modular arithmetic with bounded intervals or extend the time base
Priority starvationLow-priority work misses deadlinesAnalyze priority assignment and execution budgets
Capture overrunMissing or stale measurementsMonitor overcapture flags and define recovery
Excessive interrupt maskingHigh and variable latencyBound critical sections and measure worst-case response
PWM update at an unsafe pointOutput glitches or unexpected pulseUse documented preload/synchronization features

12. Verification and test strategy

Interrupt and timer behavior should be verified under nominal and stressed conditions.

A useful test set includes:

  1. Basic trigger: Confirm that each configured source generates the expected interrupt.
  2. Period accuracy: Measure timer period and frequency against the configured clock.
  3. Back-to-back events: Confirm that events are neither lost nor unintentionally merged.
  4. Priority and nesting: Exercise simultaneous requests and verify the intended arbitration behavior.
  5. Latency and jitter: Measure response under representative CPU, bus and communication load.
  6. Shared-data integrity: Stress producer/consumer exchanges and check for corruption or missed events.
  7. Overflow and rollover: Test timer wrap, counter overflow and long-duration operation.
  8. Fault handling: Exercise peripheral error flags, capture overrun and interrupt storms where safely possible.
  9. Deadline behavior: Verify the defined response when a task or control action cannot complete on time.
  10. Regression: Repeat timing and functional checks after changes to clock configuration, compiler options, ISR code or task priorities.

For each test, define preconditions, stimulus, expected result, timeout, observation point and evidence to retain. Record the MCU revision, clock configuration, compiler/build options and relevant software baseline.

13. Practical design checklist

  • Every interrupt source has a documented trigger and acknowledgement sequence.
  • Priority, masking, nesting and pending behavior are understood.
  • ISR execution is bounded and avoids blocking operations.
  • Work that can be deferred is performed in task or main-loop context.
  • Shared data ownership and atomicity are defined.
  • Event coalescing and buffer overflow behavior are explicit.
  • Timer clock, prescaler and reload calculations are verified.
  • Capture, compare, PWM and rollover behavior are tested where used.
  • Latency, jitter, WCET assumptions and deadline margins are assessed.
  • Watchdog, diagnostic and safe-state behavior follow system requirements.
  • Hardware, software and configuration versions are traceable.

Interrupt priority numbers, flag semantics, atomic access guarantees and timer register formulas are MCU-specific. The examples in this article are instructional patterns, not drop-in production firmware.

14. Key takeaways

  • Interrupts let the MCU respond to events without continuous polling.
  • The peripheral, interrupt controller, CPU and ISR each have distinct roles.
  • ISRs should be short, bounded and limited to work that must happen immediately.
  • volatile does not provide atomicity or general synchronization.
  • Timers support periodic events, input capture, output compare, PWM and timeouts.
  • Timer calculations must use the actual clock tree and device register semantics.
  • Latency, jitter, execution time and deadlines are different timing properties.
  • Counter rollover, event coalescing and buffer overflow must be designed explicitly.
  • Timing should be measured under representative load and linked to requirements.

15. Check your understanding

  1. What is the difference between an interrupt request being enabled, masked and pending?
  2. Why should lengthy processing normally be deferred from an ISR?
  3. Why is volatile insufficient for protecting a shared multi-byte variable?
  4. What is the difference between input capture and output compare?
  5. For an 80 MHz timer clock divided by 80, how many timer ticks are needed for a 1 ms period?
  6. Why can a 1 ms periodic interrupt fail to produce a control response within 1 ms?
  7. Under what condition is unsigned modular subtraction suitable for measuring elapsed timer ticks?
  8. Why might a one-bit event flag be unsuitable for ADC sample acquisition?

Suggested answers

  1. Enabled permits a source to request service; masked temporarily prevents service; pending indicates an event is awaiting handling according to the device's semantics.
  2. Long processing increases latency for other interrupts and makes worst-case response harder to bound.
  3. volatile does not guarantee atomic access, mutual exclusion or a consistent multi-field snapshot.
  4. Input capture records a timer value at an input event; output compare detects when the counter reaches a programmed value and can trigger an action.
  5. The divided clock is 1 MHz, so 1000 ticks are required for 1 ms. With inclusive zero-based counting, the reload value is 999.
  6. Interrupt masking, higher-priority work, ISR execution, task scheduling and other delays can consume the available time.
  7. When the measured interval is known to be shorter than one complete counter wrap and the counter values are read consistently.
  8. Repeated events can collapse into one flag indication, losing the count and possibly the individual sample values.

Related articles