Ugenz Academy/IoT Tutorial

Timers Interrupts And Millis

11 min read2,192 words

Reading progress

Keep learning

ESP32 — Timers, Interrupts and millis()

This topic is very important for building real-time ESP32 projects.

You will learn how ESP32 can:

  • Run something after a certain time
  • Repeat an action every few seconds
  • Detect a button immediately
  • Handle sensor events
  • Run multiple tasks without blocking the program
  • Create non-blocking LED, sensor, motor and IoT logic

The three important concepts are:

Timers Interrupts millis()

1. Why delay() Can Become a Problem

You have already used:

delay(1000);

This means:

Wait for 1000 milliseconds before continuing.

For a simple LED:

digitalWrite(LED_PIN, HIGH); delay(1000); digitalWrite(LED_PIN, LOW); delay(1000);

This works.

But imagine your ESP32 needs to do this:

LED → Blink PIR → Detect motion Button → Check immediately Temperature → Read Wi-Fi → Communicate Web server → Respond

If you use long delay() calls everywhere, the program becomes less responsive.


2. What Happens During delay()?

Suppose:

delay(5000);

The program waits for 5 seconds.

Conceptually:

Start ↓ delay(5000) ↓ WAIT ↓ 5 seconds ↓ Continue

During this time, your own code is not doing its normal loop work.

That's why we often use:

millis()

instead.


3. What is millis()?

millis() returns the number of milliseconds that have passed since the ESP32 started running the current program.

For example:

millis()

might return:

0 100 500 1000 5000 10000

So:

ESP32 starts ↓ 0 ms ↓ 1000 ms ↓ 2000 ms ↓ 3000 ms

4. Basic millis() Example

void setup() { Serial.begin(115200); } void loop() { Serial.println(millis()); }

You may see:

0 12 24 36 ... 1000 1012 1024

The exact values depend on execution timing.


5. Using millis() as a Timer

Suppose we want to print a message every 1 second.

unsigned long previousTime = 0; void setup() { Serial.begin(115200); } void loop() { unsigned long currentTime = millis(); if (currentTime - previousTime >= 1000) { previousTime = currentTime; Serial.println("1 second passed"); } }

Output:

1 second passed 1 second passed 1 second passed ...

6. Understanding the Logic

This line:

if (currentTime - previousTime >= 1000)

means:

Has at least 1000 milliseconds passed?

Example:

previousTime = 5000 currentTime = 6000 6000 - 5000 = 1000

Therefore:

1000 >= 1000

✅ Run the task.

Then:

previousTime = currentTime;

The timer starts counting the next interval.


7. Why unsigned long?

Use:

unsigned long

for storing millis() values.

Example:

unsigned long previousTime = 0; unsigned long currentTime;

This is the standard type used with Arduino-style millis() timing.


8. Non-Blocking LED Blink

Instead of:

digitalWrite(LED_PIN, HIGH); delay(1000); digitalWrite(LED_PIN, LOW); delay(1000);

Use:

#define LED_PIN 2 unsigned long previousTime = 0; bool ledState = false; void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { unsigned long currentTime = millis(); if (currentTime - previousTime >= 1000) { previousTime = currentTime; ledState = !ledState; digitalWrite(LED_PIN, ledState); } }

Now the ESP32 can continue running other code between LED changes.


9. Why This Is Better

With delay():

LED ↓ WAIT ↓ LED ↓ WAIT

With millis():

LED timer ────────────────┐ Sensor ──────────────────┤ Button ──────────────────┤ Wi-Fi ───────────────────┤ Web server ───────────────┤ ↓ ESP32

The loop() keeps running.


10. Multiple Tasks with millis()

This is one of the most useful ESP32 programming techniques.

Suppose:

LED → every 1 second Sensor → every 2 seconds Serial → every 5 seconds

You can do:

unsigned long ledTime = 0; unsigned long sensorTime = 0; unsigned long serialTime = 0; void loop() { unsigned long now = millis(); if (now - ledTime >= 1000) { ledTime = now; // LED task } if (now - sensorTime >= 2000) { sensorTime = now; // Sensor task } if (now - serialTime >= 5000) { serialTime = now; // Serial task } }

Conceptually:

ESP32 LOOP │ ┌───────────┼───────────┐ ↓ ↓ ↓ 1 sec 2 sec 5 sec ↓ ↓ ↓ LED Sensor Message

11. Practical Example

Let's make:

LED → Blink every 1 second LDR → Read every 2 seconds Serial → Status every 5 seconds
#define LED_PIN 2 #define LDR_PIN 34 unsigned long ledTimer = 0; unsigned long sensorTimer = 0; unsigned long statusTimer = 0; bool ledState = false; void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); } void loop() { unsigned long now = millis(); // LED if (now - ledTimer >= 1000) { ledTimer = now; ledState = !ledState; digitalWrite(LED_PIN, ledState); } // Sensor if (now - sensorTimer >= 2000) { sensorTimer = now; int value = analogRead(LDR_PIN); Serial.print("LDR: "); Serial.println(value); } // Status if (now - statusTimer >= 5000) { statusTimer = now; Serial.println("ESP32 is running..."); } }

There is no long blocking delay().


12. What is an Interrupt?

An interrupt allows the ESP32 to react to an event immediately.

Normally:

loop() ↓ check sensor ↓ check button ↓ check sensor ↓ check button

With an interrupt:

ESP32 doing something ↓ EVENT OCCURS ↓ INTERRUPT! ↓ Handle event ↓ Return to program

It's like someone calling you while you are working.


13. Real-Life Example

Imagine you're studying.

You → studying

Then:

Phone rings ↓ You stop ↓ Answer phone ↓ Finish call ↓ Continue studying

The phone call is like an interrupt.


14. GPIO Interrupt

ESP32 can trigger an interrupt when a GPIO changes state.

For example:

Button │ ↓ GPIO 4 │ ↓ Interrupt │ ↓ Function runs

15. Basic Interrupt Example

#define BUTTON_PIN 4 #define LED_PIN 2 volatile bool buttonPressed = false; void IRAM_ATTR buttonISR() { buttonPressed = true; } void setup() { pinMode(BUTTON_PIN, INPUT_PULLUP); pinMode(LED_PIN, OUTPUT); attachInterrupt( digitalPinToInterrupt(BUTTON_PIN), buttonISR, FALLING ); } void loop() { if (buttonPressed) { buttonPressed = false; digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } }

16. What is attachInterrupt()?

Syntax:

attachInterrupt( digitalPinToInterrupt(pin), function, mode );

Example:

attachInterrupt( digitalPinToInterrupt(BUTTON_PIN), buttonISR, FALLING );

It tells ESP32:

When this GPIO detects the specified event, run this interrupt function.


17. Interrupt Trigger Modes

Common modes include:

RISING

LOW → HIGH
______/‾‾‾‾

FALLING

HIGH → LOW
‾‾‾‾\______

CHANGE

Any transition:

LOW → HIGH

or:

HIGH → LOW

HIGH

Interrupt while the pin is HIGH.

This mode requires more care and is not appropriate for many simple button applications.


18. What is volatile?

You may have noticed:

volatile bool buttonPressed = false;

volatile tells the compiler:

This variable can change unexpectedly outside the normal flow of the program.

Interrupt routines are a common reason to use volatile.

For example:

volatile bool eventDetected = false;

19. What Should an ISR Do?

ISR means:

Interrupt Service Routine

Example:

void IRAM_ATTR buttonISR() { buttonPressed = true; }

Keep it very short.

Good:

buttonPressed = true;

Avoid doing heavy work inside an ISR, such as:

❌ delay() ❌ Serial printing ❌ long calculations ❌ complex library calls ❌ network requests

Instead:

Interrupt ↓ Set flag ↓ Return quickly ↓ loop() ↓ Perform actual work

20. Best Interrupt Pattern

volatile bool event = false; void IRAM_ATTR interruptFunction() { event = true; } void loop() { if (event) { event = false; // Do actual work here } }

This is a very useful pattern.


21. PIR + Interrupt

A PIR sensor can generate an event when motion occurs.

Concept:

PIR ↓ GPIO ↓ Interrupt ↓ Set motionDetected = true ↓ loop() ↓ Turn light ON

Example:

#define PIR_PIN 27 #define LED_PIN 2 volatile bool motionDetected = false; void IRAM_ATTR motionISR() { motionDetected = true; } void setup() { pinMode(PIR_PIN, INPUT); pinMode(LED_PIN, OUTPUT); attachInterrupt( digitalPinToInterrupt(PIR_PIN), motionISR, RISING ); } void loop() { if (motionDetected) { motionDetected = false; digitalWrite(LED_PIN, HIGH); } }

22. Interrupt + millis()

These two concepts work very well together.

Suppose a button triggers an interrupt, but you want the LED to stay ON for 5 seconds.

Don't do this:

void loop() { if (buttonPressed) { digitalWrite(LED_PIN, HIGH); delay(5000); } }

Instead:

#define BUTTON_PIN 4 #define LED_PIN 2 volatile bool buttonPressed = false; unsigned long ledStartTime = 0; bool ledActive = false; void IRAM_ATTR buttonISR() { buttonPressed = true; } void setup() { pinMode(BUTTON_PIN, INPUT_PULLUP); pinMode(LED_PIN, OUTPUT); attachInterrupt( digitalPinToInterrupt(BUTTON_PIN), buttonISR, FALLING ); } void loop() { unsigned long now = millis(); if (buttonPressed) { buttonPressed = false; digitalWrite(LED_PIN, HIGH); ledActive = true; ledStartTime = now; } if (ledActive && now - ledStartTime >= 5000) { digitalWrite(LED_PIN, LOW); ledActive = false; } }

Now the ESP32 can continue doing other things during those 5 seconds.


23. Hardware Timers

ESP32 also has hardware timer peripherals.

These can be used when you need more precise or hardware-based timing than a simple millis() task scheduler.

Conceptually:

Software timing: millis() ↓ loop() ↓ check time Hardware timer: Hardware timer ↓ Event/ISR ↓ Your code

The exact timer APIs differ between Arduino-ESP32 versions and ESP32 chip families, so when using hardware timers, check the API supported by your installed core and exact chip.

For most beginner projects, millis() is enough.


24. millis() vs Hardware Timer

Featuremillis()Hardware Timer
DifficultyEasyMore advanced
Main useTask schedulingPrecise timing/events
Uses loopYesCan trigger timer events
Good forLEDs, sensors, periodic tasksAdvanced timing
Beginner friendly⭐⭐⭐⭐⭐⭐⭐⭐

Start with millis().

Learn hardware timers when you need them.


25. delay() vs millis()

delay()

delay(1000);

Simple but blocking.

Task ↓ WAIT ↓ WAIT ↓ Continue

millis()

if (millis() - previous >= 1000)

Non-blocking timing.

Task A Task B Task C Task A Task B Task C

The ESP32 continues running its loop.


26. A Real IoT Example

Imagine your smart-home project has:

PIR LDR DHT22 Relay LED Buzzer Wi-Fi

You could schedule:

Every 100 ms ↓ Check buttons Every 500 ms ↓ Check PIR Every 1 sec ↓ Update LED Every 2 sec ↓ Read DHT22 Every 5 sec ↓ Send IoT data Interrupt ↓ Emergency/security event

This is much closer to how a real embedded application is structured.


27. Multiple Timers — Full Example

#define LED_PIN 2 #define PIR_PIN 27 #define LDR_PIN 34 unsigned long ledTimer = 0; unsigned long sensorTimer = 0; unsigned long statusTimer = 0; bool ledState = false; void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(PIR_PIN, INPUT); } void loop() { unsigned long now = millis(); // LED every 1 second if (now - ledTimer >= 1000) { ledTimer = now; ledState = !ledState; digitalWrite(LED_PIN, ledState); } // Sensors every 2 seconds if (now - sensorTimer >= 2000) { sensorTimer = now; int pir = digitalRead(PIR_PIN); int ldr = analogRead(LDR_PIN); Serial.print("PIR: "); Serial.print(pir); Serial.print(" | LDR: "); Serial.println(ldr); } // Status every 5 seconds if (now - statusTimer >= 5000) { statusTimer = now; Serial.println("ESP32 system running..."); } }

This one program has multiple independent schedules.


28. Important millis() Technique

Prefer:

if (now - previous >= interval)

instead of:

if (now >= previous + interval)

The subtraction pattern is the standard robust approach for handling the rollover behavior of an unsigned millisecond counter.


29. millis() Rollover

millis() does not increase forever.

Eventually, the counter wraps around.

That's why this:

if (now - previous >= interval)

is preferred.

Using an unsigned type such as:

unsigned long

and subtraction makes timing code much more robust across rollover.

You normally don't need to worry about it in small projects, but it's an important professional programming habit.


30. The Three Concepts Together

ESP32 TIMING │ ┌───────────────┼────────────────┐ │ │ │ ↓ ↓ ↓ millis() Interrupts Timers │ │ │ Periodic Immediate Precise/ tasks events hardware │ │ │ ↓ ↓ ↓ Sensors Button Advanced LEDs PIR control Wi-Fi Alarm timing

🧠 Easy Way to Remember

delay()

Wait

delay(1000);

millis()

Check how much time has passed

if (millis() - previous >= 1000)

Interrupt

React immediately to an event

attachInterrupt(...);

Hardware Timer

Use a hardware timing peripheral for advanced/precise timing


Key Points

millis() ↓ Non-blocking timing Interrupt ↓ Event-driven response Timer ↓ Precise/periodic hardware timing

For beginner and intermediate ESP32 projects, master millis() first, then learn interrupts, and finally move into hardware timers and more advanced real-time techniques.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy