ledc_fade.c

ESP32-H2 · File : ledc_fade.c · Language : C · Use case : Respiration LED avec le contrôleur LEDC

The H2 LEDC ramps by itself: ledc_set_fade_with_time computes the steps and the hardware applies the ramp while the CPU sleeps. Two calls per cycle for a 0-100% round trip in 1 s.

Hardware required

An ESP32-H2 board (RISC-V 96 MHz, IEEE 802.15.4 radio only — no Wi-Fi) such as a DevKitM-1, powered over USB. 1 LED + 330 Ω resistor on GPIO8 (or the user LED).

Wiring

LED anode on GPIO8 through 330 Ω, cathode GND. Any pin routable to the low-speed LEDC works.

How it works

An LEDC timer sets frequency (5 kHz) and resolution (10 bits); the channel carries the duty cycle. fade_start without wait launches the ramp the peripheral unwinds with no CPU task. Program it with ESP-IDF (idf.py set-target esp32h2); the USB-Serial/JTAG port (GPIO26/27) acts as console and flash port. Hold Boot + Reset for download mode if needed.

Going further

Two channels on the R and B pins of an RGB LED for a color gradient, or sync the ramp with the 802.15.4 radio.

ledc_fade.c

// ledc_fade.c — rampe automatique du LEDC (hardware fade).
#include "driver/ledc.h"
#include "esp_log.h"

#define CANAL LEDC_CHANNEL_0
#define PIN   GPIO_NUM_8

static const char *TAG = "fade";

void app_main(void)
{
    ledc_timer_config_t timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE, .duty_resolution = 10,
        .timer_num = LEDC_TIMER_0, .freq_hz = 5000, .clk_cfg = LEDC_AUTO_CLK,
    };
    ESP_ERROR_CHECK(ledc_timer_config(&timer));
    ledc_channel_config_t ch = {
        .channel = CANAL, .duty = 0, .gpio_num = PIN,
        .speed_mode = LEDC_LOW_SPEED_MODE, .timer_sel = LEDC_TIMER_0,
    };
    ESP_ERROR_CHECK(ledc_channel_config(&ch));
    ledc_fade_func_install(0);

    while (1) {
        ESP_LOGI(TAG, "montee");
        ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE, CANAL, 1023, 1000);
        ledc_fade_start(LEDC_LOW_SPEED_MODE, CANAL, LEDC_FADE_NO_WAIT);
        vTaskDelay(pdMS_TO_TICKS(1100));
        ESP_LOGI(TAG, "descente");
        ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE, CANAL, 0, 1000);
        ledc_fade_start(LEDC_LOW_SPEED_MODE, CANAL, LEDC_FADE_NO_WAIT);
        vTaskDelay(pdMS_TO_TICKS(1100));
    }
}

← Back to the board