Creating Custom Extensions
For Scratch 2 On The Raspberry Pi
Want to learn how to create your own custom extensions for Scratch 2 on your Raspberry Pi? The latest version ( 2017-06-21) of the Raspbian Raspberry Pi Operating System includes an offline copy of the Scratch 2 editor.
In this tutorial, we will show you how to create your own custom features for Scratch 2. What we will cover:
- Installing the demo.
- How To Create Custom Scratch Blocks
- Linking The Blocks to "action" code.
OK, before heading into the details, let's talk a little bit about what this demo extension actually does.
The s2-pi Demo
This demo creates, 6 custom Scratch extension blocks, summarized as follows:
- A block that establishes communication between Scratch and a Python server.
- A block that allows you to set any GPIO pin to a high or low state.
- A block that allows you to control the output level of any GPIO pin using PWM.
- A block that will generate a tone on any GPIO pin that is connected to a piezo buzzer device.
- A block that allows you to set any GPIO pin as an output pin.
- A block that allows you get the current state of any pin that has been set as an output.
Installing The Demo
Download The Demo
After downloading s2-pi from Github, I unzipped the file to the /home/pi directory. It created a directory called s2-pi-master and the files of interest are located in the s2_pi directory.
Installing s2_pi.js Into Scratch 2
Open up the Scratch 2 editor. Then, while holding the Shift key on your keyboard, click on the File selection of the menu at the top of the Screen. Select Import Experimental Extension and you will be prompted for a URL to load the file:
Using the directory structure shown above, the URL is:
After loading the file, click on the More Blocks tab, and you should see the extension blocks.
Preparing Fo The Python Server
Before starting the server, you will need to install a Python Websocket library from this page. Follow the installation instructions on the library's home page. This will only need to be done once.
Next, start pigpio daemon, pigpiod:
Starting pigpiod needs to be done each time the Raspberry Pi is powered up or reset.
And finally, from a command window start the server:
The server has not yet been tested with Python 2.
Connecting Scratch To The Server
Click on the the Connect to s2_pi server block. The connection indicator should go from yellow to green.
Using The Blocks
After connecting a digital device to the Raspberry Pi, use this block by setting the BCM pin number and the state of the pin.
You can use this block to set an LED to a light level between full brightness and off. Select the BCM pin number and enter a value between 0 and 255 to set the level.
First set a BCM pin as an input. To read the value of the input, use the Read Digital Pin reporter block.
To generate a tone, connect a Piezo device to a BCM pin, select the frequency for the tone, and when this block is executed it will issue a tone for 1 second.