Xinyuan-LilyGO / T-Deck

191 stars 43 forks source link

How to generate a simple tone on speaker #15

Open spleenware opened 8 months ago

spleenware commented 8 months ago

Can you add an example sketch on how to generate a simple tone to play on the built-in speaker (over I2S, I assume?).

technoblogy commented 8 months ago

Here's a simple version:

void beep (int freq, int duration) {
  I2S.setAllPins(7, 5, 6, 6, 6); // sckPin, fsPin, sdPin, outSdPin, inSdPin
  const int samplerate = 8000;
  int halfwave = samplerate / freq, amplitude = 500;
  unsigned long start = millis();
  if (!I2S.begin(I2S_PHILIPS_MODE, samplerate, 16)) return; // Error
  while (millis() < start + duration) {
    if (count % halfwave == 0) amplitude = -1 * amplitude;
    I2S.write(amplitude); I2S.write(amplitude);
  }
  I2S.end();
}

The frequency is in Hz and the duration in milliseconds.

spleenware commented 8 months ago

Which header files are needed, and how is I2S object constructed? (specifically for ESP32/T-Deck target)

technoblogy commented 8 months ago

You need:

#include <I2S.h>

I also found I needed this:

#include "soc/periph_defs.h" // Not sure why necessary

It's based on the SimpleTone example which is in the ESP32 core at:

/Users/david/Library/Arduino15/packages/esp32/hardware/esp32/2.0.12/libraries/I2S/examples/SimpleTone
spleenware commented 8 months ago

Ah, thank you. I hear a beep now! :-)

aaron-924 commented 3 weeks ago

Is there a reason why "Play MP3" doesn't work in the UnitTest code?