const int redPin = 2;
const int yellowPin = 3;
const int greenPin = 4;
const int buttonPin = 5;
unsigned long previousMillis = 0;
int state = 0; // 0: Green, 1: Yellow, 2: Red
bool buttonPressed = false;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
unsigned long currentMillis = millis();
// Cek tombol
if (digitalRead(buttonPin) == LOW) {
if (state != 2) { // Jika tidak dalam keadaan merah
buttonPressed = true;
}
}
// Logika lampu lalu lintas
switch (state) {
case 0: // Lampu Hijau 3 Detik
digitalWrite(greenPin, HIGH);
if (currentMillis - previousMillis >= 3000) {
previousMillis = currentMillis;
digitalWrite(greenPin, LOW);
state = 1; // Beralih ke kuning
}
break;
case 1: // Lampu Kuning 1 Detik
digitalWrite(yellowPin, HIGH);
if (currentMillis - previousMillis >= 1000) {
previousMillis = currentMillis;
digitalWrite(yellowPin, LOW);
state = 2; // Beralih ke merah
}
break;
case 2: // Lampu Merah 3 Detik
digitalWrite(redPin, HIGH);
if (currentMillis - previousMillis >= (buttonPressed ? 5000 : 3000)) {
previousMillis = currentMillis;
digitalWrite(redPin, LOW);
state = 0; // Kembali ke hijau
buttonPressed = false; // Reset tombol
}
break;
}
}