Arduino tutorial 03 - Traffic light

0 164 Easy

Project - Traffic light

 

You will start an interactive Arduino project in this lesson by making button-controlled traffic lights. When the button is pressed, the lights will change for pedestrians to pass by.

 

 

COMPONENT LIST

 

 

*Why are there 5 LEDs with 6 resistors? The extra resistor is a pull-down resistor for the button.

 

 

HARDWARE


Follow the wiring diagram below to build your circuit.
Please note that the green lines represent the color of the socket it connected and do not represent the color of the wire you must use.
Please use the provided USB cable to power the Arduino after you build the circuit. This cable provides a steady 5V to the Arduino. If you use another power source, the voltage might be too high which might overload the components.

 

fig 1 Wiring Diagram of LED Blinking


 

CODE


Sample code:

CODE
// Project - Traffic light
  
int carRed = 12;    // Pin for the car's red light  
int carYellow = 11; // Pin for the car's yellow light  
int carGreen = 10;  // Pin for the car's green light  
int button = 9;     // Pin connected to the button  
int pedRed = 8;     // Pin for the pedestrian's red light  
int pedGreen = 7;   // Pin for the pedestrian's green light  
int crossTime = 5000; 
// Time allowed for pedestrians to cross in milliseconds  
unsigned long changeTime; // Timestamp of the last button press  
  
void setup() {  
    // Initialize pin modes  
    pinMode(carRed, OUTPUT);  
    pinMode(carYellow, OUTPUT);  
    pinMode(carGreen, OUTPUT);  
    pinMode(pedRed, OUTPUT);  
    pinMode(pedGreen, OUTPUT);  
    pinMode(button, INPUT); // Set the button pin to INPUT mode  
  
    // Set initial light states  
    digitalWrite(carGreen, HIGH); // Turn on the car's green light  
digitalWrite(pedRed, HIGH);   
// Turn on the pedestrian's red light  
}  
  
void loop() {  
    int state = digitalRead(button); // Read the state of the button  
    /* Check if the button is pressed (assuming LOW is pressed) and enough time has elapsed  */
    if (state == HIGH && (millis() - changeTime) > 5000) {  
        // Call the function to change the lights  
        changeLights();  
    }  
}  
  
void changeLights() {  
    // Change the car's green light to yellow  
    digitalWrite(carGreen, LOW);  
    digitalWrite(carYellow, HIGH);  
    delay(2000); // Wait for 2 seconds  
  
    // Change the car's yellow light to red  
    digitalWrite(carYellow, LOW);  
    digitalWrite(carRed, HIGH);  
    delay(1000); // Wait for an additional 1 second for safety  
  
    // Change the pedestrian's red light to green  
    digitalWrite(pedRed, LOW);  
    digitalWrite(pedGreen, HIGH);  
  
    /* Keep the pedestrian's green light on for crossTime milliseconds  */
    delay(crossTime);  
  
    /*Flash the pedestrian's green light to indicate time is running out  */
    for (int x = 0; x < 10; x++) {  
        digitalWrite(pedGreen, HIGH);  
        delay(250);  
        digitalWrite(pedGreen, LOW);  
        delay(250);  
    }  
  
    // Turn the pedestrian's red light back on  
    digitalWrite(pedRed, HIGH);  
    delay(500); // Optional delay for stability  
  
    // Restore the car's lights to green (via yellow)  
    digitalWrite(carRed, LOW);  
    digitalWrite(carYellow, HIGH);  
    delay(1000);  
    digitalWrite(carYellow, LOW);  
    digitalWrite(carGreen, HIGH);  
  
    // Update the timestamp of the last button press  
    changeTime = millis();  
}

After uploading the sketch, take a look at how LED changes. First, the green traffic light is on and the red pedestrian light is on to allow cars to pass. Once you press the button, the pedestrian light changes from red to green and the traffic light changes from just green to yellow and then red. There is then a delay allowing time for pedestrians to cross the street. When the delay comes to an end, the green pedestrian light blinks to notify pedestrians. When this finishes, the lights change back to the initial state with the green traffic light on and the red pedestrian light on.


The above codes do look complex, but actually, it is not that difficult to understand the ideas in practice.


If you find it difficult for you to follow, try to draw a diagram like the one in the homework for Project [SOS Beacon]. This will help you to comprehend the codes a little better. Good luck!

 

 

CODE REVIEW


Based on the project[Blinking A LED] and project[SOS Beacon], most of the codes should make sense to you. The codes start from a set of variable declarations, and we have used a new term. It is explained below:

 

unsigned long changeTime;

 

 

Before we use int to store integers from -32768 to 32767. The long command we use in this project can store integers from -2147483648 to 2147483647. Unsigned long cannot store negative numbers. So it stores integers from 0 to 4294967295.
If we use int, we might go over the limit of 32 seconds (32768ml sec) and risk having errors in running the sketch. As a result, we need another command to store integers and exclude negative numbers, such as unsigned long whose limit is 49 days.
Then we enter the setup() function to configure the LED and button.

 

pinMode(button, INPUT);

 

 

We have been quite familiar with pinMode() function introduced in Project [Blinking A LED]. Its difference with LED is that the button should be set as INPUT.


In setup() function, we need to initialize the pedestrian and traffic light:

 

 

digitalWrite(carGreen, HIGH); 
// Turn on the car's green light  
digitalWrite(pedRed, HIGH);
// Turn on the pedestrian's red light  

 

 

The first line of the main sketch is to test the state of button in pin 9.

 

 

int state = digitalRead(button);

 

 

Can the box of variable be infinite big?

 


Why can some variables store large amounts of data while some can't? It depends on the storage space of the variable, a bit like a box. For example, the storage capacity of int is much smaller than unsigned long. Just like a computer has a limited storage space, a microcontroller, like your Arduino, is the same. The maximum storage space of Arduino UNO’s main chip (Atmega328) is 32k, we use different variable types depending on the situation. If we can save some storage space, why not?


Some common variables below you will come across:

 

 

There are various types of variables. int and long are for integers, char is for characters, float and double are for variables with decimal points.

 

In setup() function, there is a new command digitalRead() !

 

 

This command is used to read the digital pin’s state, whether high (1) or low (0). The command has one parameter: “pin number”.


This command passes the signal read to the variable state for further judgment.
When the state value is HIGH or 1, it means that the push button has been pressed. When the state value is LOW or 0, it means that the push button hasn't been pressed.
We can check the value of the state to test if the button is pressed.

if (state == HIGH && (millis() - changeTime) > 5000) {  
           // Call the function to change the lights  
           changeLights();  
       }  

 

 

Here we use the if() command to test conditions.

 

 

if(condition){
     Statement;
}

 

 

If the condition specified in the parenthesis is satisfied, it carries out the statement. If not, the program skips over the code. In other words, if the if() expression returns TRUE, the statement is run. If it returns FALSE, the statement is skipped. In the above codes, the first condition is whether the variable state is HIGH (or on). When the push button is pressed, the state turns HIGH. The second condition is that the value returns for “millis0” minus that for change Time is more than 5000. We use “&&” to connect the two conditions. This is a logical operator, showing that we want the above two conditions met at the same time.“milis0”is a command that returns the number of milliseconds since the Arduino board began running the current program. This number will overflow (go back to zero) after approximately 50 days. Here we use it to calculate if there is a break of more than seconds when pressing the button more than once. If shorter than 5 seconds, it skips over the code to avoid errors caused by the “bouncing” effect after pressing the button.

 

 

This is a command inside the if() command.

 

changeLights();

 

This is a function created outside of loop() function. we just need to cite the function's name if we want to use it. It does not have a returned value and does not need to pass parameters so it is a void function. When it is called, the program will run the function and go back to the main code afterwards. Beware not to miss the parenthesis when using this function as otherwise it will not be recognised.

 

HARDWARE REVIEW


Push Button


The push button we used has 4 pins. When the button has been pressed, it connects two pins left and right together so that electricity can flow through them. There are only really two electrical connections. inside the switch package, pins 1 and 4 are always connected together as are 2 and 3.

fig 2 Structure of push button (front & back)

 

fig 3 schematic diagram of push button

 

 

A push button can switch on and switch off the electricity flowing through the circuit. In the project, when it is pressed, pin 9 detects HIGH (ON), otherwise it remains LOW (OFF).

 

button diagram

fig 4 button diagram

 

 

pull-down resistor


Pull-down resistors are used in electronic logic circuits to ensure that inputs to the Arduino settle at expected logic levels if external devices are disconnected. A pull-down resistor weakly "pulls" the voltage of the wire it is connected to the ground when the other components on the line are inactive.

 

In fig 5, the input pin is not pulled to a high or low logic level, but is left “floating" instead when the button is opened. It is neither in a high or low logic state, and the Arduino might unpredictably interpret the input value as either a logical high or logical low. 


In fig 6, the button is connected between the supply voltage(5V) and the input pin. In such a circuit, when the switch is closed, the input is at a logical high value, but when the switch is open, the pull-down resistor pulls the input voltage down to ground (logical zero value), preventing an unpredictable state at the input.

fig 5 without pull-down resistor

 

fig 6 with pull-down resistor

 

EXERCISE


1.choose 6 LEDs of any color and achieve the Chasing light display.

 

 

2. When you are done, try to light up the column of LEDs in the middle and have them pass the light towards either edge.

 

 

3. light the column from left to right

 

icon Sample code.rar 1KB Download(1)
License
All Rights
Reserved
licensBg
0