Arduino, IoT made simple

Lesson 4: Melody

On this lesson we'll make our Arduino board "sing" a song of our choice. As an example, I've chosen "Take on me" by A-ha, but I'll only make it play the basic riff.

In order to achieve this, I've had to understand beforehand the concept of the "note" function.

As far as materials are concerned, I've only needed an Arduino board and a piezo buzzer. I've plugged the piezo on the pins 8 and ground.

Arduino montage

The code:

/*
Melody
Plays a melody
circuit:
* 8-ohm speaker on digital pin 8
created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone
*/
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440


// notes in the melody:
int melody[] = {
NOTE_FS4, NOTE_FS4, NOTE_D4,NOTE_B3,0,NOTE_B3,0,NOTE_E4,
0,NOTE_E4,0,NOTE_E4,NOTE_GS4,NOTE_GS4,NOTE_A4,NOTE_B4,
NOTE_A4,NOTE_A4,NOTE_A4,NOTE_E4,0,NOTE_D4,0, NOTE_FS4,
0, NOTE_FS4,0, NOTE_FS4,NOTE_E4,NOTE_E4,NOTE_FS4,NOTE_E4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
};
void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 32; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}
void loop() {
// no need to repeat the melody.
for (int thisNote = 0; thisNote < 32; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}}