ledc_basic_example_main.c 2.0 KB

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