Advertisement

Saturday 21 July 2012

Model Traffic Signal with Arduino



So now we know how to set a digital pin to be an input, we can build a project for model traffic
signals using red, yellow, and green LEDs. Every time we press the button, the traffic signal will go
to the next step in the sequence. In the UK, the sequence of such traffic signals is red, red and


amber together, green, amber, and then back to red. As a bonus, if we hold the button down, the
lights will change in sequence by themselves with a delay between each step. The components for Project 5 are listed next. When using LEDs, for best effect, try and pick LEDs of similar brightness.

Required Components:

Arduino Diecimila or
Duemilanove board or clone 1
D1 5-mm red LED 23
D2 5-mm yellow LED 24
D3 5-mm green LED 25
R1-R3 270  0.5W resistor 6
R4 100 K 0.5W
resistor 13
S1 Miniature push to make
switch 48
Hardware

The schematic diagram for the project is given bellow.The LEDs are connected in the same way as our earlier project, each with a current-limiting resistor. The digital pin 5 is “pulled” down to GND by R4 until the switch is pressed, which will make it go to 5V. A photograph of the project is shown bellow
Software 
The sketch for Project is shown. The sketch is fairly self-explanatory. We only check to see if the switch is pressed once a second, so pressing the switch rapidly will not move the light sequence on. However, if we press and hold the switch, the lights will automatically sequence round. We use a separate function set Lights to set the state of each LED, reducing three lines of code to one.
 









Project Code :

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;
int state = 0;
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
if (digitalRead(buttonPin))
{
if (state == 0)
{
setLights(HIGH, LOW, LOW);
state = 1;
}
else if (state == 1)
{
setLights(HIGH, HIGH, LOW);
state = 2;
}
else if (state == 2)
{
setLights(LOW, LOW, HIGH);
state = 3;
}
else if (state == 3)
{
setLights(LOW, HIGH, LOW);
state = 0;
}
delay(1000);
}
}
void setLights(int red, int yellow,
int green)
{
digitalWrite(redPin, red);
digitalWrite(yellowPin, yellow);
digitalWrite(greenPin, green);
}

Putting It All Together

Load the completed sketch for Project from your Arduino. Test the project by holding down the button and make sure the LEDs all light in sequence.


Data Taken from Evil genious.

1 comments: