Timer
The article explains how to use a hardware timer on ESP32, detailing a RepeatTimer example that demonstrates setting up the timer, triggering it every second, and stopping it with a button on pin 38.
Timer
Example: RepeatTimer
The program uses Timer 0 for timing and prints the timing results to the serial monitor. The timing stops when the user button on P38 is pressed.
Hardware Required:
- ESP32 IoT Programmable Controller (SKU: DFR0886)×1
Example Code:
/*
* Repeat Timer Example
* This example demonstrates how to use a hardware timer on the ESP32.
* The timer calls the onTimer function once per second.
* The timer can be stopped using a button connected to PIN 38 (IO38).
* This example code is in the public domain.
*/
// Stop button connected to PIN 38 (IO38)
#define BTN_STOP_ALARM 38
hw_timer_t * timer = NULL;
volatile SemaphoreHandle_t timerSemaphore;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t isrCounter = 0;
volatile uint32_t lastIsrAt = 0;
void ARDUINO_ISR_ATTR onTimer(){
// Increment counter and record interrupt occurrence time
portENTER_CRITICAL_ISR(&timerMux);
isrCounter++;
lastIsrAt = millis();
portEXIT_CRITICAL_ISR(&timerMux);
// Release semaphore to notify loop of the trigger
xSemaphoreGiveFromISR(timerSemaphore, NULL);
// It is safe to use digitalRead/Write here if an output state switch is needed
}
void setup() {
Serial.begin(115200);
// Set BTN_STOP_ALARM as input mode
pinMode(BTN_STOP_ALARM, INPUT);
// Create a semaphore to notify when the timer triggers
timerSemaphore = xSemaphoreCreateBinary();
// Use the first of the four available timers (index starts at 0)
// Set prescaler value to 80
// The board's clock frequency is currently 80MHz, with 80 prescaler, the count unit is microseconds
timer = timerBegin(0, 80, true);
// Attach the onTimer function to the timer
timerAttachInterrupt(timer, &onTimer, true);
// Set timer alarm to trigger onTimer function every second (value in microseconds)
// Enable repeated alarm (third parameter)
timerAlarmWrite(timer, 1000000, true);
// Start the timer alarm
timerAlarmEnable(timer);
}
void loop() {
// If the timer has triggered
if (xSemaphoreTake(timerSemaphore, 0) == pdTRUE){
uint32_t isrCount = 0, isrTime = 0;
// Read interrupt count and time
portENTER_CRITICAL(&timerMux);
isrCount = isrCounter;
isrTime = lastIsrAt;
portEXIT_CRITICAL(&timerMux);
// Print output
Serial.print("onTimer Trigger Count: ");
Serial.print(isrCount);
Serial.print(" Time: ");
Serial.print(isrTime);
Serial.println(" ms");
}
// If the button is pressed
if (digitalRead(BTN_STOP_ALARM) == LOW) {
// If the timer is still running
if (timer) {
// Stop and release the timer
timerEnd(timer);
timer = NULL;
}
}
}
Result: The serial monitor prints the timer data. When the user button on the board is pressed, the timer stops counting.!

Was this article helpful?
