CYTHEIA AIOpen the editor

Buzzer Melody

Play a simple melody with a buzzer.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

A buzzer on pin 8 makes a sound when the Arduino sends it a signal at an audible frequency, and tone() does exactly that: tone(pin, frequency, duration) produces a square wave of the given frequency for the given number of milliseconds. The pitch of a note is its frequency in hertz.

The sketch stores eight frequencies in an array called melody: 262, 294, 330, 349, 392, 440, 494 and 523 Hz are the notes C, D, E, F, G, A, B and the next C up, a C major scale. loop() steps through the array, plays each note for 200 milliseconds, prints its frequency to the Serial tab, and waits 250 milliseconds before the next one. After the eighth note it rests for a second and starts over.

Parts

Wiring

Arduino code

// Buzzer Melody
int melody[] = {262, 294, 330, 349, 392, 440, 494, 523};
int noteDuration = 200;

void setup() {
  pinMode(8, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (int i = 0; i < 8; i++) {
    tone(8, melody[i], noteDuration);
    Serial.print("Playing: ");
    Serial.println(melody[i]);
    delay(noteDuration + 50);
  }
  delay(1000);
}

Try changing it

Open this circuit and run it

Next challenge

More projects in Arduino