// Pines
const int buzzerPin = 19; // Pin donde está conectado el buzzer
const int ledPin = 4; // Pin donde está conectado el LED
// Frecuencias de las notas usadas en la canción (en Hz)
#define NOTE_C4 261
#define NOTE_D4 294
#define NOTE_E4 329
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784
// Notas de la melodía de "Happy Birthday"
int melody[] = {
NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_C5, NOTE_B4, // "Happy Birthday to You"
NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_D5, NOTE_C5, // "Happy Birthday to You"
NOTE_G4, NOTE_G4, NOTE_G5, NOTE_E5, NOTE_C5, NOTE_B4, NOTE_A4, // "Happy Birthday dear [Name]"
NOTE_F5, NOTE_F5, NOTE_E5, NOTE_C5, NOTE_D5, NOTE_C5 // "Happy Birthday to You"
};
// Duraciones de las notas (4 = negra, 8 = corchea, etc.)
int durations[] = {
4, 8, 4, 4, 4, 4, // "Happy Birthday to You"
4, 8, 4, 4, 4, 4, // "Happy Birthday to You"
4, 8, 4, 4, 4, 4, 4, // "Happy Birthday dear [Name]"
4, 8, 4, 4, 4, 4 // "Happy Birthday to You"
};
// Variable para la duración base de la nota
int tempo = 800; // Ajuste de velocidad para un ritmo más lento
void setup() {
// Configura el pin del LED como salida
pinMode(ledPin, OUTPUT);
// Configura el pin del buzzer como salida
pinMode(buzzerPin, OUTPUT);
// Esperar 2 segundos antes de comenzar la melodía
delay(2000);
// Iniciar la melodía y repetirla después de una pausa
playMelody(); // Primera reproducción
delay(2000); // Esperar 2 segundos antes de la segunda reproducción
playMelody(); // Segunda reproducción
}
void loop() {
// Dejar vacío, ya que la melodía se reproduce solo en el setup
}
// Función para reproducir la melodía
void playMelody() {
for (int thisNote = 0; thisNote < sizeof(melody) / sizeof(melody[0]); thisNote++) {
int noteDuration = tempo / durations[thisNote];
// Reproducir la nota actual si no es una pausa
if (melody[thisNote] != 0) {
tone(buzzerPin, melody[thisNote], noteDuration);
digitalWrite(ledPin, HIGH); // Enciende el LED mientras suena la nota
} else {
noTone(buzzerPin); // Silencio entre notas
digitalWrite(ledPin, LOW); // Apaga el LED durante la pausa
}
// Pausa para que el LED se mantenga encendido brevemente
delay(noteDuration);
// Apagar el LED después de la nota
digitalWrite(ledPin, LOW);
// Pausa entre notas para marcar el ritmo
delay(50); // Ajuste para mantener el ritmo del tema
}
// Apaga el buzzer al terminar la melodía
noTone(buzzerPin);
// Enciende el LED por 6 segundos al final de la canción
digitalWrite(ledPin, HIGH);
delay(6000);
digitalWrite(ledPin, LOW);
}