Tone Generator
Uses the I2S module to synthesize tones using a minimal amount of Flash memory, RAM and CPU time.
Audio is output via the I2S_TX_DATA pin using Delta-Sigma modulation. This is a high-frequency bitstream which requires low-pass filtering and suitable amplification for driving speaker/headphones.
Warning
Do not connect the output directly to a loudspeaker or headphone as you may damage the GPIO. Always buffer the signal using a transistor, op-amp, etc.
See Esp8266 Drivers for further information about I2S.
As the output pin is normally used as UART0 RX, the alternate UART pin configuration is used:
GPIO |
Alternate |
NodeMCU |
Notes |
---|---|---|---|
3 |
I2S_TX_DATA |
D9 |
Audio output |
13 |
RXD2 |
D7 |
Debug serial input |
15 |
TXD2 |
D8 |
Debug serial output |
GPIO3 is still required for programming so you’ll need to make sure the audio buffer is disconnected, or has a reasonably high impedance load. You’ll also need an additional USB-serial converter connected to GPIO13 & 15 for terminal operation.
API Documentation
-
class ToneGenerator
Generates tones with smooth transitions using Tone Buffers.
Note
During tone playback, a single
active
ToneBuffer feeds the I2S with samples. When a new tone is prepared viaqueueTone()
, a ToneBuffer is added to thepending
queue. If transitioning between tone and silence then additional fade in/out buffers are queued to implement low-pass filtering on these relatively abrupt transitions and thus reduce clicking. CallingsubmitPending()
appends thepending
queue onto thetransition
queue. The transition to the new tone (or silence) is made withini2sWrite()
, at which point buffers are released back to theavail
queue.Public Functions
-
bool begin(unsigned sampleRate)
Initialise the tone generator and I2S.
- Parameters
sampleRate –
- Returns
bool – true on success
-
void end()
Stop playback and un-initialise I2S.
Note
Releases all allocated memory
-
bool start()
Start tone playback.
-
void stop()
Stop tone playback and release any memory allocated for buffers.
Note
Leaves I2S initialised. Call
start()
to resume.
-
ToneBuffer *createTone(Voice voice, unsigned frequency, ToneEffect effect, unsigned repeatCount = 0)
Create a tone and queue it.
- Parameters
voice – Voice to use for tone
frequency – Frequency in Hz
effect –
repeatCount – Specify non-zero to repeat this tone a specific number of times
- Returns
ToneBuffer* – The queued buffer, nullptr on error
-
void queueTone(Voice voice, unsigned frequency)
Create a tone with appropriate filtering.
- Parameters
voice – Voice to use for tone Frequency in Hz @
-
inline void submitPending()
Submit queued tone buffers for playback.
-
bool begin(unsigned sampleRate)
-
class ToneBuffer
Contains samples for one full signal cycle at a specific frequency.
Note
Data is stored Delta-Sigma modulated to minimise I2S transfer overhead.
References
Used by
RingTone Player Sample
Basic Audio Sample
SoC support
esp8266
host