Arduino tone() Melody Player

Wire a small piezo disc to one pin, call tone(), and the Arduino plays "Twinkle Twinkle" — your first audio output from a microcontroller.

Difficulty: Breadboard. Estimated build time: about 25 minutes. Estimated parts cost: about US$2.00. 4-line bill of materials. Compare supplier offers when available. An Arduino sketch that plays a recognisable tune on a passive piezo speaker by sequencing notes with the built-in tone() function.

Wire the piezo

A passive piezo has two leads, polarity-agnostic for audio purposes. Connect one to Arduino D8 (or any digital pin), and the other to GND. The piezo is high-impedance so no current-limiting resistor is needed. If you want more volume, you can add an NPN transistor switch driving the piezo from a higher rail, but for breadboard testing the bare disc is plenty.

Play a single note

Upload a sketch with tone(8, 440, 500) in setup() — that plays middle A (440 Hz) for half a second. tone() runs in the background using Timer2 on the UNO, so it doesn't block other code. After the duration expires the timer stops automatically. If you call tone() again with a new frequency, it switches mid-note without any gap.

Define notes as constants

Create #define NOTE_C4 262, NOTE_D4 294, NOTE_E4 330, NOTE_F4 349, NOTE_G4 392, NOTE_A4 440, NOTE_B4 494, NOTE_C5 523 at the top of your sketch. These are the equal-tempered frequencies of the eight notes of a C-major octave. Most online "Arduino musical notes" reference files list them all the way down to C0 and up to D8.

Sequence a melody

Make two parallel arrays: int melody[] = { NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, 0, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4 } and int durations[] = { 500, 500, 500, 500, 500, 500, 1000, 250, 500, 500, 500, 500, 500, 500, 1000 }. A 0 frequency means rest. In loop(), iterate the arrays, call tone() and delay() for each note, then noTone(8) at the end. The Arduino sings "Twinkle Twinkle Little Star" once and stops.