/*
Assignment 4: Traffic Light Controller
Keeping track of time in the background, the program controls
two sets of traffic lights, made of three LEDs. Both lights will
rotate between their LEDs, lighting up red for 5 seconds, green for 4
seconds, then yellow for 1 second and repeating the colors. The first
light will start on red, while the second will start on green. If one
of the lights is green and its corresponding button is pressed, the
light should begin to turn red, turning the other light green.
*/
/* Defining a list of constants, each representing a digital pin. */
// LED pins
#define redOne 2
#define yellowOne 3
#define greenOne 4
#define redTwo 6
#define yellowTwo 7
#define greenTwo 8
// Button pins
#define buttonPinOne 5
#define buttonPinTwo 9
/* Declaring variables that will change over time. */
// Button variables to keep track of buttons.
int buttonStateOne = 0;
int buttonStateTwo = 0;
// Time variables to keep track of time.
int previousMilis = 0;
int currentMilis = 0;
// "Setup" pins to their desired mode
void setup() {
//Initialize digital pins as outputs.
pinMode(redOne, OUTPUT);
pinMode(yellowOne, OUTPUT);
pinMode(greenOne, OUTPUT);
pinMode(redTwo, OUTPUT);
pinMode(yellowTwo, OUTPUT);
pinMode(greenTwo, OUTPUT);
//Initialize digitial pins as inputs.
pinMode(buttonPinOne, INPUT);
pinMode(buttonPinTwo, INPUT);
}
// The loop will repeat as needed
void loop() {
/*
Reset from end of loop and turn off the second red light and first
yellow light. Turn on the first red light and second green light.
Repeat while 4 seconds have not passed and the second button is
not pressed during.
*/
do
{
digitalWrite(redTwo, LOW);
digitalWrite(yellowOne, LOW);
digitalWrite(redOne, HIGH);
digitalWrite(greenTwo, HIGH);
currentMilis = millis(); // Update the time
buttonStateTwo = digitalRead(buttonPinTwo); // check the second button
} while(currentMilis - previousMilis <= 4000 && buttonStateTwo == 0);
// Set the start of the next phrase
previousMilis = currentMilis;
// Reset the state of the second button
buttonStateTwo = 0;
// Set the second light to yellow
do
{
digitalWrite(greenTwo, LOW);
digitalWrite(yellowTwo, HIGH);
currentMilis = millis();
} while(currentMilis - previousMilis <= 1000);
previousMilis = currentMilis;
// Change the first light to green, and set the second light to red.
do
{
digitalWrite(redOne, LOW);
digitalWrite(yellowTwo, LOW);
digitalWrite(greenOne, HIGH);
digitalWrite(redTwo, HIGH);
currentMilis = millis();
buttonStateOne = digitalRead(buttonPinOne);
} while(currentMilis - previousMilis <= 4000 && buttonStateOne == 0);
previousMilis = currentMilis;
buttonStateOne = 0;
// Change the first light to yellow.
do
{
digitalWrite(greenOne, LOW);
digitalWrite(yellowOne, HIGH);
currentMilis = millis();
} while(currentMilis - previousMilis <= 1000);
previousMilis = currentMilis;
}