Professional Documents
Culture Documents
Arduino Traffic Light Code
Arduino Traffic Light Code
Arduino Traffic Light Code
h>
//#define DEBUG
/*
Simulate a pedestrian crossing
This code responds to two events: the passage of time and the pressing of
the call request button. Outside of responding to these events the program
has no secondary task. To optimize the performance of the CPU in its
secondary task, the primary tasks occur in response to interrupts.
*/
// Pin allocation:
const int CallbuttonPin = 2; // the "I want to cross" button
const int lightCallAcknowledge = 3; // the light that says "you pressed the button"
const int lightGreenMan = 4; // Pedestrian "walk now"
const int lightRedMan = 5; // Pedestrian "Do not start walking"
const int lightGreen = 6; // Traffic go
const int lightAmber = 7; // Traffic stop if safe
const int lightRed = 8; // Traffic stop
const int timerPin1 = 9; // lost to timing, can't be used for IO
const int timerPin2 =10; // lost to timing, can't be used for IO
const int onBoardLED = 13; // on board, can be over-ridden or even cut
typedef struct {
public:
byte timer_length; // How long to stay in this state (1 tick = 500ms)
byte action; // state to set the lights to
char next_state_on_timer;
char next_state_on_call_button;
} StateTransition;
void transition_to_next_state()
{
#ifdef DEBUG
Serial.print((int)current_state);
Serial.print(" transitions_to ");
Serial.println((int)next_state);
#endif
if (next_state == NoTransition) return;
current_state = next_state;
next_state = NoTransition;
void timer_tick()
{
if (--ticks_remaining == 0)
{
next_state = state[current_state].next_state_on_timer;
}
// See if we can service any existing call
else if (digitalRead(lightCallAcknowledge))
{
next_state = state[current_state].next_state_on_call_button;
}
}
void call_button_pressed()
{
// Don't acknowledge if it would be cleared
if (!call_button_disabled)
{
digitalWrite(lightCallAcknowledge, HIGH); // Acknowledge the request
}
}