Automate and command your next LEGO build with Scratch coding. We’ll show you just how easy it is.
Can you think of a better educational toy than LEGO? There’s DUPLO for toddlers to teach colours and fine motor skills. LEGO bricks for all ages who are dexterous with their fingers. Then there’s TECHNIC for more advanced construction.
LEGO is now becoming a popular and useful tool in schools to support the STEM curriculum, from teaching kids creativity to critical thinking, engineering and coding.
A LITTLE LEGO HISTORY
The humble plastic injection moulded bricks have been entertaining children and families since the late 1940’s! By 1986, the clever team at LEGO had worked out a way to control LEGO with a computer, and in 1988 they released the intelligent MINDSTORMS Robotics Invention System with motors and sensors that could be controlled. After various iterations over the years, the LEGO MINDSTORMS EV3 hit the shelves in 2013. EV3 retails for around A$400 to A$500.
In 2009, LEGO released WeDo, an educational set designed for Kindergarten to Grade 2. WeDo version 2.0 became available in 2016, and is commonly used in the education sector.
In early 2017, LEGO unveiled LEGO BOOST, a Building and Coding Set designed to teach kids between 7 to 12 how to code. BOOST is a lot more affordable (around A$200) and enables kids to add movement, sound and personality to their builds.
If you don’t own a LEGO WeDo, BOOST or EV3 then perhaps it’s the best time to get one for home or school. They also make a great gift for a budding LEGO enthusiast.
SOMETHING ABOUT SCRATCH
Scratch coding was developed in 2003, with the aim to teach young kids to code. This was done offline using a personal computer, once you had downloaded and installed the program. Scratch version 2.0 was released in 2013, which included many improvements such as a more intuitive layout, sound and vector editing, clones and many more code blocks, and the ability to code your projects online.
Scratch 3.0 was released at the start of 2019. In addition to many more Sprites, sound effects and backgrounds, the code editor was compatible with tablets. Many more extensions were added, including Text to Speech, Video sensing, Translate, and extensions to connect to the real-world such as Makey Makey, micro:bit, LEGO MINDSTORMS EV3, LEGO BOOST, LEGO WeDo 2.0, and the Go Direct Force & Acceleration sensor.
A BROAD OVERVIEW
Considering that LEGO has inspired kids with the recent LEGO Masters TV series in the UK and Australia, we thought it was an opportunity to inspire kids to code their LEGO as well.
Thanks to the collaboration between the Scratch and LEGO design teams, we are able to get Scratch to command the WeDo, BOOST, and MINDSTORMS EV3 LEGO sets. This article will only describe how to code the BOOST and EV3, but similar coding methods can be applied to the WeDo.
You will obviously need to have access to one of these LEGO sets, and a computer or tablet with Internet access and Bluetooth enabled.
Our introductory Scratch programs do not need the robots fully constructed. This allows you to quickly and easily operate many of the sensors and motors, without any time-consuming LEGO construction. However, you will need to fully construct either the EV3 EV3RSTORM or Vernie BOOST robot for the full program to work. This enables you to drive your robot about, and have fun shooting the cannon at objects in the room.
By the end of the article, you should be confident with the Scratch interface and how to code, know how to connect to your LEGO robot and be inspired to build your own programmable LEGO creations.
Scratch 3.0: We Have Lift Off!!
Scratch is a fantastic and easy way to teach kids as young as 6 how to code.
Simply drag-and-drop the coloured code blocks on the screen, which intuitively snap together to make their program. The blocks are like individual instructions that form what is called a script.
The blocks are colour-coded into groups depending on their function, such as Motion, Looks, Sound, Events, Control and more.
Want the Cat Sprite character on the stage to skip 10 steps when you press the Space bar? Easy! Simply drag-and-drop the code blocks to match our example above to see (and listen) what happens.
Kids can add sound effects, change sprite characters and backgrounds, and can even upload or create their own using the easy-to-use editing tool. They can add their own animations, create games, stories, and much more.
Programs can be saved and shared online, or downloaded to your computer or tablet, which you can re-upload later. To access Scratch simply go to https://scratch.mit.edu.
Note: There is an offline Desktop editor available to download so you can work on your projects without an Intenet connection.
CONNECTING WITH THE REAL WORLD
As we mentioned in the introduction, Scratch can also interface with real-world devices, from the video camera in your computer or tablet to cool electronics like the micro:bit and Makey Makey (See Issues 019 and 021 for using those with Scratch). Of course, Scratch also works with LEGO BOOST, WeDo and MINDSTORMS EV3.
A small program called Scratch Link is usually required to be installed on your computer or laptop, which as the name suggests, links your real-world device to Scratch.
MINDSTORMS EV3: If you plan to use Scratch with your MINDSTORMS EV3 then visit https://scratch.mit.edu/ev3 to download and install the Scratch Link program on your Mac or PC.
BOOST: If you plan to use Scratch with your LEGO BOOST then visit https://scratch.mit.edu/boost to download and install the Scratch Link program on your Mac or PC.
We think the best way to learn is to jump right in and learn as you play. Let’s show you how to control your BOOST or EV3 with Scratch.
Below, we are going to show you how to connect your LEGO BOOST to your computer or tablet, and guide you through some programming so you can control Vernie. Ideally, you will have Vernie fully built, but if not, our first few programs will still work for you. Please also ensure that Bluetooth is also enabled on your computer or tablet.
START SCRATCH LINK
For LEGO BOOST and your computer to be able to communicate, you first need to run the Scratch Link program that we described on the previous page.
LET’S START CODING
Open up a web browser on your computer or tablet and go to http://scratch.mit.edu. You then need to select ‘Create’ from the main menu to start the Scratch Editor. The Editor is where you create your code.
If you have a login for Scratch then do so, or you can register for free by selecting the 'Join Scratch' button. This is a great way to keep your programs saved for future use or to share with others.
Before we start programming, it is good practice to enter a name for our project so we can find it later. We have used “My first BOOST program”, but you can make up your own title.
To add the LEGO BOOST extension we need to select the blue icon in the lower left of the screen.
Choose the LEGO BOOST option, then on the next screen select the ‘Start Searching’ button. You will be asked to press the green button on the main BOOST module.
You have successfully connected when the LED on the BOOST module turns blue and the word ‘Connected’ shows on your computer screen. Go ahead and select the ‘Go to Editor’ button. You will notice a lot of green blocks shown in the blocks palette on the screen.
TIP: A small green tick at the top of those green blocks also indicates that you are connected to the LEGO BOOST. If that tick turns orange you need to click on it to re-establish the connection.
If you haven’t built Vernie just yet, you can run this simple program to test that you are connected.
Place your BOOST module in front of you as shown here, then drag-and-drop the following code block into the Script area.
Change the motor option to motor B, then click on the green block. You should see and hear the motor spin for 1 second. Try changing the setting to 5 seconds and see what happens.
Let's now go one step further with our motor test to control their direction. Drag-and-drop the code blocks that you see here in the above screenshot. Make sure you match the motor, key pressed and motor direction settings.
This code makes both the A and B motors change direction when you press the up or down key on your keyboard (You should notice that we have the motor direction go 'this way' when you press Up, and 'that way' when you press down).
The 'turn motor on' code block makes the motors run continuously until you press the Space key. By pressing the Space key you enable the 'turn motor off' code block.
VERNIE GETS DIZZY
If you have a fully built Vernie, then follow these steps to make Vernie turn on the spot. Drag-and-drop the ‘turn motor _ for _ rotations’ motion block. Match our screenshot by setting the motor to ‘A’ and rotations to 10. Press that green block to see Vernie spin around. If Vernie turned around, then congratulations. You have just programmed a real robot! Now is a good time to save your project by selecting File › Save now.
TIP: To slow down how fast Vernie turns you can use the ‘set motor speed to’ motion block, and change 100% to something lower.
VERNIE CAN SEE COLOURS
Did you know that Vernie can see colours? Let’s show you how Vernie can tell you the colours of different LEGO blocks. Grab yourself some large blocks, including a mix of red, blue, green, yellow, white and black blocks.
To start a new Scratch program, select File › New. Enter a project name “Vernie can see colours” or something similar.
Drag-and-drop the code blocks as you see in our screenshot here. Select the colour of a LEGO brick you have and type that colour into the Looks block. Repeat this for as many colours as you want to test. In our example, we just used the Red and Blue blocks.
In Vernie’s chest, you will see an LED light that is illuminated. Place a LEGO block about 10 to 15mm in front of that colour sensor. You should see Cat Sprite on your screen say what colour Vernie is seeing. Very cool, right? If your program works, remember to save it by going to File › Save now.
If you still haven’t found the time to put Vernie together you can just connect a black cable between the colour sensor to port C or D on the BOOST module.
COLOUR CHECKER WITH VOICE
We have made an exciting program to demonstrate the BOOST colour sensing feature. You can download this from the Resources section on our website, then upload to your Scratch Editor by choosing File › Load from your computer › Vernie_Colour_Detection.sb3.
This program makes the Cat Sprite change colour to match the colour of the block, and say the colour through your computer speakers using the ‘Text to Speech’ extension. It’s loads of fun!
TIP: With this colour sensor, you could possibly design your own LEGO piece sorter.
VERNIE KNOWS HIS LEFT FROM HIS RIGHT
A clever sensor within BOOST knows when it’s being tilted up, down, left or right. Let’s make a quick program to demonstrate this or you can download the file from our website.
First, add the ‘Text to Speech’ extension, the same way you added the LEGO BOOST extension earlier.
Drag-and-drop four ‘when tilted’ Hat blocks and four speak blocks onto the script area. Enter the settings as you see here in the screenshot.
Hold Vernie in front of you with its face towards you. Hold tight so Vernie doesn’t fall and smash apart on the table or floor. Gently tilt Vernie over to the left, right, towards you with its head facing down, or up so its face looks to the roof. The Scratch program should say Vernie’s position through your speakers. Nice work!
Note: This works by just using the BOOST module itself if you haven’t built Vernie.
TIP: With this tilt sensor, you could possibly make your LEGO BOOST become a remote control for a Scratch game.
Now, save the program and proceed to our exciting final program.
REMOTE CONTROLLED VERNIE
Now for some fun driving Vernie around the house or classroom using the arrow keys on your keyboard. For some extra fun, we will give Vernie the ability to shoot his shoulder mounted cannon, if you have that piece added (Refer to your LEGO BOOST instructions for this cannon add-on).
We have made the program ‘BOOST FULL Control with Cannon’ available on our website to save you time, or you can copy what we show you here onto your Script area.
TIP: You can also get the code by searching for the DIYODE account on Scratch. Simply enter "diyodemag" into the search field to see the projects that we have created here, and many more.
Once you have all of the code blocks in place, and the settings matching our code, you can press the green flag to start. You then use the arrow keys on your keyboard to drive Vernie forward, reverse, left or right.
The reason why we use the ‘repeat until’ control block for each key is to make Vernie move continuously while you are pressing the button. Once the key is ‘not’ being pressed Vernie stops moving in that direction.
To fire Vernie’s cannon (if you have it attached to Vernie), you press the Space key. This moves the motor connected to port D on the BOOST module, which rotates Verni's head enough to release the cannon. We use four motion blocks to turn the head ‘this way’ then return to the original position by moving ‘that way’.
Note: On our Vernie build, a 0.25 rotation setting was enough to trigger the cannon. Any more rotation and the black LEGO rod that holds Vernie’s head comes off. You may need to adjust the rotation setting higher or lower slightly to match your Vernie build so that the cannon fires without the LEGO rod popping off.
Congratulations! You have successfully programmed Vernie.
TIP: To disconnect from Vernie, click on the small green tick at the top of the BOOST blocks list and select ‘Disconnect’ in the pop-up screen. The LED colour will change on Vernie, and after a minute or so, Vernie will turn off automatically to save battery power.
WHERE TO FROM HERE?
Now you can have some fun driving Vernie about and shooting objects (Not at a person or animal, please!).
To make Vernie faster or slower you can change the ‘set motor speed to’ block from 25% to something higher.
Add some sound effects by adding Sounds to each key press. You will need to select the ‘Sounds’ tab, search and add the effects you like, go back to the ‘Code’ tab and insert the ‘play sound’ block under each ‘if key pressed then’ orange control block.
Create a completely different robot design and program your own actions. You can get inspiration on the LEGO website for other amazing BOOST creations: https://www.lego.com/boost/
One motor related code block we have not mentioned is the 'motor position' block.
This reports the degree that the selected motor is currently positioned at. This is useful to know if you need to move the motor this or that way, depending on its position.
You could also trigger other Scripts depending on the motor position, for example.
Programming MINDSTORMS EV3:
On the following pages, we are going to show you how to connect your LEGO MINDSTORMS to your computer or tablet, and guide you through some programming so you can control it. You will, of course, need EV3 already built and with fresh or fully charged batteries. Ensure that Bluetooth is also enabled on your computer or tablet.
ENABLE BLUETOOTH ON EV3
First, we need to power up our EV3 and enable the Bluetooth setting.
On the EV3 you need to use the arrow keys on the front to access the settings menu. Look for the word ‘Bluetooth’ on the screen. If there is a tick in the checkbox beside the word Bluetooth then we’re good to go. If the checkbox is not ticked, you need to select it and enable it within the menu. You may be prompted to set up a pin code (You can leave the default 1234) and proceed. A pop-up screen may appear on your computer or tablet to complete the pairing process. Refer to the LEGO MINDSTORMS EV3 manual if you are not sure.
START SCRATCH LINK
For LEGO MINDSTORMS EV3 and your computer to be able to communicate, you first need to run the Scratch Link program that we described earlier in this article.
LET’S START CODING
Open up a web browser on your computer or tablet and go to http://scratch.mit.edu. You then need to select ‘Create’ from the main menu to start the Scratch Editor. The Editor is where you create your code.
If you have a login for Scratch then do so. This is a great way to keep your programs saved for future use or to share with others. You will see in the screenshot that we have logged in using our diyodemag account. You can check out our account to see all the code we’ve prepared for this article.
Before we start programming, it is good practice to enter a name for our project so we can find it later. We have used “My first EV3 program”, but you can make up your own title.
To add the LEGO MINDSTORMS extension we need to select the blue icon in the lower left of the screen.
Choose the LEGO MiNDSTORMS EV3 option.
Check that your EV3 is turned on, then you can select the ‘Start Searching’ button.
When you see the Device Name listed, press the ‘Connect’ button.
The pop-up screen will show you that you have successfully connected to your EV3. You can then select the ‘Go to Editor’ button. You will notice a lot of green blocks shown in the blocks palette on the screen.
TIP: A small green tick at the top of those green blocks also indicates that you are connected to the LEGO EV3. If that tick turns orange you need to click on it to re-establish the connection.
If you haven’t built your EV3 yet, you can follow these simple instructions to test that Scratch and EV3 are talking.
Place the EV3 Brick and a motor in front of you and connect a black cable between the motor and socket B on the brick.
Drag-and-drop the above motor block onto the script area. Change the motor to B, then click on the green block to see the motor spin for 1 second.
Let’s check that we can control EV3 with our Scratch program by moving EV3’s legs.
Drag-and-drop the motor motion blocks into your Scratch script area, as shown here. Make sure you select the correct ‘this/that way’ blocks, and also change the motor setting to motors B or C.
Click on the blocks and EV3 should move forward and backward with each leg. Nice work! You can save your project by selecting ‘File’, then ‘Save now’, and move on to the next program.
TIP: If you built EV3 as per instructions, motor A is the cannon, B and C are the legs and D is not connected.
PRESS THE RED BUTTON
You may have noticed that your EV3 has a red push button near the right shoulder. Let’s show you how to trigger your Scratch program when that button is pressed.
Note: If you haven’t built EV3, wire a cable between the push button and input 1 on the Brick to test the code.
Start a new Scratch program by selecting File › New in the menu, then name the project “EV3 Button Test” or similar.
Drag-and-drop in the ‘when button pressed’ Hat block and make sure it is set to 1. You can then drag-and-drop the ‘beep note’ block.
TIP: The beep note block makes the EV3 Brick make noises. You can change the note sound by changing the number setting. A piano style keyboard will appear for you to choose a note of your liking.
Go ahead and press the red button on EV3. If EV3 makes a sound then you can move on to the next program. If not, review the steps.
EV3 SEES THE LIGHT
On EV3’s left shoulder is a light sensor that can detect the brightness of objects in front of it. This sensor could be used in a program to detect when a room is light or dark, or for enabling EV3 to follow a black line, for example.
Note: Still haven’t built EV3? Just wire the Light Sensor to input 3 on the EV3 brick to test the code.
In our example here, we will get EV3 to say “Hey, who turned out the lights” when you cover the light sensor. You will need to add the ‘Text to Speech’ extension to make this program.
TIP: If you tick the checkbox beside the ‘brightness’ block you can see the brightness setting in the top corner of the Stage. This will help you understand what brightness setting the sensor is detecting.
It appears that the ‘distance’ function in Scratch only supports the Ultrasonic Sensor (Part number 45504) and not the infrared sensor supplied in the EV3 kit.
If you are fortunate enough to have this part then a program like shown here should stop the motors when EV3 gets too close to an object. The setting could be changed up or down for the code to trigger when the object is closer or farther away.
Tip: If you tick the checkbox beside the ‘distance’ block, you can see the distance measurement in the top corner of the Stage. This will help you understand what distance the ultrasonic sensor is detecting so you know what distance setting you need for your code to take action.
TAKE EV3 FOR A SPIN
Now that you have mastered the basics, let’s make a program so we can drive EV3 around the room. We’ll also have some fun by adding in the EV3’s cannon, and provide some fun sound effects.
You can create your program by following what we describe below, or you can download the program from our website.
To upload into Scratch, select ‘File’, then ‘Load from your computer’ and select the ‘EV3 Control Cannon Effects.sb3’ file.
If you are making your program instead, then be sure to carefully match what we describe here, along with all the settings. Choosing the wrong motor, for example, will give you different results.
Before you start this program we need to add the ‘Text to Speech’ extension, then add some sound effects. Select the Sounds tab, search for and add the ‘Alert’ and 'Engine' sounds. Return to the ‘Code’ tab once these two sounds have been added.
- The ‘when flag clicked’ Hat block starts the program
- This program will have sound effects, so our ‘set volume to’ block turns the volume to 50%. Adjust this to set a volume you are comfortable with
- We found that the cannon works best when the motor runs at 50%. You can change this setting later if your cannon doesn’t fire correctly
- Our program is going to talk, so we’re going with the ‘tenor’ voice option in the ‘set voice’ block. Experiment with this later to hear different voices
- Our EV3 is going to say “Object detected” when we fire the cannon. You can change this to whatever message you like
- When we start the program we’re going to make an Engine noise. Vroom, vroom!!
Add this code to make EV3 drive right when you press the right arrow key on your keyboard. Be sure to select ‘right arrow’ in both the Hat block and the Sensing block.
You also need to make sure you select the ‘turn that way’ for motor ‘C’ in the top script and the ‘turn this way’ for motor ‘B’ in the bottom script. This makes the tracks on EV3 go in opposite directions, so EV3 turns on the spot. i.e. One track goes ‘that way’ and the other track goes ‘this way’. The ‘repeat until’ control block keeps EV3 moving until you take your finger off the key. We use the ‘not’ Operator to know when the key is not being pressed.
Add this code to make EV3 drive left when you press the left arrow key on your keyboard. Again, be sure to use the correct ‘turn this way’ and ‘turn that way’ blocks with the right motor selected.
Add this code to make EV3 drive forward when you press the Up arrow key on your keyboard. You will notice that both scripts use the ‘turn this way’ blocks because the motors need to drive forward in the same direction.
Add this code to make EV3 drive backward when you press the Down arrow key on your keyboard. You will notice that both scripts use the ‘turn that way’ blocks because the motors need to drive backward in the same direction.
OBJECT DETECTED, OPEN FIRE
This code lets you propel EV3’s red cannon balls to hit targets strategically placed around your room.
In this program, we are going to teach you about the ‘broadcast’ function. This is where the program sends a message to other scripts listening so they can take action depending on what the broadcast says. In our case, to fire the cannon.
The first script triggers the ‘Ready Aim Fire’ broadcast when we press the Space bar on the keyboard.
The second script triggers the ‘Ready Aim Fire’ broadcast when we press the red button on our EV3.
The main script triggers when it detects the ‘Ready Aim Fire’ broadcast and does the following:
- The ‘stop all sounds’ block stops the Engine sound if we pressed the Space bar straight after starting the program
- The ‘speak’ block plays the text that we assigned in the variable in the Setup script above
- We play the Alert sound and repeat this three times by using the ‘repeat’ control block
- Finally, we fire the red ball from the cannon by activating motor A for 1.5s.
Tip: You may need to adjust the seconds setting of motor A to get the cannon to fire correctly, and then to return to its original position. If the seconds setting is incorrect the cannon might fire twice. Make adjustments by just 0.1 seconds at a time to get it right. You can also adjust the speed of motor A in the Setup script.
Time to take EV3 through its paces.
Put EV3 onto a flat surface with plenty of space to drive around. Use the arrow keys to navigate around the room. When you see a target (no, not your brother or sister!) you can fire the cannon. Be warned though, the cannon is surprisingly powerful and the red cannonball might disappear under a cupboard, or similar.
Tip: You can adjust the height of EV3’s arm by turning the gear behind his arm. This may be necessary if you are trying to hit a target at a certain height.
WHERE TO FROM HERE?
Try experimenting by changing the settings in the Setup script. You can change the voice pitch, volume and what EV3 says before it fires. You can also change the Engine starting effect to something else by adding more sound effects by going to the Sounds tab.
If you had the Ultrasonic Sensor head you could get EV3 to avoid obstacles as you drive by using the distance block.
Of course, EV3 has many other configurations that you could adapt this program to. Or, use your imagination and make your own custom robot.
Perhaps in time, Scratch will update to more blocks so you can do more things. A block for EV3’s Infrared Sensor, for example. Making use of the screen on EV3 would also be very cool.
LEGO® is a trademark of the LEGO Group of companies which does not sponsor or endorse DIYODE magazine.