// MusicBuzzer example

void setup() {
    // Initialize the serial communication at 9600 baud
    Serial.begin(9600);
    
    // Set pin 3 as an output and enable the buzzer
    pinMode(3, OUTPUT);
    pinMode(3, OUTPUT);
}

void loop() {
    // Play four different notes using simple tones and durations
    playNote(60, 4); // Middle C (C4) - 1 second duration
    delay(1000);
    
    playNote(64, 2); // A above middle C (A4) - 50 milliseconds duration
    delay(50);
    
    playNote(67, 2); // Bb above middle C (Bb4) - 50 milliseconds duration
    delay(50);
    
    playNote(69, 2); // B above middle C (B4) - 50 milliseconds duration
    delay(50);
}

void playNote(uint16_t frequency, uint16_t duration) {
    // Generate the tone using the specified frequency and duration
    unsigned long period = (frequency / 25.67) * 48;
    
    // Calculate the start time of the tone based on the current time in ms
    unsigned long startTime = millis() + duration;
    
    while(millis() < startTime) {
        // Play a single cycle of the sine wave using the specified frequency and period
        analogWrite(3, map(sin((startTime - millis()) * 0.5), -1, 1,0,255));
        
        delayMicroseconds(period);
    }
}