ABC of Electronics cosycom.com
ESP32 BASICS · LESSON 18

Hardware Timers & the RTC

Scheduling code to run at precise intervals without blocking the rest of your program.

Hardware timers let the ESP32 run a piece of code at a precise, repeating interval without a delay() call blocking everything else — essential once a sketch needs to juggle more than one task.

timer_basic.ino
hw_timer_t* timer = NULL;
volatile bool tick = false;

void IRAM_ATTR onTimer() {
  tick = true;
}

void setup() {
  Serial.begin(115200);
  timer = timerBegin(0, 80, true);       // 80 prescaler -> 1 MHz tick
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 1000000, true); // fire every 1,000,000 ticks = 1s
  timerAlarmEnable(timer);
}

void loop() {
  if (tick) {
    Serial.println("One second passed");
    tick = false;
  }
}

The RTC

Separately, the ESP32 keeps a real-time clock that continues running through deep sleep and can be used to wake the chip after a set delay, as covered in the deep sleep lesson, or to keep a rough sense of wall-clock time once it's been synced over the network.

KEY IDEA
Hardware timers and millis()-based timing solve the same problem — hardware timers just don't depend on your main loop being free to check the clock.