// Define the pin where the buzzer is connected
const int buzzerPin = 12;

// Define the notes for Happy Birthday
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_G5  784
#define NOTE_A5  880

// Define the melody for Happy Birthday
int melody[] = {
  NOTE_C5, NOTE_C5, NOTE_D5, NOTE_C5, NOTE_F5, NOTE_E5, // Happy Birthday to You
  NOTE_C5, NOTE_C5, NOTE_D5, NOTE_C5, NOTE_G5, NOTE_F5, // Happy Birthday to You
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_A5, NOTE_F5, NOTE_E5, NOTE_D5, // Happy Birthday Dear [Name]
  NOTE_C5, NOTE_C5, NOTE_D5, NOTE_C5, NOTE_F5, NOTE_E5, // Happy Birthday to You
};

int noteDurations[] = {
  4, 4, 4, 4, 4, 4, // Happy Birthday to You
  4, 4, 4, 4, 4, 4, // Happy Birthday to You
  4, 4, 8, 8, 4, 4, 4, // Happy Birthday Dear [Name]
  4, 4, 4, 4, 4, 4, // Happy Birthday to You
};

void setup() {
  // Set the buzzer pin as output
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  // Play the melody
  for (int thisNote = 0; thisNote < 24; thisNote++) {
    // Calculate the note duration
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzerPin, melody[thisNote], noteDuration);

    // Pause between notes
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    // Stop the tone
    noTone(buzzerPin);
  }

  // Add a delay before repeating the song
  delay(2000); // Delay for 2 seconds before repeating
}
Loading
esp32-s3-devkitc-1