Recently I got my first Aruino Board (Arduino Uno, as a matter of fact) in the context of a lecture I am attending. After connecting a LED to it and letting it blink I decided to create my first Chiptunes track on it. So I picked a Piezo Speaker, looked at the toneMelody example and decided to adapt it to the song Aerodynamic by Daft Punk (i got the tones from here: Aerodynamic guitar tabs).
Thanks to the aforementioned toneMelody example, there is a external file called pitches.h which holds a list of 88 notes going from B0 to D#5, so there’s no need to worry about that. After picking a note, playing it will be the next task. This works as follows:
void setup() { int noteDuration = 1000/4; tone(8, NOTE_C1, noteDuration); delay(noteDuration); noTone(8); }
Basically, there are three steps in playing a tone. Step 1 is to actually play it. tone() takes three arguments: the output pin, the note and the duration of its play(1000/4 means quarter note, 1000/8 would be an eight note and so on). In step 2 we define how long the system will wait while the note is played until we stop playing the note at a desired pin in step 3. If we would skip the delay()-method, we wouldn’t hear any sound at all because it would be stopped immediately after it would be played. Choosing a higher delay time than play time means to create a pause after the note.
So after talking about that, here’s my code for Aerodynamic:
/* Aerodynamic Plays a melody circuit: * 8-ohm speaker on digital pin 8 created 17 Oct 2012 modified 17 Oct 2012 by Petzy This sketch is based on the toneMelody example: http://arduino.cc/en/Tutorial/Tone */ #include "pitches.h" // notes in the melody: int melody[] = { NOTE_D4, NOTE_F3, NOTE_B3, NOTE_F3, // D4-F3-B3-F3 NOTE_D4, NOTE_GS3, NOTE_B3, NOTE_GS3, // D4-Ab3-B3-Ab3 NOTE_G4, NOTE_B3, NOTE_E4, NOTE_B3, // G4-B3-E4-B3 NOTE_E4, NOTE_A3, NOTE_CS4, NOTE_A3, // E4-A3-C#4-A3 NOTE_D4, NOTE_FS4, NOTE_B3, NOTE_FS4, // D4-F#4-B3-F#4 NOTE_D4, NOTE_GS3, NOTE_B3, NOTE_GS3, // D4-Ab3-B3-Ab3 NOTE_G4, NOTE_B3, NOTE_E4, NOTE_B3, // G4-B3-E4-B3 NOTE_E4, NOTE_A3, NOTE_CS4, NOTE_A3, // E4-A3-C#-A3 }; int outputPin = 8; int maxChords = 8; int maxRepeats = 4; // every chord will be repeated 4 times int noteDuration = 1000/8; // 4 = quarter note, 8 = eight note, etc. void setup() { // play sound once playSound(); } void playSound() { // play all 8 chords for (int chords = 0; chords < maxChords; chords++) { // play every chord 4 times for (int chordTone = 0; chordTone < 4; chordTone++) { // play all 4 tones of every chord for (int repeats = 0; repeats < maxRepeats; repeats++) { // play the tone tone(outputPin, melody[chords*maxRepeats + repeats], noteDuration); // set a delay between the notes delay(noteDuration); // stop the tone playing noTone(outputPin); } } } }