1. Introduction
In this post, we will play "Happy Birthday" melody by ESP with Sigma-delta Modulation. Actually, you can use "digitalWrite" but Sigma-delta Modulation make the output smoother.
The mechanism to play melody you can find here.
2. Hardware
ESP32 G27 connect LM386 IN
ESP32 5V (or 3.3 V) connect LM386 Vcc
ESP32 GND connect LM386 GND
3. Software
In order to use Sigma-delta Modulation in ESP please refer this.
Here is the full source code:
In this post, we will play "Happy Birthday" melody by ESP with Sigma-delta Modulation. Actually, you can use "digitalWrite" but Sigma-delta Modulation make the output smoother.
The mechanism to play melody you can find here.
2. Hardware
We will use cheap Audio Power Amplifier LM386 to aplify the melody.
Figure: LM386 Low Voltage Audio Power Amplifier
Pins are connected as:ESP32 G27 connect LM386 IN
ESP32 5V (or 3.3 V) connect LM386 Vcc
ESP32 GND connect LM386 GND
3. Software
In order to use Sigma-delta Modulation in ESP please refer this.
Here is the full source code:
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 | int speakerPin = 27; //"happy birthday melody notes" char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc"; int beats[] = { 2, 2, 8, 8, 8, 16, 1, 8, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 8, 2, 8, 8, 8, 16 }; void playTone(int tone) { for (long i = 0; i < 100; i++) { sigmaDeltaWrite(0, 0); delayMicroseconds(tone); sigmaDeltaWrite(0, 100); delayMicroseconds(tone); } } void playNote(char note) { //notes char note_name[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B', 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'x', 'y' }; int timeHigh[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956, 834, 765, 593, 468, 346, 224, 655 , 715 }; // play the tone corresponding to the note name for (int i = 0; i < sizeof(note_name); i++) { if (note_name[i] == note) { playTone(timeHigh[i]); } } } void setup() { sigmaDeltaSetup(0, 12000); //attach pin speakerPin to channel 0 sigmaDeltaAttachPin(speakerPin, 0); //initialize channel 0 to off sigmaDeltaWrite(0, 0); } void loop() { for (int i = 0; i < strlen(notes); i++) { // space is rest note if (notes[i] == ' ') { delay(beats[i] * 100); } else { playNote(notes[i]); } // pause between notes delay(100); } } |
7 Comments