0

Good evening!

I am quite new with Arduino but not in programming. Still, I have already done some programs with few leds.

I was just wandering how to create a circuit and a program that would play the "happy birthday" song with the following materials:

enter image description here

I have a breadbord and some wires.

Else, do you have some links where I could start learning how to play music with it?

asked Feb 8, 2016 at 22:07
2

1 Answer 1

0

Thanks to Mikael Patel for suggesting that link (your Google-Fu must be strong!).

I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.

//ONG LIT YIT 2013年07月20日
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and
// an Arduino board and
//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)
const int speakerPin = 9;
const int LENGTH = 28; // the number of notes
const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
const int tempo = 150;
void playTone(int tone, int duration) 
 {
 for (long i = 0; i < duration * 1000L; i += tone * 2) 
 {
 digitalWrite(speakerPin, HIGH);
 delayMicroseconds(tone);
 digitalWrite(speakerPin, LOW);
 delayMicroseconds(tone);
 }
 } // end of playTone
void playNote(const char note, const int duration) 
 {
 char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
 'c', 'd', 'e', 'f', 'g', 'a', 'b',
 'x', 'y'
 };
 const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
 956, 834, 765, 593, 468, 346, 224,
 655 , 715
 };
 const int SPEE = 5;
 // play the tone corresponding to the note name
 for (int i = 0; i < 17; i++) 
 {
 if (names[i] == note) {
 int newduration = duration / SPEE;
 playTone(tones[i], newduration);
 }
 }
} // end of playNote
void setup() 
 {
 pinMode(speakerPin, OUTPUT);
 } // end of setup
void loop() 
 {
 for (int i = 0; i < LENGTH; i++) 
 {
 if (notes[i] == ' ') 
 {
 delay(beats[i] * tempo); // rest
 } 
 else 
 {
 playNote(notes[i], beats[i] * tempo);
 }
 // pause between notes
 delay(tempo);
 }
} // end of loop

I also cleaned up the code a bit.

answered Feb 8, 2016 at 23:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.