汎用タイマー(GPTimer)

[English]

この文書は ESP-IDF の汎用タイマー(GPTimer)ドライバーの機能を紹介します。目次は次のとおりです。

概要

GPTimer は ESP32-S3 の [タイマーグループ周辺機能] 向け専用ドライバーです。異なるクロック源とプリスケーラを選び、ナノ秒級分解能の要件に対応できます。柔軟なタイムアウトアラームと、アラーム時のカウント値自動更新により、高精度なタイミング周期を実現します。

ハードウェアタイマーの 高分解能、広いカウント範囲、高応答 を基に、主な用途は次のとおりです。

  • 自由動作のカレンダクロックとして他モジュールへタイムスタンプを提供する

  • 周期アラームで周期タスクを実行する

  • ワンショットアラームで、アラーム値の非同期更新を含む単調増加ソフトタイマリストを実装する

  • GPIO モジュールと組み合わせて PWM 出力や入力キャプチャを行う

  • など

クイックスタート

この節では GPTimer ドライバーの使い方を簡潔に説明します。実例で初期化・開始、アラーム設定、コールバック登録を示します。典型的な流れは次のとおりです。

GPTimer ドライバーの一般的な利用フロー(クリックで拡大)

タイマーの作成と開始

まずタイマーインスタンスを作成します。次のコードは分解能 1 MHz のタイマー作成例です。

gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT, // Select the default clock source
    .direction = GPTIMER_COUNT_UP,      // Counting direction is up
    .resolution_hz = 1 * 1000 * 1000,   // Resolution is 1 MHz, i.e., 1 tick equals 1 microsecond
};
// Create a timer instance
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));
// Enable the timer
ESP_ERROR_CHECK(gptimer_enable(gptimer));
// Start the timer
ESP_ERROR_CHECK(gptimer_start(gptimer));

タイマー作成時は gptimer_config_t でクロック源、カウント方向、分解能などを設定します。これらがタイマーの動作を決めます。gptimer_new_timer() でインスタンスを作るとハンドルが返ります。ハンドル gptimer_handle_t はタイマーメモリオブジェクトへのポインタです。

gptimer_config_t のその他のメンバーは次のとおりです。

  • gptimer_config_t::clk_src はクロック源です。gptimer_clock_source_t に列挙され、1 つだけ選べます。源ごとに分解能、精度、消費電力が異なります。

  • gptimer_config_t::direction はカウント方向です。gptimer_count_direction_t から 1 つ選びます。

  • gptimer_config_t::resolution_hz は内部カウンタの分解能です。1 ティックは 1 / resolution_hz 秒です。

  • gptimer_config_t::intr_priority は割り込み優先度です。0 なら既定優先度、それ以外は指定値を使います。

  • gptimer_config_t::flags でドライバー挙動を微調整します。例:

    • gptimer_config_t::flags::allow_pd はスリープ時に周辺機能の電源オフを許可するかです。スリープ前にレジスタ文脈をバックアップし、復帰時にリストアします。省電力になる一方メモリ消費が増えます。未対応チップで有効にすると not able to power down in light sleep などのエラーになります。

注釈

チップ上のハードウェアタイマーがすべて割り当て済みのとき、gptimer_new_timer() は ESP_ERR_NOT_FOUND を返します。

開始前に gptimer_enable() で有効化が必要です。内部状態機がアクティブになり、電源管理ロック申請などのシステムサービス登録を含みます。gptimer_disable() で解放します。

注釈

gptimer_enable() と gptimer_disable() は対で使い、連続して同じ関数を 2 回呼んではいけません。

gptimer_start() でカウントを開始します。最大/最小(方向による)でオーバーフローし 0 から再開します。 gptimer_stop() で停止します。停止は現在カウント値をクリアしません。クリアは後述の gptimer_set_raw_count() を使います。 gptimer_start() と gptimer_stop() は冪等です。既に開始/停止済みなら再呼び出しは効果がありません。

注釈

開始の**中間状態** (開始処理の途中)のとき、別スレッドが gptimer_start() や gptimer_stop() を呼ぶと ESP_ERR_INVALID_STATE を返し、不確定動作を避けます。

カウント値の設定と取得

新規タイマーの内部カウンタは既定で 0 です。gptimer_set_raw_count() で別の値に設定できます。最大値はハードウェアのビット幅に依存します(通常 54 bits 以上)。

注釈

動作中に gptimer_set_raw_count() を呼ぶと、即座に新しい値へジャンプし、そこからカウントします。

gptimer_get_raw_count() は現在のカウント値を取得します(0 開始と仮定した累積値)。単位変換前の生カウントです。時間へは分解能に基づき変換し、分解能は gptimer_get_resolution() で取得します。

// Check the timer's resolution
uint32_t resolution_hz;
ESP_ERROR_CHECK(gptimer_get_resolution(gptimer, &resolution_hz));
// Read the current count value
uint64_t count;
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &count));
// (Optional) Convert the count value to time units (seconds)
double time = (double)count / resolution_hz;

周期アラームイベントの発生

タイムスタンプに加え、アラーム機能をサポートします。次は 1 秒ごとに発火する周期アラームの設定例です。

gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT, // Select the default clock source
    .direction = GPTIMER_COUNT_UP,      // Counting direction is up
    .resolution_hz = 1 * 1000 * 1000,   // Resolution is 1 MHz, i.e., 1 tick equals 1 microsecond
};
// Create a timer instance
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));

static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    // General process for handling event callbacks:
    // 1. Retrieve user context data from user_ctx (passed in from gptimer_register_event_callbacks)
    // 2. Get alarm event data from edata, such as edata->count_value
    // 3. Perform user-defined operations
    // 4. Return whether a high-priority task was awakened during the above operations to notify the scheduler to switch tasks
    return false;
}

gptimer_alarm_config_t alarm_config = {
    .reload_count = 0,      // When the alarm event occurs, the timer will automatically reload to 0
    .alarm_count = 1000000, // Set the actual alarm period, since the resolution is 1us, 1000000 represents 1s
    .flags.auto_reload_on_alarm = true, // Enable auto-reload function
};
// Set the timer's alarm action
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

gptimer_event_callbacks_t cbs = {
    .on_alarm = example_timer_on_alarm_cb, // Call the user callback function when the alarm event occurs
};
// Register timer event callback functions, allowing user context to be carried
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, NULL));
// Enable the timer
ESP_ERROR_CHECK(gptimer_enable(gptimer));
// Start the timer
ESP_ERROR_CHECK(gptimer_start(gptimer));

gptimer_set_alarm_action() でアラーム動作を設定します。カウントが指定アラーム値に達するとアラームイベントが発生します。発生時に既定カウントを自動リロードすれば周期アラームになります。

gptimer_alarm_config_t の主要メンバーは次のとおりです。

  • gptimer_alarm_config_t::alarm_count はアラームを発火させる目標カウントです。到達でイベント発生。カウント方向を考慮し、現在値がアラーム値を**超えていれば**即時発火します。

  • gptimer_alarm_config_t::reload_count はアラーム時にリロードするカウントです。gptimer_alarm_config_t::flags::auto_reload_on_alarm が true のときのみ有効です。実際の周期は |alarm_count - reload_count| です。実用上 5 µs 未満の周期は非推奨です。

注釈

gptimer_set_alarm_action(gptimer, NULL); はアラーム機能の無効化を意味します。

gptimer_register_event_callbacks() でイベントコールバックを登録します。割り込みコンテキストで実行されるため、ブロックや複雑処理は避けてください。user_data でコンテキストを渡せます。

GPTimer でサポートするコールバック:

  • gptimer_alarm_cb_t アラームコールバック。データは gptimer_alarm_event_data_t: - gptimer_alarm_event_data_t::alarm_value は目標アラーム値です。 - gptimer_alarm_event_data_t::count_value は割り込みハンドラ入り時のカウントで、遅延や自動リロードによりアラーム値と異なることがあります。

注釈

gptimer_enable() の前にコールバックを登録してください。さもないと割り込みが正しく動きません。

ワンショットアラームイベントの発生

ワンショットアラームだけが必要な用途もあります。次は 1 秒後に 1 回だけ発火する例です。

gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT, // Select the default clock source
    .direction = GPTIMER_COUNT_UP,      // Counting direction is up
    .resolution_hz = 1 * 1000 * 1000,   // Resolution is 1 MHz, i.e., 1 tick equals 1 microsecond
};
// Create a timer instance
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));

static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    // This is just a demonstration of how to stop the timer when the alarm occurs for the first time
    gptimer_stop(timer);
    // General process for handling event callbacks:
    // 1. Retrieve user context data from user_ctx (passed in from gptimer_register_event_callbacks)
    // 2. Get alarm event data from edata, such as edata->count_value
    // 3. Perform user-defined operations
    // 4. Return whether a high-priority task was awakened during the above operations to notify the scheduler to switch tasks
    return false;
}

gptimer_alarm_config_t alarm_config = {
    .alarm_count = 1000000, // Set the actual alarm period, since the resolution is 1us, 1000000 represents 1s
    .flags.auto_reload_on_alarm = false; // Disable auto-reload function
};
// Set the timer's alarm action
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

gptimer_event_callbacks_t cbs = {
    .on_alarm = example_timer_on_alarm_cb, // Call the user callback function when the alarm event occurs
};
// Register timer event callback functions, allowing user context to be carried
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, NULL));
// Enable the timer
ESP_ERROR_CHECK(gptimer_enable(gptimer));
// Start the timer
ESP_ERROR_CHECK(gptimer_start(gptimer));

周期アラームと異なり、上記は自動リロードを無効にします。アラーム後は既定値へ戻らずオーバーフローまでカウントします。アラーム直後に停止したい場合はコールバックで gptimer_stop() を呼びます。

リソースの解放

不要になったら gptimer_delete_timer() でソフトウェア/ハードウェアリソースを解放します。削除前に停止済みであることを確認してください。

高度な機能

基本を理解したら、GPTimer の追加機能を掘り下げられます。

動的アラーム値の更新

コールバック内で gptimer_set_alarm_action() を呼び、アラーム値を動的更新して単調増加ソフトタイマリストを実装できます。次はアラーム発生時に次の発火時刻を再設定する例です。

gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT, // Select the default clock source
    .direction = GPTIMER_COUNT_UP,      // Counting direction is up
    .resolution_hz = 1 * 1000 * 1000,   // Resolution is 1 MHz, i.e., 1 tick equals 1 microsecond
};
// Create a timer instance
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));

static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    gptimer_alarm_config_t alarm_config = {
        .alarm_count = edata->alarm_value + 1000000, // Next alarm in 1s from the current alarm
    };
    // Update the alarm value
    gptimer_set_alarm_action(timer, &alarm_config);
    return false;
}

gptimer_alarm_config_t alarm_config = {
    .alarm_count = 1000000, // Set the actual alarm period, since the resolution is 1us, 1000000 represents 1s
    .flags.auto_reload_on_alarm = false, // Disable auto-reload function
};
// Set the timer's alarm action
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

gptimer_event_callbacks_t cbs = {
    .on_alarm = example_timer_on_alarm_cb, // Call the user callback function when the alarm event occurs
};
// Register timer event callback functions, allowing user context to be carried
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, NULL));
// Enable the timer
ESP_ERROR_CHECK(gptimer_enable(gptimer));
// Start the timer
ESP_ERROR_CHECK(gptimer_start(gptimer));

電源管理

電源管理 CONFIG_PM_ENABLE が有効なとき、スリープ前にクロック源が調整/無効化され、GPTimer の精度が失われることがあります。

GPTimer ドライバーは内部で電源管理ロックを作成します。gptimer_enable() でロックが有効になり、システムがスリープに入らず精度を維持します。消費電力を下げるには gptimer_disable() でロックを解放できますがタイマーは止まるため、復帰後に再開が必要です。

スレッドセーフ

ドライバーはクリティカルセクションでレジスタ操作の原子性を保証します。ハンドル内の主要メンバーも保護されます。内部状態機はアトミック命令でスレッドセーフを確保し、無効な同時操作(start と stop の競合など)を防ぎます。追加ロックなしでマルチスレッド環境で API を使えます。

割り込みコンテキストでも使える関数:

  • gptimer_start()

  • gptimer_stop()

  • gptimer_get_raw_count()

  • gptimer_set_raw_count()

  • gptimer_get_captured_count()

  • gptimer_set_alarm_action()

キャッシュセーフ

Flash 読み書き時はキャッシュが一時無効になり、この間 GPTimer 割り込みハンドラーが応答できずコールバックが遅れることがあります。キャッシュ無効時もハンドラーを動かすには CONFIG_GPTIMER_ISR_CACHE_SAFE を有効にします。

注釈

有効時、割り込みコールバックとコンテキストデータは**内部ストレージ**に置く必要があります。キャッシュ無効時は Flash から読み込めないためです。

性能

割り込み応答を改善するため CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM があります。有効時ハンドラーを内部 RAM に置き、Flash 読み出しのキャッシュミス遅延を減らします。

注釈

コールバックとコンテキストは Flash に残る可能性があり、IRAM_ATTR と DRAM_ATTR で手動配置が必要な場合があります。

割り込みコンテキストで呼べる一部関数は CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM で IRAM 配置でき、キャッシュミス損失を避け、キャッシュ無効時にも使えます。

その他の Kconfig オプション

  • CONFIG_GPTIMER_ENABLE_DEBUG_LOG はグローバルログレベルに関わらず GPTimer のデバッグログをすべて有効にします。デバッグ時の詳細ログ取得に役立ちます。

リソース消費

idf-size(英語) でコード/データ消費を確認できます。以下は ESP32-C2 を例とした試験条件です。

  • コンパイラ最適化 -Os で最小コードサイズ。

  • 既定ログレベル ESP_LOG_INFO。

  • 次の最適化オプションを無効:
    • CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM — 割り込みハンドラーを IRAM に置かない。

    • CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM — 制御関数を IRAM に置かない。

    • CONFIG_GPTIMER_ISR_CACHE_SAFE — キャッシュセーフを有効にしない。

以下の数値は参考値であり、チップモデルで異なる場合があります。

Component Layer

Total Size

DIRAM

.bss

.data

.text

Flash Code

.text

Flash Data

.rodata

soc

8

0

0

0

0

0

0

8

8

hal

206

0

0

0

0

206

206

0

0

driver

4251

12

12

0

0

4046

4046

193

193

各 GPTimer ハンドルはヒープから約 100 バイトを動的割り当てします。gptimer_config_t::flags::allow_pd が有効なら、スリープ中にレジスタ文脈保存で約 30 バイト追加を消費します。

アプリケーション例

  • peripherals/timer_group/gptimer は ESP SoC で汎用タイマー API を使い周期アラームと各種アラーム動作を生成する方法を示します。

  • peripherals/timer_group/wiegand_interface は 2 タイマー(ワンショットと周期)でアラームコールバックから割り込みと GPIO 出力を変え、Wiegand 波形を模倣します。

API リファレンス

GPTimer ドライバー API

注釈

このビルドには、Doxygen が生成する関数一覧は含まれません。関数シグネチャは英語版を参照してください。

英語版の関数一覧

GPTimer ドライバー型

注釈

型定義の Doxygen 一覧は英語版を参照してください。

英語版

GPTimer HAL 型

注釈

HAL 型の Doxygen 一覧は英語版を参照してください。

英語版

GPTimer ETM API