//Name
//COURSE NAME: Microcontroller Programming
//ID:
// Global variables to store the pin number of the components used
int redLed = 3;
int yellowLed = 5;
int greenLed = 6;
int button = 4;
//Variable to store the state of the button which is initially set to 0(mean not press)
int buttonState = 0;
void setup() {
/// Configuration of the pins on how to behave
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(button, INPUT);
// Turn off
// digitalWrite(redLed, LOW);
// digitalWrite(yellowLed, LOW);
// digitalWrite(greenLed, LOW);
// For serial monitor
Serial.begin(9600);
}
void loop() {
/// The red light of the traffic light turn on
digitalWrite(redLed, HIGH); //Set red light on
digitalWrite(yellowLed, LOW); //Set yellow light off
digitalWrite(greenLed, LOW); //Set green light off
Serial.println("Red");
redLight();
// delay(2500); // Delay the red light for seconds
//The green light of the traffic light turn on
digitalWrite(redLed, LOW); //Set red light on
digitalWrite(yellowLed, LOW); //Set yellow light off
digitalWrite(greenLed, HIGH); //Set green light off
Serial.println("Green");
delay(3000);
//The yellow light of the traffic light turn on
digitalWrite(redLed, LOW); //Set red light on
digitalWrite(yellowLed, HIGH); //Set yellow light off
digitalWrite(greenLed, LOW); //Set green light off
Serial.println("Yellow");
yellowLight();
//The flash of the yellow light
digitalWrite(yellowLed, LOW); //Set yellow light off
delay(500);
digitalWrite(yellowLed, HIGH); //Set yellow light off
delay(500);
}
void redLight(){
// delay(3000);
//Checking if the button is pressed
for( int i = 1; i < 8; i++){
int state = digitalRead(button);
if(state == 0){
Serial.println(i);
delay(1000);
}
else if (state == 1) {
Serial.println("Button has been pressed under red");
buttonPressed();
return;
}
}
}
void yellowLight(){
// delay(3000);
//Checking if the button is pressed
for( int i = 1; i < 5; i++){
int state = digitalRead(button);
if(state == 0){
Serial.println(i);
delay(1000);
}
else if (state == 1) {
Serial.println("Button has been pressed under yellow");
buttonPressed();
return;
}
}
}
void greenLight(){
// delay(3000);
//Checking if the button is pressed
for( int i = 1; i < 10; i++){
int state = digitalRead(button);
if(state == 0){
Serial.println(i);
delay(1000);
}
}
}
void buttonPressed(){
digitalWrite(yellowLed, HIGH); //Turn the yellow light on
digitalWrite(redLed, LOW); //Turn the red light off
digitalWrite(greenLed, LOW); //Turn the green light off
delay(1000); // Delay for one second
digitalWrite(yellowLed, LOW); //Turn the yellow light off
digitalWrite(redLed, LOW); //Turn the red light off
digitalWrite(greenLed, HIGH); //Turn the green light on
delay(5000); //Delay for five seconds
}