Skip to content

Tone melody

A component which produces some kind of action when it receives a signal from the Arduino is called an actuator. An LED is an example of an actuator, but there are many other kinds including motors and speakers. In this tutorial we will use a simple speaker to play a simple melody when the sketch first starts.

The code for this example is shown in the box below. You can load it into your Arduino IDE from the File menu: File → Examples → 02.Digital → toneMelody

The code illustrates the use of a header file. The definitions of the notes are contained in the file pitches.h which is included in the sketch by the command at line 1. This file is included with the example in the Arduino IDE on a separate tab.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; 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.
}

Connecting the piezo buzzer is quite easy. Please use the diagram below to set up your circuit.

Challenge

At the moment, the melody only plays once when the sketch first starts.

Change the circuit and the sketch so that the melody plays whenever a button is pressed.