Site icon CADSample.Com Free DWG CAD File

Arduino Project – Model Traffic Signal

Arduino Project – Model Traffic Signal

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.

Hardware

The schematic diagram for the project is shown in below. 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 in Figure 4-2 and the board layout in Figure 4-3.

Software

The sketch for Project 5 is shown in Listing Project 5.
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 setLights to set the state of each LED, reducing three lines of code to one.

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);

 

 

 

 

 

 

rare
Exit mobile version