README.md
1# _LEDC Basic Example_
2
3(See the README.md file in the upper level 'examples' directory for more information about examples.)
4
5This example shows how to use the LEDC to generate a PWM signal using the `LOW SPEED` mode.
6To use `HIGH SPEED` mode check if the selected SoC supports this mode.
7
8## How to use example
9
10### Hardware Required
11
12* A development board with ESP32, ESP32-S2, ESP32-C3 or ESP32-S3 SoC (e.g., ESP32-DevKitC, ESP-WROVER-KIT, etc.)
13* A USB cable for power supply and programming
14
15Connect the GPIO to an oscilloscope to see the generated signal:
16
17|ledc channel| GPIO |
18|:----------:|:-----:|
19| Channel 0 | GPIO5 |
20
21### Configure the project
22
23The example uses fixed PWM frequency of 5 kHz, duty cycle in 50%, and output GPIO pin. To change them, adjust `LEDC_FREQUENCY`, `LEDC_DUTY`, `LEDC_OUTPUT_IO` macros at the top of ledc_basic_example_main.c.
24
25Depending on the selected `LEDC_FREQUENCY`, you will need to change the `LEDC_DUTY_RES`.
26
27To dinamicaly set the duty and frequency, you can use the following functions:
28
29To set the frequency to 2.5 kHZ i.e:
30
31```c
32ledc_set_freq(LEDC_MODE, LEDC_TIMER, 2500);
33```
34
35Now the duty to 100% i.e:
36
37```c
38ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 8191);
39ledc_update_duty(LEDC_MODE, LEDC_CHANNEL);
40```
41
42To change the duty cycle you need to calculate the duty range according to the duty resolution.
43
44If duty resolution is 13 bits:
45
46Duty range: `0 to (2 ** 13) - 1 = 8191` where 0 is 0% and 8191 is 100%.
47
48### Build and Flash
49
50* [ESP-IDF Getting Started Guide](https://idf.espressif.com/)
51
52Build the project and flash it to the board, then run monitor tool to view serial output:
53
54```bash
55idf.py -p PORT flash monitor
56```
57
58(To exit the serial monitor, type ``Ctrl-]``.)
59
60See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
61
62## Example Output
63
64Running this example, you will see the PWM signal with a duty cycle of 50%.
65
66![PWM](image/ledc_pwm_signal.png)
67
68## Troubleshooting
69
70* Duty Resolution
71
72 * If you get the following error log `ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution.` you need to change the `LEDC_DUTY_RES` to a lower resolution and change the range of the duty.
73
74* Programming fail
75
76 * Hardware connection is not correct: run `idf.py -p PORT monitor`, and reboot your board to see if there are any output logs.
77 * The baud rate for downloading is too high: lower your baud rate in the `menuconfig` menu, and try again.
78
79For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon.
80