#define led_red 2
#define led_yellow 0
#define led_green 4
#define button 16
#define buzzer 17
#define no_cross 0
#define cross 1
int currentstate = no_cross; //the first current state is no crossing
unsigned long previousMillis = 0; //setting a long non negative variable
const long interval = 1000; //Interval for yellow LED
void setup() {
Serial.begin(9600);
pinMode(led_red, OUTPUT);
pinMode(led_yellow, OUTPUT);
pinMode(led_green, OUTPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis(); //storing the current time in millis
int value = digitalRead(button); //value is the condition of the button
if (value == HIGH) { // if button is pressed
if (currentstate != cross){ // if the current state is not crossing
currentstate = cross; // then current state is crossing
Serial.println("Please Cross The Road!"); //Message
digitalWrite(led_green, HIGH); //Setting the led in HIGH state
digitalWrite(led_red, LOW); //Setting the led in LOW state
digitalWrite(led_yellow, LOW); //Setting the led in LOW state
tone(buzzer, 1000);// High sound for the buzzer
delay(4000); // Wait for 4 seconds
}
}
else{ //if button is not pressed
if(currentstate == cross){ //if the current state is crossing
currentstate = no_cross; //the current state is not crossing
digitalWrite(led_green, LOW); //Setting the led in LOW state
digitalWrite(led_red, HIGH); //Setting the led in HIGH state
noTone(buzzer); // Low sound for the buzzer
Serial.println("No one is crossing the road!"); //Message
}
}
if (currentMillis - previousMillis >= interval) { //if the current time minus the variable is greater than the interval
previousMillis = currentMillis; // the variable is equal the current time
digitalWrite(led_yellow, !digitalRead(led_yellow)); //blinking the yellow LED
}
}