SpeakerDacSine.ino 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. I2S sine wave
  3. This example produces a digital sine wave on the build in DAC1
  4. which is connected to the speaker
  5. Hardware:
  6. microcontroller board: M5StackFire
  7. speaker amplifier internaly connected to DAC pin 25
  8. September 2018 ChrisMicro
  9. */
  10. #define DACPIN 25 // speaker DAC, only 8 Bit
  11. #define SAMPLINGFREQUENCY 44100
  12. #define NUMBEROFSAMPLES SAMPLINGFREQUENCY * 1 // paly 1 seconds
  13. #define DAC_MAX_AMPLITUDE 127 / 4 // max value is 127, but it is too loud
  14. #define AUDIOBUFFERLENGTH NUMBEROFSAMPLES
  15. uint8_t AudioBuffer[AUDIOBUFFERLENGTH];
  16. void setup() {
  17. const float frequency = 440;
  18. const float amplitude = DAC_MAX_AMPLITUDE;
  19. // store sine wave in buffer
  20. for (int n = 0; n < NUMBEROFSAMPLES; n++) {
  21. int16_t sineWaveSignal =
  22. (sin(2 * PI * frequency / SAMPLINGFREQUENCY * n)) * amplitude;
  23. AudioBuffer[n] = sineWaveSignal + 128;
  24. }
  25. }
  26. void loop() {
  27. uint32_t start = micros();
  28. for (int n = 0; n < NUMBEROFSAMPLES; n++) {
  29. // wait for next sample
  30. while (start + (1000000UL / SAMPLINGFREQUENCY) > micros())
  31. ;
  32. start = micros();
  33. dacWrite(DACPIN, AudioBuffer[n]);
  34. }
  35. delay(3000);
  36. }