Sound Mobile Robot

1 int buzzerPin = 11;
2 int length = 15; // the number of notes
3 char notes[] = "ccggaagffeeddc "; // a space represents a rest
4 int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
5 int tempo = 300;
6 void playTone(int tone, int duration) {
7 for (long i = 0; i < duration * 1000L; i += tone * 2) {
8 digitalWrite(buzzerPin, HIGH);
9 delayMicroseconds(tone);
10 digitalWrite(buzzerPin, LOW);
11 delayMicroseconds(tone);
12 }
13 }
14 void playNote(char note, int duration) {
15 char names[] = { 'c' , 'd' , 'e' , 'f' , 'g' , 'a' , 'b' , 'C' };
16 int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
17 // play the tone corresponding to the note name
18 for (int i = 0; i < 8; i++) {
19 if (names[i] == note) {
20 playTone(tones[i], duration);
21 }
22 }
23 }
24 void setup() {
25 pinMode(buzzerPin, OUTPUT);
26 pinMode(2, INPUT);
27 }
28 void loop() {
29 if (digitalRead(2) == HIGH) {
30 for (int i = 0; i < length; i++) {
31 if (notes[i] == ' ' ) {
32 delay(beats[i] * tempo); // rest
33 } else {
34 playNote(notes[i], beats[i] * tempo);
35 }
36 // pause between notes
37 delay(tempo / 2);
38 }
39 }
40 }

Comments

Popular Posts