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 http://goo.gl/dANpKr -O isgh4.sh

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

sudo bash isgh4.sh

(If logged in as a different user to standard pi, then  type sudo bash isgh.sh 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

Troubleshooting

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

sudo python blink11.py

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.

About these ads

232 responses »

Comment navigation

  1. Steve says:

    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.

    Steve

    • cymplecy says:

      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 :)

      Simon

  2. peter says:

    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 127.0.0.1 und Port 42001.

    Danke.
    Gruss

    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 127.0.0.1 and port 42001.

    Thank you.
    Greeting

  3. Steve says:

    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?

    Steve

    • cymplecy says:

      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?

      Simon

      • Steve B says:

        Hi Simon,
        I’m using this board…
        http://quick2wire.com/products/quick2wire-interface-board-kit/

        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…
        https://projects.drogon.net/raspberry-pi/wiringpi/pins/

        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.

        Steve

      • Steve B says:

        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
        etc

        where…
        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

        Steve

      • Steve B says:

        Maybe this page will help…
        http://wiringpi.com/pins/

      • cymplecy says:

        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 :(

        Simon

  4. Inti Garcés says:

    Hi, I’ve tried but something was wrong. blink2.py 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?

    • cymplecy says:

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

      Simon

  5. Inti Garcés says:

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

    Reading https://www.raspberrypi.org/phpBB3/viewtopic.php?f=77&t=16183 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!
    Inti

    • cymplecy says:

      What distribution are you using? On Raspbian the default pi user should own all subfolders of Documents

      Simon

      • Inti Garcés says:

        Yes, I’m using Raspbian. You are right but pi user wasn’t the owner :(

      • cymplecy says:

        mm – I’d better download the latest see if they’ve got a bug in it – ta :)

        Simon

      • cymplecy says:

        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 :)

        Thanks

        Simon

    • Inti Garcés says:

      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 $ ./scratch_gpio2.sh&
    [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/rsc.sb
    Xlib: extension “MIT-SHM” missing on display “localhost:10.0″.
    Traceback (most recent call last):
    File “/home/pi/simplesi_scratch_handler/scratch_gpio_handler2.py”, 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/scratch_gpio_handler2.py
    Traceback (most recent call last):
    File “./simplesi_scratch_handler/scratch_gpio_handler2.py”, 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.

    • [Misleading typo] I meant to write: “the blink11 script (nor anything else I try from your tests) is NOT changing the state of any GPIO pins.”

    • 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 https://pypi.python.org/pypi/RPi.GPIO and got:

      pi@raspberrypi ~/RPi.GPIO-0.5.3a $ sudo python setup.py 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/__init__.py -> 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
      /home/pi/RPi.GPIO-0.5.3a

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

  7. Tony says:

    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
    /home/pi
    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?

    • cymplecy says:

      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 :(

      Simon

      • 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. don isenstadt says:

    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..
    -don

  10. […] is a way to allow Scratch and the Raspberry Pi to communicate, based on the work of cymplecy. He wrote a program (source code available) which allows the device and Scratch to communicate, and […]

  11. Neil Higgins says:

    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?

    • cymplecy says:

      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

      regards
      Simon

      • Neil Higgins says:

        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

      • cymplecy says:

        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
        e.g
        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 :)

        Simon

      • cymplecy says:

        But this morning – I can’t get the script I was using last night to fail!!!!

        Something very wierd going on :(

      • higginsneila says:

        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.

  12. Wyn says:

    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.

    Wyn

    • cymplecy says:

      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 :))
      simplecy@googlemail.com :)

      Simon

      • Steve says:

        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,

        Cheers

        Steve

  13. Hi,

    Your scratch code sounds very interesting. Would it be possible to make it available for all so that we can use and modify, please?

    Thanks,
    Richard

  14. Jack says:

    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.

    Thanks!
    Jack

    • cymplecy says:

      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

      Simon

      • Jack says:

        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.

        Thanks!
        Jackson

  15. Jim says:

    Hi,

    I’ve successfully installed GPIO4 and successfully tested the output commands.
    pinhigh
    pinlow
    pinpattern
    allon
    alloff

    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:
    slider
    light
    sound
    resistance-A
    resistance-B
    resistance-C
    resistance-D
    tilt
    distance
    motoracount

    How do I get access to the input pins?

    Thanks,

    • cymplecy says:

      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

      • Jack says:

        Great! Will try this out as soon as we return home from the Xmas holidays.

      • Jim says:

        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.

  16. Ray says:

    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.

    Ray

  17. 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.

    Cheers,
    Kazuhiro Abe

  18. Hi

    Where is the “original” documentation for Scratch and GPIO? I have looked but only found a different source.

  19. 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?

    • cymplecy says:

      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 :)

      Simon

      • 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.

      • cymplecy says:

        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)

        Simon

    • cymplecy says:

      BTW I have started a simple method of trying to document all he syntax but its not complete yet
      http://cymplecy.wordpress.com/2013/12/27/scratchgpio-documentation/

  20. A Bryant says:

    Thank you, came across this while trying to understand how to get a PiGlow working!

  21. Michael says:

    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
    Michael

    • cymplecy says:

      I’ll plug a stepper into mine at the weekend and check to makes sure I’ve not introduced a bug.

      You might want to just try out this http://www.raspberrypi-spy.co.uk/2012/07/stepper-motor-control-in-python/

      which uses same wiring sequence so that would double check whether its my software or a hardware issue :)

      simon

      • Michael says:

        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.

        Michael

    • cymplecy says:

      Re clipping – its just a WordPress blog – looks fine with me which bit in particular is clipped?

      Simon

      • Michael says:

        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.
        regards
        Michael

      • cymplecy says:

        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 :)

  22. Steve says:

    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

    • cymplecy says:

      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 :)

      Simon

    • Michael says:

      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.
      regards
      Michael

      • cymplecy says:

        Power one up for testing now :)

      • cymplecy says:

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

        The one connected to 11,12,13,15 seems to work ok
        e.g https://vine.co/v/MzQvVbt6KPg

        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
        forever
        broadcast pin11on
        wait 0
        broadcast pin11off
        wait0
        (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 :)

        Simon
        and

      • cymplecy says:

        Since then, I’ve found the little bug that was stopping Stepper B from working (the one on 16,18,22 and 7)

        Just to make sure we are on the same page – switch to using my development version

        http://cymplecy.wordpress.com/2013/11/26/scratchgpio-development-testing/

        Simon

  23. Michael says:

    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
    Michael

    • cymplecy says:

      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.

      Simon

  24. 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.

    Robert

    • cymplecy says:

      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
      regards
      Simon

  25. […] Scratch GPIO addition – Great website with guidance here. […]

  26. Kieron says:

    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.

    • cymplecy says:

      Unfortunately, I just run my handler by sudo python scratch…..py. 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

      Simon

  27. […] ScratchGPIO – Introduction for Beginners […]

  28. […] Scratch programming on their PCs are just getting started with Raspberry Pi. We’re using this Scratch modification together with the hardware I’m making which is based on this circuit. The main thing here is […]

  29. Dave says:

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

    I have a problem installing. After bash isgh4.sh i get… (below). Any ideas?

    isgh4.sh: line 1: –2014-04-07: command not found
    isgh4.sh: line 2: syntax error near unexpected token `(‘
    isgh4.sh: line 2: `Resolving goo.gl (goo.gl)… 74.125.228.65, 74.125.228.72, 74.125.228.67, …’

Comment navigation

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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