-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Copy pathSimple_tone.ino
83 lines (69 loc) · 2.23 KB
/
Simple_tone.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
This example generates a square wave based tone at a specified frequency
and sample rate. Then outputs the data using the I2S interface to a
MAX08357 I2S Amp Breakout board.
I2S Circuit:
* Arduino/Genuino Zero, MKR family and Nano 33 IoT
* MAX08357:
* GND connected GND
* VIN connected 5V
* LRC connected to pin 0 (Zero) or 3 (MKR), A2 (Nano) or 25 (ESP32)
* BCLK connected to pin 1 (Zero) or 2 (MKR), A3 (Nano) or 5 (ESP32)
* DIN connected to pin 9 (Zero) or A6 (MKR), 4 (Nano) or 26 (ESP32)
DAC Circuit:
* ESP32 or ESP32-S2
* Audio amplifier
- Note:
- ESP32 has DAC on GPIO pins 25 and 26.
- ESP32-S2 has DAC on GPIO pins 17 and 18.
- Connect speaker(s) or headphones.
created 17 November 2016
by Sandeep Mistry
For ESP extended
Tomas Pilny
2nd September 2021
Lucas Saavedra Vaz (lucasssvaz)
22nd December 2023
anon
10nd February 2025
*/
#include <ESP_I2S.h>
// The GPIO pins are not fixed, most other pins can be used for the I2S function.
#define I2S_LRC 25
#define I2S_BCLK 5
#define I2S_DIN 26
const int frequency = 440; // frequency of square wave in Hz
const int amplitude = 500; // amplitude of square wave
const int sampleRate = 8000; // sample rate in Hz
i2s_data_bit_width_t bps = I2S_DATA_BIT_WIDTH_16BIT;
i2s_mode_t mode = I2S_MODE_STD;
i2s_slot_mode_t slot = I2S_SLOT_MODE_STEREO;
const int halfWavelength = sampleRate / frequency / 2; // half wavelength of square wave
int32_t sample = amplitude; // current sample value
unsigned int count = 0;
I2SClass i2s;
void setup() {
Serial.begin(115200);
Serial.println("I2S simple tone");
i2s.setPins(I2S_BCLK, I2S_LRC, I2S_DIN);
// start I2S at the sample rate with 16-bits per sample
if (!i2s.begin(mode, sampleRate, bps, slot)) {
Serial.println("Failed to initialize I2S!");
while (1)
; // do nothing
}
}
void loop() {
if (count % halfWavelength == 0) {
// invert the sample every half wavelength count multiple to generate square wave
sample = -1 * sample;
}
// Right channel, low 8 bit then hight 8 bit
i2s.write(sample);
i2s.write(sample >> 8);
// Left channel, low 8 bit then hight 8 bit
i2s.write(sample);
i2s.write(sample >> 8);
// increment the counter for the next sample
count++;
}