clock, time, watch

ESP32 Software Timer Library

The ESP32 is a great piece of a microcontroller. It sports I2C, SPI, Serial ports, and several GPIO pins that can be programmed or polled at will. The ESP32 also comes with 4 hardware timers that can be utilized.

Timers are frequently used in software for animation, Watch-dog/timeouts, polling of hardware, flashing LEDs, and more.

Timers allow your program to carry on like normal but break off once in a while to perform another task. This is similar to an interrupt, except an interrupt is hardware controlled and there are rules around what you can change from an interrupt handler and how long you can spend there. For example, if you wish to alter the value of a variable, you need to declare that variable as “volatile”.

With a timer handler, you can modify any in-scope variables (including globals) and perform tasks without worrying too much about how much time it takes.

And its all transparent to the main loop of your program.

Introducing my ESP32 Software Timer library.

This software timer implementation allows an unlimited number of timers and has a 1-millisecond resolution. It uses NO hardware timers and only needs a call from your main loop.

Let’s look at an example:

				
					#include "Timer.h"

Timer T;

// Called Automatically by an expired timer
void HandleTimer(TimerInstance *T)
{
    Serial.printf("HandlerTimer is called with %s\n",T->TimerName);
}    

void setup() {
  Serial.begin(115200);

           // TimerName,      mS, Recurring,  Callback Function
  T.AddTimer("OneSecond",  1000, true,       HandleTimer);      // After 1 second, calls HandleTimer. Retriggers
  T.AddTimer("ThreeSecond",  3000, true,       HandleTimer);      // After 3 seconds, calls HandleTimer. Retriggers
  T.AddTimer("FiveSecond",  5000, false,      HandleTimer);     // After 3 seconds, calls HandleTimer. Does not retrigger
}

void loop()
{
  T.loop();    
}
				
			

First, we create an instance of our Timer manager:

				
					#include "Timer.h"
Timer T;
				
			

Next, we create a new timer:

				
					TimerInstance *T1 =   T.AddTimer("OneSecond",  1000, true,       HandleTimer);      // After 1 second, calls HandleTimer. Retriggers
				
			

And finally, call our Timer’s loop method from within your loop function.

				
					void loop()
{
  T.loop();    
}


				
			

And that’s it. Now you have a timer, interrupting your program flow and calling a function intermittently.
Here’s an example of flashing an LED light by adding one line to HandleTimer():

				
					// Called Automatically by an expired timer
void HandleTimer(TimerInstance *T)
{
    Serial.printf("HandlerTimer is called with %s\n",T->TimerName);
    digitalWrite(LED_BUILTIN  , 1-digitalRead(LED_BUILTIN ));  // Toggle LED
}    
				
			

It’s just that easy to flash an LED.

You can find the library at my Github