SpeakerDacSine.ino 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. {
  18. const float frequency = 440;
  19. const float amplitude = DAC_MAX_AMPLITUDE;
  20. // store sine wave in buffer
  21. for (int n = 0; n < NUMBEROFSAMPLES; n++)
  22. {
  23. int16_t sineWaveSignal = ( sin( 2 * PI * frequency / SAMPLINGFREQUENCY * n )) * amplitude;
  24. AudioBuffer[n] = sineWaveSignal+128;
  25. }
  26. }
  27. void loop()
  28. {
  29. uint32_t start = micros();
  30. for (int n = 0; n < NUMBEROFSAMPLES; n++)
  31. {
  32. // wait for next sample
  33. while (start + ( 1000000UL / SAMPLINGFREQUENCY) > micros() );
  34. start = micros();
  35. dacWrite(DACPIN, AudioBuffer[n]);
  36. }
  37. delay(3000);
  38. }