Bables14cfulfordiupucmet
Created February 21, 2019

Arduino Melody (Project 7)

Plays a pleasant melody over and over...... and over....

Arduino Melody (Project 7)

Things used in this project

Code

melody.ino

C/C++
int speakerPin = 9; // Pin connected to the piezo
 int length = 15; // Number of notes
 char notes[] = "ccggaagffeeddc "; // A space represents a rest
 int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
 int tempo = 300;
 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);
 }
}
// Set timeHigh value to specific notes
void playNote(char note, int duration) {
 char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
 int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
 for (int i = 0; i < 8; i++) { // Play tone that corresponds
 // to note name
 if (names[i] == note) {
 playTone(tones[i], duration);
 }
 }
}

void setup() {
  // put your setup code here, to run once:
 pinMode(speakerPin, OUTPUT); // Set speakerPin as output
}

void loop() {
  // put your main code here, to run repeatedly:
 for (int i = 0; i < length; i++) {
 if (notes[i] == ' ') {
 delay(beats[i] * tempo); // Rest
 }
 else {
 playNote(notes[i], beats[i] * tempo);
 }
 delay(tempo / 2); // Pause between notes
 }
}

Credits

Bables14
14 projects • 2 followers
Contact
cfulford
16 projects • 4 followers
Contact
iupucmet
15 projects • 4 followers
Contact

Comments

Please log in or sign up to comment.