A piezo buzzer is dramatically simpler than a speaker. It's a small disc of piezoelectric ceramic glued to a metal diaphragm. Apply a voltage and the disc flexes; apply the opposite voltage and it flexes the other way. Wave a voltage back and forth at 440 hertz and the diaphragm vibrates at 440 hertz — pushing air, making sound, producing the note middle A.
tone() is a timer trick
Arduino's tone(pin, frequency) function configures one of the ATmega328P's timers to toggle the pin at exactly that frequency. The CPU goes back to doing whatever it was doing; the timer hardware keeps the wave going forever, or until noTone(pin). This is "fire and forget" digital signal generation — the timer is a separate piece of silicon dedicated to producing precisely-timed toggles.
Behind the scenes: Timer2 on the Uno is set to CTC (Clear Timer on Compare match) mode. The OCR2A register is loaded with a value that, given the prescaler, produces the requested half-period. Each compare match toggles the pin via the COM2A bits. Frequency = F_CPU / (2 × prescaler × (OCR2A + 1)). The library does the arithmetic for you.
From a tone to a melody
A song is a sequence of (note, duration) pairs. Store the frequencies in one array, the durations in another, walk both:
int notes[] = { 262, 294, 330, 349, 392, 440, 494, 523 }; // C-major scale
int durations[] = { 200, 200, 200, 200, 200, 200, 200, 400 };
for (int i = 0; i < 8; i++) {
tone(8, notes[i]);
delay(durations[i]);
noTone(8);
delay(40); // small gap so adjacent notes don't blur
}
That's eight notes and you're playing scales. The "small gap" between notes is important — without it, two notes of the same frequency would merge into one long tone, and even different frequencies would sound slurred.
Why this matters beyond music
The same primitive — produce a square wave at a chosen frequency — drives ultrasonic distance sensors (40 kHz), infrared remote controls (38 kHz carrier), buzzers in microwaves and smoke detectors, and the "beep" that every appliance with a button makes. The Arduino timer hardware doesn't know it's making music. It just toggles a pin.