1 of 49

ALGORITHMS

2 of 49

We frequently see many traffic signals while traveling. Have you ever wondered how they work? 

3 of 49

This project emphasises writing code to operate a traffic signal with a timer in p5js. 

tool: p5.js 

4 of 49

  • To use code to draw the signal as using various shapes.

  • To Learn about timers and add functionality to the traffic signal.  

  • To code the traffic lights in p5js. 

5 of 49

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. 

6 of 49

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.  

7 of 49

  • A red-coloured signal indicates that the vehicle should stop,
  • and a green signal tells the vehicle to go ahead.
  • Many traffic signals, especially in heavy traffic areas, have an orange signal that tells the vehicle to reduce its speed and prepare to stop.
  • Traffic signals also have a counter which displays the seconds remaining for a signal colour to change.  

Traffic signals have small computers inside them. Programmers write code to control the timer and the operation of the lights.

8 of 49

In today’s lesson, we will write a program to simulate the working of a basic traffic signal in the p5js editor.  

9 of 49

To write a code in p5js to operate a traffic signal with a timer, We will follow the given sequence of steps:  

  • Use code to draw the signal as using various shapes.
  • Learn about timers and add functionality of the timers to update the signal.
  • Code to update the traffic lights.  

10 of 49

11 of 49

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.  

12 of 49

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. 

13 of 49

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. 

14 of 49

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. 

15 of 49

Part 2- Draw a Signal Structure

Step 1: Draw a vertical rectangle as a pole for the signal. 

16 of 49

Part 2- Draw a Signal Structure

Step 3: Draw a rectangle at the centre of the canvas for the body. 

17 of 49

Part 2- Draw a Signal Structure

Step 2: Draw a square at the centre of the canvas for the body. 

18 of 49

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. 

19 of 49

  • We will change the colours of the light circles to show them as switched on or off.
  • To display a bright red or green light, the colour value should be 255.
  • To show a switched off light, the colour value will be 100.
  • Since the colour values are changing, we will need to use variables to code.  

20 of 49

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. 

21 of 49

Part 4- Add a Variable

Step 3: Add variables in the fill() commands for their respective coloured circles.

  • We will use variables here instead of values. 

22 of 49

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.  

23 of 49

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

24 of 49

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 

25 of 49

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. 

26 of 49

Swap algorithm: It typically involves three steps in coding:

  1. Store the value of the first variable in a temporary variable.
  2. Assign the value of the second variable to the first variable.
  3. Assign the value stored in the temporary variable to the second variable.

This is the simplest way. There are other methods as well but we will focus on this one for now.

27 of 49

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’. 

28 of 49

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’.

29 of 49

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. 

30 of 49

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.  

31 of 49

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. 

32 of 49

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.  

33 of 49

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. 

34 of 49

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

35 of 49

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. 

36 of 49

We have already learnt about flowcharts that create logic and algorithms for code. We can create a flowchart for this logic. 

37 of 49

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.  

38 of 49

Part 5- Add a Timer

Step 4: Assign value for ‘timeDelay’ as (currentTime – previousTime) before the swap algorithm code. 

39 of 49

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’. 

40 of 49

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. 

41 of 49

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. 

42 of 49

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. 

43 of 49

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. 

44 of 49

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.  

45 of 49

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.

46 of 49

47 of 49

  • What is an Algorithm?

  • Explain the Timer countdown.

48 of 49

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. 

49 of 49