/**
* ESP32 Timer Interrupt Demo
*
* Blink LED with hardware timer interrupt.
*
* Date: April 16, 2025
* Author: Mike
* License: 0BSD
*/
// Settings
static const uint16_t timer_divider = 80; // clock ticks at 1 MHz now
static const uint64_t timer_max_count = 1000000;
// Pins (change this if your Arduino board does not have LED_BUILTIN defined)
static const int led_pin = LED_BUILTIN;
// Globals
static hw_timer_t* timer = NULL;
//*****************************************************************************
// Interrupt Service Routines (ISRs)
/**
* Use IRAM_ATTR qualifier to make sure the ISR resdie in the internal ram instead of
* flash so that it can be accessed faster.
*/
void IRAM_ATTR onTimer() {
// Toggle lED.
int pin_state = digitalRead(led_pin);
digitalWrite(led_pin, !pin_state);
}
//*****************************************************************************
// Main (runs as its own task with priority 1 on core 1)
void setup() {
// Pin configuration.
pinMode(led_pin, OUTPUT);
// Serial configuration.
Serial.begin(115200);
vTaskDelay(1000 / portTICK_PERIOD_MS);
Serial.println("---ESP32 Timer Interrupt Demo---");
// Create and start timer (frequency in Hz)
timer = timerBegin(1000000);
// Check if the timer configuration works.
if (timer == NULL){
Serial.println("ERROR: Timer configuration failed. ");
}
else{
Serial.println("Timer configuration is successful. ");
}
// Provide ISR to timer (timer, function)
// Attach interrupt to timer
timerAttachInterrupt(timer, &onTimer);
// Configure alarm value and autoreload of the timer. (timer, alarm_value, autoreload, reload_count)
timerAlarm(timer, timer_max_count, true, 0);
}
void loop() {
// Do nothing
}