alarm.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * SPDX-FileCopyrightText: 2023 Helmut Pozimski <helmut@pozimski.eu>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0-only
  5. */
  6. #include <driver/ledc.h>
  7. #include <esp_err.h>
  8. #include <freertos/FreeRTOS.h>
  9. #include <freertos/event_groups.h>
  10. #define MODE LEDC_LOW_SPEED_MODE
  11. #define CHANNEL LEDC_CHANNEL_0
  12. #define DUTY 4095
  13. /* TODO: This code works reasonably well for low frequencies
  14. * but has nasty high-pitched interference for high frequencies.
  15. * It needs to be checked if this is caused by the code or the
  16. * circutry.
  17. */
  18. void alarm_init(uint32_t frequency) {
  19. ledc_timer_config_t ledc_timer = {
  20. .speed_mode = MODE,
  21. .timer_num = LEDC_TIMER_0,
  22. .duty_resolution = LEDC_TIMER_13_BIT,
  23. .freq_hz = frequency, // Set output frequency at 5 kHz
  24. .clk_cfg = LEDC_AUTO_CLK
  25. };
  26. ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
  27. ledc_channel_config_t ledc_channel = {
  28. .speed_mode = MODE,
  29. .channel = CHANNEL,
  30. .timer_sel = LEDC_TIMER_0,
  31. .intr_type = LEDC_INTR_DISABLE,
  32. .gpio_num = 5,
  33. .duty = 0,
  34. .hpoint = 0
  35. };
  36. ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
  37. }
  38. void beep(uint32_t length_ms) {
  39. ESP_ERROR_CHECK(ledc_set_duty(MODE, CHANNEL, DUTY));
  40. ESP_ERROR_CHECK(ledc_update_duty(MODE, CHANNEL));
  41. vTaskDelay(length_ms / portTICK_PERIOD_MS);
  42. ESP_ERROR_CHECK(ledc_set_duty(MODE, CHANNEL, 0));
  43. ESP_ERROR_CHECK(ledc_update_duty(MODE, CHANNEL));
  44. }