General Purpose Timer (GPTimer)

Introduction

The GPTimer (General Purpose Timer) is the driver of ESP32-C3 Timer Group peripheral. It features a hardware timer with high resolution and flexible alarm action. The behavior when the internal counter of a timer reaches a specific target value is called timer alarm. When a timer alarms, a user registered per-timer callback would be called.

Typically, a general purpose timer can be used in scenarios like:

  • Free running as a wall clock, fetching a high-resolution time stamp at any time and any places

  • Generate period alarms, trigger events periodically

  • Generate one-shot alarm, respond in target time

Functional Overview

The following sections of this document cover the typical steps to install and operate a timer:

  • Resource Allocation - covers which parameters should be set up to get a timer handle and how to recycle the resources when GPTimer finishes working.

  • Set and Get count value - covers how to force the timer counting from a start point and how to get the count value at anytime.

  • Set Up Alarm Action - covers the parameters that should be set up to enable the alarm event.

  • Register Event Callbacks - covers how to hook user specific code to the alarm event callback function.

  • Enable and Disable timer - covers how to enable and disable the timer.

  • Start and Stop timer - shows some typical use cases that start the timer with different alarm behavior.

  • Power Management - describes how different source clock selections can affect power consumption.

  • IRAM Safe - describes tips on how to make the timer interrupt and IO control functions work better along with a disabled cache.

  • Thread Safety - lists which APIs are guaranteed to be thread safe by the driver.

  • Kconfig options - lists the supported Kconfig options that can be used to make a different effect on driver behavior.

Resource Allocation

Different ESP chips might have different numbers of independent timer groups, and within each group, there could also be several independent timers. 1

From driver’s point of view, a GPTimer instance is represented by gptimer_handle_t. The driver behind will manage all available hardware resources in a pool, so that users don’t need to care about which timer and which group it belongs to.

To install a timer instance, there’s a configuration structure that needs to be given in advance: gptimer_config_t:

With all the above configurations set in the structure, the structure can be passed to gptimer_new_timer() which will instantiate the timer instance and return a handle of the timer.

The function can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when there are no more free timers (i.e. all hardware resources have been used up), then ESP_ERR_NOT_FOUND will be returned. The total number of available timers is represented by the SOC_TIMER_GROUP_TOTAL_TIMERS and its value will depend on the ESP chip.

If a previously created GPTimer instance is no longer required, you should recycle the timer by calling gptimer_del_timer(). This will allow the underlying HW timer to be used for other purposes. Before deleting a GPTimer handle, you should disable it by gptimer_disable() in advance or make sure it has not enabled yet by gptimer_enable().

Creating a GPTimer Handle with Resolution of 1MHz

gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT,
    .direction = GPTIMER_COUNT_UP,
    .resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us
};
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));

Set and Get Count Value

When the GPTimer is created, the internal counter will be reset to zero by default. The counter value can be updated asynchronously by gptimer_set_raw_count(). The maximum count value is dependent on the hardware timer’s bit-width, which is also reflected by the SOC macro SOC_TIMER_GROUP_COUNTER_BIT_WIDTH. When updating the raw count of an active timer, the timer will immediately start counting from the new value.

Count value can be retrieved by gptimer_get_raw_count(), at anytime.

Set Up Alarm Action

Most of the use cases of GPTimer should set up the alarm action before starting the timer, except for the simple wall-clock scenario, where a free running timer is enough. To set up the alarm action, one should configure several members of gptimer_alarm_config_t based on how he takes use of the alarm event:

To make the alarm configurations take effect, one should call gptimer_set_alarm_action(). Especially, if gptimer_alarm_config_t is set to NULL, the alarm function will be disabled.

备注

If an alarm value is set and the timer has already crossed this value, the alarm will be triggered immediately.

Register Event Callbacks

After the timer starts up, it can generate specific event (e.g. the “Alarm Event”) dynamically. If you have some function that should be called when event happens, you should hook your function to the interrupt service routine by calling gptimer_register_event_callbacks(). All supported event callbacks are listed in the gptimer_event_callbacks_t:

  • gptimer_event_callbacks_t::on_alarm sets callback function for alarm event. As this function is called within the ISR context, user must ensure that the function doesn’t attempt to block (e.g., by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The function prototype is declared in gptimer_alarm_cb_t.

One can save his own context to gptimer_register_event_callbacks() as well, via the parameter user_data. The user data will be directly passed to the callback functions.

This function will lazy install interrupt service for the timer but not enable it. So user should call this function before gptimer_enable(), otherwise the ESP_ERR_INVALID_STATE error will be returned. See also Enable and Disable timer for more information.

Enable and Disable Timer

Before doing IO control to the timer, user needs to enable the timer first, by calling gptimer_enable(). Internally, this function will:

  • switch the timer driver state from init to enable.

  • enable the interrupt service if it has been lazy installed by gptimer_register_event_callbacks().

  • acquire a proper power management lock if a specific clock source (e.g. APB clock) is selected. See also Power management for more information.

On the contrary, calling gptimer_disable() will do the opposite, that is, put the timer driver back to the init state, disable the interrupts service and release the power management lock.

Start and Stop Timer

The basic IO operation of a timer is to start and stop. Calling gptimer_start() can make the internal counter work, while calling gptimer_stop() can make the counter stop working. The following will illustrate on how to start a timer with or without alarm event.

Start Timer As a Wall Clock

ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
// Retrieve timestamp at anytime
uint64_t count;
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &count));

Trigger Period Events

typedef struct {
    uint64_t event_count;
} example_queue_element_t;

static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    BaseType_t high_task_awoken = pdFALSE;
    QueueHandle_t queue = (QueueHandle_t)user_ctx;
    // Retrieve count value from event data
    example_queue_element_t ele = {
        .event_count = edata->count_value
    };
    // Optional: send the event data to other task by OS queue
    // Don't introduce complex logics in callbacks.
    // Suggest dealing with event data in the main loop, instead of in this callback.
    xQueueSendFromISR(queue, &ele, &high_task_awoken);
    // return whether we need to yield at the end of ISR
    return high_task_awoken == pdTRUE;
}

gptimer_alarm_config_t alarm_config = {
    .reload_count = 0, // counter will reload with 0 on alarm event
    .alarm_count = 1000000, // period = 1s @resolution 1MHz
    .flags.auto_reload_on_alarm = true, // enable auto-reload
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

gptimer_event_callbacks_t cbs = {
    .on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));

Trigger One-Shot Event

typedef struct {
    uint64_t event_count;
} example_queue_element_t;

static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    BaseType_t high_task_awoken = pdFALSE;
    QueueHandle_t queue = (QueueHandle_t)user_ctx;
    // Stop timer the sooner the better
    gptimer_stop(timer);
    // Retrieve count value from event data
    example_queue_element_t ele = {
        .event_count = edata->count_value
    };
    // Optional: send the event data to other task by OS queue
    xQueueSendFromISR(queue, &ele, &high_task_awoken);
    // return whether we need to yield at the end of ISR
    return high_task_awoken == pdTRUE;
}

gptimer_alarm_config_t alarm_config = {
    .alarm_count = 1 * 1000 * 1000, // alarm target = 1s @resolution 1MHz
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

gptimer_event_callbacks_t cbs = {
    .on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));

Dynamic Alarm Update

Alarm value can be updated dynamically inside the ISR handler callback, by changing the gptimer_alarm_event_data_t::alarm_value. Then the alarm value will be updated after the callback function returns.

typedef struct {
    uint64_t event_count;
} example_queue_element_t;

static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    BaseType_t high_task_awoken = pdFALSE;
    QueueHandle_t queue = (QueueHandle_t)user_data;
    // Retrieve count value from event data
    example_queue_element_t ele = {
        .event_count = edata->count_value
    };
    // Optional: send the event data to other task by OS queue
    xQueueSendFromISR(queue, &ele, &high_task_awoken);
    // reconfigure alarm value
    gptimer_alarm_config_t alarm_config = {
        .alarm_count = edata->alarm_value + 1000000, // alarm in next 1s
    };
    gptimer_set_alarm_action(timer, &alarm_config);
    // return whether we need to yield at the end of ISR
    return high_task_awoken == pdTRUE;
}

gptimer_alarm_config_t alarm_config = {
    .alarm_count = 1000000, // initial alarm target = 1s @resolution 1MHz
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

gptimer_event_callbacks_t cbs = {
    .on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer, &alarm_config));

Power Management

When power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will adjust the APB frequency before going into light sleep, thus potentially changing the period of a GPTimer’s counting step and leading to inaccurate time keeping.

However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. Whenever the driver creates a GPTimer instance that has selected GPTIMER_CLK_SRC_APB as its clock source, the driver will guarantee that the power management lock is acquired when enable the timer by gptimer_enable(). Likewise, the driver releases the lock when gptimer_disable() is called for that timer.

If the gptimer clock source is selected to others like GPTIMER_CLK_SRC_XTAL, then the driver won’t install power management lock for it, which is more suitable for a low power application as long as the source clock can still provide sufficient resolution.

IRAM Safe

By default, the GPTimer interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time application.

There’s a Kconfig option CONFIG_GPTIMER_ISR_IRAM_SAFE that will:

  1. Enable the interrupt being serviced even when cache is disabled

  2. Place all functions that used by the ISR into IRAM 2

  3. Place driver object into DRAM (in case it’s mapped to PSRAM by accident)

This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consumption.

There’s another Kconfig option CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So that these functions can also be executable when the cache is disabled. These IO control functions are as follows:

Thread Safety

The factory function gptimer_new_timer() is guaranteed to be thread safe by the driver, which means, user can call it from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context, the driver uses a critical section to prevent them being called concurrently in both task and ISR.

Other functions that take the gptimer_handle_t as the first positional parameter, are not treated as thread safe. Which means the user should avoid calling them from multiple tasks.

Kconfig Options

Application Examples

API Reference

Functions

esp_err_t gptimer_new_timer(const gptimer_config_t *config, gptimer_handle_t *ret_timer)

Create a new General Purpose Timer, and return the handle.

备注

The newly created timer is put in the init state.

参数
  • config[in] GPTimer configuration

  • ret_timer[out] Returned timer handle

返回

  • ESP_OK: Create GPTimer successfully

  • ESP_ERR_INVALID_ARG: Create GPTimer failed because of invalid argument

  • ESP_ERR_NO_MEM: Create GPTimer failed because out of memory

  • ESP_ERR_NOT_FOUND: Create GPTimer failed because all hardware timers are used up and no more free one

  • ESP_FAIL: Create GPTimer failed because of other error

esp_err_t gptimer_del_timer(gptimer_handle_t timer)

Delete the GPTimer handle.

备注

A timer can’t be in the enable state when this function is invoked. See also gptimer_disable() for how to disable a timer.

参数

timer[in] Timer handle created by gptimer_new_timer()

返回

  • ESP_OK: Delete GPTimer successfully

  • ESP_ERR_INVALID_ARG: Delete GPTimer failed because of invalid argument

  • ESP_ERR_INVALID_STATE: Delete GPTimer failed because the timer is not in init state

  • ESP_FAIL: Delete GPTimer failed because of other error

esp_err_t gptimer_set_raw_count(gptimer_handle_t timer, uint64_t value)

Set GPTimer raw count value.

备注

When updating the raw count of an active timer, the timer will immediately start counting from the new value.

备注

This function is allowed to run within ISR context

备注

This function is allowed to be executed when Cache is disabled, by enabling CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM

参数
  • timer[in] Timer handle created by gptimer_new_timer()

  • value[in] Count value to be set

返回

  • ESP_OK: Set GPTimer raw count value successfully

  • ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid argument

  • ESP_FAIL: Set GPTimer raw count value failed because of other error

esp_err_t gptimer_get_raw_count(gptimer_handle_t timer, uint64_t *value)

Get GPTimer raw count value.

备注

With the raw count value and the resolution set in the gptimer_config_t, you can convert the count value into seconds.

备注

This function is allowed to run within ISR context

备注

This function is allowed to be executed when Cache is disabled, by enabling CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM

参数
  • timer[in] Timer handle created by gptimer_new_timer()

  • value[out] Returned GPTimer count value

返回

  • ESP_OK: Get GPTimer raw count value successfully

  • ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid argument

  • ESP_FAIL: Get GPTimer raw count value failed because of other error

esp_err_t gptimer_register_event_callbacks(gptimer_handle_t timer, const gptimer_event_callbacks_t *cbs, void *user_data)

Set callbacks for GPTimer.

备注

User registered callbacks are expected to be runnable within ISR context

备注

This function should be called when the timer is in the init state (i.e. before calling gptimer_enable())

参数
  • timer[in] Timer handle created by gptimer_new_timer()

  • cbs[in] Group of callback functions

  • user_data[in] User data, which will be passed to callback functions directly

返回

  • ESP_OK: Set event callbacks successfully

  • ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument

  • ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init state

  • ESP_FAIL: Set event callbacks failed because of other error

esp_err_t gptimer_set_alarm_action(gptimer_handle_t timer, const gptimer_alarm_config_t *config)

Set alarm event actions for GPTimer.

备注

This function is allowed to run within ISR context, so that user can set new alarm action immediately in the ISR callback.

备注

This function is allowed to be executed when Cache is disabled, by enabling CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM

参数
  • timer[in] Timer handle created by gptimer_new_timer()

  • config[in] Alarm configuration, especially, set config to NULL means disabling the alarm function

返回

  • ESP_OK: Set alarm action for GPTimer successfully

  • ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid argument

  • ESP_FAIL: Set alarm action for GPTimer failed because of other error

esp_err_t gptimer_enable(gptimer_handle_t timer)

Enable GPTimer.

备注

This function will transit the timer state from init to enable.

备注

This function will enable the interrupt service, if it’s lazy installed in gptimer_register_event_callbacks().

备注

This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the gptimer_config_t, while CONFIG_PM_ENABLE is enabled.

备注

Enable a timer doesn’t mean to start it. See also gptimer_start() for how to make the timer start counting.

参数

timer[in] Timer handle created by gptimer_new_timer()

返回

  • ESP_OK: Enable GPTimer successfully

  • ESP_ERR_INVALID_ARG: Enable GPTimer failed because of invalid argument

  • ESP_ERR_INVALID_STATE: Enable GPTimer failed because the timer is already enabled

  • ESP_FAIL: Enable GPTimer failed because of other error

esp_err_t gptimer_disable(gptimer_handle_t timer)

Disable GPTimer.

备注

This function will do the opposite work to the gptimer_enable()

备注

Disable a timer doesn’t mean to stop it. See also gptimer_stop() for how to make the timer stop counting.

参数

timer[in] Timer handle created by gptimer_new_timer()

返回

  • ESP_OK: Disable GPTimer successfully

  • ESP_ERR_INVALID_ARG: Disable GPTimer failed because of invalid argument

  • ESP_ERR_INVALID_STATE: Disable GPTimer failed because the timer is not enabled yet

  • ESP_FAIL: Disable GPTimer failed because of other error

esp_err_t gptimer_start(gptimer_handle_t timer)

Start GPTimer (internal counter starts counting)

备注

This function should be called when the timer is in the enable state (i.e. after calling gptimer_enable())

备注

This function is allowed to run within ISR context

备注

This function will be placed into IRAM if CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is on, so that it’s allowed to be executed when Cache is disabled

参数

timer[in] Timer handle created by gptimer_new_timer()

返回

  • ESP_OK: Start GPTimer successfully

  • ESP_ERR_INVALID_ARG: Start GPTimer failed because of invalid argument

  • ESP_ERR_INVALID_STATE: Start GPTimer failed because the timer is not enabled yet

  • ESP_FAIL: Start GPTimer failed because of other error

esp_err_t gptimer_stop(gptimer_handle_t timer)

Stop GPTimer (internal counter stops counting)

备注

This function should be called when the timer is in the enable state (i.e. after calling gptimer_enable())

备注

This function is allowed to run within ISR context

备注

This function will be placed into IRAM if CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is on, so that it’s allowed to be executed when Cache is disabled

参数

timer[in] Timer handle created by gptimer_new_timer()

返回

  • ESP_OK: Stop GPTimer successfully

  • ESP_ERR_INVALID_ARG: Stop GPTimer failed because of invalid argument

  • ESP_ERR_INVALID_STATE: Stop GPTimer failed because the timer is not enabled yet

  • ESP_FAIL: Stop GPTimer failed because of other error

Structures

struct gptimer_alarm_event_data_t

GPTimer alarm event data.

Public Members

uint64_t count_value

Current count value

uint64_t alarm_value

Current alarm value

struct gptimer_event_callbacks_t

Group of supported GPTimer callbacks.

备注

The callbacks are all running under ISR environment

备注

When CONFIG_GPTIMER_ISR_IRAM_SAFE is enabled, the callback itself and functions callbed by it should be placed in IRAM.

Public Members

gptimer_alarm_cb_t on_alarm

Timer alarm callback

struct gptimer_config_t

General Purpose Timer configuration.

Public Members

gptimer_clock_source_t clk_src

GPTimer clock source

gptimer_count_direction_t direction

Count direction

uint32_t resolution_hz

Counter resolution (working frequency) in Hz, hence, the step size of each count tick equals to (1 / resolution_hz) seconds

uint32_t intr_shared

Set true, the timer interrupt number can be shared with other peripherals

struct gptimer_config_t::[anonymous] flags

GPTimer config flags

struct gptimer_alarm_config_t

General Purpose Timer alarm configuration.

Public Members

uint64_t alarm_count

Alarm target count value

uint64_t reload_count

Alarm reload count value, effect only when auto_reload_on_alarm is set to true

uint32_t auto_reload_on_alarm

Reload the count value by hardware, immediately at the alarm event

struct gptimer_alarm_config_t::[anonymous] flags

Alarm config flags

Type Definitions

typedef struct gptimer_t *gptimer_handle_t

Type of General Purpose Timer handle.

typedef bool (*gptimer_alarm_cb_t)(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)

Timer alarm callback prototype.

Param timer

[in] Timer handle created by gptimer_new_timer()

Param edata

[in] Alarm event data, fed by driver

Param user_ctx

[in] User data, passed from gptimer_register_event_callbacks()

Return

Whether a high priority task has been waken up by this function

Type Definitions

typedef soc_periph_gptimer_clk_src_t gptimer_clock_source_t

GPTimer clock source.

备注

User should select the clock source based on the power and resolution requirement

Enumerations

enum gptimer_count_direction_t

GPTimer count direction.

Values:

enumerator GPTIMER_COUNT_DOWN

Decrease count value

enumerator GPTIMER_COUNT_UP

Increase count value

1

Different ESP chip series might have different numbers of GPTimer instances. Please refer to Chapter Timer Group (TIMG) in ESP32-C3 Technical Reference Manual for more details. The driver won’t forbid you from applying for more timers, but it will return error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g. gptimer_new_timer()).

2

gptimer_event_callbacks_t::on_alarm callback and the functions invoked by itself should also be placed in IRAM, users need to take care of them by themselves.