int redCarPin = 8;
int yellowCarPin = 9;
int greenCarPin = 10;
int greenWalkPin = 11;
int redWalkPin = 12;
int soundPin = 6;
int buttonPin = 7;
int time = 2000;
int soundTime = 500;
bool isPressed = false;
enum State
{
NONE = 0,
RED = 1,
YELLOW_RED = 2,
YELLOW = 3,
GREEN = 4,
GREEN_PUMP = 5
};
State state = GREEN;
void SoundSignal(int pin, int duration, int& pauseTime, int frequency)
{
for(int i = 0; i < 200; i += 10, soundTime -= 10)
{
tone(pin, frequency, duration);
delay(soundTime);
}
}
void setup()
{
// For car.
pinMode(greenCarPin, OUTPUT);
pinMode(yellowCarPin, OUTPUT);
pinMode(redCarPin, OUTPUT);
// For walker.
pinMode(redWalkPin, OUTPUT);
pinMode(greenWalkPin, OUTPUT);
// For button.
pinMode(buttonPin, INPUT);
// For dunamic.
pinMode(soundPin, OUTPUT);
}
void loop()
{
if (digitalRead(buttonPin) == HIGH && !isPressed) // If button was pressed.
{
isPressed = true;
delay(time * 2); // Stopping the execution, because the cars have
// to have time to pass the traffic lighter.
}
switch(state)
{
case GREEN: // Green light for car.
// If the green light is lighting for car
// for pedestrian it will be red.
digitalWrite(greenCarPin, HIGH);
digitalWrite(redWalkPin, HIGH);
if(isPressed) // The pedestrian pressed the button.
{
soundTime = 500; // Set the time of the sound alert.
state = GREEN_PUMP; // Switch to next traffic light state.
}
break;
case GREEN_PUMP: // Flashing of green light for cars.
for(int i = 0; i < 6; i++)
{
digitalWrite(greenCarPin, LOW);
delay(200);
digitalWrite(greenCarPin, HIGH);
delay(200);
}
digitalWrite(greenCarPin, LOW); // Turn off the green light.
state = YELLOW; // Move to next state.
break;
case YELLOW: // Yellow light for cars.
digitalWrite(yellowCarPin, HIGH); // Turn on the yellow light for cas.
delay(time);
digitalWrite(yellowCarPin, LOW); // Turn off the yellow light for cars.
digitalWrite(redWalkPin, LOW); // Turn off the red light for pedestrians.
state = RED; // Swiching to the next state.
break;
case RED: // Red light for cars.
digitalWrite(redCarPin, HIGH); // Turn on the red light for cars.
digitalWrite(greenWalkPin, HIGH); // Turn on the green light for pedestriants.
SoundSignal(soundPin, 250, soundTime, 250); // Turn on the sound alert.
state = YELLOW_RED; // Move to the next state.
break;
case YELLOW_RED: // The bright of yellow and red lights for cars.
digitalWrite(yellowCarPin, HIGH); // Turn on the yellow light for cars.
SoundSignal(soundPin, 250, soundTime, 250); // Turn on the sound alert.
// Turning off yellow and red lights for cars.
digitalWrite(redCarPin, LOW);
digitalWrite(yellowCarPin, LOW);
digitalWrite(greenWalkPin, LOW); // Turn off the green light for pedestriants.
state = GREEN; // Move to the next state.
isPressed = false; // Set the button to released state.
break;
}
}