#include <Servo.h> // Library untuk servo
#include <Wire.h> // Library untuk komunikasi I2C
#include <Adafruit_GFX.h> // Library untuk grafik dasar OLED
#include <Adafruit_SSD1306.h> // Library untuk OLED display
int buzzerPin = 7;
int buttonPin = 8; // Pin untuk tombol
int buttonState = 0; // Variabel untuk menyimpan status tombol
Servo myServo; // Membuat objek servo
int servoPin = 9; // Pin untuk servo
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Define notes in frequencies (Hz)
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// Notes and durations
int melody[] = {
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4,
NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4
};
int noteDurations[] = {
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2
};
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT); // Set button pin sebagai input
myServo.attach(servoPin); // Menghubungkan servo ke pin servo
myServo.write(0); // Posisi awal servo (tertutup)
// Inisialisasi OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Alamat I2C OLED adalah 0x3C
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Jika gagal, hentikan program
}
display.clearDisplay(); // Bersihkan layar OLED
display.display(); // Tampilkan perubahan
}
void loop() {
// Baca status tombol
buttonState = digitalRead(buttonPin);
// Jika tombol ditekan, mainkan melodi dan aktifkan servo
if (buttonState == HIGH) {
delay(2000); // Delay 2 detik sebelum servo bergerak
myServo.write(90); // Servo bergerak (buka)
// Tampilkan pesan "Kereta Lewat" di OLED
display.clearDisplay();
display.setTextSize(2); // Set ukuran teks
display.setTextColor(SSD1306_WHITE); // Warna teks putih
display.setCursor(0, 20); // Posisi teks
display.println("Kereta Lewat"); // Teks yang ditampilkan
display.display(); // Tampilkan ke OLED
// Mainkan melodi
for (int thisNote = 0; thisNote < 14; thisNote++) {
// Hitung durasi not (1000 ms dibagi jenis not)
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
// Pause antar not
int pauseBetweenNotes = noteDuration * 1.3;
delay(pauseBetweenNotes);
// Matikan tone setelah not selesai dimainkan
noTone(buzzerPin);
}
// Setelah melodi selesai, tutup servo
myServo.write(0); // Servo kembali ke posisi awal (tertutup)
// Hapus pesan dari OLED
display.clearDisplay();
display.display(); // Perbarui tampilan untuk menghapus tulisan
}
}