SineTone.ino
1 // SPDX-FileCopyrightText: 2017 Limor Fried for Adafruit Industries 2 // 3 // SPDX-License-Identifier: MIT 4 5 /* 6 This example generates a sine wave based tone at a specified frequency 7 and sample rate. Then outputs the data using the I2S interface. 8 9 Public Domain 10 */ 11 12 #include <I2S.h> 13 14 #define FREQUENCY 440 // frequency of sine wave in Hz 15 #define AMPLITUDE 10000 // amplitude of sine wave 16 #define SAMPLERATE 44100 // sample rate in Hz 17 18 int16_t sinetable[SAMPLERATE / FREQUENCY]; 19 uint32_t sample = 0; 20 21 #define PI 3.14159265 22 23 void setup() { 24 Serial.begin(115200); 25 Serial.println("I2S sine wave tone"); 26 27 // start I2S at the sample rate with 16-bits per sample 28 if (!I2S.begin(I2S_PHILIPS_MODE, SAMPLERATE, 16)) { 29 Serial.println("Failed to initialize I2S!"); 30 while (1); // do nothing 31 } 32 33 // fill in sine wave table 34 for (uint16_t s=0; s < (SAMPLERATE / FREQUENCY); s++) { 35 sinetable[s] = sin(2.0 * PI * s / (SAMPLERATE/FREQUENCY)) * AMPLITUDE; 36 } 37 } 38 39 40 void loop() { 41 if (sample == (SAMPLERATE / FREQUENCY)) { 42 sample = 0; 43 } 44 45 // write the same sample twice, once for left and once for the right channel 46 I2S.write((int16_t) sinetable[sample]); // We'll just have same tone on both! 47 I2S.write((int16_t) sinetable[sample]); 48 49 // increment the counter for the next sample in the sine wave table 50 sample++; 51 }