ScratchGPIO – Introduction for Beginners

This post refers to an older version of ScratchGPIO
Please use the new Version 5

This post is being left here as some books refer to the older version

Scratch Controlling the GPIO Pins on a Raspberry Pi
Part 1 of 4
(Version 4 – 20 Feb 2014)

This post is intended to make it as Simple as Pi to get up and running and make your Raspberry Pi control some lights and small motors and to respond to switches and sensors. Minimum Requirements – a Raspberry Pi with Raspbian installed (a working internet connection is very handy but not required)  a breadboard, some Light Emitting Diodes (LEDs), some resistors and some wire connectors. Total cost £5-£10. Blue italics are extra information for those who like to understand things a bit more – Pink italics are for the more advanced users and  can be completely ignored by normal users.

How to get a Raspberry Pi to control the GPIO Pins using Scratch —————————————————————
Your Raspberry Pi needs to be connected to the internet to install the software but not needed to run ScratchGPIO. Copy the text below ( left click just before the s of sudo and drag right until all the text in the line as been selected) then right-click and select copy. Open up an LX Terminal window and select Edit and the Paste that into an LX Terminal window and run it to download the installer.

sudo wget -O

Once the installer has been downloaded then just type (or copy and paste the text below as before)

sudo bash

(If logged in as a different user to standard pi, then  type sudo bash yourusername) This will install all the necessary extra software and some simple examples. (If you do not have internet on your Pi then, put your SD card into a card reader and try using your browser to right-click and save the script direct to your SD card and then put it back into you Pi and run the second instruction) Connecting Components Up ———————————————————————

EXTREME care should be taken when connecting hardware to the GPIO pins. You can cause your Pi to die by connecting the wrong things together – only do this if your confident of your ability to follow instructions correctly 🙂

AT A MINIMUM – get a breadboard and use some female-male 0.1 leads (available from lots of on-line suppliers or your local Maplin shop) Check out GPIO pin guides to make sure you know what pins are what. Wire up Pin 1 (3.3V) to (at least) a 330ohm resistor – connect that resistor to the long lead of an LED and then connect other end of LED to Pin 6 (0V). It should light up. If it doesn’t try reversing your LED. Now move the lead from Pin 1 to Pin 11. Using ScratchGPIO Run the special Scratch icon (Scratch GPIO) on your desktop. (It is actually a completely normal version of Scratch, it just runs a little Python background program as well that handles communications between Scratch and the GPIO and automatically enables Scratch’s Remote Sensor Connections(RSC)) To test out control from Scratch, click on File then Open and then click on the My Projects button and select blink11 and click on OK. Once the project opens, just click on the OK to enable Remote Sensor Connections. To run the script just click on the Green Flag.

blink11Your LED should now blink on for 1 second and off for 2 seconds – see trouble shooting if this doesn’t happen.

What more can I do with Scratch and the GPIO
As it comes, you can control six pins as outputs (Pins 11,12,13,15,16 and 18) and treat all the rest as simple inputs (22,7,3,5,24,26,19,21,23,8 and 10) (GPIO pin numbers/ordering do not follow anything that makes sense to most people so you just have to go with the seemingly random numbering arrangement)

As you can see in the blink11 script , you can simply use a broadcast message telling Pins to go on or off (Up to 3.3V and down to 0V) The valid messages are pinson along with the corresponding pin off messages. pinsoff

You can also say allonoff And you can replace the word  on with high and replace off with low if you want to talk in pure logic levels.

You can combine message together to make a single broadcast so to turn Pin11 and Pin13 on and all others off you can sayjoined oroff11on13on

Alternatively you can use the pinpattern broadcast to achieve the same result e.g:bpinpattern2This will also set just pins 11 and 13 on.

Inputs To check an input, you should go into the Sensing block and click on the word “slider” at the bottom and you’ll notice that you have pins 22,7,3,5,24,26,19,21,23,8 and 10. inputs If you connect a switch to one of these pins (through a resistor don’t forget) to OV, then you can detect when the switch is open or closed. The inputs will normally read 1 and go to 0 when they are connected (through a resistor) to ground. Click on the checkbox next to pin7 and try it out.

Using variables instead of broadcasts
For more advanced Scratchers, you can use variables instead (or as well as broadcast messages) .

For example: create a global variable called pin11 To make pin11 go on or off  use vonoff On can be replaced with high or 1 and off can be replaced with low or 0 so that you can use whatever logic scheme you’d like.

vallonoffTo set all outputs to on or off use

To use a “bit-pattern” to set/unset multiple outputs simultaneously usevpp (this will set Pin 11 , Pin 13,  Pin 16  and Pin 18 on and Pins 12 and 15  off)

vbug3Note – currently there is an unfortunate “bug” in Scratch in that it remembers variable states and only sends changes out.    Even when you press the Green Flag, it will not send the state of all the variables out, it will only send them when a variable changes. I recommend (nay insist even!) setting any gpio variables to an invalid value – say a full-stop and then to their initial state in a Green Flag start-up script.

Need more Pins as outputs?
If you need more than 6 pins to be outputs  then, for example, you can use broadcast pin7on and pin7 will change from an input to an output.

If for some reason,  you need more input pins you can use broadcast config11in to change pin 11 from an output to an input

Further documentation

Part 2 – using Motors and varying brightness of LEDs


To test if the software necessary to control the GPIO is correctly installed open a LXTerminal session and type

sudo python

If this doesn’t give an error but doesn’t make a LED on Pin 11 blink then we have real problems Houston 😦 Try connecting the lead going to Pin 11 back to Pin 1 to make sure the LED lights up then just in case you have a loose connection.

242 thoughts on “ScratchGPIO – Introduction for Beginners

  1. Hi,
    Found your pits and I have installed the software and got it talking to my gertboard to control LEDs and a motor. Struggling with the switch inputs . Think I have got the board wired up correctly and using the correct pins in scratch, the gertboard examples state I need to set a pull up resistor in GPIO for it to work. Can I do this via scratch or would it require a modification to the python interface?

    I will investigate further and make sure I have not made a mistake, planning on taking my PI and the gertboard into school Friday for a code club. They have all been getting in with the scratch examples, thought I would show them how to control some hardware.


    • Hi Steve
      I’ve not got a Gertboard myself and I think you are the first person who’s come along here with one 🙂 As default, I set 11,12,13,15,16,18,22 and 7 as outputs and all the other pins as inputs (With GPIO pull-ups enabled). If Gertboard uses any of the default output pins as inputs E.g 22 and 7, then you’d need to broadcast Config22In and broadcast Config7In (just once per session – I put them in a On Green Flag event) to get data from them.
      Outputs aren’t an issue because as soon as default input is used as an output then my prog will change it from input to output.

      I HIGHLY recommend fully testing any code ideas BEFORE facing the young Scratchers 🙂


  2. Hallo, könnt ihr hier einmal schreiben , wie überhaupt die Daten vom Scratch1.4 aufgenommen werden ? Ich versuche verzweifelt eine Netzwerkverbindung mit Sratch 14.4 aufzubauen zum PC , um überhaupt mal ein Wort nach Scratch1,4 zu senden . mit IP und Port 42001.


    Hi, you can write here again, as all the data from the Scratch1. 4 be included? I’m trying desperately to connect to a network with Sratch 14.4 to the PC, to ever send a Word to Scratch1, 4. with IP and port 42001.

    Thank you.

  3. Hi Simon,
    I think the work you have done to enable control of the Pi’s GPIO though Scratch is fantastic.
    However, I hooked up a quick2wire interface board to my RPi so that it is easier/safer for my children to use. Do you have any plans to implement WiringPi pin numbers for the broadcast/pin patterns/variables as well as/instead of the native GPIO pin numbers?


    • I’d never considered it before. I used to have support for the Broadcom GPIO numbering scheme but I abandoned it when the some of the physical pins changed from Rev 1 to Rev 2 boards but I am planning on adding that support back in as quite a few peripherals mark their outputs using that scheme but I’ve not seen anything that refers to wiring pi numbering.

      What quick2wire board are you using?


      • Hi Simon,
        I’m using this board…

        I may have made a mistake by calling them WiringPi numbers, they are in fact the GPIO numbering scheme. I was looking at this diagram when I wrote the last post…

        It’s good to hear that you are thinking of putting the GPIO labelling scheme back in – it will make life so much simpler when controlling the inputs and outputs through this extension board.


      • I’m getting myself confused here… It’s not the BCM numbering scheme I’m looking for, it’s a scheme that mimics the names of the pins.

        What I’m looking for is that ability to write something like:

        broadcast gpio0high
        broadcast gpio2high
        broadcast gpio6high

        gpio0 refers to pin11 or BCM GPIO 17
        gpio2 refers to pin13 or BCM GPIO 21 (R1 boards)/BCM GPIO 27 (R2 boards)
        gpio6 refers to pin22 or BCM GPIO 25


      • So what is it your after? 🙂
        To be able to refer to RPI GPIO pins using @drogons wiringpi numbering scheme – if so – going to be a long time before that happens – if ever (Just too much work for little gain I’m afraid)

        Refer to RPi GPIO pins using BCM numbering scheme? – will be done before Christmas 🙂

        Create addon support for that quickwire board? = possible if SKPang send me one to play with – otherwise not (got 2 other boards in the queue at the moment for adding support for already)
        Just not enough time to do eveyrthing I’m afraid 😦


  4. Hi, I’ve tried but something was wrong. work properly and made the led to blink, but nothing happens when I try with Scratch2GPIO, I haven’t any sensor pin either. Any hint?

    • Hi
      Do you have an up to date copy of Raspian?
      if you run
      sudo python ./simplesi_scratch_handler/
      do you get an error msg about GPIO?


  5. Hi Simon. running I received this error :
    “There was an error connecting to Scratch!
    I couldn’t find a Mesh session at host:, port: 42001”

    Reading I realized that pi user wasn’t the owner of “Documents/ Scratch Project directory”, My problem was solved making pi the owner of Document folder recursively.

    Thanks for your answer and your great work!

      • I’ve found the problem – if you use a clean Raspbian, then the Documents/Scratch Projects folder does not exist and my installer creates them but since installer is running sudo – they are created as being owned by root.

        The Documents/Scratch Projects folder is only created on 1st run of normal Scratch 🙂

        I’ll alter my script to make sure that is I end up creating them – they are owned by pi 🙂



    • I commented this communication to my 9 years old son and it was very instructive for him. The error, your soon answer, the solution, the use of English language to communicate(we are from Spain), a lot of fun! 🙂
      We are using a Scratch 2 GPIO in a project of a terrorific and noiser costume for Halloween 🙂
      Thanks again for your work!

  6. Hi, this may be quite basic (my Linux is rusty!) but (using MobaXterm to control my Pi) I’m getting the errors below when I try to run your script:

    pi@raspberrypi ~/simplesi_scratch_handler $ ./
    [1] 1749
    pi@raspberrypi ~/simplesi_scratch_handler $ kill: invalid option — ‘9’
    Executing: /usr/lib/squeak/4.4.7-2357/squeakvm -encoding UTF-8 -vm-display-x11 -xshm -plugins /usr/lib/scratch/plugins/:/usr/lib/squeak/4.4.7-2357/ /usr/share/scratch/Scratch.image /home/pi/Documents/Scratch Projects/
    Xlib: extension “MIT-SHM” missing on display “localhost:10.0”.
    Traceback (most recent call last):
    File “/home/pi/simplesi_scratch_handler/”, line 24, in
    import RPi.GPIO as GPIO
    ImportError: No module named RPi.GPIO

    I get the same error about RPi.GPIO if I try to run the Python script from the CLI:

    pi@raspberrypi ~ $ sudo python ./simplesi_scratch_handler/
    Traceback (most recent call last):
    File “./simplesi_scratch_handler/”, line 24, in
    import RPi.GPIO as GPIO
    ImportError: No module named RPi.GPIO

    Scratch starts apparently OK in a Xterm window, but the blink11 script (nor anything else I try from your tests) is changing the state of any GPIO pins.

    I have also tried this as you describe, using lxsession to start a desktop and then starting Scratch_GPIO from the icon, but that seems to fail in the same way.

    • One of the many things I’m not familiar with is where to find Python libraries. I did try installing the current RPi.GPIO, from and got:

      pi@raspberrypi ~/RPi.GPIO-0.5.3a $ sudo python install
      running install
      running build
      running build_py
      creating build
      creating build/lib.linux-armv6l-2.7
      creating build/lib.linux-armv6l-2.7/RPi
      copying RPi/ -> build/lib.linux-armv6l-2.7/RPi
      running build_ext
      building ‘RPi.GPIO’ extension
      creating build/temp.linux-armv6l-2.7
      creating build/temp.linux-armv6l-2.7/source
      gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c source/py_gpio.c -o build/temp.linux-armv6l-2.7/source/py_gpio.o
      source/py_gpio.c:23:20: fatal error: Python.h: No such file or directory
      compilation terminated.
      error: command ‘gcc’ failed with exit status 1
      pi@raspberrypi ~/RPi.GPIO-0.5.3a $ pwd

      Possibly I’m doing that from the wrong directory or as the wrong user?

  7. Hi Simon

    Thanks for this, a great way to get kids into programming and GPIO. I had the same problem with an older version of the GPIO that doesn’t support ‘setwarning’, but as soon as I removed the old version, following the uninstall GPIO instructions, then used apt-get install RPi.GPIO, it worked first time.

    Thanks again, Tony

  8. Thanks Simon. I tried what worked for Andrew, but it doesn’t seem as if I have an older vn installed. I get:

    pi@raspberrypi ~ $ pwd
    pi@raspberrypi ~ $ sudo apt-get remove python-rpi.gpio
    Reading package lists… Done
    Building dependency tree
    Reading state information… Done
    E: Unable to locate package python-rpi.gpio
    E: Couldn’t find any package by regex ‘python-rpi.gpio’
    pi@raspberrypi ~ $ find /usr | grep python | grep -i gpio
    pi@raspberrypi ~ $ sudo apt-get install python-rpi.gpio
    Reading package lists… Done
    Building dependency tree
    Reading state information… Done
    E: Unable to locate package python-rpi.gpio
    E: Couldn’t find any package by regex ‘python-rpi.gpio’
    pi@raspberrypi ~ $

    I have now tested my GPIO using the wiringPi gpio test CLI program; so my problem’s not hardware but just in driving the GPIO from Python (and therefore from Scratch).

    Am I merely missing Python.h (my C is rusty too!) from the correct location – as suggested by the fail of gcc when I try to install RPi.GPIO?

    • I just don’t know the details of how package management works 😦 I do know that if you download the last Raspbian distro and make a clean install then it works fine. All the problems people have is with using old versions. I think the package management system isn’t managing to update really old versions. I myself have never had this problem so I’m not much help I’m afraid 😦


      • Thanks anyway. You’ve spurred me into refreshing my Linux admin skills (after too many years of having a team of techies to do that sort of thing for me ;->). I’ve built a new Raspbian and got the hang of using apt-get properly, and I now have a LED blinking happily on pin11, controlled from Scratch, so I’m ready to play with some stepper motors!

  9. Simon,
    your instructions and code are great.. I am a complete noob to scratch but I got the samples working.. so then I wanted to make the switch work.. I set up pin 10 and used a 270ohm resistor from pin 10 through my switch to gnd… I then tested it out and when when I use the input sensor block I can see the value go from 1 to 0 when I press the switch .. the problem is setting up the test in scratch.. how is this accomplished?? I would like the “reporter” to fit in a when hat block.. so
    if I press the switch and the value goes from 1 to 0 the program takes off .. but this does not seem to work?? Any examples or other doc would be greatly appreciated..

  10. This is fantastic!! I have been wanting to demonstrate to my daughter how real computers control real-world stuff, and this is just the ticket for her to see for herself. Congratulations and thanks so much! One comment, one query. Comment (by no means a criticism): I set up two LEDs flashed by two sprites, one at 1 second period and the other at 2 second period. They do not stay synchronised at all. I guess that’s down to Scratch’s execution model. Query: Am I right in understanding that Scratch 2 will be entirely web-based and therefore incapable of this?

    • Can you email me your script and see if I can improve things simplecy at google mail dot com
      There is a beta version of an off-lineversion of Scratch2 for PCs (and since Flash based – it won’t work on an RPi)
      I have got a method of controlling the ports from a desktop/laptop PC (look for SID in my other posts).
      its possible to get this working with Scratch 2 (not done it yet) so that would be the way to do it


      • Err … It’s not clear how to send you the .sb file via the blog. Anyway it’s exceedingly simple – I just have one sprite pushing a pin high and low with one second waits, and another sprite pushing another pin high and low with half-second waits, both in infinite loops. I’m using pins 18 and 22 to drive LEDs on a Gertboard (not that that should matter). There’s a very obvious roll in the phase between the two LEDs. Cheers, Neil

      • Neil – two things – I thought I’d answered this comment a while ago but now can’t find it so sorry for that !

        basically – it said – its down to Scratch not keeping time propery

        2nd’y – I think you’ve discovered an actual Scratch bug (which is good because hopefully we can fix it 🙂

        I was playing with trying to make a clock using the PiRingo (12 leds in a circle) and I found wired things happening (I was trying to keep one led steady to inidcate hour and the minute led was flashing)

        To cut a long story short – I had 2 wait’s executing at same time and things went wrong – when I replaced one of waits with using the timer
        set starttime to time
        wait until (timer – starttime) > 1
        (this replaces a wait 1 block)
        then the problem disappeared

        When I was making adjustments later on – I add in a another wait block and things went wrong again

        Anyway – going to double check using a different script but thought I’d better write this down now 🙂


      • You have been busy since I last looked! A script that won’t reliably fail could imply that session history has come into play during your previous session – environment variables, global variables, etc.. If your session did not start with a clean slate, perhaps something was carried over from the previous script (?) When I get a chance I’ll try the same thing in Scratch (non-GPIO) and see if I observe the same timing irregularity.

  11. Hi Simon,

    Thanks for a fabulous resource.

    I have modified the code a little so that I can drive a Maplin robot arm from Scratch
    This is using the python USB bindings – so not GPIO – But I will send you the modified script if you would like.

    Right now it is a bit of an ugly hack, but if you are interested in including it I will tidy it up before sending.


    • Excellent – I’ve got one of those arms but never got round to getting it working with Scratch. I was planning on building an direct interface to the motors and doing it that way but if you’ve done it via USB then that saves a lot of effort and expense 🙂

      Could I have a copy to try out please (I completely not worried about state of code – as you can tell from my own efforts :))


      • Hi,

        I runa code club and have started taking my own PI in and getting the students controlling LEDs via scratch GPIO. I have noticed the post about the USB modification to control a Maplins robot arm which I have. Is this code available? The club has just received 3 PIs from google so next term I was thinking of using one to control the arm and the other two LEDs etc via a breadboard.

        If th code needs further work, testing etc I have for the time to assist,



  12. Hi,

    My daughter has been using your GPIO2 in her school project and got a number of sensor inputs working! Thanks to your code! She’s excited to learned you now have GPIO4 with output pins & promptly installed it on her raspberry pi. However, when she checks the ‘slider’ sensor value, the menu lists only ‘motoracount’ rather than listing all the pins … not even the input pins are showing & the program with sensors that worked on GPIO2 doesn’t work with GPIO4. Any idea what problems she might be running into? My daughter tells me she saw similar thing happened w/ GPIO2, but very intermittently & is solved by re-booting her raspberry pi … reboot does not help however with GPIO4. Any help to isolate issue is very much appreciated.


    • It a feature so it doesn’t clutter up the sensor list with inputs that don’t do anything but I may have gone 2 far 🙂
      It also waits to see if you have any addon board in use so it doesn’t report anything until intitially.
      A workaround is to simple make Green flag broadcast AllOff and then pins 22 and 7 will appear.

      Obviulsy I’ll have to have a bit of a rethink since its people like your daughter that this is aimed at 🙂

      Can you email me a script that doesn’t work please (or a pic of a screen with it showing should do)

      simplecy at google mail dot com


      • Sorry for some reason i did not get email notification of your response. Thanks for the quick reply.

        My daughter left her raspberry pi at school over the weekend & she will send you the script directly when she returns to school Monday.


  13. Hi,

    I’ve successfully installed GPIO4 and successfully tested the output commands.

    Now I’m trying to read inputs. However when I click on slider in the sensor area I do no see any pins listed. Instead I see the following selections:

    How do I get access to the input pins?


    • You’ve got an older version and I’ve just released the latest version today which fixes that bug 🙂 Would you mind just re-downloading and re-installing it and then use the ScratchGPIO4 desktop icon – not the ScratchGPIO4Plus icon. Then you should get the pin sensor values


      • Simon,

        I just downloaded and the pins are available. I’ll give it a test and let you know if I discover any issues. Thanks for the quick response and a great application.

  14. Hi unable to download scratch gpio software,
    I am getting ” no such file or directory” message after entering the “sudo wget ……..” Command . When I put the URL into a browser Google gives 404 page not found error

    Any ideas.


  15. Hi, Simon
    I hope you remember me. We discussed at the physical computing forum of Scratch site about my mod for Raspberry Pi GPIO.
    I am writing a book for kids that focuses Raspberry Pi and Scratch with my friends now.
    Of course this book covers your Scratch GPIO! Thank you for your great work.
    I found some important changes in the recent version, 4.1.09.
    One is some input pins, e.g. pin22, are pull down now. These were pull up in version 4.
    Another is usable input pins are always appear in sensor menu. These were appended dynamically in version 4.
    I am little bit confusing about this specification changes. I understand evolution is very important. However I would like to know stable fixed specification.
    Thank you for your help.

    Kazuhiro Abe

  16. I mean where it tells you about “Broadcast pin12high”, “Set pin11 =100” etc. It’s where the GPIO library meets Scratch. Is there documentation for that – or is that all your invention?

    • The original code base was from Thomas Preston’s work at Manchester University for controlling the PiFace.
      I don’t remember there being much documentation at that time (18 months ago) and it has pretty much changed out of all recognition since then.

      I “invented” much of the broadcast syntax (well me and a lot of feed back from fellow enthusiasts on twitter) and I decided on variable values going from 0 -100 and using MotorA and MotorB mapping to pins 11 and 12.

      I want it to be as simple as possible for 8-11 year olds (and their teachers) to use and understand.

      I work as a primary school technician and have also been helping/teaching Scratch for about 7 years so I think I know the mindset of the teachers and pupils in primaries 🙂

      If you have any ideas or suggestions I’m very keen to hear them 🙂


      • I’ll let you know. Just started working with them in schools. I’m impressed by the ability to control motors and read sensors. I’ve been using Scratch for Arduino which has similar functions. All very exciting.

      • Which Scratch for Ardunio have you played with

        There’s S4a which is an actual mod of Scratch so the blocks are hard coded into it.
        Also Ardublocks which is a very good for transition tool as it generates actual Arduino standalone code
        And theres my ScA of course (2nd class compared to the above but I’m in the middle of bringing it up to ScratchGPIO level)


  17. Hi Simon
    Congratulations and thank you for your great work on this. I have been working my way through it but I am having mixed success. I have got as far as variable speed motor control using a 2803 chip and an external power supply but I am getting nowhere with driving a stepper motor. I have some of the 28BY motors you mention and I wired one of them up as in your diagram. I set up a simple script to broadcast StepperA and then set MotorA first to 50 for 5 seconds, pause for 1 second and -50 for 5 seconds. The motor runs ok but it goes the same direction each time instead of reversing.
    I am using pins 11,12,13,15 on a rev2 board with 512MB, made in China.
    I hope you can help.
    As an aside, your beginners page from which I am sending this has a problem in that the instructions are clipped on the right hand side. I have tried both Chrome and Firefox so it shouldn’t just be a browser artefact.
    best regards

      • Hi Simon
        Thank you for your patience and help. I used the python demo program to get more familiar with what is going on and I found that I had swapped the connections to pi pins 11 & 12. I now have the motor turning happily from python.

        I will now try scratchgpio again with the correct wiring.


      • Hi Simon
        Thanks for the instant reply! Now that I look again the problem is that everything from the first instruction on how to install is in a window which doesn’t wrap but which I see can be scrolled. I was afraid I might have missed something but I see now how to access the whole lot.
        I’ll check out the reference you gave for the stepper, I am only too aware of how easy it is to make an error in connections and not be able to see it later.

      • Just a seasy for me to introduce code reversions as well 🙂
        I’m just away till Sunday so won’t be able to look at it until then – just prompt me on Sunday evening 🙂

  18. Hi Simon,

    I have trouble reading a switch, I thought the internal resistors for the inputs we pulled high, so I connected pin 24 through a 1K resistor and the switch to ground. This is based on response to an earlier question.

    The input never changed state so I connected the other end of the switch to pin 1, 3.3 volts and it now works reliably. This makes me think the internal resistors on the inputs are set to pulled low, is that correct.

    I have been using scratch gpio in school as part of my code club, at the moment we are simulating traffic lights, I want to use the switch input for the “singing jelly baby” project.

    Keep up the good work

    Steve G

    • Cuurent stable release pulls-low. This was done as the default state of high is considered not to be “right” as normally attached boards expect low signals as initial condidtion.

      So I threq the baby out wit hthe bath water! 🙂

      I wil be- re-instating default pull-high on all pins excpet 11,12,13,15,16 and 18 which will be set as outputs in V5 wit h the pull-down settings only enabled when the +Plus version is launched – they should keep it simple for beginners but satisfy the more advanced user.

      I can’t change V4 because someone has written a book and uses the pull-down convention so I’ll need to create a new link etc !

      The life of an open-source developer is not smooth 🙂


    • Hi Simon
      (You said to remind you on Sunday)
      I can drive a stepper motor from python no problem so the connections are finally ok. I am still having no luck from scratch though. I have looked through the handler program and it seems to be using the same pins for stepperA although I can’t follow most of it.
      I have an led in parallel with the 2803 output from pin11 in the pi and it flickers while I am using python but stays off with scratch.
      I did an apt-get update and a rpi-update for other reasons recently but I reinstalled your scratchgpio4 after that just in case.
      Is there anything else I can try or have you had a chance to make sure it still works with a stepper motor? If you had time to post a scratch program that works showing where steppera gets broadcast and showing the speed and position variables in use it would be great.

      • Ok my stepper (well one of them!) is working

        The one connected to 11,12,13,15 seems to work ok

        So basically,
        on Green Flag
        broadcast stepper
        set MotorA to 0

        on Spacebar
        set MotorA to 100

        and my motor turns
        I also knocked up this loop
        broadcast pin11on
        wait 0
        broadcast pin11off
        (and then repeat for pins 12,13 and 15)

        This should make the stepper (and you leds) turn very slowly

        If you stick a LED on pin 11 and do broadcast pin11on – does it come on?

        I’m checking what is wrong with my MotorB stepper but that shouldn’t affect your situation.
        Try these steps and get back to me please 🙂


  19. Hi Simon
    Success! The problem was in the original greenflag broadcast. I had “StepperA” which I think is what is in your instructions so I tried changing to “stepper” as in your example and all is working perfectly now. Thank you very much for your help on this, giving your time like this is much appreciated.
    You may be amused to know that the external power supply I use to drive the motors is in fact a mains adaptor/charger from a Commodore calculator I bought around 1974! Its last job was to power an electric motor built from a kit bought in the Deutsches Museum in Munich – said to be the best science museum in the world.
    regards and thanks again

    • Sorry about that!
      I’ve corrected the docs as well 🙂
      If you need to use 2 motors – you’ll have to use the dev version until I merge the fix into the stable version.


  20. Simon,
    Thanks for your excellent work.
    I’ve now realised that I needed to upgrade to GPIO version 4 for the revised / extended instruction set and have just done so.

    I’m using the same SR-04 Ultrasonic sensor as in your Introduction page 4, however I’m using two different ports rather than the one as you have. This works fine with a Python program but I cannot get the Scratch version to work.

    You have ‘Sonarnn’ with nn as 23 the pin number and ‘ultrann’ in your broadcast instructions but the difference between these two instructions is not clear. I can edit the pin selection in the Broadcast instruction but not the Sensor instruction and, of course, I need to have two different pin numbers rather than the same one as you have.

    Any advice greatly appreciated.


    • ScratchGPIO deosn’t handle using one pin for pinging and listening on another pin. I took the desicion to use the 1 pin approach because you normally need to add some resistors anyway so you may as well configure it for 1 pin use and it makes the programming side of things easier and only uses 1 physical pin. But I could be persuaded to bring it back if there was a good reason.
      The difference between Sonar and Ultra is that Sonar cam first and you broadcast Sonar8 and 1 sec later – the sensor value sonar8 will be updated with the distanace found.
      Buts lots of times, the Scratcher just wants to be checking the distance on a continuous basis so I introduced Ultra8 (8 can be replaced by any pin number)- you just need to broadcast Ultra8 once and sensor value Ultra8 will be updated once a second with the distance value without the need to do any more broadcasts

  21. Hi Simon. Just wondering if you can answer a puzzle for me. I use RPi.GPIO in python scripts but always need to run IDLE as root on the Pi before the scripts will run. Ive used your scratch handler quite a bit, thank you, to allow my students to write scratch programs that access the GPIO header but ive noticed they’ve never needed root privileges to do this. Ive had a look at your scratch handler and it also uses RPi.GPIO. I was just wondering how that is. Did you find a way to use RPi.GPIO without root access ? Could you help me do the same ? Its a long story but I cant give IDLE root access anymore and its hampering my students progress. Thanks for any help you might be able to give.

    • Unfortunately, I just run my handler by sudo python scratch… I think the best way to try and find a solution would be to ask on the RPi forum as I’m no Linux privileges expert


  22. HI – Great to have GPIO from Scratch – Thanks for working this out!

    I have a problem installing. After bash i get… (below). Any ideas? line 1: –2014-04-07: command not found line 2: syntax error near unexpected token `(‘ line 2: `Resolving (…,,, …’

  23. Hi – firstly thanks for putting this together – very useful.
    I am after a bit of advice. I am new to RPis and approach it from a non programming background bar some php/sql work. However I want to show how Scratch can do most things kids would want to do (and adults)
    I have successfully connected a DS18B20 thermometer which I can read from either the terminal screen or from a small Python script updating the file. But how do I get this result into Scratch??? I’ve looked and looked and looked!!
    I think Broadcast holds the answer but not sure but how I get a result broadcast from the Python file, I have no idea and also no idea how Scratch would execute that file.
    Maybe there is a much easier way!!
    It’s the first bit of a homemade hot water solar panel system I am building. The rest will be controlling pumps and actuation valves.
    Thanks in advance

  24. Hi. Nice job packaging this. It really is something that Scratch should have built in. It looks like it is when it’s installed too. Nice!

    I’m trying to get a PCF8591 to work. I’ve wired it on in the manner of and I can properly run the Python code he has on that page just below the schematic. I fiddle with the voltage divider pot and see values from 0 to 255. When I go into Scratch, I see ‘adc1’ through ‘adc4’ as sensor choices, so that tells me that the chip is communicating. ALso good. If I write a little Scratch program that simply reads the value and displays it or uses it to set the rotation of the sprite, I only get one reading and that value just comes in over and over. So if I set the pot midrange, I’ll get 128 as the only reading. I can then exit out and restart with the pot in a different spot and I’ll get a different reading that doesn’t change.

    Is there something obvious I’m missing? Thanks!


    • Sounds like handler giving one reading and then failing. I’m away till tomorrow so can’t check till then. If you just tick the sensof check box next to the ADC your using you can see the display updating normally. I’m assuming it doesn’t with you but can you check anyway please

    • I just powered up my ADC board from @4tronik and its working fine for me sorry. I’ve also got a robot prototype with one of the chips built into it and both devices return updated values several time a second.

      Just in case its something else – try rebooting and then going into LX terminal – cd scratchgpio5 sudo python and lets see if the handler is crashing out with some error


      • Simon-

        Without knowing what the difference between that board and how an 8591 is simply wired in via I2C, I’m not sure I know how to move forward with this. I tried running the code in a window as you suggested:

        pi@raspberrypi ~ $ cd scratchgpio5/ pi@raspberrypi ~/scratchgpio5 $ sudo python PWM/Servo imported OK ADC/DAC imported OK Minecraft imported OK Board Revision 2 Debug enabled 2 PiGlow init i2cbus: 1 self.bus: 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: — — — — — — — — — — — — — 10: — — — — — — — — — — — — — — — — 20: — — — — — — — — — — — — — — — — 30: — — — — — — — — — — — — — — — — 40: — — — — — — — — — — — — — — — — 50: — — — — — — — — — — — — — — — — 60: — — — — — — — — — — — — — — — — 70: — — — — — — — — No PiGlow Detected No Compass Detected Error accessing device at address 0x40 No PWM/Servo Board PCA9685 detected init PCF8591 128 PCF8591 init completed ADC/DAC PCF8591P Detected No AdaMatrix Detected No PiMatrix Detected pi camera init user pi complete PATH: /home/pi/scratchgpio5 Starting to connect… Trying There was an error connecting to Scratch! I couldn’t find a Mesh session at host:, port: 42001 Trying There was an error connecting to Scratch! I couldn’t find a Mesh session at host:, port: 42001 Trying There was an error connecting to Scratch! I couldn’t find a Mesh session at host:, port: 42001 pi@raspberrypi ~/scratchgpio5 $ sudo python PWM/Servo imported OK ADC/DAC imported OK Minecraft imported OK Board Revision 2 Debug enabled 2 PiGlow init i2cbus: 1 self.bus: 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: — — — — — — — — — — — — — 10: — — — — — — — — — — — — — — — — 20: — — — — — — — — — — — — — — — — 30: — — — — — — — — — — — — — — — — 40: — — — — — — — — — — — — — — — — 50: — — — — — — — — — — — — — — — — 60: — — — — — — — — — — — — — — — — 70: — — — — — — — — No PiGlow Detected No Compass Detected Error accessing device at address 0x40 No PWM/Servo Board PCA9685 detected init PCF8591 128 PCF8591 init completed ADC/DAC PCF8591P Detected No AdaMatrix Detected No PiMatrix Detected pi camera init user pi complete PATH: /home/pi/scratchgpio5 Starting to connect… Trying Connected! Sender Init Running…. DEBUG:root:Final change sent value for pin 3 is 0 DEBUG:root:Final change sent value for pin 5 is 0 DEBUG:root:Final change sent value for pin 7 is 0 DEBUG:root:Final change sent value for pin 8 is 0 DEBUG:root:Final change sent value for pin 10 is 0 DEBUG:root:Final change sent value for pin 11 is 0 DEBUG:root:Final change sent value for pin 12 is 0 DEBUG:root:Final change sent value for pin 13 is 0 DEBUG:root:Final change sent value for pin 15 is 0 DEBUG:root:Final change sent value for pin 16 is 0 DEBUG:root:Final change sent value for pin 18 is 0 DEBUG:root:Final change sent value for pin 19 is 0 DEBUG:root:Final change sent value for pin 21 is 0 DEBUG:root:Final change sent value for pin 22 is 0 DEBUG:root:Final change sent value for pin 23 is 0 DEBUG:root:Final change sent value for pin 24 is 0 DEBUG:root:Final change sent value for pin 26 is 0 DEBUG:root:datalen: 0 DEBUG:root:RAW: cycle_trace has changed to disconnected Scratch disconnected cleanup threads started Sender Stop Set Threads told to stop Waiting for join on main threads to complete Stopping 3 Stopping 5 Stopping 7 Stopping 8 Stopping 10 Stopping 11 Stopping 12 Stopping 13 Stopping 15 Stopping 16 Stopping 18 Stopping 19 Stopping 21 Stopping 22 Stopping 23 Stopping 24 Stopping 26 Stopping Matrix cleanup threads finished Thread cleanup done after disconnect resetting pin mode reset pin 3 reset pin 5 reset pin 7 reset pin 8 reset pin 10 reset pin 11 reset pin 12 reset pin 13 reset pin 15 reset pin 16 reset pin 18 reset pin 19 reset pin 21 reset pin 22 reset pin 23 reset pin 24 reset pin 26 Pin Reset Done Starting to connect… Trying Connected! Sender Init Running…. DEBUG:root:Final change sent value for pin 3 is 0 DEBUG:root:Final change sent value for pin 5 is 0 DEBUG:root:Final change sent value for pin 7 is 0 DEBUG:root:Final change sent value for pin 8 is 0 DEBUG:root:Final change sent value for pin 10 is 0 DEBUG:root:Final change sent value for pin 11 is 0 DEBUG:root:Final change sent value for pin 12 is 0 DEBUG:root:Final change sent value for pin 13 is 0 DEBUG:root:Final change sent value for pin 15 is 0 DEBUG:root:Final change sent value for pin 16 is 0 DEBUG:root:datalen: 62 DEBUG:root:RAW: :sensor-update “adc1” 192 “adc2” 192 “adc3” 192 “adc4” 192 DEBUG:root:dataList: [‘sensor-update “adc1” 192 “adc2” 192 “adc3” 192 “adc4” 192’] DEBUG:root:Final change sent value for pin 18 is 0

      • Its a mystery – all looks like it should work – no errors and you say it works with python code???? I’ve ordered a a PCF8591 chip and I’ll wire it up like that article and see what happens at my end then – we’ll get to the bottom of this!


      • Well, my chip arrived and I wired it up as per that blog and it works fine for me 😦 I’m at a loss to understand how it works OK with you using that Python code but not with my code 😦

  25. […] the Arduino only requires a few lines of code for this, the Raspberry Pi requires that you firstly download a library to control the GPIO pins (outputs/inputs), then choose which language you want to program with or use a visual language like […]

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 )

Connecting to %s