ESP32 Timer Interrupt (Arduino): timerBegin Examples

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:

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:

ChipHardware TimersCounter WidthTimer Clock SourcestimerBegin() Frequency Range
ESP32464-bitAPB 80MHz1,221Hz – 40MHz
ESP32-S2464-bitAPB 80MHz, XTAL 40MHz611Hz – 40MHz
ESP32-S3454-bitAPB 80MHz, XTAL 40MHz611Hz – 40MHz
ESP32-C3254-bitAPB 80MHz, XTAL 40MHz611Hz – 40MHz
ESP32-C6254-bitPLL 80MHz, XTAL 40MHz, RC_FASTUp to 40MHz
ESP32-H2254-bitPLL 48MHz, XTAL 32MHz, RC_FASTUp 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 block diagram: APB clock, 16-bit divider set by timerBegin, 64-bit counter, alarm comparator set by timerAlarm, timer interrupt ISR and auto-reload

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.

ESP32 timer interrupt animation: the timer counter counts up to the alarm value, fires the interrupt and auto-reloads to the reload value

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 FrequencyTick TimeAlarm Value For 1msAlarm Value For 1s
timerBegin(10000) (10kHz)100µs1010,000
timerBegin(1000000) (1MHz)1µs1,0001,000,000
timerBegin(10000000) (10MHz)100ns10,00010,000,000
timerBegin(40000000) (40MHz)25ns40,00040,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).

FunctionWhat 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:


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):

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)


Components For This Tutorial’s LABs

QTY.Component NameAmazon.comAliExpress
1ESP32 DevKit V1 (DOIT) BoardAmazonAliExpress
1LEDs KitAmazonAliExpress
1Resistors Kit (330Ω)AmazonAliExpress
1BreadboardAmazonAliExpress
1Jumper Wires PackAmazonAliExpress
1Micro USB CableAmazonAliExpress
1Oscilloscope (Optional, Siglent SDS1104X-E)AmazonAliExpress

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.

ESP32 timer interrupt wiring diagram: ESP32 DevKit V1 GPIO21 to a 330 ohm resistor and LED, GPIO22 scope probe point, GPIO25 to GPIO35 jumper wire, oscilloscope CH1 and CH3 probes

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:

  1. Start a hardware timer at 1MHz (1 tick = 1µs)
  2. Attach the Timer0_ISR() function to the timer’s alarm interrupt
  3. 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)

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.

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.

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.

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.

ESP32 timer interrupt every 50ms on the oscilloscope: GPIO21 square wave at 10Hz from the timer ISR LED toggle

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)

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.

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.

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.

ESP32 timer stop and restart on the oscilloscope: the 250ms GPIO21 toggle stops after timerStop and resumes after timerRestart and timerStart

And this is the serial monitor output:

ESP32 timer start stop restart serial monitor output: counter frozen value after timerStop and restart from 0


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)

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.

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.

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 one-shot timer pulse on the oscilloscope: 1.5ms pulse on GPIO21 generated with timerAlarm auto-reload false


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)

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).

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 multiple timers on the oscilloscope: GPIO21 at 500Hz and GPIO22 at 1.667kHz from 2 hardware timers sharing one ISR with timerAttachInterruptArg


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)

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.

ESP32 timerAlarm reload_count test on the oscilloscope: reload_count 0 toggles GPIO21 every 1ms, reload_count 500 toggles GPIO22 every 500us

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)

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:

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:

ESP32 Frequency Counter Result

This is the serial monitor output on my ESP32 DevKit V1:

ESP32 timer frequency counter serial monitor output: generated vs measured frequency for 50Hz, 1kHz, 10kHz, 25kHz and 50kHz

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)

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:

ESP32 timerBegin frequency range test serial output: timerBegin returns NULL for 1000Hz, 1220Hz and 80MHz, works from 1221Hz to 40MHz, and rounds 3MHz and 7MHz

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 PeriodExpected FrequencyMeasured FrequencyResult
100µs5kHz5.010kHzWorks
20µs25kHz25.00kHzWorks
10µs50kHz50.56kHz – 50.85kHzWorks, with visible jitter
5µs100kHz96.99kHzBarely: heavy jitter, the ISR can’t keep up
2µs250kHz126kHzFails: 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:

ESP32 timer interrupt every 10us on the oscilloscope: 50kHz square wave on GPIO21 from the timer ISR

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.

ESP32 2us timer interrupt fails on the oscilloscope: GPIO21 toggles at 126kHz instead of 250kHz and the ESP32 hangs

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 jitter on the oscilloscope with infinite persistence: 10us ISR edge timing spread on GPIO21


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:


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:

MethodResolutionWhere Your Code RunsBest For
Hardware timer (timerBegin())25ns (40MHz)Interrupt (ISR)Precise µs timing, pulses, measuring time. 4 timers on the ESP32
esp_timer (ESP-IDF)1µsA high-priority task (callback)Many software timers, periods of 50µs or more, longer callbacks
Ticker library1µs (attach_us()), built on esp_timeresp_timer task (callback)Simple periodic jobs, blinking, polling sensors
FreeRTOS software timer1ms (the RTOS tick)Timer service taskRTOS projects, timeouts
millis() / micros()1ms / 1µsYour 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

Does the ESP32 have an RTC?

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.

Can an ESP32 timer wake it up from deep sleep?

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().

How do I change the ESP32 timer interrupt period while the code is running?

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.

Does the same timer code work on the ESP32-S3 and ESP32-C3?

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.

Do ESP32 timer interrupts work with WiFi?

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.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

14 thoughts on “ESP32 Timer Interrupt (Arduino): timerBegin Examples”

  1. 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.

    Reply
    • 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.

      Reply
  2. 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 🙂

    Reply
  3. 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.

    Reply
  4. 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.

    Reply
  5. 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

    Reply

Leave a Comment