sound.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 DAC_CHANNEL 1
  14. #define DAC_PIN GPIO_NUM_25 // GPIO pin for DAC output GPIO25=Channel 1
  15. #define TONE_FREQ 440 // Frequency of the tone in Hz
  16. #define TONE_DURATION 1000 // Duration of the tone in ms
  17. #define QUIET_DURATION 1000 // Duration of the quiet period in ms
  18. bool soundEnabled = false;
  19. static void play_tone(int frequency, float duration, int quietDuration) {
  20. int semitones = 0;
  21. int t_freq = frequency * pow(2.0, semitones / 12.0);
  22. int8_t cw_offset = 0;
  23. dac_cw_config_t cosineConf = {DAC_CHANNEL_1, DAC_CW_SCALE_8, DAC_CW_PHASE_0, t_freq, cw_offset};
  24. if (frequency == 0) {
  25. dac_output_disable(DAC_CHANNEL_1);
  26. } else {
  27. dac_cw_generator_config(&cosineConf);
  28. dac_output_enable(DAC_CHANNEL_1);
  29. }
  30. // Loop with 50mS loops until the duration is complete
  31. for(int i = 0; i < duration; i+=50) {
  32. vTaskDelay(pdMS_TO_TICKS(50));
  33. if( soundEnabled == false ) {
  34. break;
  35. }
  36. }
  37. dac_output_disable(DAC_CHANNEL_1);
  38. }
  39. static void setupSound() {
  40. int8_t cw_offset = 0;
  41. dac_cw_config_t cosineConf = {DAC_CHANNEL_1, DAC_CW_SCALE_8, DAC_CW_PHASE_0, 440, cw_offset};
  42. dac_output_disable(DAC_CHANNEL_1);
  43. dac_cw_generator_config(&cosineConf);
  44. dac_cw_generator_enable();
  45. dac_output_disable(DAC_CHANNEL_1);
  46. ESP_LOGI("SOUND", "Sound setup");
  47. }
  48. static void sound_task(void *pvParameters) {
  49. ESP_LOGI("SOUND", "Sound task starts....");
  50. setupSound();
  51. while (1) {
  52. vTaskDelay(pdMS_TO_TICKS(1000));
  53. if( soundEnabled ) {
  54. play_tone(TONE_FREQ, TONE_DURATION, QUIET_DURATION);
  55. }
  56. }
  57. }
  58. void initSound() {
  59. xTaskCreate(sound_task, "sound_task", 2048, NULL, 10, NULL);
  60. ESP_LOGI("SOUND", "Sound initialized");
  61. }
  62. void enableNotificationSound(bool enable)
  63. {
  64. if (soundEnabled != enable) {
  65. ESP_LOGI("SOUND", "Notification sound %s", enable ? "enabled" : "disabled");
  66. char mqtt_s[50];
  67. char value_s[10];
  68. sprintf(mqtt_s,"kitchen/fridge/doorAlarm");
  69. sprintf(value_s,"%s",enable ? "active" : "inactive");
  70. sendMQTTMessage(mqtt_s, value_s);
  71. }
  72. soundEnabled = enable;
  73. }
  74. #else
  75. void initSound() {};
  76. void enableNotificationSound(bool enable) {};
  77. #endif