Introduction: Arduino Song - Mary Had a Little Lamb

This arduino project is a melody player, that plays a song when you press a button

Step 1: Set Up the Arduino

Here is the arduino set-up

Step 2: Code

#define c

3830 // 261 Hz

#define d 3400 // 294 Hz

#define e 3038 // 329 Hz

#define f 2864 // 349 Hz

#define g 2550 // 392 Hz

#define a 2272 // 440 Hz

#define b 2028 // 493 Hz

#define C 1912 // 523 Hz

#define R 0

int speakerOut = 9;

int button = 2;

void setup() {

pinMode(speakerOut, OUTPUT);

pinMode (button, INPUT);

}

int melody[] = { e, R, d, R, c, R, d, R, e, R,e, R,e, R,d, R,d, R,d, R,e, R,g, R,g, R,e, R,d, R,c, R,d, R,e, R,e, R,e, R,e, R,d, R,d, R,e, R,d, R,c, R,c };

int beats[] = { 4, 1 , 4, 1, 4, 1, 4, 1, 4, 1 ,8, 1, 4, 1,4, 1, 8, 1 ,4, 1 ,4, 1, 8, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4,1,8};

int MAX_COUNT = sizeof(melody) / 2;

long tempo = 100000;

int pause = 10;

int rest_count = 20;

int tone_ = 0;

int beat = 0;

long duration = 0;

void playTone() {

long elapsed_time = 0;

if (digitalRead(button)==HIGH){

if (tone_ > 0) {

while (elapsed_time < duration) {

digitalWrite(speakerOut,HIGH);

delayMicroseconds(tone_ / 2);

digitalWrite(speakerOut, LOW);

delayMicroseconds(tone_ / 2);

elapsed_time += (tone_);

}

}

else {

for (int j = 0; j < rest_count; j++) {

delayMicroseconds(duration);

}

}

}

}

void loop() {

for (int i=0; i

tone_ = melody[i];

beat = beats[i];

duration = beat * tempo;

playTone();

delayMicroseconds(pause);

}

}