Timers are very important peripherals in embedded systems. If your application depends on precise timing, then timers are only thing that are up for that job.
ESP32 provides four timers in two groups. All the timers are 64 bit each with 16 bit prescaler.
ESP32 timer API features :
configure as up-counter or down-counter
configure a match value (alarm value) , we can provide ISR function which will be executed on match
initial value for counter can be set
can be configured to auto reload the counter value on match
What are we doing here
We are going to user a timer to generate accurate 500Hz square wave with 50% duty cycle. You can easily increase the frequency of the wave with out loosing precision (I am using this example to explain the precision of timers, if you just need a square wave you can simply use PWM API)
You can see in the above image that we have generated 500Hz square wave
Using the timers in ESP32 is very simple. first we need to configure the timer with the required settings, we will be using timer 0 in group 0
timer_init(timer_group, timer_id, &config_struct)
we need to pass timer group, timer id and configuration structure to the timer_init function. Then we can set the initial value for the counter using the following function