Happy Birthday TONEs for Passive Piezzo Buzzer

Someone else posted this and had the rhythm wrong so I have fixed it here:

// Happy Birthday Notes Defined
int melody2[] = {
  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, NOTE_A4, NOTE_C5, NOTE_F5, NOTE_C5, NOTE_A4, NOTE_F4
};

int durations2[] = {
  6, 16, 4, 4, 4, 2,
  6, 16, 4, 4, 4, 2, 
  6, 16, 4, 4, 4, 4, 4,
  6, 16, 4, 4, 4, 
  12, 12, 12, 12, 12, 12, 4
   
 
};

//End of Happy Birthday Notes Define

Here was the code (Good code bad rhythm). Combine the two and you have Happy Birthday as intended.

// -------------------------------------------------
// Copyright (c) 2022 HiBit <https://www.hibit.dev>
// -------------------------------------------------

#include "pitches.h"

#define BUZZER_PIN 9

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[] = {
  4, 8, 
  4, 4, 4,
  2, 4, 8, 
  4, 4, 4,
  2, 4, 8,
  
  4, 4, 4, 
  4, 4, 4, 8,
  4, 4, 4,
  2
};

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

void loop()
{
  int size = sizeof(durations) / sizeof(int);

  for (int note = 0; note < size; note++) {
    //to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int duration = 1000 / durations[note];
    tone(BUZZER_PIN, melody[note], duration);

    //to distinguish the notes, set a minimum time between them.
    //the note's duration + 30% seems to work well:
    int pauseBetweenNotes = duration * 1.30;
    delay(pauseBetweenNotes);
    
    //stop the tone playing:
    noTone(BUZZER_PIN);
  }
}

This one uses dotted duration.

Yes it does. Dotted eighth note with sixteenth. But... the original was not right in any transcription from what I can tell. Couldn't even keep a tempo to tap along in 3/4 (standard happy B-Day) with that one. The note pitches were all correct.

Small nit pick.. but I can't handle it when even a toy has something not right. One of my kids had a commercially made music playing teddy bear and I had to get rid of it because the notes were way out of tune with one another. It drove me nuts when I'd have to hear it over and over again. Those toys are annoying enough when everything is right.

I hear you... i spent a long time re-timing "Still Alive" and "Moonlight Sonata" and I can still hear bloops.

After some time at this you'll start noticing defects like this, not just in toys.

It's kinda a curse.If you are lucky, your friends and family will understand.

a7

Have you try RTTTL ?

This is a random example but many exist on the web.