For this worksheet you'll need a breadboard, three LEDs, a button, a buzzer, and the necessary jumper cables and resistors. You can purchase these individually, or get everything you need in the CamJam EduKit.
To get started, you'll need to place all the components on the breadboard and connect them to the Raspberry Pi.
-
First, you need to understand how each component is connected:
- A button needs a GPIO pin and ground
- An LED needs a GPIO pin and ground, but it also needs a resistor to protect it
- A buzzer needs a GPIO pin and ground
To save on using 5 different ground pins, you can just plug a single GND pin into the negative row on a breadboard. This is called a common ground.
-
Place the components on the breadboard and connect them to the Raspberry Pi GPIO pins, as shown below:
-
This table shows which GPIO pin is connected to which component, in case you get lost:
| Component | GPIO pin |
|---|---|
| Button | 21 |
| Red LED | 25 |
| Amber LED | 8 |
| Green LED | 7 |
| Buzzer | 15 |
-
Open Scratch and save a new file.
-
The first step is to configure all the GPIO pins, so that they are set to be inputs and outputs. Use broadcast blocks, as shown below:
-
Now use another
when greenflag clickedblock to set a variable calledpushedtoFalsewhen the script starts: -
Now use a
foreverloop to wait for the button to be pushed: -
And finally, you can change the value of the
pushedvariable toTrueif the button is pushed:
-
Now you can create a basic traffic light sequence. The sequence for traffic lights is Red-->Red/Amber-->Green-->Amber, and constantly repeated. This is the perfect excuse for a loop.
-
The script below will create your basic traffic light sequence:
-
Test out the light sequence by clicking the
greenflag. -
You want to be able to interrupt the sequence when the button is pushed, to allow a pedestrian to cross the road. An
if/elseblock will help with this: -
Test out the sequence, and then try pushing the button. The traffic light sequence should finish and then stop.
To help the visually impaired, a crossing normally beeps when it is safe to cross.
- You can create a new broadcast to manage this. Call it
beep. The first thing it should do is make sure the light is red:
- Next, you can use a
repeatblock to switch the buzzer on and off a few times:
- Once the beeping has finished, the script should turn the red LED off, and then reset the
pushedvariable back toFalse:
- Lastly, you can have the main script
broadcast beep and waitwhen the button has been pushed:
- And now you should have a working traffic light and crossing, all in Scratch!
- Can you alter the beeping, so that it becomes faster to warn the pedestrian that their time is nearly up?
- How about adding in a second set of lights, to simulate a crossroads?
Back to Physical computing with Scratch










