The timer function on the ESP32 is a crucial feature that allows you to measure time and perform tasks periodically. It is commonly used for:

Reading sensor data: Reading temperature, humidity, light, and other sensor values at specific intervals.

Displaying information: Displaying sensor values or device status on a screen.

Controlling devices: Scheduling the on/off times of lights, motors, or other devices.

Reading and writing data to a server: Timing the reading and writing of data to a cloud server.

In Arduino IDE, there are some functions, such as:

millis( )

The millis() function returns the number of milliseconds that have passed since the program started running. It is useful for tasks that require tracking longer periods of time, such as blinking LEDs, measuring the time between events, or creating non-blocking delays.

unsigned long previousMillis = 0;
const long interval = 1000; // 1 second

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

void loop() { 
unsigned long currentMillis = millis(); 

if (currentMillis - previousMillis >= interval) { 
previousMillis = currentMillis; 
Serial.println("1 second has passed"); 
}
}

micros()

The micros() function returns the number of microseconds that have elapsed since the program started running. It is useful for tasks requiring higher precision, such as measuring pulse timing, or applications that require fast response times.

Pros and cons

Advantages: Non-blocking: These functions do not block the program, allowing you to perform other tasks while waiting. Easy to use: Simply call the function and compare the return value with the desired time. Accuracy: millis() has millisecond accuracy, while micros() has microsecond accuracy. Disadvantages: Time limit: millis() will overflow after approximately 50 days, and micros() will overflow after approximately 70 minutes. However, you can handle overflow using modulo arithmetic.

The timer uses the Ticker library

Using the Ticker library on the ESP32 makes it easy to set up periodic tasks without blocking the main program. This library uses software timers, ensuring efficient use of system resources and allowing for effective management of multiple tasks. Furthermore, Ticker is pre-installed when you set up the ESP32 board, saving you time and effort.

  1. Declaring libraries and variables:

    In the declaration section of your program, you need to declare the Ticker library and create a Ticker object. For example:

    Library declaration: #include <Ticker.h> Creating a Ticker object: Ticker ticker;