In this tutorial, you’ll learn how to use the ESP32 timer interrupt and the ESP32 hardware timers in Arduino IDE with the new Arduino-ESP32 core 3.x API. We’ll discuss how the ESP32 timers work, how to set the timer interrupt period with timerBegin() and timerAlarm(), and how to start, stop, and restart a timer, generate a one-shot pulse, run multiple timers, and measure time between events with a timer.
Then, we’ll build 7 ESP32 timer example projects, and every one of them is tested on my bench with an oscilloscope. Along the way, you’ll see the real limits of the ESP32 timers that the official documentation gets wrong (the minimum timerBegin() frequency and what reload_count really does), and we’ll fix the compile errors you get when old ESP32 timer code meets the new core 3.x. Without further ado, let’s get right into it!
ESP32 Timer Interrupt Example (Arduino Core 3.x)
To get a periodic ESP32 timer interrupt in Arduino, you need 3 function calls in the setup(): timerBegin(1000000) to start a hardware timer that ticks at 1MHz (1 tick = 1µs), timerAttachInterrupt() to attach your ISR function, and timerAlarm(timer, 50000, true, 0) to fire the interrupt every 50,000 ticks (50ms) with auto-reload. Here is an LED toggle on GPIO21 every 50ms:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* * LAB Name: ESP32 Timer Interrupt Example (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define LED_PIN 21 hw_timer_t *Timer0_Cfg = NULL; void IRAM_ATTR Timer0_ISR() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } void setup() { pinMode(LED_PIN, OUTPUT); Timer0_Cfg = timerBegin(1000000); // Timer Tick Rate = 1MHz (1 tick = 1us) timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR); // Attach The ISR Function To The Timer timerAlarm(Timer0_Cfg, 50000, true, 0); // Alarm Every 50,000 ticks (50ms), Auto-Reload ON } void loop() { // Do Nothing! } |
To change the interrupt period, change the alarm value: the period is the alarm value divided by the timer frequency. So with a 1MHz timer, timerAlarm(Timer0_Cfg, 1000, true, 0) fires every 1ms, and timerAlarm(Timer0_Cfg, 1000000, true, 0) fires every 1 second.
Note: All examples in this tutorial are tested with: ESP32 DevKit V1 (ESP32-WROOM-32), Arduino-ESP32 core 3.3.12, Arduino IDE 2.x. If your old ESP32 timer code stopped compiling with too many arguments to function 'hw_timer_t* timerBegin(uint32_t)', jump to the core 3.x changes section.
How Many Timers Does ESP32 Have?
The ESP32 has 4 hardware timers (general-purpose timers in 2 groups of 2). Each one is a 64-bit up-counter with a 16-bit clock divider (prescaler) and an alarm that can trigger an interrupt and auto-reload the counter. The newer ESP32 chips have fewer or narrower timers. Here are the numbers for each chip, from Espressif’s GPTimer documentation and the timerBegin() source code of the Arduino core 3.3.12:
| Chip | Hardware Timers | Counter Width | Timer Clock Sources | timerBegin() Frequency Range |
|---|---|---|---|---|
| ESP32 | 4 | 64-bit | APB 80MHz | 1,221Hz – 40MHz |
| ESP32-S2 | 4 | 64-bit | APB 80MHz, XTAL 40MHz | 611Hz – 40MHz |
| ESP32-S3 | 4 | 54-bit | APB 80MHz, XTAL 40MHz | 611Hz – 40MHz |
| ESP32-C3 | 2 | 54-bit | APB 80MHz, XTAL 40MHz | 611Hz – 40MHz |
| ESP32-C6 | 2 | 54-bit | PLL 80MHz, XTAL 40MHz, RC_FAST | Up to 40MHz |
| ESP32-H2 | 2 | 54-bit | PLL 48MHz, XTAL 32MHz, RC_FAST | Up to 24MHz |
Note that the ESP32-S3 timers are 54-bit too, not only the ESP32-C3 (as the Arduino timer docs say). In practice, it makes no difference: a 54-bit counter at 1MHz takes about 570 years to overflow. The ESP32 also has other timers that aren’t covered by these functions: the 64-bit esp_timer system timer, the LEDC timers for ESP32 PWM, the RTC timer that wakes it up from sleep modes, and the watchdog timers. We’ll compare the timer options at the end of this tutorial.
How ESP32 Hardware Timers Work
Each ESP32 timer takes its clock from a clock source (the 80MHz APB clock on the ESP32). This clock is divided down by a 16-bit prescaler (any divider from 2 to 65,536), and the result is the timer tick frequency. The 64-bit counter counts up by 1 on each tick. Therefore, we control the timer tick time by choosing the divider. In the Arduino core 3.x, you don’t write the divider yourself: you pass the tick frequency you want to timerBegin(), and the core calculates the divider for you.

ESP32 Timer Alarm & Auto-Reload
ESP32 timers can trigger an alarm (event) that causes an interrupt and/or reloads the counter, depending on your configuration. The alarm event is triggered when the counter value matches the alarm value you’ve set with timerAlarm(). With auto-reload enabled, the counter is reloaded to the reload value (0 by default) at the alarm, and it starts counting up again. So you get a periodic interrupt, which is very useful to execute some pieces of logic periodically in your project, without a delay() that blocks the CPU. The animation below shows exactly this.

The second half of the animation shows what the 4th parameter of timerAlarm(), reload_count, really does. It’s the counter value loaded back at each alarm, not a number of repeats. We’ll prove it on the scope in LAB 5.
ESP32 Timer Interrupt Period Formula
In order to generate periodic events with the ESP32 timer, we need 2 numbers: the timer tick frequency (set by timerBegin()) and the alarm value in ticks (set by timerAlarm()). The interrupt period is:
Tip: TOUT = Alarm Value / Timer Frequency. With timerBegin(1000000) (1MHz, 1µs per tick) and an alarm value of 50,000: TOUT = 50,000 / 1,000,000 = 50ms.
Let’s say we’d like to toggle an LED every 1ms. A 1MHz timer frequency makes the calculation easy (1 tick = 1µs), so the alarm value is 1ms / 1µs = 1,000 ticks. If you need a finer resolution, use a higher timer frequency: at 40MHz, each tick is 25ns, and 1ms is 40,000 ticks. And because the counter is 64-bit (or 54-bit), even very long periods fit. A 1-hour interrupt at 1MHz is an alarm value of 3,600,000,000 ticks.
| Timer Frequency | Tick Time | Alarm Value For 1ms | Alarm Value For 1s |
|---|---|---|---|
timerBegin(10000) (10kHz) | 100µs | 10 | 10,000 |
timerBegin(1000000) (1MHz) | 1µs | 1,000 | 1,000,000 |
timerBegin(10000000) (10MHz) | 100ns | 10,000 | 10,000,000 |
timerBegin(40000000) (40MHz) | 25ns | 40,000 | 40,000,000 |
If your output toggles a pin in the ISR (like the LAB examples), remember that the square wave you see on the pin has twice the interrupt period: an interrupt every 50ms gives a 100ms period (10Hz) on the scope.
ESP32 Timer Arduino Functions (Core 3.x)
These are the timer functions in the current Arduino-ESP32 core (3.x), which is built on the ESP-IDF GPTimer driver. There’s no timer number anymore: timerBegin() takes a free hardware timer and returns a pointer to it, or NULL if no timer is left (or the frequency can’t be reached).
| Function | What It Does |
|---|---|
hw_timer_t *timerBegin(uint32_t frequency) | Takes a free hardware timer, sets its tick frequency in Hz, and starts it. Returns NULL on failure |
timerEnd(timer) | Stops the timer and releases it |
timerAttachInterrupt(timer, fn) | Attaches your ISR function void fn() to the timer’s alarm interrupt |
timerAttachInterruptArg(timer, fn, arg) | Same, with an argument: void fn(void *arg) |
timerDetachInterrupt(timer) | Detaches the ISR (and disables the alarm) |
timerAlarm(timer, alarm_value, autoreload, reload_count) | Sets the alarm value in ticks, auto-reload on/off, and the counter value loaded back at each alarm (use 0) |
timerStart(timer) | Starts (resumes) the counter |
timerStop(timer) | Stops (freezes) the counter. No alarms while it’s stopped |
timerRestart(timer) | Resets the counter to 0. It doesn’t start a stopped timer |
timerWrite(timer, value) | Writes the counter value (in ticks) |
timerRead(timer) | Reads the counter value in ticks (uint64_t) |
timerReadMicros(timer), timerReadMillis(timer) | Reads the counter value in µs or ms (uint64_t) |
timerReadSeconds(timer) | Reads the counter value in seconds (double) |
timerGetFrequency(timer) | Returns the real tick frequency in Hz, after rounding |
A few details that aren’t obvious from the function names (I checked each one in the core’s esp32-hal-timer.c source and on the bench):
- timerBegin() has a frequency range. The divider can only be 2 to 65,536, so on the ESP32 (80MHz) the timer frequency must be between 1,221Hz and 40MHz. timerBegin(1000) returns NULL, and the next timer call crashes your code if you don’t check it (see LAB 7).
- A frequency that doesn’t divide 80MHz exactly is rounded, with a warning in the serial monitor. timerBegin(3000000) gives you 3,076,923Hz. Use timerGetFrequency() to get the real value.
- timerBegin() starts the timer by itself. You don’t need timerStart() after it. To set up a timer without running it, call timerStop() right after timerBegin() (LAB 3).
- reload_count is not a repeat count. The Arduino docs describe it as the “number of autoreloads”, but it’s passed to the IDF driver as the counter value loaded back at each alarm. Always pass 0 unless you really want a shorter period (LAB 5).
- One-shot timer: timerAlarm(timer, ticks, false, 0) fires once. The counter keeps running after the alarm, so write 0 and set the alarm again to fire it again (LAB 3).
Measure Code Execution Time With an ESP32 Timer
A free-running hardware timer is also a precise stopwatch. With a 40MHz timer, you can measure how long a piece of code takes with a 25ns resolution:
|
1 2 3 4 5 6 |
hw_timer_t *Stopwatch = timerBegin(40000000); // 40MHz: 1 tick = 25ns uint64_t t0 = timerRead(Stopwatch); // ... the code you want to measure ... uint64_t t1 = timerRead(Stopwatch); Serial.printf("Took %llu ticks = %.3f us\n", t1 - t0, (t1 - t0) / 40.0); |
ESP32 Timer Code Changes in Arduino Core 3.x (Old vs New)
Arduino-ESP32 core 3.0 (May 2024, now 3.3.x) rewrote the timer API on top of the ESP-IDF GPTimer driver. The timer number, the prescaler, and the count direction are gone, and the alarm functions were merged into one timerAlarm(). That’s why ESP32 timer code written before 2024 (including the first version of this tutorial) fails to compile on a new Arduino IDE. Here is what to change, based on the official 2.x to 3.0 migration guide and my compile tests with core 3.3.12:
| Old (Core 2.x) | New (Core 3.x) |
|---|---|
timerBegin(0, 80, true);(timer 0, prescaler 80, count up) | timerBegin(1000000);(80MHz / 80 = 1MHz tick frequency) |
timerAttachInterrupt(timer, &ISR, true); | timerAttachInterrupt(timer, &ISR); |
timerAlarmWrite(timer, 50000, true);timerAlarmEnable(timer); | timerAlarm(timer, 50000, true, 0); |
timerAlarmDisable(timer); | timerStop(timer); or timerDetachInterrupt(timer); |
timerSetDivider(timer, div); | timerEnd(timer); then timerBegin(newFrequency); |
timerReadMilis(timer); | timerReadMillis(timer); |
timerSetAutoReload(), timerAlarmRead(), timerSetCountUp() | Removed. Auto-reload is a timerAlarm() parameter, and the timer always counts up |
To convert the old timerBegin(timer, prescaler, countUp) to the new one, divide 80MHz by the old prescaler: a prescaler of 80 becomes timerBegin(1000000), and a prescaler of 2 becomes timerBegin(40000000). The alarm values in ticks stay the same.
If you compile old ESP32 timer code with core 3.x, you’ll get errors like these (this is the exact output from compiling the old LAB code of this tutorial with core 3.3.12):
|
1 2 3 4 |
error: too many arguments to function 'hw_timer_t* timerBegin(uint32_t)' error: too many arguments to function 'void timerAttachInterrupt(hw_timer_t*, void (*)())' error: 'timerAlarmWrite' was not declared in this scope; did you mean 'timerWrite'? error: 'timerAlarmEnable' was not declared in this scope; did you mean 'timerAlarm'? |
And the other way around, if you compile the new core 3.x code on an old core 2.x, you get too few arguments to function 'hw_timer_t* timerBegin(uint8_t, uint16_t, bool)'. In that case, update the ESP32 boards package in the Arduino IDE Boards Manager (see the ESP32 Arduino IDE setup guide). Here is the old version of the timer interrupt LAB, for reference. The fixed core 3.x version is LAB 1 below.
Old ESP32 timer interrupt code (Arduino core 2.x, doesn’t compile on 3.x)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* * LAB: 25 * Name: ESP32 Timer Interrupt Example * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define LED 21 hw_timer_t *Timer0_Cfg = NULL; void IRAM_ATTR Timer0_ISR() { digitalWrite(LED, !digitalRead(LED)); } void setup() { pinMode(LED, OUTPUT); Timer0_Cfg = timerBegin(0, 80, true); timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR, true); timerAlarmWrite(Timer0_Cfg, 50000, true); timerAlarmEnable(Timer0_Cfg); } void loop() { // Do Nothing! } |
Components For This Tutorial’s LABs
| QTY. | Component Name | Amazon.com | AliExpress |
| 1 | ESP32 DevKit V1 (DOIT) Board | Amazon | AliExpress |
| 1 | LEDs Kit | Amazon | AliExpress |
| 1 | Resistors Kit (330Ω) | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires Pack | Amazon | AliExpress |
| 1 | Micro USB Cable | Amazon | AliExpress |
| 1 | Oscilloscope (Optional, Siglent SDS1104X-E) | Amazon | AliExpress |
ESP32 Timer LABs Wiring Diagram
All 7 LABs in this tutorial use the same simple wiring, so you can wire it once and run all the examples. An LED on GPIO21 through a 330Ω resistor, a second output on GPIO22 for the 2-timer LABs, and a jumper wire from GPIO25 to GPIO35 for the frequency counter LAB. I connected my oscilloscope CH1 to GPIO21 and CH3 to GPIO22, but the scope is optional: you’ll see the LED blink, and LABs 2, 6, and 7 print their results to the serial monitor.

GPIO21 → 330Ω resistor → LED anode (long leg), and the oscilloscope CH1 probe
GPIO22 → oscilloscope CH3 probe (LABs 4 and 5)
GPIO25 → jumper wire → GPIO35 (LAB 6 test signal)
GND → LED cathode (short leg), and both probe ground clips
ESP32 Timer Interrupt LED Toggle (LAB 1)
In this first ESP32 timer interrupt example, we’ll set up a hardware timer to fire an interrupt every 50ms, and toggle an LED in the ISR. This is the core 3.x version of the original LAB of this tutorial. Here is what the code does:
- Start a hardware timer at 1MHz (1 tick = 1µs)
- Attach the Timer0_ISR() function to the timer’s alarm interrupt
- Set the alarm to 50,000 ticks (50ms) with auto-reload, so Timer0_ISR() runs every 50ms and toggles the LED. Keep repeating…
Wiring: the LED on GPIO21 through the 330Ω resistor, with its cathode to GND.
Here is The Application Code For This Example (ESP32_Timer_Interrupt_LAB1.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* * LAB Name: ESP32 Timer Interrupt Example (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define LED_PIN 21 hw_timer_t *Timer0_Cfg = NULL; void IRAM_ATTR Timer0_ISR() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } void setup() { pinMode(LED_PIN, OUTPUT); Timer0_Cfg = timerBegin(1000000); // Timer Tick Rate = 1MHz (1 tick = 1us) timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR); // Attach The ISR Function To The Timer timerAlarm(Timer0_Cfg, 50000, true, 0); // Alarm Every 50,000 ticks (50ms), Auto-Reload ON } void loop() { // Do Nothing! } |
ESP32 Timer Interrupt Code Explanation
First of all, we define the LED pin and a pointer to the hardware timer. hw_timer_t is defined in the ESP32 core, so you don’t need to include anything. Just make sure an ESP32 board is selected in the Tools menu.
|
1 2 3 |
#define LED_PIN 21 hw_timer_t *Timer0_Cfg = NULL; |
The Timer0_ISR() function is the timer interrupt handler. It’s marked with IRAM_ATTR so it’s placed in the internal RAM and runs fast. It only toggles the LED, and that’s how an ISR should be: short, with no delay() or Serial.print() inside.
|
1 2 3 4 |
void IRAM_ATTR Timer0_ISR() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } |
In the setup() function, timerBegin(1000000) takes a free hardware timer and sets it to tick at 1MHz. The core calculates the divider for you (80MHz / 80). Then we attach the ISR and set the alarm: 50,000 ticks, auto-reload enabled, and a reload value of 0. The timer is already running, so there’s nothing else to do.
|
1 2 3 |
Timer0_Cfg = timerBegin(1000000); timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR); timerAlarm(Timer0_Cfg, 50000, true, 0); |
ESP32 Timer Interrupt Result
The LED blinks at 10Hz (ON for 50ms, OFF for 50ms). The capture below shows GPIO21 on channel 1 of my oscilloscope (yellow trace, 20ms/div). Each edge of the square wave is one timer interrupt, where the ISR toggles the pin. The pin toggles every 50.00ms (the interrupt period), so one full period is 100ms and the square wave frequency is 10.00Hz. Both values are marked on the capture.

This is the demo video from my original test of this LAB on the ESP32 DevKit board. The core 3.x version above gives the same result.
ESP32 Timer Start, Stop & Restart (LAB 2)
In this example, we’ll stop and restart a running ESP32 timer with the BOOT button on the DevKit board (GPIO0), so you don’t need any extra button. The timer toggles the LED every 250ms. Press BOOT once to stop the timer, and the LED stops blinking. Press it again to restart the timer from 0.
Wiring: the LED on GPIO21 through the 330Ω resistor, with its cathode to GND. The BOOT button is on the board (GPIO0).
Here is The Application Code For This Example (ESP32_Timer_Start_Stop_Restart_LAB2.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/* * LAB Name: ESP32 Timer Start, Stop & Restart (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define LED_PIN 21 #define BTN_PIN 0 // The On-Board BOOT Button hw_timer_t *Timer0_Cfg = NULL; bool Timer_Running = true; void IRAM_ATTR Timer0_ISR() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(BTN_PIN, INPUT_PULLUP); Timer0_Cfg = timerBegin(1000000); // 1MHz Tick Rate (1 tick = 1us) timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR); timerAlarm(Timer0_Cfg, 250000, true, 0); // Toggle The LED Every 250ms Serial.println("Timer Running. Press BOOT To Stop / Restart."); } void loop() { static uint32_t Last_Press = 0; if (digitalRead(BTN_PIN) == LOW && (millis() - Last_Press) > 300) { Last_Press = millis(); if (Timer_Running) { timerStop(Timer0_Cfg); // Freeze The Counter (No More Alarms) digitalWrite(LED_PIN, LOW); Serial.printf("Timer Stopped. Counter Frozen At: %llu us\n", timerRead(Timer0_Cfg)); } else { timerRestart(Timer0_Cfg); // Reset The Counter To 0 (Doesn't Start It!) timerStart(Timer0_Cfg); // Start Counting Again Serial.println("Timer Restarted From 0"); } Timer_Running = !Timer_Running; } } |
ESP32 Timer Start/Stop Code Explanation
timerStop() freezes the counter, so no more alarms happen and the ISR stops running. The counter keeps its value, and we print it with timerRead() (at 1MHz, the count is in µs). Then we turn the LED OFF, because it may have stopped in the ON state.
|
1 2 |
timerStop(Timer0_Cfg); Serial.printf("Timer Stopped. Counter Frozen At: %llu us\n", timerRead(Timer0_Cfg)); |
To restart the timer, we call timerRestart() and then timerStart(). The function name can be misleading: timerRestart() only resets the counter to 0, and it doesn’t start a stopped timer. So you need timerStart() after it. If you call only timerStart(), the timer resumes from the frozen count, and the first period after the restart is shorter.
|
1 2 |
timerRestart(Timer0_Cfg); // Counter back to 0 timerStart(Timer0_Cfg); // Start counting again |
ESP32 Timer Start/Stop Result
The capture below shows GPIO21 on channel 1 of my oscilloscope (yellow trace, 500ms/div) while the BOOT button is pressed. The marked regions show the timer running (the pin toggles every 250ms), the BOOT press that calls timerStop() (the output stops toggling), and the second BOOT press that calls timerRestart() and timerStart(), after which the pin toggles again with a full 250ms period.

And this is the serial monitor output:

ESP32 One-Shot Timer Pulse (LAB 3)
In this example, we’ll use an ESP32 timer in one-shot mode to generate a precise 1.5ms pulse each time you press the BOOT button. The pin goes HIGH, the timer is started, and the timer interrupt sets the pin LOW after exactly 1.5ms. The CPU is free the whole time. You can use the same idea for a trigger pulse, a servo-style pulse, or a timeout.
Wiring: the LED on GPIO21 through the 330Ω resistor, with its cathode to GND. The BOOT button is on the board (GPIO0).
Here is The Application Code For This Example (ESP32_Timer_One_Shot_Pulse_LAB3.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/* * LAB Name: ESP32 One-Shot Timer Pulse (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define PULSE_PIN 21 #define BTN_PIN 0 // The On-Board BOOT Button #define PULSE_US 1500 // Pulse Width = 1500us (1.5ms) hw_timer_t *Timer0_Cfg = NULL; void IRAM_ATTR Timer0_ISR() { digitalWrite(PULSE_PIN, LOW); // End Of The Pulse timerStop(Timer0_Cfg); } void Fire_Pulse() { timerWrite(Timer0_Cfg, 0); // Counter Back To 0 timerAlarm(Timer0_Cfg, PULSE_US, false, 0); // One-Shot Alarm (Auto-Reload OFF) digitalWrite(PULSE_PIN, HIGH); // Start Of The Pulse timerStart(Timer0_Cfg); } void setup() { Serial.begin(115200); pinMode(PULSE_PIN, OUTPUT); pinMode(BTN_PIN, INPUT_PULLUP); Timer0_Cfg = timerBegin(1000000); // 1MHz Tick Rate (1 tick = 1us) timerStop(Timer0_Cfg); // timerBegin() Starts The Timer, Stop It Until Needed timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR); Serial.println("Press BOOT To Fire One 1.5ms Pulse On GPIO21"); } void loop() { static uint32_t Last_Press = 0; if (digitalRead(BTN_PIN) == LOW && (millis() - Last_Press) > 300) { Last_Press = millis(); Fire_Pulse(); Serial.println("Pulse Fired!"); } } |
ESP32 One-Shot Timer Code Explanation
Because timerBegin() starts the timer by itself, we stop it right away in the setup() function. The timer then waits until we need a pulse.
|
1 2 |
Timer0_Cfg = timerBegin(1000000); timerStop(Timer0_Cfg); |
To fire a pulse, we reset the counter to 0, set a one-shot alarm (auto-reload = false) at 1,500 ticks, set the pin HIGH, and start the timer. When the counter reaches 1,500, the ISR sets the pin LOW and stops the timer, ready for the next pulse.
|
1 2 3 4 |
timerWrite(Timer0_Cfg, 0); timerAlarm(Timer0_Cfg, PULSE_US, false, 0); digitalWrite(PULSE_PIN, HIGH); timerStart(Timer0_Cfg); |
ESP32 One-Shot Timer Result
The capture below shows the pulse on GPIO21 on channel 1 of my oscilloscope (yellow trace, 500µs/div, single trigger mode). The rising edge is where the code sets the pin HIGH and starts the timer, and the falling edge is where the one-shot alarm ISR sets the pin LOW. The measured pulse width is 1.51ms. The extra 10µs over 1.5ms is the time from setting the pin HIGH to the timer starting, plus the time the ISR takes to start after the alarm. If you need it exact, subtract it from the alarm value.

ESP32 Multiple Timers With timerAttachInterruptArg (LAB 4)
In this example, we’ll run 2 hardware timers at the same time with 2 different periods, and use one ISR function for both with timerAttachInterruptArg(). The argument tells the ISR which pin to toggle. This is useful when you have several timers doing the same job on different pins.
- Timer 1: toggles GPIO21 every 1ms (500Hz square wave)
- Timer 2: toggles GPIO22 every 300µs (1.667kHz square wave)
Wiring: oscilloscope CH1 on GPIO21, CH3 on GPIO22, and both ground clips on GND.
Here is The Application Code For This Example (ESP32_Multiple_Timers_Arg_LAB4.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/* * LAB Name: ESP32 Multiple Timers With timerAttachInterruptArg (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define OUT1_PIN 21 #define OUT2_PIN 22 hw_timer_t *Timer0_Cfg = NULL; hw_timer_t *Timer1_Cfg = NULL; // One ISR For Both Timers, The Argument Tells It Which Pin To Toggle void IRAM_ATTR Timer_ISR(void *arg) { uint32_t pin = (uint32_t)arg; digitalWrite(pin, !digitalRead(pin)); } void setup() { pinMode(OUT1_PIN, OUTPUT); pinMode(OUT2_PIN, OUTPUT); Timer0_Cfg = timerBegin(1000000); // 1MHz Tick Rate timerAttachInterruptArg(Timer0_Cfg, &Timer_ISR, (void *)OUT1_PIN); timerAlarm(Timer0_Cfg, 1000, true, 0); // Toggle GPIO21 Every 1ms (500Hz) Timer1_Cfg = timerBegin(1000000); // A 2nd Hardware Timer timerAttachInterruptArg(Timer1_Cfg, &Timer_ISR, (void *)OUT2_PIN); timerAlarm(Timer1_Cfg, 300, true, 0); // Toggle GPIO22 Every 300us (1.667kHz) } void loop() { // Do Nothing! } |
ESP32 Multiple Timers Code Explanation
The ISR takes a void * argument, and we cast it back to the pin number. Each timerBegin() call takes a different free hardware timer, so the ESP32 can run up to 4 of these at the same time (2 on the ESP32-C3 and C6).
|
1 2 3 4 5 6 7 |
void IRAM_ATTR Timer_ISR(void *arg) { uint32_t pin = (uint32_t)arg; digitalWrite(pin, !digitalRead(pin)); } timerAttachInterruptArg(Timer0_Cfg, &Timer_ISR, (void *)OUT1_PIN); |
ESP32 Multiple Timers Result
The capture below shows both outputs on my oscilloscope (1ms/div). Channel 1 (yellow) is GPIO21, driven by timer 1, at 500.02Hz. Channel 3 (cyan) is GPIO22, driven by timer 2, at 1.667kHz (a 599.98µs period). Each output runs from its own hardware timer, and one period of each signal is marked on the capture.

ESP32 timerAlarm reload_count Test (LAB 5)
In this example, we’ll test what the 4th parameter of timerAlarm() really does. The Arduino timer docs call it the “number of autoreloads” (with 0 meaning unlimited), so timerAlarm(timer, 1000, true, 500) should stop after 500 reloads. In the core’s source code, it’s passed to the ESP-IDF driver as the value the counter is reloaded to at each alarm. The following test shows which description is correct. 2 timers get the same alarm value (1,000 ticks at 1MHz), and only the reload_count is different:
- GPIO21: timerAlarm(Timer0_Cfg, 1000, true, 0)
- GPIO22: timerAlarm(Timer1_Cfg, 1000, true, 500)
Wiring: oscilloscope CH1 on GPIO21, CH3 on GPIO22, and both ground clips on GND.
Here is The Application Code For This Example (ESP32_Timer_Reload_Count_Test_LAB5.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/* * LAB Name: ESP32 timerAlarm() reload_count Test (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define OUT1_PIN 21 #define OUT2_PIN 22 hw_timer_t *Timer0_Cfg = NULL; hw_timer_t *Timer1_Cfg = NULL; void IRAM_ATTR Timer_ISR(void *arg) { uint32_t pin = (uint32_t)arg; digitalWrite(pin, !digitalRead(pin)); } void setup() { Serial.begin(115200); pinMode(OUT1_PIN, OUTPUT); pinMode(OUT2_PIN, OUTPUT); // Same alarm value (1000 ticks = 1ms) on both timers, only reload_count differs Timer0_Cfg = timerBegin(1000000); timerAttachInterruptArg(Timer0_Cfg, &Timer_ISR, (void *)OUT1_PIN); timerAlarm(Timer0_Cfg, 1000, true, 0); // Reloads to 0 -> 1000 ticks per alarm Timer1_Cfg = timerBegin(1000000); timerAttachInterruptArg(Timer1_Cfg, &Timer_ISR, (void *)OUT2_PIN); timerAlarm(Timer1_Cfg, 1000, true, 500); // Reloads to 500 -> only 500 ticks per alarm delay(1000); Serial.println("GPIO21: timerAlarm(timer, 1000, true, 0) -> expect toggle every 1000us"); Serial.println("GPIO22: timerAlarm(timer, 1000, true, 500) -> toggles every 500us (reload_count is a START VALUE, not a repeat count)"); } void loop() { // Do Nothing! } |
ESP32 reload_count Test Result
If reload_count were a number of reloads, both pins would toggle every 1ms for the first 500 alarms. In the capture below, channel 1 (yellow) is GPIO21 with a reload_count of 0, and channel 3 (cyan) is GPIO22 with a reload_count of 500. GPIO22 toggles every 500µs (500.09µs) from the start and keeps going forever, while GPIO21 toggles every 1ms (999.99µs). At each alarm, the counter is reloaded to 500, so it only counts 500 ticks to the next alarm.

Note: Always pass 0 as the last parameter of timerAlarm() for a normal periodic interrupt. A non-zero reload_count shortens the period to (alarm value – reload_count) ticks after the first alarm. And if it’s equal to the alarm value, timerAlarm() fails with an invalid argument error.
ESP32 Frequency Counter With a Timer (LAB 6)
In this example, we’ll use an ESP32 timer to measure time between events, which is the other big use of timers. We’ll build a simple frequency counter: a free-running 40MHz timer (25ns resolution) and an external interrupt on GPIO35. At each rising edge of the input signal, the interrupt counts the edge and reads the timer. Every 500ms, the loop() takes the number of periods and the time they took, and the frequency is periods / time.
To test it without a signal generator, the ESP32 generates its own test signal on GPIO25 with the LEDC PWM (50, 1k, 10k, 25k, and 50kHz), and a jumper wire feeds it back to GPIO35.
Wiring: a jumper wire from GPIO25 to GPIO35.
GPIO25 and GPIO35 are pins of the original ESP32. On the ESP32-S3 or C3, change the 2 pin numbers to any free output pin and input pin of your board.
Here is The Application Code For This Example (ESP32_Timer_Frequency_Counter_LAB6.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
/* * LAB Name: ESP32 Timer Frequency Counter (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define SIGNAL_OUT_PIN 25 // Test Signal Output (LEDC PWM, 50% Duty) #define SIGNAL_IN_PIN 35 // Signal Input (Jumper Wire From GPIO25) #define TIMER_FREQ 40000000UL // 40MHz Timer Tick Rate (25ns Resolution) #define GATE_TIME_MS 500 // Measure Over 500ms Of Edges hw_timer_t *Timer0_Cfg = NULL; portMUX_TYPE Timer_Mux = portMUX_INITIALIZER_UNLOCKED; volatile uint32_t Edge_Count = 0; volatile uint64_t Last_Edge = 0; void IRAM_ATTR Signal_ISR() { uint64_t Now = timerRead(Timer0_Cfg); portENTER_CRITICAL_ISR(&Timer_Mux); Edge_Count = Edge_Count + 1; // Count The Rising Edges Last_Edge = Now; // And Timestamp The Latest One portEXIT_CRITICAL_ISR(&Timer_Mux); } void Read_Edges(uint32_t *count, uint64_t *time) { portENTER_CRITICAL(&Timer_Mux); // Copy The 64-Bit Value Safely *count = Edge_Count; *time = Last_Edge; portEXIT_CRITICAL(&Timer_Mux); } const uint32_t Test_Freqs[] = {50, 1000, 10000, 25000, 50000}; void setup() { Serial.begin(115200); Timer0_Cfg = timerBegin(TIMER_FREQ); // Free-Running 64-Bit Counter, No Alarm Needed pinMode(SIGNAL_IN_PIN, INPUT); attachInterrupt(SIGNAL_IN_PIN, Signal_ISR, RISING); } void loop() { for (uint8_t i = 0; i < sizeof(Test_Freqs) / sizeof(Test_Freqs[0]); i++) { uint32_t Count0, Count1; uint64_t Time0, Time1; ledcAttach(SIGNAL_OUT_PIN, Test_Freqs[i], 8); // Generate The Test Signal ledcWrite(SIGNAL_OUT_PIN, 128); // 50% Duty Cycle delay(100); // Let The Signal Settle Read_Edges(&Count0, &Time0); delay(GATE_TIME_MS); Read_Edges(&Count1, &Time1); uint32_t Periods = Count1 - Count0; // Full Periods Between The 2 Timestamped Edges uint64_t Ticks = Time1 - Time0; double Measured_Freq = (Ticks > 0) ? ((double)Periods * TIMER_FREQ / Ticks) : 0; Serial.printf("Generated: %6lu Hz | Periods: %6lu | Ticks: %9llu | Measured: %10.2f Hz\n", (unsigned long)Test_Freqs[i], (unsigned long)Periods, Ticks, Measured_Freq); ledcDetach(SIGNAL_OUT_PIN); } Serial.println("------------------------------------------------------------------------"); } |
ESP32 Frequency Counter Code Explanation
The timer is started with timerBegin(40000000), and no alarm or interrupt is attached to it. It just counts. The external interrupt on GPIO35 counts the rising edges and timestamps the latest one:
|
1 2 3 4 5 6 7 8 |
void IRAM_ATTR Signal_ISR() { uint64_t Now = timerRead(Timer0_Cfg); portENTER_CRITICAL_ISR(&Timer_Mux); Edge_Count = Edge_Count + 1; Last_Edge = Now; portEXIT_CRITICAL_ISR(&Timer_Mux); } |
The ESP32 is a 32-bit CPU, so reading or writing a 64-bit variable takes 2 instructions, and an interrupt can happen in between. That’s why the shared 64-bit Last_Edge and the edge count are written inside a critical section in the ISR, and copied together inside a critical section in the loop(). The loop() reads them twice, 500ms apart, and the frequency is the number of periods between the 2 timestamped edges divided by the time between them:
|
1 2 3 |
uint32_t Periods = Count1 - Count0; uint64_t Ticks = Time1 - Time0; double Measured_Freq = (double)Periods * TIMER_FREQ / Ticks; |
ESP32 Frequency Counter Result
This is the serial monitor output on my ESP32 DevKit V1:

Every frequency from 50Hz to 50kHz reads exactly, in every sweep. Note that this is the best case: the LEDC test signal and the timer both come from the same 80MHz clock, so any clock error cancels out. With an external signal, the reading is as accurate as the ESP32’s 40MHz crystal, which is still far better than you’ll need for most projects.
Why not just measure one period, like the first version of this LAB? I tested that too. 50Hz, 1kHz, and 10kHz read exactly, but 25kHz read between 23,015Hz and 24,540Hz, and 50kHz once read 44,693Hz. The timer is exact, but the interrupt doesn’t always start at the same time after the edge (a few microseconds of latency), and at 25kHz one period is only 40µs, so 2-4µs of latency is a 5-10% error. Averaging over many periods divides that error by the number of periods.
This is the demo video from my original test of this LAB, where I printed the frequency on an I2C LCD instead of the serial monitor.
Note: This frequency counter is simple enough to show how a timer measures time between events, but it’s not ideal for high frequencies. At a 50kHz input, the CPU handles 50,000 interrupts per second. For high frequencies, use the ESP32’s PCNT (pulse counter) peripheral, which counts the edges in hardware, and read the count every second with a timer.
ESP32 Timer Limits & Fastest Timer Interrupt (LAB 7)
In this last example, we’ll test the limits of the ESP32 timers. The first part calls timerBegin() with frequencies from 1kHz to 80MHz and prints what really happens. The second part runs a 1MHz timer and lets you set the interrupt period to 100, 20, 10, 5, or 2µs by sending 1 – 5 from the serial monitor, to find the fastest timer interrupt that still works.
Wiring: oscilloscope CH1 on GPIO21 and its ground clip on GND.
Here is The Application Code For This Example (ESP32_Timer_Limits_Speed_Test_LAB7.ino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
/* * LAB Name: ESP32 Timer Frequency Limits & Speed Test (Arduino Core 3.x) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #define OUT_PIN 21 hw_timer_t *Fast_Timer = NULL; void IRAM_ATTR Fast_Timer_ISR() { digitalWrite(OUT_PIN, !digitalRead(OUT_PIN)); } void Try_Frequency(uint32_t freq) { hw_timer_t *t = timerBegin(freq); if (t == NULL) { Serial.printf("timerBegin(%9lu) -> NULL (Failed!)\n", (unsigned long)freq); } else { Serial.printf("timerBegin(%9lu) -> OK, Real Tick Rate = %9lu Hz\n", (unsigned long)freq, (unsigned long)timerGetFrequency(t)); timerEnd(t); } } void Set_Alarm_Period(uint32_t period_us) { timerAlarm(Fast_Timer, period_us, true, 0); Serial.printf("Alarm Period = %lu us -> Expected Square Wave = %lu Hz On GPIO21\n", (unsigned long)period_us, (unsigned long)(500000UL / period_us)); } void setup() { Serial.begin(115200); delay(1000); Serial.println("--- timerBegin() Frequency Range Test ---"); const uint32_t Freqs[] = {1000, 1220, 1221, 10000, 1000000, 3000000, 7000000, 40000000, 80000000}; for (uint8_t i = 0; i < sizeof(Freqs) / sizeof(Freqs[0]); i++) { Try_Frequency(Freqs[i]); } Serial.println("--- Fastest Timer Interrupt Test ---"); Serial.println("Send 1, 2, 3, 4 or 5 To Set The Alarm Period: 100, 20, 10, 5, 2 us"); pinMode(OUT_PIN, OUTPUT); Fast_Timer = timerBegin(1000000); // 1MHz Tick Rate (1 tick = 1us) timerAttachInterrupt(Fast_Timer, &Fast_Timer_ISR); Set_Alarm_Period(100); } void loop() { if (Serial.available()) { char c = Serial.read(); const uint32_t Periods[] = {100, 20, 10, 5, 2}; if (c >= '1' && c <= '5') { Set_Alarm_Period(Periods[c - '1']); } } } |
ESP32 timerBegin Frequency Range Result
This is the serial monitor output on my ESP32 DevKit V1, with the first 4 periods selected after the range test:

timerBegin(1000) and timerBegin(1220) return NULL, and 1,221Hz is the lowest frequency that works (80MHz / 65,536 = 1,220.7Hz). timerBegin(80000000) fails too, because the smallest divider is 2, so 40MHz is the maximum. And 3MHz and 7MHz don’t divide 80MHz exactly, so the timer really runs at 3,076,923Hz (divider 26) and 7,272,727Hz (divider 11). If your timing depends on it, always check timerGetFrequency(), or pick a frequency that divides 80MHz exactly (1MHz, 10MHz, 40MHz, and so on).
ESP32 Fastest Timer Interrupt Result
Here is what I measured on GPIO21 with my oscilloscope for each interrupt period. The ISR toggles the pin, so the expected square wave frequency is 1 / (2 x period):
| Interrupt Period | Expected Frequency | Measured Frequency | Result |
|---|---|---|---|
| 100µs | 5kHz | 5.010kHz | Works |
| 20µs | 25kHz | 25.00kHz | Works |
| 10µs | 50kHz | 50.56kHz – 50.85kHz | Works, with visible jitter |
| 5µs | 100kHz | 96.99kHz | Barely: heavy jitter, the ISR can’t keep up |
| 2µs | 250kHz | 126kHz | Fails: the ESP32 freezes |
So the fastest ESP32 timer interrupt that works reliably in Arduino is about 10µs (100,000 interrupts per second). The capture below shows GPIO21 on channel 1 of my oscilloscope (yellow trace) with a 10µs interrupt period. Each edge is one interrupt, so the square wave frequency is about 50kHz:

At 2µs, the interrupt never stops firing: each ISR call (with the interrupt entry and exit code) takes about 4µs, so the next alarm is already waiting when it returns. The loop() never runs again, the serial monitor stops responding, and the pin toggles at an irregular 126kHz instead of the expected 250kHz, as shown in the capture below (GPIO21 on channel 1). The ESP32 reports no exception and no watchdog reset occurs. It stops responding until it is reset.

The capture below shows the jitter of the 10µs interrupt on GPIO21 (channel 1), with the oscilloscope’s infinite persistence enabled. Every sweep is triggered on the same rising edge (marked on the capture), so the spread of the following edges shows the variation in the ISR start time. In my measurements, the pulse width at a 10µs period varied from 9.31µs to 10.71µs. It’s fine for blinking, sampling, and timeouts, but if you need clean edges at high frequencies, generate the signal with a hardware peripheral like LEDC PWM instead of toggling a pin in an ISR.

ESP32 Timer Interrupt Rules (ISR Do’s & Don’ts)
The timer ISR runs in interrupt context, and it blocks everything else on that CPU core while it’s running. Follow these rules to keep your ESP32 timer interrupt code fast and crash-free:
- Mark the ISR with IRAM_ATTR (or ARDUINO_ISR_ATTR) so it runs from the internal RAM.
- Keep it short. Set a flag, toggle a pin, or read a value, and do the rest in the loop(). No delay(), no Serial.print(), and no WiFi or file functions in the ISR.
- Declare the variables shared with the ISR as volatile, so the compiler doesn’t cache them in a register.
- Protect 64-bit (and multi-variable) shared data with a critical section ( portENTER_CRITICAL_ISR() in the ISR, portENTER_CRITICAL() in the loop), like in LAB 6.
- Don’t go too fast. Each interrupt costs a few microseconds of CPU time. Below about 10µs, the CPU spends most of its time in the ISR (see LAB 7).
- Expect some delay while the flash is being written (OTA updates, EEPROM/Preferences writes). The Arduino core doesn’t place the timer driver in IRAM, so timer interrupts wait until the flash write is done.
Here is the flag pattern, which is the safe way to run longer code at a timer period:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
volatile bool Timer_Flag = false; void IRAM_ATTR Timer0_ISR() { Timer_Flag = true; // Only set a flag in the ISR } void loop() { if (Timer_Flag) { Timer_Flag = false; Serial.println("Tick!"); // The slow work goes here } } |
ESP32 Hardware Timer vs esp_timer vs Ticker vs millis()
The hardware timer interrupt isn’t the only way to run code periodically on the ESP32. Here is how the options compare, so you can pick the right one for your project:
| Method | Resolution | Where Your Code Runs | Best For |
|---|---|---|---|
Hardware timer (timerBegin()) | 25ns (40MHz) | Interrupt (ISR) | Precise µs timing, pulses, measuring time. 4 timers on the ESP32 |
esp_timer (ESP-IDF) | 1µs | A high-priority task (callback) | Many software timers, periods of 50µs or more, longer callbacks |
Ticker library | 1µs (attach_us()), built on esp_timer | esp_timer task (callback) | Simple periodic jobs, blinking, polling sensors |
| FreeRTOS software timer | 1ms (the RTOS tick) | Timer service task | RTOS projects, timeouts |
millis() / micros() | 1ms / 1µs | Your loop() (polling) | Non-blocking code without interrupts |
If you’re new to timers in general, check out why you should use a timer instead of delay and the timer modules tutorial for the full theory. For the same concepts on STM32, check out the STM32 timers tutorial.
ESP32 Timer Troubleshooting
too many arguments to function ‘hw_timer_t* timerBegin(uint32_t)’
Your code uses the core 2.x timer API, which was changed in Arduino-ESP32 core 3.0. Replace timerBegin(0, 80, true) with timerBegin(1000000) (80MHz divided by the old prescaler), remove the 3rd argument of timerAttachInterrupt(), and replace timerAlarmWrite() + timerAlarmEnable() with timerAlarm(timer, ticks, true, 0). See the core 3.x changes section.
‘timerAlarmWrite’ was not declared in this scope
Same cause: timerAlarmWrite(), timerAlarmEnable(), and timerAlarmDisable() were removed in core 3.0. Replace timerAlarmWrite(timer, 50000, true); timerAlarmEnable(timer); with one timerAlarm(timer, 50000, true, 0);.
too few arguments to function ‘hw_timer_t* timerBegin(uint8_t, uint16_t, bool)’
This is the opposite case: new core 3.x code compiled on an old core 2.x. Update the ESP32 boards package to the latest 3.x version in the Arduino IDE Boards Manager.
timerBegin() Returns NULL
Either the frequency is out of range (below 1,221Hz or above 40MHz on the ESP32, below 611Hz on the S2, S3, and C3), or all hardware timers are already used. The serial monitor shows Resolution cannot be reached with any clock source, aborting! for an out-of-range frequency. For slow interrupts, keep the timer at 1MHz and use a bigger alarm value instead of a lower frequency.
Timer Interrupt Period Is Wrong
Check 3 things. The square wave from a pin toggle has twice the interrupt period (an interrupt every 50ms gives 10Hz). The last parameter of timerAlarm() must be 0 (a non-zero reload_count shortens the period). And timerGetFrequency() tells you if the timer frequency was rounded (the “resolution lost” warning).
The Timer Won’t Stop or Restart
Use timerStop() to stop the counter, and timerRestart() followed by timerStart() to run it again from 0. timerRestart() alone only resets the counter. On core 3.1.x, calling timerStart() on a timer that is already running logs gptimer_start(396): timer is not ready for a new start. It’s harmless, and you can remove the extra timerStart() after timerBegin().
ESP32 Crashes, Reboots, or Freezes With a Timer Interrupt
Usually the ISR does too much: Serial.print(), delay(), or a long calculation inside the ISR, or an interrupt period that’s too short for the ISR code. At a 2µs period, the ESP32 stopped responding without printing any error message (see LAB 7). Move the work to the loop() with a flag (see the ISR rules above). Also check that timerBegin() didn’t return NULL before you use the timer.
Wrap Up
To conclude this tutorial, we’ve seen how to use the ESP32 timer interrupt in Arduino core 3.x: how many timers each ESP32 chip has, how the timer, the alarm, and auto-reload work, the timerBegin() and timerAlarm() functions and their real limits, and how to port old core 2.x timer code. We’ve also built 7 tested examples: a timer interrupt LED, start/stop/restart, a one-shot pulse, multiple timers, the reload_count test, a frequency counter, and the fastest timer interrupt test. You can build on top of these examples for motor control, audio generation, sampling sensors at a fixed rate, and much more.
If you’ve got any questions or suggestions, drop me a comment below and I’ll be glad to help! And check out the ESP32 Programming Tutorials series for more ESP32 tutorials.
Download ESP32 Timers Project Files
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
ESP32 Timer FAQ
Yes. The ESP32 has an RTC timer that keeps counting in deep sleep and wakes the chip up, but it has no battery-backed calendar like a DS3231 module. For the date and time, sync the ESP32 clock from the internet with NTP, or add an external RTC module.
Not the hardware timers in this tutorial: they stop in deep sleep. Use the RTC timer instead with esp_sleep_enable_timer_wakeup(microseconds) before esp_deep_sleep_start().
Call timerAlarm() again with the new alarm value, for example timerAlarm(timer, 2000, true, 0) for 2ms at a 1MHz timer frequency. LAB 7 does this from the serial monitor.
Yes. The core 3.x timer functions are the same on all ESP32 chips. The ESP32-C3 and C6 have only 2 hardware timers instead of 4, and the minimum timerBegin() frequency on the S2, S3 and C3 is 611Hz instead of 1,221Hz.
Yes. The hardware timer keeps counting, and its interrupts keep running while WiFi is active. WiFi adds a little jitter to the ISR start time, so for edges that must be exact to the nanosecond, use a hardware peripheral (LEDC, RMT or MCPWM) to generate the signal instead of toggling a pin in an ISR.
Everything worked fine until about 2 weeks ago,,,,, but the code doesn’t seem to work anymore because (I think) Espressif recently updated their Arduino timer libraries…
Typical compile error message is now….
error: too many arguments to function ‘hw_timer_t* timerBegin(uint32_t)’
159 | Timer0_Cfg = timerBegin(0, 8, true); // timer 0, 80MHz/8 = 10MHz = 0.1us/tick
all calls now expect single arguments it seems???
Any help would be much appreciated.
Hi Justin,
I’ve received similar questions recently. It seems like the latest Arduino core update from Espressif has invalidated most of the online tutorials/sketches.
An easy fix that will help you, in the meantime, is to just revert back to the latest stable version:
Open Tools > Board > Board Manager > Search for ESP32 > Select version: 2.0.17
This is to keep your old esp32 sketches working as they used to be until we update our tutorials/code examples according to the latest API changes.
It looks like a lot of work is ahead of us 🙁
All the best,
Khaled M.
Brilliant – thank you so much Khaled!…
I feared I might have made a simple mistake.
Will revert to previous stable version as you suggest!
Thanks,
Justin
You’re welcome, Justin! The tutorial is now updated for core 3.x, so you can move back to the latest core and use the new code. The old vs new functions table is here: https://deepbluembedded.com/esp32-timers-timer-interrupt-tutorial-arduino-ide/#esp32-timer-core-3-changes ^^
Same problem here…thanks for for the fix, just did downgrade the eps32 board to 2.0.17 and it worked..
Hi Fred,
The downgrade works, but it’s no longer needed. The tutorial is now updated and tested on core 3.3.12. Replace timerBegin(0, 80, true) with timerBegin(1000000), remove the 3rd argument of timerAttachInterrupt(), and replace timerAlarmWrite() + timerAlarmEnable() with one timerAlarm(timer, ticks, true, 0).
The full old vs new table: https://deepbluembedded.com/esp32-timers-timer-interrupt-tutorial-arduino-ide/#esp32-timer-core-3-changes
Would love to see this tutorial updated for v3.0 as there is currently no tutorial site explaining how the new Timer APIs for Arduino works. It looks like Espressif have hired the worst people from Microchip to design their new APIs to be as little user friendly as possible 🙂
Hi Jensa,
The tutorial is now fully updated for core 3.x, with 7 examples tested on my bench and an old vs new functions table. It also covers two details the official docs get wrong: the minimum timerBegin() frequency and what the reload_count parameter of timerAlarm() actually does: https://deepbluembedded.com/esp32-timers-timer-interrupt-tutorial-arduino-ide/#esp32-timeralarm-reload-count
Hi, I too am very interested in a core 3.x tutorial for timers. I have been able to get a small sketch working to blink an LED using the hardware timers in Core 3.x however I cannot stop the timers and restart them. I also need to be able to start and stop the timers when a button is pressed. I have tried timerStop(timer); timerWrite(timer, 0); but the led just keeps blinking away as if no stop commands were given. very frustrating this situation with a complete rewrite of the syntax for timers in core 3.x. To what end? What’s the benefit? Tons of extra work for us all just to use timers that were working under 2.x. Guess I will also have to revert.
Hi Luna,
In core 3.x, timerStop(timer) freezes the counter, so the ISR stops firing. If the LED keeps blinking, check that you pass the same hw_timer_t pointer that timerBegin() returned, and that nothing calls timerStart() again afterwards. To run it again from 0, call timerRestart() followed by timerStart(), because timerRestart() alone only resets the counter.
LAB 2 in the updated tutorial does exactly this with a button: https://deepbluembedded.com/esp32-timers-timer-interrupt-tutorial-arduino-ide/#esp32-timer-start-stop-restart
I used your example with the 10us TickTime. The default MCU CPU frequency for my ESP32 DEVKIT is 160 MHz. When checking the timer stability with an oscilloscope with persistance, it is not very stable. When setting it to 160 MHz by myself it’s stable enough, I dont know the reason why this may have effect.
Hi BroaD,
The timer itself counts from the 80MHz APB clock, so its period doesn’t depend on the CPU frequency. What varies on the scope is the ISR start time: the interrupt entry and the pin toggle run on the CPU, so their timing changes with the CPU clock and with whatever else the CPU is doing. At a 10µs period, I measured a pulse width from 9.31µs to 10.71µs on my DevKit V1. For clean edges at high frequencies, generate the signal with the LEDC PWM peripheral instead: https://deepbluembedded.com/esp32-timers-timer-interrupt-tutorial-arduino-ide/#esp32-timer-limits-fastest-interrupt
Here is a simple example using a Seeed XIAO ESP32-C3. It prints a “.” every 5 seconds.
Arduino IDE 2.3.10
hw_timer_t *Timer0_Cfg = NULL;
void IRAM_ATTR Timer0_ISR()
{
Serial.println(“.”);
}
void setup() {
Serial.begin(115200);
while (!Serial){}
Timer0_Cfg = timerBegin(10000); //frequency of 10000hz
timerAttachInterrupt(Timer0_Cfg, &Timer0_ISR);
timerAlarm(Timer0_Cfg, 50000, true,0); //Alarms at a count of 50000, autoreload = true
timerStart(Timer0_Cfg);
}
void loop() {
}
Timestamped serial output:
08:17:31.950
08:17:36.987
08:17:41.981
08:17:46.977
08:17:51.997
08:17:56.956
08:18:01.987
08:18:06.956
08:18:11.953
08:18:16.968
08:18:21.975
Thanks for sharing, DarrylK! One note: in core 3.x, timerBegin() already starts the timer, so the timerStart() call isn’t needed (on some 3.1.x versions it logs “timer is not ready for a new start”). Also, keep Serial.println() out of the ISR and set a flag instead, as shown here: https://deepbluembedded.com/esp32-timers-timer-interrupt-tutorial-arduino-ide/#esp32-timer-isr-rules ^^