#include <Arduino.h>

// The Mega sends a control signal to a transistor driver; the buzzer is not powered directly from the pin.
const uint8_t BUZZER_PIN = 12;  // Drives the added transistor, not the load directly.

// Tell the Mega that the buzzer-control pin is an OUTPUT.
void setup() {
  pinMode(BUZZER_PIN, OUTPUT);
}

// Repeat the beep pattern forever.
void loop() {
  // Count 20 beeps, from beep 0 through beep 19.
  for (int beep = 0; beep < 20; ++beep) {
    // The ?: operator chooses a duration: first 5 at 500 ms, next 5 at 300 ms, last 10 at 100 ms.
    const int duration = beep < 5 ? 500 : (beep < 10 ? 300 : 100);
    // HIGH drives the transistor input and activates the buzzer.
    digitalWrite(BUZZER_PIN, HIGH);
    delay(duration);
    // LOW switches the buzzer off between beeps.
    digitalWrite(BUZZER_PIN, LOW);
    delay(duration);
  }
  // After the sequence, leave the buzzer on for five seconds.
  digitalWrite(BUZZER_PIN, HIGH);
  // The next loop starts with the output still HIGH; there is no separate silent gap here.
  delay(5000);
}
