esp-pwm.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include "driver/ledc.h"
  4. #include "hal/ledc_types.h"
  5. #include "soc/clk_tree_defs.h"
  6. #include "esp_clk_tree.h"
  7. #include "esp_log.h"
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/task.h"
  10. const char* TAG = "MAIN_CPP";
  11. void app_main() {
  12. ESP_LOGI(TAG, "BOOT\n");
  13. const uint32_t timer_freq = 2731;
  14. uint32_t clk_freq = 0;
  15. ESP_ERROR_CHECK(esp_clk_tree_src_get_freq_hz(SOC_MOD_CLK_RC_FAST, ESP_CLK_TREE_SRC_FREQ_PRECISION_EXACT, &clk_freq));
  16. uint32_t duty_resolution = ledc_find_suitable_duty_resolution(clk_freq, timer_freq);
  17. if (duty_resolution == 0) {
  18. ESP_LOGE(TAG, "Could not determine optimal duty resolution.\n");
  19. return;
  20. }
  21. ledc_timer_config_t ledc_config = {
  22. .speed_mode = LEDC_LOW_SPEED_MODE,
  23. .timer_num = LEDC_TIMER_0,
  24. .freq_hz = timer_freq,
  25. .duty_resolution = duty_resolution,
  26. .clk_cfg = LEDC_USE_RC_FAST_CLK
  27. };
  28. ESP_ERROR_CHECK(ledc_timer_config(&ledc_config));
  29. ledc_channel_config_t ledc_ch_config = {
  30. .gpio_num = 9,
  31. .speed_mode = LEDC_LOW_SPEED_MODE,
  32. .channel = LEDC_CHANNEL_0,
  33. .timer_sel = LEDC_TIMER_0,
  34. .duty = (uint32_t) (pow(2, duty_resolution) / 2),
  35. // .hpoint = ((uint32_t) pow(2, duty_resolution)) - 1,
  36. .hpoint = 0,
  37. .sleep_mode = LEDC_SLEEP_MODE_KEEP_ALIVE,
  38. .flags.output_invert = false
  39. };
  40. ESP_ERROR_CHECK(ledc_channel_config(&ledc_ch_config));
  41. while (true) {
  42. vTaskDelay(10000);
  43. }
  44. }