↓ Skip to main content
  1. Engineering Notes & Articles/

Timers and Interrupts: Stop Using delay() and Master Non-Blocking Programming

·2195 words· loading · loading · ·
Table of Contents
Embedded Systems Fundamentals - This article is part of a series.
Part 5: This Article

Almost everyone learning microcontrollers starts with the same legendary program: turn an LED on, call delay(1000), turn the LED off, then delay(1000) again. Just to prove a board powers up and runs code, this is undeniably handy.

However, the moment your project grows into a real system—say, reading a temperature sensor every 2 seconds, blinking a status LED every 500 ms, driving a stepper motor, and needing to halt within milliseconds the instant an emergency stop button is pressed—a delay()-based program collapses immediately. Buttons feel “deaf,” serial data from sensors gets truncated, and the entire system feels sluggish.

Why does this happen? Because delay() is blocking code that freezes the entire CPU. To level up from copying hobbyist sketches to designing responsive, reliable firmware, you must master three core concepts: non-blocking timing, Hardware Timers, and Interrupts.


Why Is delay() Dangerous in Embedded Systems?
#

When a microcontroller executes delay(2000), the processor isn’t resting while quietly handling other tasks. It is trapped inside an empty spin loop (busy-waiting) for a full 2,000 milliseconds—burning millions of clock cycles just counting down without executing any useful instructions.

During those 2 seconds:

  • The microcontroller cannot check buttons pressed by the user.
  • The microcontroller does not read incoming data from UART, I2C, or SPI—potentially causing a buffer overflow and lost data.
  • The microcontroller cannot update the display or react to hazard signals from limit switches.

A simple analogy: Using delay() is like boiling water in the kitchen and standing frozen staring at the pot for 10 minutes—refusing to answer a ringing phone, refusing to chop vegetables, and refusing to open the door when a package arrives. In reality, you only need to glance at the wall clock occasionally—or set an alarm—while getting other things done.


Step 1: Non-Blocking Timing with the System Tick (millis())
#

The simplest way to stop using delay() is to leverage the internal time counter that runs continuously in the background from the moment the microcontroller boots. In the Arduino ecosystem this function is millis() (and micros() for microseconds); in STM32 HAL it is HAL_GetTick(); in ESP-IDF there is esp_timer_get_time().

Instead of halting the CPU, you simply record the last time a task ran, then check the elapsed difference on every pass of loop() (polling):

unsigned long lastSensorRead = 0;
unsigned long lastLedToggle  = 0;

const unsigned long SENSOR_INTERVAL = 2000; // 2 seconds
const unsigned long LED_INTERVAL    = 500;  // 0.5 seconds

void loop() {
    unsigned long now = millis();

    // Task 1: Check the button continuously with zero blocking!
    if (digitalRead(EMERGENCY_BTN) == LOW) {
        stopAllMotors();
    }

    // Task 2: Blink the LED every 500 ms
    if (now - lastLedToggle >= LED_INTERVAL) {
        lastLedToggle = now;
        toggleStatusLed();
    }

    // Task 3: Read the sensor every 2000 ms
    if (now - lastSensorRead >= SENSOR_INTERVAL) {
        lastSensorRead = now;
        readTemperatureSensor();
    }
}

With this pattern, all three tasks appear to run concurrently without getting in each other’s way. The emergency button is checked thousands of times per second, while the LED and sensor stay right on schedule.

The Timer Rollover (Overflow) Trap
#

Because millis() returns an unsigned long (32-bit), it tops out at $4,294,967,295\text{ ms}$—about 49.7 days—before wrapping back to 0 (rollover).

  • Wrong: if (millis() >= nextRunTime) $\rightarrow$ Can lock up completely for 49 days when rollover occurs.
  • Right: if (now - lastRunTime >= INTERVAL) $\rightarrow$ Thanks to unsigned integer arithmetic, this subtraction is 100% immune to rollover.

Step 2: Understanding Hardware Timers
#

The millis() pattern inside loop() is great for millisecond-level periodic tasks. But what if you need to:

  • Sample an ADC every 100 microseconds (10 kHz) with zero jitter, even while loop() is busy writing to an OLED screen?
  • Count pulses from a high-speed rotary encoder?
  • Generate precision pulse trains for a stepper motor?

For high-precision timing, we cannot rely on a software loop. Instead, we use a dedicated on-chip peripheral called a Hardware Timer.

Anatomy of a Hardware Timer
#

At its core, a Hardware Timer is simply a digital counter that runs autonomously in hardware—independently of the CPU—driven by the microcontroller’s clock. Its three main registers are:

  1. Counter Register (CNT): A register (typically 16-bit or 32-bit) that increments (or decrements) by 1 on each tick.
  2. Prescaler (PSC): A clock frequency divider. Because CPU clocks are very fast (e.g., 80 MHz), a 16-bit counter (max 65,535) would overflow in microseconds. The prescaler slows down the tick rate—for example, dividing by 80 so each timer tick equals exactly 1 microsecond.
  3. Auto-Reload / Period Register (ARR): The upper limit of the count. As soon as the Counter reaches this value, it resets to 0 and triggers an event or interrupt.

The timer trigger frequency ($f_{\text{event}}$) is calculated deterministically with the formula:

$$f_{\text{event}} = \frac{f_{\text{clock}}}{(\text{PSC} + 1) \times (\text{ARR} + 1)}$$

(Note: +1 is used on architectures such as STM32 and ESP32 because registers are zero-indexed.)

Calculation Example: Suppose we use a microcontroller with a timer clock $f_{\text{clock}} = 80\text{ MHz}$ and want to trigger a sample every $1\text{ ms}$ ($f_{\text{event}} = 1000\text{ Hz}$):

  • Set PSC = 79 (divides 80 MHz by 80 $\rightarrow$ timer clock becomes $1\text{ MHz}$, so 1 tick = $1\text{ }\mu\text{s}$).
  • Set ARR = 999 (counts 1,000 times from 0 to 999 $\rightarrow$ exactly $1000\text{ }\mu\text{s} = 1\text{ ms}$).

As a result, the hardware fires a signal every $1.000\text{ ms}$ with rock-solid consistency, no matter how busy the main CPU is.

Other Hardware Timer Capabilities
#

Beyond basic timekeeping, Hardware Timers in modern MCUs power several vital features:

  • PWM Generation: Produces pure hardware PWM signals without touching the CPU.
  • Input Capture: Measures pulse widths or external signal frequencies (e.g., HC-SR04 ultrasonic sensors or RC receiver signals) with sub-microsecond accuracy.
  • Hardware Encoder Mode: Automatically counts quadrature motor encoder pulses without dropping a single step.

Step 3: Understanding Interrupts
#

If polling is checking the front door every five seconds to see if a guest has arrived, an Interrupt is a doorbell. You don’t have to keep walking to the door—just focus on your main work, and the moment the bell rings, pause briefly, open the door, and resume right where you left off.

How the Interrupt Mechanism Works
#

When an important event occurs—either outside the chip or inside an internal peripheral—the hardware sends an interrupt signal to the CPU:

  1. The CPU finishes the machine instruction it is currently executing.
  2. The CPU saves its current execution state (Program Counter and key registers) onto the Stack (context saving).
  3. The CPU immediately jumps to a dedicated function called an ISR (Interrupt Service Routine) that we registered.
  4. Once the ISR finishes, the CPU restores the registers from the Stack and resumes the main program as if nothing happened.

This entire round-trip happens blazingly fast—often in just tens to hundreds of nanoseconds.

Types of Interrupt Sources
#

  • External Interrupt (GPIO / EXTI): Triggered by a voltage transition on a physical pin—configurable for rising edge (RISING), falling edge (FALLING), or both (CHANGE). Ideal for emergency buttons, water flow sensors, or DATA_READY signals from external sensor ICs.
  • Timer Interrupt: Triggered when a Hardware Timer reaches its limit (ARR). Ideal for periodic signal sampling or display multiplexing.
  • Peripheral Interrupt: Triggered when a new byte arrives on UART, an I2C/SPI transfer completes, or an ADC conversion finishes. This prevents missed communication data without forcing the CPU to wait.

Interrupt Priority (NVIC)
#

What if two interrupts fire at the exact same moment—say, an emergency stop button and an incoming UART byte? 32-bit microcontrollers (such as ARM Cortex-M with NVIC — Nested Vectored Interrupt Controller) let us assign priority levels. A higher-priority interrupt is serviced first and can even preempt a lower-priority ISR (interrupt nesting).


5 Golden Rules for Writing ISRs (Interrupt Service Routines)
#

With the power of interrupts comes serious responsibility. A tiny mistake inside an ISR can trigger mysterious crashes, watchdog resets, or corrupted data that are notoriously hard to trace. Stick strictly to these five golden rules:

1. Keep ISRs as Fast and Short as Possible
#

An ISR is no place for heavy math, sending HTTP packets, or waiting on sensor responses. The longer you stay inside an ISR, the longer other interrupts are delayed and the more sluggish the system becomes.

  • Best Pattern (Flag & Defer): Inside the ISR, simply set a flag variable or push a tiny piece of data into a queue (ring buffer), then exit immediately. Let the main loop() handle the heavy lifting.

2. Always Use volatile for Shared Variables
#

If a variable is modified inside an ISR and read inside loop(), declare it with volatile (for example, volatile bool buttonPressed = false;).

Without volatile, an aggressive C/C++ optimizing compiler may assume the variable never changes inside loop() and cache it in a temporary register without ever re-reading it from RAM. Consequently, your main program never notices that the ISR updated it!

3. Never Call Blocking or Non-Reentrant Functions Inside an ISR
#

Things you must avoid inside an ISR:

  • delay() (besides freezing the system, delay() itself often relies on timer interrupts that are disabled while an ISR runs—causing a permanent hang!).
  • Serial.print() / printf() (extremely slow and relies on internal UART interrupts).
  • Blocking I2C/SPI transfers and LCD/OLED screen updates.
  • Dynamic memory allocation (malloc / new / manipulating String objects).

4. Watch Out for Race Conditions & Use Critical Sections
#

On 8-bit microcontrollers (like AVR), reading a multi-byte variable (e.g., a uint32_t counter requiring 4 read instructions) inside loop() can be interrupted by an ISR right after reading the 2nd byte. The result is a corrupted hybrid value (torn read).

The fix is to wrap reads of shared variables in a Critical Section—briefly disabling interrupts, copying the value into a local variable, and re-enabling them:

volatile uint32_t pulseCount = 0;

// Inside ISR (on ESP32, add the IRAM_ATTR attribute)
void IRAM_ATTR onPulseDetected() {
    pulseCount++;
}

// Inside main loop()
uint32_t readSafePulseCount() {
    noInterrupts();               // Enter Critical Section
    uint32_t copy = pulseCount;   // Fast copy to local variable
    interrupts();                 // Exit Critical Section
    return copy;
}

(ESP32-specific note: ISRs must be marked with IRAM_ATTR so their code resides in internal RAM rather than external Flash—accessing Flash while an interrupt is active can trigger a Guru Meditation Error / panic crash.)

5. Never Attach a Raw External Interrupt to a Mechanical Button Without Debouncing
#

Remember the switch bouncing phenomenon from Article 3: a single press of a mechanical button can fire an ISR a dozen times within a few milliseconds. If you still want to use an interrupt for a button, make sure there is a hardware RC filter or a minimum elapsed-time check before raising the flag.


Comparison Summary: When to Use Which?
#

Approach How It Works Timing Accuracy Responsiveness When Should You Use It?
delay() (Blocking) Halts CPU execution in place Low – Medium Very Poor Only for initial startup (setup()), ultra-short hardware pauses (delayMicroseconds), or a first blink test.
millis() Polling (Non-Blocking) Checks elapsed time inside loop() Medium (millisecond level, affected by loop() length) Good Everyday periodic tasks: reading temperature sensors, blinking LEDs, sending cloud updates, software debouncing, timeouts.
Hardware Timer + Interrupt Autonomous peripheral interrupts the CPU at the exact event Very High (down to microseconds, minimal jitter) Very High Precision periodic signal sampling, emergency stops, rotary encoders, flow meters, UART/SPI data reception.

5 Common Mistakes to Avoid
#

  1. Writing Serial.println("Button pressed!") inside an ISR for debugging This is the #1 cause of microcontrollers randomly freezing or rebooting. If you want to verify whether an ISR fired, simply set a flag volatile bool triggered = true; and print the serial message inside loop()—or toggle a GPIO pin and observe the waveform on a logic analyzer/oscilloscope.
  2. Forgetting to reset the flag after handling it in loop() If an ISR sets dataReady = true; and you forget to clear it back to false in loop(), your handler will run nonstop thousands of times per second.
  3. Assuming millis() automatically makes all code non-blocking Using millis() will not save responsiveness if one of your task functions still calls a blocking sensor library (such as sensor.read() waiting 750 ms internally, or an HTTP/Wi-Fi request blocking for a 5-second timeout). Always check whether your libraries offer asynchronous / non-blocking modes.
  4. Comparing timestamps with addition (millis() >= targetTime) Works flawlessly during a 10-minute bench test, then mysteriously locks up after 49 days in the field. Always stick to subtraction: (now - lastTime) >= interval.
  5. Creating too many unnecessary interrupts Not every menu button or slow sensor needs an interrupt. For ordinary human input (like navigation buttons) or room-temperature sensors, periodic polling with millis() or a single 10 ms Timer Interrupt is much cleaner, safer, and more noise-immune than wiring up 6 separate external interrupts.

By leaving delay() behind and combining millis(), Hardware Timers, and Interrupts, you can already build responsive, professional bare-metal systems. However, when your project grows massive—juggling Wi-Fi/MQTT connections, a touchscreen UI, TLS encryption, SD card storage, and actuator control all at once—manually orchestrating dozens of flags and state machines inside a single loop() eventually becomes a maintenance nightmare. That is the moment you need a “project manager” inside your microcontroller: a Real-Time Operating System (RTOS). We will explore when to move from bare-metal to FreeRTOS or Zephyr in Article 6.

Embedded Systems Fundamentals - This article is part of a series.
Part 5: This Article