1 /* LEDC (LED Controller) basic example
2
3 This example code is in the Public Domain (or CC0 licensed, at your option.)
4
5 Unless required by applicable law or agreed to in writing, this
6 software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7 CONDITIONS OF ANY KIND, either express or implied.
8 */
9 #include <stdio.h>
10 #include "driver/ledc.h"
11 #include "esp_err.h"
12
13 #define LEDC_TIMER LEDC_TIMER_0
14 #define LEDC_MODE LEDC_LOW_SPEED_MODE
15 #define LEDC_OUTPUT_IO (5) // Define the output GPIO
16 #define LEDC_CHANNEL LEDC_CHANNEL_0
17 #define LEDC_DUTY_RES LEDC_TIMER_13_BIT // Set duty resolution to 13 bits
18 #define LEDC_DUTY (4095) // Set duty to 50%. ((2 ** 13) - 1) * 50% = 4095
19 #define LEDC_FREQUENCY (5000) // Frequency in Hertz. Set frequency at 5 kHz
20
example_ledc_init(void)21 static void example_ledc_init(void)
22 {
23 // Prepare and then apply the LEDC PWM timer configuration
24 ledc_timer_config_t ledc_timer = {
25 .speed_mode = LEDC_MODE,
26 .timer_num = LEDC_TIMER,
27 .duty_resolution = LEDC_DUTY_RES,
28 .freq_hz = LEDC_FREQUENCY, // Set output frequency at 5 kHz
29 .clk_cfg = LEDC_AUTO_CLK
30 };
31 ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
32
33 // Prepare and then apply the LEDC PWM channel configuration
34 ledc_channel_config_t ledc_channel = {
35 .speed_mode = LEDC_MODE,
36 .channel = LEDC_CHANNEL,
37 .timer_sel = LEDC_TIMER,
38 .intr_type = LEDC_INTR_DISABLE,
39 .gpio_num = LEDC_OUTPUT_IO,
40 .duty = 0, // Set duty to 0%
41 .hpoint = 0
42 };
43 ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
44 }
45
app_main(void)46 void app_main(void)
47 {
48 // Set the LEDC peripheral configuration
49 example_ledc_init();
50 // Set duty to 50%
51 ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, LEDC_DUTY));
52 // Update duty to apply the new value
53 ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
54 }
55