Story
This is my 3rd tutorial with a focus on Scratch and Physical Computing. Regarding this topic, I have already published:
- Physical Computing â Scratch for Arduino, where as the name says, I explored how to use Scratch and Arduino to interact with the physical world.
- Physical Computing â Scratch for Raspberry Pi, same but using Raspberry Pi and Scratch 1.4
Here, we will learn the new version of Scratch, the 2.0, exploring some new and exciting projects.
In short,
We will learn:
- What is Scratch 2.0 and its differences with Scratch 1.4
- How to interact with LEDs, Push-Buttons and a Buzzer
- How to create Special Blocks
- How to handle with variables
- How to integrate animations and the Physical world.
Letâs go!
Step 1: Bill of Material â BoM
For the experiences in this tutorial, you will need at least the items:
- Raspberry Pi (V2 or V3)
- LEDs (Red, Yellow, and Green)
- 1 Button
- 1 Active Buzzer
- Resistors: 3 x 220 ohm
- Cables
- Full Breadboard
Step 2: The Scratch 2.0
As we know, Scratch is a great tool to teach beginners how to code, but before starting our tutorial, I really recommend that you go familiarize yourself with the Scratch 2.0 language, following some basic tutorials. Doing that will help you to better understand how to use a Raspberry Pi for Physical Computing.
There are 2 ways to do that:
- Go to Scratch Official Website, or
- Go to Official Raspberry Foundation site,
A new offline Scratch 2 version started to be delivered bundled with the last Raspbian OS release, and it is really great, with several new features that will help you to create a more professional codification.
WARNING: At least with me, the actual version introduced some âfreezing issuesâ, that could be related with Flash. Those freezings appeard whe I tried to upload new background or sprits.
Opening the program:
When you have the Pixel desktop in front of you, go to left up corner Application Menu (the âRaspberry Pi logoâ) and open it. You will find as one of the options: âProgrammingâ.
- Open it and click on âScratch 2â (note that the old version Scratch 1.4 (named as âScratchâ) is also there.
- Once you open the Scratch program, you will get the screen shown above.
- Click on âMore Blocksâ
- Click on âAdd an extensionâ. The option âPi GPIOâ Library will be available. Select it and click [OK]
- The PI GPIO library will be installed and the âgreen ledâ shows that it is running properly.
- 2 news blocks will be now available to be used with your Physical Computing programs.
The first block:
set gpio <GPIO number> to [output high]
above has 3 possible parameters:
- output high
- output low
- input
The second block:
gpio <
GPIO number
> is high?
will return:
- âTrueâ or âFalseâ depending on GPIO digital level (âTrue = 1â and âFalse = 0â).
Scratch 2.0 also allows the creation of custom blocks, allowing code to be encapsulated and used (possibly multiple times) in a project. We will see how to do it in the examples.
Step 3: The GPIO Pin Numbering
We will not cover how to prepare the Raspberry Pi to be used in this tutorial, but If you need any help, please refer to this link: Installing Raspbian with NOOBS.
Our Raspberry Pi will be running with the latest Raspbian version of the Operational System, having PIXEL, as our desktop environment.
Once we will interact with the physical world it is good to remember that our gateway to that will be the Raspberry Pi GPIO connector. The above photo shows the connector, where I have drawn some fictional components in red.
Pin Numbering Important to mention that we will use Broadcom (BCM) pin numbering for the GPIO pins, as opposed to physical (BOARD) numbering. Any pin marked âGPIOâ in the above diagram can be used as a pin number. For example, if a LED was attached to âGPIO13â (physical pin 33) you would specify the pin number as 13 and not â33â.
Step 4: Blinking a LED
tâs time for the âHello Worldâ of Physical Computing, the âblink of a LEDâ!
Letâs start connecting a LED to GPIO 13 of our Raspberry Pi (RPi, for short).
For starting, drag 2 new âset gpioâ blocks to the SCRIPTS AREA,
set gpiot <13> to [output high]
set gpio <13> to [output low]
Clicking on those blocks you will turn ON and OFF the LED
Now, letâs create a real blink code using Scratch 2.
- Start your program when the âGreen Flagâ is clicked, for that you will need the block:
- When âgreen flagâ clicked (it is the first block in the âEvent menuâ â colored in brown)
- Drag the loop block âForeverâ (you will find it on âControl menuâ â colored in yellow)
- Inside the loop Forever, put the blocks that you used on the before.
- if you run your code, you will see that nothing happens, or better, the LED will be ON and OFF so quickly that you will not realize it. So, you must add some delay, letâs say 1 second after each block.
Step 5: Using Custom Blocks â Multiples LEDs Blinking
Now, that we know how to control one LED, letâs install 2 new ones, with different colors:
- RED
- YELLOW
- GREEN
Repeat what you did at last step, connecting the LEDs as shown above:
- RED ==> GPIO 13
- YELLOW ==> GPIO 19
- GREEN ==> GPIO 26
Suppose that we want now the 3 LEDs blinking independently at different frequencies. The first thing that you can do is to copy the set of block developed on the last step, changing the GPIO number and the delays for each one of the blocks, letâs say:
- Blink Block for GPIO 13 ==> delay: 1 second
- Blink Block for GPIO 19 ==> delay: 2 seconds
- Blink Block for GPIO 26 ==> delay: 4 seconds
It would work, but letâs use the opportunity here and introduce a new feature of Scratch 2, the âCustom Blocksâ.
First, letâs create a custom block naming it âsetupâ, that will be used to turn OFF all LEDs
- Go to âMore Blocksâ menu
- Select âMake a Blockâ
- Enter the name âsetupâ and click OK
You will see that a new block will appear âdefine [setup]â, below it, we can add 3 blocks setting the GPIOs to LOW as shown at above print screen. Now, this custom block âsetupâ (that it is, in fact, a âfunctionâ), can be called anytime in the program. Letâs call it at starting, under the green flag, so anytime time that the program run, we will guarantee that the LEDs will be OFF.
Now, we will create a more elaborate custom block. We will create a type that can receive parameters allowing further generalization and reuse of code blocks. The idea is to create a generic âBlink blockâ, where the parameters will be the GPIO number and the time. So, our final block will be like:
blink <GPIO> <time>
So, letâs do the following:
- Go to âMore Blocksâ menu
- Select âMake a Blockâ
- Enter the name âBlinkâ and click at sub-menu âOptionsâ
- Click on the first option: âAdd number inputâ and type âGPIOâ
- Click again on same option and type âtimeâ
- Enter OK
Now, a new block will appear:
define [Blink] [GPIO] [time]
Under this block we will add the blocks that we used for the blink, but, instead of specific numbers, we will add the âblueâ and generic parameters: âGPIOâ and âtimeâ
Now if we want to blink the LEDs independently it is enough to use blocks like those:
Blink <13> <1>
Blink <16> <2>
Blink <26> <4>
The code for this example is here:Â blink_V2.sb2
Step 6: Introducing a Push-Button and Variables
Using a push-button with the Raspberry Pi and Scratch 2 is a âstraight forward taskâ. with the Scratch 1.4, we saw that an internal pull-up resistor was used. Here, instead, we will use âdirect logicâ, or:
- If Push-Button is pressed (closed) ==> GPIO = â1 â (3.3V)
- If Push-Button not pressed (open) ==> GPIO = â0â (0V)
So, letâs connect the button as shown in above diagram.
WARNING: you must use the 3.3V output (physical pin number #1). The RPi does not support 5V on its GPIOs
For reading our push-button, we will create a new variable âbuttonâ to be associated with its state:
- If Push-button is PRESSED ==> âbutton = ONâ
- If Push-Button is NOT PRESSED ==> âbutton= OFFâ
The blocks to that will be:
if <20> is high?> then
else
We will include those blocks on a new block that we will call: âgpioStatusâ and by the way, we will do the same for LEDs, creating variables associated to each one of them:
- red
- yellow
- green
And will associate values to those variables, and we will act on correspondent GPIO accordingly:
- If Red LED should be ON ==> variable âred = ONâ ==> GPIO 13 ==> âhighâ
- If Yellow LED should be ON ==> variable âyellow = ONâ ==> GPIO 19 ==> âhighâ
- If Green LED should be ON ==> variable âgreen = ONâ ==> GPIO 26 ==> âhighâ
And of course, the opposite for LEDs off.
All above logic should also be included at âgpioStatusâ function, that will be running during all the time. So, we will not need to be worried about GPIOs anymore. Instead, we will use the variables to build our program logic.
For example, letâs create a program that:
- Run the LEDs in a fixed sequence on a given frequency as a normal traffic light:
- RED
- YELLOW
- GREEN
And so on. If a button is pressed, the frequency is changed, letâs say around 3 times faster.
The first thing to do is to create a new variable, named âtimeâ that will have a value, letâs say:
- 1 second if the variable âbuttonâ is OFF and
- 0.3 seconds if âbuttonâ is ON.
As you can see, we are in fact controlling timeâs value actuating on a physical push-button, but here only âvariablesâ are used.
We can do the same for the LEDs sequence. We will set red, yellow and green variables, ON or OFF, keeping them ON using the variable âtimeâ now.
Here the code used in the example:Â 3LED_button_V2.db2
Step 7: Letâs Animate!
One of the great features of Scratch is the animation. So, letâs introduce some very simple animation on our projects.
Letâs change the last project a little. Now, The traffic lights will perform its sequence only when the push button is pressed. If not pressed, all lights must be off. The code is very simple. Try to do it before you see my solution.
OK, but letâs make the things more interesting. Letâs create a new sprite a âBlue Buttonâ (I left with its default name, sprite 1. You can change it) that will have 2 possible costumes:
- button OFF
- button ON
I used the internal editor to create the simple costumes. We will want that this sprite will always appear at Stage, but with its costume âbutton OFFâ if the push-button is released (variable button = OFF) and of course, with the costume âbutton ONâ if the push-button is pressed. One simple block that should run all the time.
Now we must create the Traffic Light that will show the LED status on the Stage. We can do it or creating a new Sprite, or creating new backdrops. We will do the second on, so you can see 2 different examples of animation creation here.
With the paint editor, I created 3 empty circles, that I called âOFFâ. Coping this backdrop 3 times, I filled one of the circles with one of the LEDs color (Red, Yellow, and Green) in this sequence. I name them (SURPRISE!): RED, YELLOW, and GREEN.
So, at Backdropâs Script tab I included a piece of code that will run forever, changing the backdrop according to LED variables (see above). Very simple and straight forward.
And thatâs it! As you can see, the final project is a group of various simple parts, whatâs make it at end also very simple to understand.
NOTE: The secret here is to be ORGANIZED with the code.
Below a video with our project and animation running:
The code can be downloaded from here:Â Traffic Lights V2.sb2
Step 8: Itâs Show Time!
On the last step, we had a lot of fun creating simple animation and mixing physical and virtual things together. Letâs now, do a more elaborate project.
Before we enter in the animation part of it, letâs complete the HW. This project will have a pedestrian Traffic Light and so, we will include a Buzzer that will produce a sound (âBeepâ), during the time allowed for pedestrians crossing a street. The buzzer will be installed at GPIO 16. AS we did before, to simplify things, letâs create a new variable âbeepâ that will activate GPIO 16 High or Low. The logic will be included at gpioStatus, same we did for the LEDs.
Letâs take our little friend, the MJRoBot and show him London, the birthplace of Raspberry Pi!
For starting, we must define the general specification regarding our project:
- Our little friend will start its journey around London, moving right to left across all stage area.
- When he touches the left Stageâs border, we must change for the next Londonâs backdrop.
- When he reaches Abbey Road, he must stop because there is a pedestrian cross (Yes! The famous one!)
- Suppose that was installed there, a traffic light to protect tourists. The robot will ask us to press the push-button for him, so he can go across the street, same as Paul, John, George, and Ringo did years ago) but in an opposite direction đ
Letâs this time create two new sprites:
- A Traffic Light (in opposite for using several backdrops) with 3 costumes (red, yellow and green)
- The little robot, the MJRoBot that has 2 costumes to help him to walk (or something that resembles walking). đ
We will have 4 backdrops. 3 for London surrounds and the most important one: Abbey Road.
Thatâs it!
Try to code it by yourself and only after, compare your solution with mine! There are several different ways to do that.
Enjoy it!
A quick video about the final project working:
My code solution here:Â MJRoBot around London V1.sb2
Step 9: Conclusion
As always, I hope this project can help others find their way in the exciting world of electronics.