Assignment 5: Music Box


Assignment 5: Music Box

Goal of this Module: Make a music box using SquareWear
Assignment 5: Music Box Document Download

Module: Music Box Lesson
Materials
  
 
doll1

Twinkle Twinkle
  
doll2

Code
  /*
* Plays Twinkle twinkle on SquareWear
* using buzzer on digital pin 9
* Written by Shani Mensing, edited by Audrey St. John
* Adapted from example code in the public domain.
* http://arduino.cc/en/Tutorial/Tone
*/

// the pin we will use for output
// specific to SquareWear
#define BUZZER_PIN 9

//------------Modify The Code Below Only------------------------
// Notes for the song. A space represents a rest
// Add the notes needed using the note sheet. Spaces acts like breaks
char song[] = "ccggaag ffeeddc ggffeed";

// beats per note
// Add the beats needed to complete the song.
// The amount of beats should match the amount of notes and spaces
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1,
               1, 1, 1, 1, 1, 1, 2, 1,
               1, 1, 1, 1, 1, 1, 2, 4};
//----------------Modify The Code Above Only-------------------


//---------------- Do Not Edit The Code Below------------------------
// speed of song
int tempo = 300;
// convenience notes means we don't need Pitches.h
// names of the notes
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
// corresponding tones for C4 - B4, C5 (looked up values from Pitches.h)
int tones[] = { 262, 295, 330, 349, 392, 440, 494, 523 };

// play the song using the variables: song, songLength, beats
void playSong()
{
 // for each note in the melody:
 for (int noteIndex = 0; noteIndex < sizeof(song); noteIndex++)
 {
// if it's a space
if (song[noteIndex] == ' ')
{
  // rest
  delay( beats[noteIndex] * tempo/5);
}
// otherwise it's the name of a note
else
{
  // play the note at that index for the specified time
  playNote(song[noteIndex], beats[noteIndex] * tempo);
}
    // pause between notes
delay(tempo);
 }
}
// play the tone corresponding to the note name
void playNote(char noteName, int duration)
{
 // loop through the names
 for (int i = 0; i < sizeof(names); i++)
 {
// if we found the right name
if (names[i] == noteName)
{
  // play the tone at the same index
  tone( BUZZER_PIN, tones[i], duration);
  // don't bother looking through the rest of the names
  break;
}
 }
}
/**
* The code in this special method is executed
* once when the microcontroller is turned on
* (or the program is uploaded).
**/
void setup()
{
 // play the song at the beginning
 playSong();
}

/**
* The code in this special method is constantly executed
* after setup has occurred.
**/
void loop()
{
 // it will be annoying to constantly hear the melody,
 // so let's do nothing!
}
//------------------------------------------------------------
Make Your Own Melody
 
doll3

Music Box
 
doll4