ALGORITHMS
We frequently see many traffic signals while traveling. Have you ever wondered how they work?
This project emphasises writing code to operate a traffic signal with a timer in p5js.
tool: p5.js
Every day, we travel using different vehicles. Some days we use cars or motorcycles, other days we use bicycles . We can even travel in a truck. A commonality between all these vehicles is that they have to follow traffic signals. Even pedestrians have to follow them.
Traffic signals play an important part in our transportation system. They control traffic and help to avoid accidents. They use different coloured lights which tell vehicles and people to STOP and GO. Traffic signals are not only used on streets but also on train tracks.
Traffic signals have small computers inside them. Programmers write code to control the timer and the operation of the lights.
In today’s lesson, we will write a program to simulate the working of a basic traffic signal in the p5js editor.
To write a code in p5js to operate a traffic signal with a timer, We will follow the given sequence of steps:
Part 1- Draw a Background
Step 1: Add the ‘noStroke’ command to draw shapes without a border.
Step 2: Add rectMode(CENTER); command to draw centre aligned rectangles.
Part 1- Draw a Background
Step 3: Draw a background Sky using a rectangle at “x=width/2” and “y=height/2” and dimensions to fill the canvas.
Part 1- Draw a Background
Step 4: Draw land in the background using another rectangle, such that it covers the lower half of the canvas.
In the rectMode(CENTER); command, the x and y values are of the centre of the rectangle. Also, note the following diagram showing dimensions for further positioning the signal elements.
Part 2- Draw a Signal Structure
Step 1: Draw a vertical rectangle as a pole for the signal.
Part 2- Draw a Signal Structure
Step 3: Draw a rectangle at the centre of the canvas for the body.
Part 2- Draw a Signal Structure
Step 2: Draw a square at the centre of the canvas for the body.
Part 3- Draw Traffic Signals
Step 1: Draw two circles as red and green lights.
Step 2: Use the fill() command to colour one light red and the other green.
Part 4- Add a Variable
Step 1: Declare two variables 'r’ and ‘g’ at the top of the code.
Step 2: Assign the initial values to the variables 'r’ and ‘g’ in the setup function as ‘255’ and ‘100’, respectively.
Part 4- Add a Variable
Step 3: Add variables in the fill() commands for their respective coloured circles.
In a signal at any given time, only one of the red and green lights should be switched on. The other one should be off. If we exchange the values of 'r’ and ‘g’ variables, then the light that was on will turn off, and other one will be switched on. We can repeat process of exchanging values inside a variable and alternate which light switches on.
The concept of exchanging values inside variables is often used in programming. Before programming, the logical sequence of such tasks is decided. A logical sequence like this is called an algorithm. Let us learn about algorithms in detail.
A logical sequence like this is called an algorithm
An algorithm is a step-by-step procedure of how to perform a specific task to solve a specific logical or mathematical problem.
�For example: we have a set of numbers
[3, 4, 6, 2, 5, 7]
We can create a general set of logical commands to arrange these numbers in an ascending order.
[2, 3, 4, 5, 6, 7]
This set of generic steps to achieve this for any sequence will be an algorithm, which is used to write code. The same algorithm can be used to arrange any other set of numbers in an ascending order.
Algorithm
We will learn about an algorithm that can swap values between variables. �
Swap Algorithm – We can use the swap algorithm to exchange or swap values stored in two variables.
Swap algorithm: It typically involves three steps in coding:
This is the simplest way. There are other methods as well but we will focus on this one for now.
Part 4- Add a Variable
Step 5: Use the swap algorithm to change traffic signal colours.
Step 6: Create a temporary variable ‘t’ and assign the value of ‘r’ to ‘t’.
Part 4- Add a Variable
Step 7: Assign the value of ‘g’ to ‘r’.
Step 8: Assign the value stored in temporary variable ‘t’ to ‘g’.
Part 4- Add a Variable
Now the lights will switch on and off continuously as per the draw() function. The switch happens too fast and is not visible. However, we can use the console to check if it is working correctly.
Step 9: Add the console.log(r,g) command to check if the swap operation is taking place.
Even though the variable values are swapped, right now, we can see that both the lights are switched ON. To avoid this, let us add a delay between the transitions using the millis() command.
The millis() command returns the number of milliseconds (1000 milliseconds = 1 second) since the code starts running, i.e. when setup() is called. This is used to time events and animation sequences.
We can create a variable “currentTime” and assign the millis() function to it for timing the signals.
Part 4- Add a Variable
Step 10: Create a variable “currentTime” and assign the millis() function to it.
Step 11: Declare a variable called currentTime at the beginning of the code.
Part 4- Add a Variable
Step 12: Assign the value of time elapsed to the variable. Use the millis() command in the draw() function since it needs to be continuously updated.
Step 13: Comment out other console.log() commands and add new one to check the value in the ‘currentTime’ variable.
As the code starts executing, variable ‘currentTime’ displays the updated value of time lapsed. We can check if time elapsed is greater than 1 second, i.e. 1000 milliseconds. After the first second, we will keep track of every second.
Create another variable called ‘previousTime’ with an initial value of ‘0’ and check the difference between the two variables after each second elapsed.
If timeDelay >= 1000 (1000 ms), then 1 second is over. To check when the next second has passed, update the value in ‘previousTime’ to ‘1000’.
The ‘CurrentTime’ value continuously increases as the code runs. The initial value in the ‘previousTime’ variable is set to ‘0’. Save the difference between two variables (currentTime – previousTime) in a new variable called timeDelay.
In this way, we can count each second that passes by updating the ‘previousTime’ variable when 1000 ms are have passed. Every time a second passes, we can update the counter to keep track of time.
We have already learnt about flowcharts that create logic and algorithms for code. We can create a flowchart for this logic.
Part 5- Add a Timer
Step 1: Add a timer using the millis() function
Step 2: Declare variables ‘previousTime’ and ‘timeDelay’.
Step 3: Set their initial value to ‘0’ in the setup() function.
Part 5- Add a Timer
Step 4: Assign value for ‘timeDelay’ as (currentTime – previousTime) before the swap algorithm code.
Part 5- Add a Timer
Step 5: Use if condition to check if timeDelay value is greater than or equal to (>=) 1000 ms, i.e. 1 second.
Step 6: If the condition is satisfied, set the value of the previousTime variable to ‘currentVariable’.
Part 5- Add a Timer
Now our code detects every single second that passes. We can use this to change the signal colours each second.
Step 7: Move the swap algorithm code inside the ‘if’ condition to check the value in the ‘timeDelay’ variable.
Part 5- Add a Timer
The red and green lights switch on alternately after every second. Usually, one light at a signal is on for more than 10 or 20 seconds. We can use a counter variable to count the number of seconds and increase the signal time. To update the code, undo the previous step of moving the swap algorithm in the if condition.
Step 8: Declare a counter variable at the top of the code and set the initial value to the required time. For example, 10 for 10 seconds.
Part 5- Add a Timer
With every second that passes, we can decrease the value of the counter variable by ‘1’. If the value becomes ‘0’, we can reset it to ’10’ using the ‘if’ condition. This way, we can change the signal lights after 10 seconds instead of just 1.
Step 9: Decrease the value of the ‘counter’ variable by ‘1’ after every second by adding it in the ‘if’ condition.
Part 5- Add a Timer
Step 10: Create another if condition to check if counter value is less than 0. If yes, set it back to 10.
Step 11: Check if the counter value has swapped after every 10 seconds and move code for the swap algorithm in the ‘if’ condition.
Part 6- Show the Timer Counter
Now we can see that the signal changes colour after every 10 seconds. We can also display the counter in the square box at the top, just like in real traffic signals.
Step 1: Add the fill() command to set the text colour.
Step 2: Add the textSize(); command to set a text size suitable to the square box.
Part 6- Show the Timer Counter
Step 3: Add the textAlign(CENTER); command to centre align the text to the display.
Step 4: Use the text(text value, x position, y position); command to display the counter digits. The text value will be the value of the counter variable, and the x and y positions are used to keep the text in the centre of the square.
With this, our traffic signal simulation is complete. Run the code to check if it is working correctly. Try using different timer values for signals and separate timers for red and green lights.