ESP-IDF : Using timers in ESP32

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)

ESP32 Timers
ESP32 Timers

You can see in the above image that we have generated 500Hz square wave

Program:

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

    timer_set_counter_value(timer_group, timer_id, counter_init_value)

Match value(at which counter value, the interrupt will be triggered) can specified using timer_set_alarm_value

    timer_set_alarm_value(timer_group, timer_id, match_value)

we have initialized the timer and we set the alarm value also , now we need to enable interrupts and specify the ISR

    timer_enable_intr(timer_group, timer_id)
    timer_isr_register(timer_group, timer_id, isr_func_name, prams_to_isr, ESP_INTR_FLAG_IRAM, handle_for_interrupt)

and finally start the timer

    timer_start(timer_group, timer_id)

full code is available on this git repo

 

10 Comments

Add a Comment

Your email address will not be published. Required fields are marked *