Unit 5: Audible Signals
Code:
const int BUZZER_PIN = 8; // Digital pin for active buzzer
// Notes of the melody
const int NOTE_C4 = 262;
const int NOTE_D4 = 294;
const int NOTE_E4 = 330;
const int NOTE_F4 = 349;
const int NOTE_G4 = 392;
const int NOTE_A4 = 440;
const int NOTE_B4 = 494;
const int NOTE_C5 = 523;
// Melody to play
int melody[] = {
NOTE_G4, NOTE_G4, NOTE_E4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_F4, NOTE_G4,
NOTE_G4, NOTE_E4, NOTE_A4, NOTE_G4, NOTE_E4
};
// Duration of each note (in ms)
int noteDurations[] = {
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 500, 500, 500
};
// Function to play the melody
void playMelody() {
for (int i = 0; i < sizeof(melody) / sizeof(int); i++) {
tone(BUZZER_PIN, melody[i], noteDurations[i]);
delay(noteDurations[i] * 1.3); // Delay between notes
}
}
void setup() {
pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output
}
void loop() {
// Play the melody
playMelody();
}