Arduino Traffic Light Example

So here is an example I wrote for some students.  This simulates traffic lights with one arduino for each direction and uses a random timer to decide which device turns green first - then the devices control each other (each can have different times but the code is the same on both devices.


 * Traffic light demonstration
 * two arduinos, both running this code will operate
 * as traffic lights for an intersection if both set up as follows:
 * RED LED on pin 13
 * YELLOW LED on pin 12
 * GREEN LED on pin 11
 * Pin 7 on first Arduino connected to pin 6 on the second
 * Pin 6 on first Arduino connected to pin 7 on the second
 * NO failsafe in this version (lost communication means undocumented behaviour)
 * V2.1, Steve
 * May 2016

#define RED         13
#define YELLOW      12
#define GREEN       11
#define CONTROL_IN  7
#define CONTROL_OUT 6

// Set the time in mS that the yellow and green light is on for
// Note: this can be different for each controller, and red on one
// is simply the sum of green and yellow on the other
// so the green light controls how long traffic is stopped the other way
int yellow_time     = 750;
int green_time      = 2500;

void setup() {
	// LEDs require digital outputs
	pinMode(RED,    OUTPUT);
	pinMode(GREEN,  OUTPUT);

	// This is the control line that receives signals from the other controller
	// And this is the control line to signal the other controller

	// Switch off both control lines to begin with
	digitalWrite(CONTROL_IN,  LOW);
	digitalWrite(CONTROL_OUT, LOW);
	// Randomise the pseudo-random number generator

void loop() {
	// RED light on - ALWAYS start RED to avoid accidents
	digitalWrite(RED, HIGH);
	// Give one controller a chance to turn GREEN first

	// Check to see if the other controller wins
	if (digitalRead(CONTROL_IN)) {  
		// Other controller wins, this controller stays RED
		// until CONTROL_IN goes LOW **/
		while (digitalRead(CONTROL_IN)) {
			// Do nothing, just wait for the switchover
	} // End of inital round, start normal light roatation
	while (true) {
		// Switch to GREEN for green_time
		digitalWrite(CONTROL_OUT, HIGH);
		digitalWrite(RED, LOW);
		digitalWrite(GREEN, HIGH);
		digitalWrite(GREEN, LOW);
		// Then YELLOW for yellow_time
		digitalWrite(YELLOW, HIGH);
		// Drop control signal and switch to RED 
		// Heres hoping the other controller will read this LOW condition
		// and switch to GREEN
		digitalWrite(CONTROL_OUT, LOW);
		digitalWrite(YELLOW, LOW);
		digitalWrite(RED, HIGH);
		// Now wait for other controller
		while (digitalRead(CONTROL_IN)) {
			// Do nothing, wait for green light to end on other controller