#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "pitches.h"
// Inisialisasi LCD I2C
LiquidCrystal_I2C lcd(0x27, 16, 2); // Alamat I2C 0x27 untuk LCD 16x2
// Inisialisasi pin tombol dan buzzer
const int buttonPin = 9;
const int buzzerPin = 8;
bool isPlaying = false;
// Not-not untuk lagu Happy Birthday
int melody[] = {
NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_C5, NOTE_B4,
NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_D5, NOTE_C5,
NOTE_G4, NOTE_G4, NOTE_G5, NOTE_E5, NOTE_C5, NOTE_B4, NOTE_A4,
NOTE_F5, NOTE_F5, NOTE_E5, NOTE_C5, NOTE_D5, NOTE_C5
};
int noteDurations[] = {
4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 2
};
// Kecepatan teks bergulir (dalam milidetik)
int scrollSpeed = 200;
void setup() {
lcd.begin(16, 2); // Inisialisasi LCD dengan 16 kolom dan 2 baris
lcd.backlight();
pinMode(buttonPin, INPUT);
pinMode(buzzerPin, OUTPUT);
lcd.print("Switch ON to play");
delay(2000); // Tampilkan pesan awal selama 2 detik
}
void loop() {
isPlaying = digitalRead(buttonPin) == HIGH;
if (isPlaying) {
playHappyBirthday();
} else {
noTone(buzzerPin); // Matikan buzzer jika switch OFF
}
// Teks bergulir
scrollText("Happy Birthday!", 16, scrollSpeed);
}
void playHappyBirthday() {
for (int thisNote = 0; thisNote < 26; thisNote++) {
if (!isPlaying) {
noTone(buzzerPin);
return;
}
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(buzzerPin); // Matikan buzzer setelah setiap nada
delay(10); // Beri jeda kecil untuk menghindari overlap nada
}
}
void scrollText(String message, int displayLength, int speed) {
for (int i = 0; i < message.length() + displayLength; i++) {
lcd.setCursor(0, 1);
String displayText = "";
for (int j = 0; j < displayLength; j++) {
if (i + j < message.length()) {
displayText += message[i + j];
} else {
displayText += " ";
}
}
lcd.print(displayText);
delay(speed);
}
}