Scratch GPIO Development

This blog entry is for me to provide feedback on what’s happening in developing my Scratch GPIO hander set-up.

This code WILL PROBABLY NOT be compatible with the 1.x release and is intended for experimenters and helpers.

Its for both coders with suggestions and importantly users (particularly teachers/educators/parents with kids) to provide input into what the handler does and the syntax used to do it.

My development code is available on Git Hub

I’d welcome collaborators who share my vision to enable 10 year olds and younger to make things flash/beep/turn/step using a Raspberry Pi and some cheap components. This project is NEVER going to be an I2C bus controller πŸ™‚Β  (But as Sean says – never say never again!)

I’ve created a ScratchGPIO login on the Scratch Site so that we can all start to upload and share Scratch GPIO code – I want to share the password with any educator who’d can contribute examples and lessons – just contact me for it πŸ™‚

Changes made from 1.x codebase
All pins now default to inputs until addressed as outputs and then they are switched dynamically between digital, PWM or Stepper Motor mode as needed

Any pin can now be used for DC motor or variable brightnes LED using PWM as I now use the a threaded libary PyzPWM

(Although I expect to start using the PWM within RPi.GPIO now that Ben Croston has added it in πŸ™‚ )

PWM output is controlled by variables starting with “Power” e.g Set power11 to 50Β  will set pin 11 to a 50% duty cycle and effectively give an average 1.65V instead of 3.3VΒ  (MotorA/B on pins11/12 retained for simpler syntax for younger pupils)

“Power” is more generic and can be applied even when just varying a LEDS brightness (prompting for this change came from Aaron Shaw’s RGB LED MagPi article Page 26)

PinPattern usage has been removed at this time as not compatible with the concept of any pin being input or output – needs thinking about how to re-introduce.

Single Pin Ultrasonics – if you connect an Ultrasonic Module as per this diagram, then we only need one GPIO pin to trigger it and receive the returned pulse


So now you simply use it (assuming connected to pin 23)Β  use broadcast sonar23 and then just use the sensor item sonar23 to get the distance measured in cm

Stepper motors
Currently got 5 wire unipolar steppers addressed using “StepperX” broadcast to tell Scratch that we’ve connected them . “StepperA” means one connected to Pins 11,12,13 and 15, “StepperB” means one connected to Pins 16,18,22 and 7.Β  They are then controlled using normal MotorA or MotorB variables to control their speed but since they are bi-directional, you can use values of -100 to 100.

Also I have syntax for saying stepping a finite number of steps.Β  You need to broadcast a “StepperA” or “StepperB” to initialise as above but then change (not set) variables PositionA orΒ  PositionB for the numbers of steps you wish each stepper to turn ( using change and not set overcomes a bug/feature of Scratch itself)

Tasks currently in progress

Begining to document

Tasks to be done next but not yet in progress

Add back in PinPattern in some fashion to allow multiple pinout changes in one command

Make sure AllOn /Alloff can still be used

Add global Invert broadcast that inverts all high/on/1 commands to pin being set to 0V and all low/off/0 to set a pin to 3.3V (Needed if dealing with components that need to be dragged to 0V to turn them on)

Add in code to deal with H bridge DC motorsΒ  (I’d need to build a bot with one first πŸ™‚ )

Tasks just a gleam in my eye
Add in Servo control (so I can make robot arms wave around)

Plugin in modules for specific hardware (e.g Raspberry Ladder Board, PiBorg, H-Bridge Motors,BerryBoard) etc

30 thoughts on “Scratch GPIO Development

  1. I like your suggested changes and ‘servo’ would be great. The term pulse is fine but power is already used with many school controllers interfaces and would I would like to suggest it would be more appropriate. So to reduce motor speed kids will be told to reduce power. Pulsing can also mean flashing so can convey wrong meaning as LEDs are made to flash(pulse) but to control brightness it is the power that is reduced by pulsing.
    You are onto a winner with Servo control.

    • Power – I think you may be right πŸ™‚

      I did think of it a while ago but dismissed it because as I used to be an engineer and we all know its not power but average voltage πŸ™‚

      But your right, at 10 years old, we really don’t need to go into Voltage vs Power differences – lets face it – the kids are taught that the primaries colours are Red,Yellow and Blue but they still manage to become artists πŸ™‚


  2. Excellent plans. I am all for getting kids to get computers to do physical things, makes it so much more engaging for them and makes the RPi a real computer.
    Can you provide some more detail about the servo control, are you able to get software PWM working well enough to drive them? If so that will be superb!
    I’m building up a list of great value kit for use with the Raspberry Pi, so I will give you a heads up when I’ve tried them – yes some include I2C – but we can work that out another time… ;-).

    I shall be more than happy to help where I can, and fit in with how you plan to do it.

    • Servo control is not over the horizon but its on it. I need the clever people who write the Python/C libs to get it working (which might not happen as RPi has no native concept of servos) – this is maybe where I2C is actually needed πŸ™‚

  3. The MagPi article generated enough interest for me to try this, but I struggled a bit.

    I think a key issue in getting this used by educators would be providing simple, clear, step-by-step examples of each piece of functionality, i.e., blinking LED, servo movement, e.t.c, using just standard components. (Certainly not a custom board like the LEDborg in the second article).

    Overall, I think this is a very powerful concept (programs controlling things in physical world) and would love to help where I can.

    • Great – that’s what we need πŸ™‚ Just make sure that anything you do is easiliy modifieable as Scratch GPIO V2.0 is developemnt is under way (Power variable has been introduced and all pins default to inputs and any can be used as outputs are examples of changes done sos far) I’ve created a ScratchGPIO login on the Scratch site – contact me via email for password if you want to upload code examples to it πŸ™‚

  4. At digital side, the ‘Keyword’ to enable the digital pin as “pin&pinnumber”, i try to use Tsop sensor connect to analogy input, how shall i enable it, is there any keyword for that.?

  5. Nice approach to bridging out from Scratch. I’ve been looking at a way to do this for a while so this is going to be a great help. My plan is to create a bridge to MQTT so I can remove the need to run scratch on the PI (I have a Java based MQTT bridge created already). I have a couple of questions which I hope you might be able to answer (or point me in the right direction πŸ˜‰ ).

    1) Do you have details on the message payload which is passed via the Mesh socket?

    2) Have you had any experience enabling Mesh on a MacOS based version of Scratch? I’ve followed the instructions have adjusted the underlying smalltalk class to enable the share menu item but using shift + click isn’t working. I can work around this by using one of your samples and stripping out the code and leaving the shell (which looks to me to include the mesh settings) but it would be good to get this working. Also are you able to confirm that the mesh settings are embedded in the projects .sb file?

    • Id MQTT this ?I don’t undeerstand why you want to bridge out from Scratch but also remove need to run Scratch????? πŸ™‚

      The message payload is just a series of white spaced broadcast values, variable names and variable values

      I’ve no experience of MacOS at all – I know people have used my ScA code on Mac computers to control Arduinos from Scratch->Python->Firmata and that works fine.

      I know each project knows whether Remote Sensor Connections are enabled for itself so it must be held as some sort of flag in the .sb file.

      I’m a very pragmatic programmer – if it works – I’m happy πŸ™‚


      • πŸ™‚ So the reason for using MQTT is so I can allow my son to develop using Scratch on one of my Macs and have the code drive the GPIO on the PI rather than VNC in to the PI to get access to Scratch running on the actual PI. I’ve used this approach to drive the GPIO on the PI from an Android based phone (my Galaxy SII).

        Thanks for the heads up on the message payload I’ll look to know up a simple Java app and see where I get to (I’m a bit more of a Java coder than Python).

        No worries re lack of MacOS experience. I’ve tried to enable Mesh on Ubuntu as well with no joy so I think I may be missing a step. Given I have a work around and I only need to work on the loopback address I can live without getting this fixed. If I get this working then the flow will look like:

        Scratch -> Java -> MQTT -> Mosquitto -> Java -> GPIO

        Given MQTT is a Pub/Sub protocol this will allow me to flow data to and from the PI.

        Either way should be a fun project

      • I didn’t know any python 6 months ago – its like easy peasy baby Java without { and } πŸ™‚

        I’m with yoru approach – you just want to treat the RPi as an intelligent remote in/out device πŸ™‚

        That’s very similar to what I’ve started on ScA (Scratc h controlling Arduino) except I basically re-using the stuff from this project on that one to save wheel re-invention πŸ™‚

        When you’ve got something ready to demo – give me a shout as I’d be very interested in it πŸ™‚

  6. Yeah Python isn’t a major issue and I have used it but I can live with out another language to program with πŸ˜‰ Also I have some nice libraries to drive MQTT from Java which I can re-use here πŸ™‚

    I’ll certainly create a blog post if I get it all going and will drop a link in here.

    • Not had a lot of time to tinker with the Java code but managed to get some time this evening. Receiving updates and broadcasts from Scratch is working fine but the reverse is proving to be a bit more of a challenge. Broadcasts are being picked up by Scratch fine but sensor-update is failing. Did you hit any issues getting this working with Python?

      • Not at all – prob just going to be a little syntax error
        this is prob the relevent code used
        def broadcast_pin_update(self, pin_index, value):
        #sensor_name = “gpio” + str(GPIO_NUM[pin_index])
        #bcast_str = ‘sensor-update “%s” %d’ % (sensor_name, value)
        #print ‘sending: %s’ % bcast_str
        if ADDON_PRESENT[0] == 1:
        #do ladderboard stuff
        switch_array = array(‘i’,[3,4,2,1])
        #switch_lookup = array(‘i’,[24,26,19,21])
        sensor_name = “switch” + str(switch_array[pin_index-10])
        sensor_name = “pin” + str(PIN_NUM[pin_index])
        bcast_str = ‘sensor-update “%s” %d’ % (sensor_name, value)
        print ‘sending: %s’ % bcast_str

        def send_scratch_command(self, cmd):
        n = len(cmd)
        a = array(‘c’)
        a.append(chr((n >> 24) & 0xFF))
        a.append(chr((n >> 16) & 0xFF))
        a.append(chr((n >> 8) & 0xFF))
        a.append(chr(n & 0xFF))
        self.scratch_socket.send(a.tostring() + cmd)

        I never wrote this bit- its generic Python->Scratch code


  7. The strange thing is my Java Code is really just a port of this and the broadcast command works but not the sensor-update. Looks like some more digging around is required.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s