sound.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "sound.h"
  2. #include <stdio.h>
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. //#include "driver/gpio.h"
  6. #include "esp_log.h"
  7. #include "sdkconfig.h"
  8. //#include "driver/dac.h"
  9. #include "math.h"
  10. #include "config.h"
  11. #include "mqtt.h"
  12. #ifdef SOUND_ENABLED
  13. #define BUZZ_PIN GPIO_NUM_25 // GPIO pin for DAC output GPIO25=Channel 1
  14. #define BUZZ_SHORT_DURATION 200 // Duration of the buzz in ms
  15. #define QUIET_DURATION 1000 // Duration of the quiet period in ms
  16. static bool alarmEnabled = false; // Tracks the state of the normal alarm
  17. static void activate_buzzer(int on_time, int off_time, int repetitions) {
  18. for (int i = 0; i < repetitions; i++) {
  19. gpio_set_level(BUZZ_PIN, 1); // Set GPIO high
  20. vTaskDelay(pdMS_TO_TICKS(on_time)); // Wait for the specified on time
  21. gpio_set_level(BUZZ_PIN, 0); // Set GPIO low
  22. vTaskDelay(pdMS_TO_TICKS(off_time)); // Wait for the specified off time
  23. }
  24. }
  25. static void setupSound() {
  26. // Configure GPIO25 as output and set it to inactive (low) by default
  27. gpio_config_t io_conf = {
  28. .pin_bit_mask = (1ULL << BUZZ_PIN),
  29. .mode = GPIO_MODE_OUTPUT,
  30. .pull_up_en = GPIO_PULLUP_DISABLE,
  31. .pull_down_en = GPIO_PULLDOWN_DISABLE,
  32. .intr_type = GPIO_INTR_DISABLE
  33. };
  34. gpio_config(&io_conf);
  35. // Set GPIO25 to low (inactive)
  36. gpio_set_level(BUZZ_PIN, 0);
  37. ESP_LOGI("SOUND", "Sound setup");
  38. }
  39. static void sound_task(void *pvParameters) {
  40. ESP_LOGI("SOUND", "Sound task starts....");
  41. setupSound();
  42. activate_buzzer(50, 0, 1); // Initial short beep to indicate sound system is ready
  43. while (1) {
  44. while( alarmEnabled ) {
  45. activate_buzzer(BUZZ_SHORT_DURATION, QUIET_DURATION, 1);
  46. }
  47. vTaskDelay(pdMS_TO_TICKS(100)); // Check alarm state every second
  48. }
  49. }
  50. void setAlarmState(bool enabled) {
  51. alarmEnabled = enabled;
  52. //ESP_LOGI("SOUND", "Alarm state set to: %s", enabled ? "ENABLED" : "DISABLED");
  53. }
  54. void triggerNotificationSound() {
  55. ESP_LOGI("SOUND", "Triggering short notification sound");
  56. activate_buzzer(100, 0, 1); // 100ms beep, no quiet time, single iteration
  57. }
  58. void initSound() {
  59. xTaskCreate(sound_task, "sound_task", 2048, NULL, 10, NULL);
  60. ESP_LOGI("SOUND", "Sound initialized");
  61. }
  62. #else
  63. void initSound() {};
  64. void triggerNotificationSound() {};
  65. void setAlarmState(bool enabled) {};
  66. #endif