Skip to content

Instantly share code, notes, and snippets.

@shweshi
Created February 28, 2025 14:46
Show Gist options
  • Save shweshi/32fca36787fd0fdfe9d09aa0118bee04 to your computer and use it in GitHub Desktop.
Save shweshi/32fca36787fd0fdfe9d09aa0118bee04 to your computer and use it in GitHub Desktop.

Revisions

  1. shweshi created this gist Feb 28, 2025.
    68 changes: 68 additions & 0 deletions hbd_melody.ino
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    const int buzzerPin = 15; // Buzzer connected to GPIO 15

    void setup() {
    pinMode(buzzerPin, OUTPUT);
    }

    void loop() {
    playHappyBirthday();
    delay(2000); // Short pause between loops
    }

    // Full note definitions (including sharps/flats)
    #define NOTE_C4 262
    #define NOTE_CS4 277
    #define NOTE_D4 294
    #define NOTE_DS4 311
    #define NOTE_E4 330
    #define NOTE_F4 349
    #define NOTE_FS4 370
    #define NOTE_G4 392
    #define NOTE_GS4 415
    #define NOTE_A4 440
    #define NOTE_AS4 466
    #define NOTE_B4 494
    #define NOTE_C5 523
    #define NOTE_REST 0 // Silent pause

    // Manual tone generation (works on all boards)
    void playTone(int pin, int frequency, int duration) {
    if (frequency == NOTE_REST) {
    delay(duration); // Rest (silent pause)
    return;
    }

    int period = 1000000 / frequency; // Microseconds per cycle
    int cycles = (duration * 1000L) / period; // Total cycles for duration

    for (int i = 0; i < cycles; i++) {
    digitalWrite(pin, HIGH);
    delayMicroseconds(period / 2);
    digitalWrite(pin, LOW);
    delayMicroseconds(period / 2);
    }
    }

    // Happy Birthday melody
    void playHappyBirthday() {
    int melody[] = {
    NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_F4, NOTE_E4,
    NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_G4, NOTE_F4,
    NOTE_C4, NOTE_C4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_E4, NOTE_D4,
    NOTE_AS4, NOTE_AS4, NOTE_A4, NOTE_F4, NOTE_G4, NOTE_F4
    };

    int durations[] = {
    500, 250, 750, 750, 750, 1500,
    500, 250, 750, 750, 750, 1500,
    500, 250, 750, 750, 750, 750, 1500,
    500, 250, 750, 750, 750, 1500
    };

    int length = sizeof(melody) / sizeof(melody[0]);

    for (int i = 0; i < length; i++) {
    playTone(buzzerPin, melody[i], durations[i]);
    delay(50); // Short pause between notes
    }
    }