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