Scratch controlling Shrimp/Arduino

Note 01Feb133 -V0.50 Radical code review and full supportfor 2 stepper motors

Following on from my worldwide (Well North-West England anyway) success with my Scratch GPIO package, I wanted to achieve the same end result with Scratch and a Shrimp/Arduino. This would give the same end result (Scratch interfacing with LEDs,switches, sensors etc.) but at much lower cost per classroom workstation.

Whereas an RPi setup requires quite a bit of extra hardware(PSU or battery, WiFi and either Screen/Kbd/mouse or less-satisfying VNC experience) the Shrimp/Arduino set-up only requires the Shrimp or Arduino to be plugged into an existing computer. And with a complete Shrimp costing £5, then financially is streets ahead.

There are existing Scratch modifications (S4A is best known) but they are “hard-coded” modifications of Scratch itself and I wanted to use standard Scratch 1.4 and get a background program coded in Python to handle communications between Scratch and a Shrimp/Arduino. There is an existing protocol called Firmata which allows for simple commands to be issued over a serial link and I’ve used the Pyfirmata library in Python to do the heavy lifting.

At the moment, the whole project is in alpha status and this is where I’ve got so far

First video of it in action
[youtube=http://youtu.be/Vah5Jcp5i0o]

And Additional video of it running on a Win7 64bit school machine controlling a ShrimpingIt Shrimp 🙂

[youtube=http://youtu.be/-w4L5f1KgS0]

Video 3:  Scratch accepting analog input

[youtube=http://www.youtube.com/watch?v=jktJpovBI3c]

(Current version has temp dropped analog input because I’m getting a few errors – prob  need to sample it a lower rate)

V0.35 now has PWM/Motor control 🙂

[youtube=http://www.youtube.com/watch?v=84sLcL_dpZM]

V0.36 now has servo control

[youtube=http://youtu.be/oVt-rc97Xmc]

Demo of a possible programming problem for pupils

[youtube=http://www.youtube.com/watch?v=REqdjPUC6-g]

How to setup your computer to do this

You need a Windows PC (tested on an XP machine – should work on Win7 – should work on Linux with minor mods but not yet coded or tested) and a Shrimp or Arduino Uno.

There area lot of steps to go through if you’ve not installed it before so please be patient 🙂

Install Main Arduino code and get your Arduino driver up and working (or your Shrimp Driver if using one instead)

First of all get Firmata uploaded and working on your Shrimp/Arduino

Start the standard Arduino program and upload the StandardFirmata sketch from Examples -> Firmata -> StandardFirmata.

Use the Firmata test program

http://www.firmata.org/wiki/Main_Page#Firmata_Test_Program

to make sure your PC is talking to your Shrimp/Arduino OK.

Then you need to install Python 2.7 on your computer.

(No instructions for that as plenty out there on T’internet)

Then we need to install the PySerial package

This is from http://www.instructables.com/id/The-Arduino-Internet-Gizmo/step19/Installing-the-software/

Install pySerial as follows:

Download pySerial from http://pypi.python.org/pypi/pyserial – click on pyserial-2.6.tar.gz to download the library.

Download and install 7-Zip if you haven’t already got something to unpack .gz files

Run 7-Zip (Start -> All Programs -> 7-Zip -> 7-Zip File Manager).

Open the pyserial-2.6.tar.gz file with 7-Zip (File -> Open).

Double click the “dist” folder.

Single click on the “pyserial-2.6.tar” file and click the “Extract” button at the top of the window.  When asked where to put the file, specify c:Python27Libsite-packagespyserial-2.6

Exit from 7-Zip

Now that you have downloaded pySerial, install it:

Open a command window (Start -> All Programs -> Accessories -> Command Prompt) and type into the command line: cd c:Python27Libsite-packages-pyserial-2.6

Install pySerial by typing this command: c:Python27python.exe setup.py install

Now we need to install Pyfirmata as well

Currently, you’ll need to download a very slightly modified copy of PyFirmata but hopefully I can get the mod into the master source code shortly.

https://www.dropbox.com/s/yrnmn1gz9p9qftq/pyFirmata-master-sw1.zip

(Click on the Zip link button) then unzip. (as an example lets assume you unzip it to e:pyFirmata-master)

Run a cmd window and change your path to the download location

e:
cd pyFirmata-master

then add the library to your python install
c:Python27python.exe setup.py install

Download my Python Scratch_Arduino_Handler alpha script V0.46

https://www.dropbox.com/s/0gemnvdx683z8jp/050_sca.py

We can now run it (I press F5 from IDLE myself)

The program will attempt to identify a working Arduino or Shrimp programmed with StandardFirmata and use that Com Port – please let me know if it doesn’t work for you (and you can edit the code to manually set the port for your system if needed)

Launch Scratch and enable Remote Sensor Connections by
right-clicking on the () Sensor Value block, found in the sensing category and then selecting the “Enable remote sensor connections” option.

You should now be able to blink the Arduino on-board LED (or connect a LED/Resistor to your Shrimp) and run the following simple Scratch script

When Green Flag is pressed
forever
broadcast pin13on
wait 1
broadcast pin13off
wait 1

to get yourself a blinking LED

V0.35 now lets you vary the outputs of pins9,10 and 11 using PWM

1st off create a variable called motor11 then run the following Scratch script

When Green Flag is pressed
set motor11 to 0

When Spacebar pressed
repeat 99
change motor11 by 1
wait 0.1

You should see an LED on pin11 go from off to full brightness over a 6 secs interval (LED brightness is non-linear so effect most noticeable at low values)

Servos
You can control servos connected to Pins 7,8,12 and 13.
Simply create a variable called say, servo12 then run the following Scratch script

When Green Flag is pressed
set servo12 to 0

When Spacebar pressed
repeat 10
change servo12 by 10
wait 1

if you’ve connected the control wire for a servo to pin 12, then it should rotate to starting position and then on spacebar just turn 10 times

Stepper Motors
The setup supports up to two unipolar stepper motor3 (5 wire ones) using pins 6,7,89 for steppera and pins 10,11,12 and 13 for stepperb (Red common wire connects to Gnd)

When Green Flag is pressed
set stepperb to 0

When u key pressed
change stepperb by 10

When d key pressed
change stepperb by -10

This code will let you speed up and slow down a stepper connected to pins 10,11,12 and 13  (and go into reverse if stepperb is negative)

Advanced users:  the delay between each step is set to 0.005 secs.  You can adjust this by creating a Scratch variable called stepdelay and set its value to smaller than 0.005 to speed up your motor but beware that if you use too small a value, the motor will mis-step.

Good Luck 🙂

Version changes

Note 31Jan13 -V0.46 StepperB added and slow data input to 1 per 0.1 secs

Note 31Jan13 -V0.45 FIx PWM regression 🙂

Note 29Jan13 -V0.44 auto detect com port,steppers,servos etc 🙂

You may also like...

68 Responses

  1. SDM says:

    Hi Simon, the links don’t work. I can find them in the source of the page, but there not clickable in the text.

  2. geekmoore says:

    I’m trying this on OSX at the moment so that could be my problem. I’ve got the python program running without error. I have a scratch program that uses the up and down arrow to turn pin 13 on or off, it is connecting to the python script and python returns that it is setting the pins to 1 or 0 correctly. The arduino has a working and tested copy of firmata and its Rx light flashes when I run the script. BUT the LED does not turn on (tested with real LED in pin 12 as well). Any ideas?

    I’m off to find a windows machine that does not have python 3.2 installed so I can put 2.7 on it and see if thats the problem

    • cymplecy says:

      The only thing I can think of at the moment is are your running the StandardFirmata (as opposed to the other versions)sketch on the Arduino?

      Can you run pyfirmata from the a terminal and talk to your Arduino that way?

      Simon

  3. geekmoore says:

    Yes I am running the standard firmata and its talks fine to the firmata test program. I’ll try writing a simple python script to test pyfirmata, i’m installing python 2.7 on a windows machine as we speak so I can find out if the problem is OSX.

    • cymplecy says:

      Good luck – I think its the thing to bet on – like I say, if you can get a terminal up and run pyfirmata in interactive mode you could find the serial code is working in pyfirmata on a Mac.

      Simon

  4. geekmoore says:

    Sorted it, forgot I was using a modified Firmata for use over bluetooth. Solution was to set connection rate to 9600. All working over USB and Bluetooth now 🙂

  5. SDM says:

    Hi Simon, I saw your request for testers on Twitter. As soon as I’ve got all the parts for my Shrimp delivered, I’ll make one and then test your code.

  6. geekmoore says:

    Tested PWM over USB and Bluetooth and its controls the motors fine.

  7. SDM says:

    Hi Simon,

    I have a question about burning the boatloader on a blank ATMEGA328P-PU. (I also posted this on http://shrimping.it/blog/bill-of-materials/):

    Can you make a how-to to load the boatloader on a ATMEGA328P-PU with another Shrimp and Optiloader? The link under ‘using Optiloader’ (on shrimping.it) uses a Arduino UNO as ‘host’, but I don’t have one.

    I’ve ordered one preloaded ATMEGA328P-PU and one without boatloader. I understand that I have to make a Shrimp with the preloaded one, but then I’m a bit confused which wiring I should use to burn the boatloader onto the other ATMEGA328P-PU.

    I hope you can help!

  8. SDM says:

    Hi Simon, I’ve got my first Shrimp working (first it didn’t work, but that was due to a bad connections between the ATMEGA and my breadboard, changing breadboard solved a lot!).
    I also got it connected to Scratch. The only thing I’m missing in your how-to is that you have to upload the standardfirmata-sketch to the Shrimp.
    Maybe you can add it to this page?

    • cymplecy says:

      I think you just missed it – its the 2nd instruction 🙂

      • SDM says:

        Oops! You’re right. It’s late 😉

        P.S. I’ve also tested PWM, but my led isn’t fully on (not as bright as with pin7on) when it’s on 100%.
        Also I’ve noticed that the python-script constantly send a pin2on and pin2off. Is that normal?

        • cymplecy says:

          I’ll check out the PWM at my end to see if I’m sending the right values.
          The problem with inputs is that an Ardunio/Shrimp is VERY sensitive to inputs so 2,3,4 and 5 can easily pick up stray signals (more so on a Shrimp). I’m trying to set software pull-ups (which is why I needed the modified pyfirmata) but either its not working or the software pull-ups aren’t good enough to do the job.
          As long as the data doesn’t over-run the serial link then we should be OK anyway.

          Let me know if it causes a real-world problem 🙂

          Thanks for all the feedback BTW 🙂

          Simon
          (Just playing with getting a stepper motor to continously rotate as a background task! 🙂 )

  9. SDM says:

    Sorry, used servo-pin instead of PWM. That’s probably the reason why my led doesn’t get brighter.
    But now I’ve tried PWM, and it doesn’t work. Used pin9 (as motor9) and pin11 as (motor11). The python-scripts goes from “sensor value 0” to “sensor value 99” but my led doesn’t light up (not even a bit).
    Any ideas what’s wrong?

  10. SDM says:

    Hi Simon,

    I’ve noticed that pins 0-5 are very sensitive with static electricity. When I touch my Shrimp (without touching anything metal) the python-script starts updating pins 0-5 (not all, but a couple).
    I’ve changed your script a bit, so that it doesn’t use these pins.
    Can you confirm that I did it correctly?

    #PIN_NUM = array(‘i’,[2,3,4,5,6,7,8,9,10,11,12,13])#list of Arduino Uno pin nums
    #PIN_USE = array(‘i’,[0,0,0,0,2,1,1,2,2, 2, 1, 1 ])#1 indicates output , 0 indicates input
    #ANALOG_PIN_NUM = array(‘i’,[0,1,2,3,4,5])
    PIN_NUM = array(‘i’,[6,7,8,9,10,11,12,13])#list of Arduino Uno pin nums
    PIN_USE = array(‘i’,[2,1,1,2,2, 2, 1, 1 ])#1 indicates output , 0 indicates input
    ANALOG_PIN_NUM = array(‘i’,[0,1,2,3,4,5])

    • SDM says:

      Damn, just noticed that these pins are used as input. When enabling them again it does interfere with my buttonpress (on the breadboard). Any solutions?
      Can I use other pins as input?

      • SDM says:

        Just noticed that in all the cases I use a pin as input, it will constantly gets updated with 0,1,0,1,etc. Scratch can’t cope with the speed of these updates, so it doesn’t update the value of the input at all or correctly.
        When pressing the button, the updating stops and it sends a 0 to Scratch. When releasing the button, it continues sending 0,1,0,1,0,1. So it’s not usable in Scratch.

        I have the following schematic: gnd – resistor 100Ohm – button – pin4.
        Do I have to change anything?

        Are the analog inputs usable?

        P.S. Sorry, for the many replies 😉

        • cymplecy says:

          As I said, the inputs are VERY sensisitive and is not connected to +5V or 0V through a resistor, then they will just go up and down due to stray noise pickup from other parts of the Shrimp/ Arduino 🙁

          The best way to stop this at the moment is to have gnd-resistor 100 ohm (I use 330ohm myself) – button – pin 4 – 10k resistor – 5V

          e.g pull pin 4 up to 5V if switch not pushed.

          Note – at the moment I try and set pins 2 and 4 to have software enabled pull down resistors and pins 1 and 3 to have pullups so if you are going to use Pin4 for this, I’d do a broadcast pin4on first to switch Pin4 to try using software pullup.

          But you’ll still need the 10k resistor to actually pull it up as the internal software ones don’t seem good enough for the job 🙁

          (Or switch to Pin3 instead of using 4 if you don;t/can’t use the pin4on broadcast)

          To prove its a hardware issue, run the firmata test .exe file and you’ll see the values going up and down there as well.

          I did have analog working but amount of data caused serial overflows so I just disabled it.

          My intended solution is to slow the input pin (analog and digital) scanning down and just feed back the values say once every 0.1 secs.

          Currently engaged in getting stepper motors to continously turn but at a variable rate 🙂

          Simon

          PS Keep the questions and challenges coming 🙂

        • cymplecy says:

          V0.46 limits input pin updates to 1 every 0.1 sec – is that enough to slow the data down without missing switch events?

          Simon

    • cymplecy says:

      Sorry – just seen this comment 🙁
      in PIN_USE 0=input,1=digital out,2=pwm,3=servo
      So best to just leave PIN-NUM array alone and change
      PIN_USE= array(‘i’,[1,1,0,1,2,1,1,2,2, 2, 1, 1 ])
      and that will just leave pin 4 as the only input.

      As I said in other reply, the only true solution at the moment is an actual pullup resistor

      Simon

      • SDM says:

        Hi Simon,
        Thanks. I’ve got it working now.
        I’ve made a small board with 4 pullup resistors (10k) for pin 2-5.

        VCC(pin5) – 10k – pin2
        VCC(pin5) – 10k – pin3
        VCC(pin5) – 10k – pin4
        VCC(pin5) – 10k – pin5

        When connected to my Shrimp the 4 input pins are working perfectly!

  11. SDM says:

    N.B. It did influence my Scratch-script. My PWM-script didn’t light up my LED fully when it was updating pin 0-5.

  12. SDM says:

    VCC(pin5) – 10k – pin2
    VCC(pin5) – 10k – pin3
    VCC(pin5) – 10k – pin4
    VCC(pin5) – 10k – pin5

    should be

    VCC(pin7 on ATMEGA) – 10k – pin2
    VCC(pin7 on ATMEGA) – 10k – pin3
    VCC(pin7 on ATMEGA) – 10k – pin4
    VCC(pin7 on ATMEGA) – 10k – pin5

  13. SDM says:

    Is there a clean way to stop the Python-script?
    Because everytime I close the window and then start the script again, my Shrimp isn’t recognized.
    I have to reconnect the Shrimp and start the script again, then everything works fine again.

  14. anderssmith says:

    I’m trying to get it to work om my osx 10.6 machine, but I’m new to Python and I get an error about winreg….
    I guess I don’t need access to the Windows registry as I’m on a mac, but am I missing something?
    Can I just comment out the _winreg import line in the o50_sca.py script?

    thanks
    anders

  15. anderssmith says:

    got it working now. I commented out _winreg import, the automatic com_port_open and set the comm-port manually.

    This is the greatest thing since sliced bread. I can’t wait to get my kids doing some physical computing and extending their scratch games.

    Thanks

    • cymplecy says:

      Glad you got it going – I’m hoping some Mac guru will will be able to code up the auto com port (or I might simply do a config file with a default com port in it) – PS What is the name of your default CIM port and I’ll add it in so less typign for you in future releases 🙂

  16. davka003 says:

    This seems like a very good project. Just ordered a Arduino mega based robot platform ( http://robosavvy.com/store/product_info.php/manufacturers_id/35/products_id/1575 ) and think about using this software as a basis for its control. Hopefully I can contribute somewhat with 5+ years of professional python coding.

  17. SDM says:

    Hi Simon,

    I’ve tweaked your script a bit (removed the Windows autodetect and added a basic Linux-autodetect) and it now runs on Linux also (Debian).
    Just to let you know 😉

    I’ve hadn’t had time to test it thoroughly, but if you or somebody else is interested, let me know and I will send it.

    • cymplecy says:

      yes please – what I’d like to do is have just the one script that works across all 3 platforms (PC/MAC/Linux) so it’d nice to have OS detect and select the approprirate auto-com port 🙂

  18. kannan says:

    I am getting error while i installed setup.py after that nothing gotta works.please tell some suggestions.

    • cymplecy says:

      Hi Kannan
      I’m very busy as the moment working on Scratch GPIO for Raspberry Pi but I will look into it within a week 🙂
      Simon

      • kannan says:

        Thanks cymplecy, i debugged my error , it’s started the process and python communicate with arduino. i have seen all the pin number listed with input/output but at the end while it try to connect with arduino it say “There was an error while communicating” along with showed ip and port number, these error occured continuously right behind one another.

        • cymplecy says:

          Those “error” messages will go away once you have started Scratch and enabled Remote Sensor Connections 🙂 Follow ALL instructions 🙂

    • cymplecy says:

      The software is between alpha and beta stages but does work for outputs/PWM/Servos very well at the moment 🙂

      • kannan says:

        you mentioned that there was a remote sensor connection in sensing category but when i opened S4A nothing like that in sensing category.

        • cymplecy says:

          I’m not using S4A 🙂 I am using normal Scratch 🙂 You right-click the bottom block in the Sensing catagory 🙂 Google for Remote Sensor Connections Scratch

          regards

          Simon

  19. kannan says:

    Thanks once again cymplecy , as per your words i did and finally got my output but when it starts processed , getting slow down in scratch.And let me have one question ” is it possible to send a data via xbee with pc to arduino in robot.

  20. kannan says:

    1) is there any possible to send a direct data from scratch via xbee to remote xbee with arduino?
    2) can you send me a keywords like pinled13 on/off and selecting com port and all?

  21. SDM says:

    Hi Simon,

    Just saw your new version of Scratch controlling GPIO on RPi.
    Are you planning to port the new stuff to Scratch controlling Arduino/Shrimp also?

    I’m especially interested in multiple commands in one broadcast and in the bitpattern-option.

    Does the variable-with-a-dot-trick work in this version of ScA?

    • cymplecy says:

      yep – I want to get the RPI stuff out of the way and then copy the new stuff into ScA. The multiple commands in one braodcast should be working already – AFAIK its already in ScA – bitpattern might not be though 🙂 Variable with dot trick should work in any Scratch to force variable output – my code ignores the . as nonsensical value and then takes the next value as being the right one – I’m trying to get agreement to change behaviour of Scratch but I don’t think anyone at MIT is interested anymore in Scratch 1.4 🙁

      • SDM says:

        Hi Simon, just to let you know:

        Getting a sonar (HC-SR04) to work with Firmata doesn’t work. I’ve tried and after Googling I found out that it isn’t possible at all.

        Bitpattern does work already, although not entirely correctly
        Multiple broadcasts also works.

        I’m tweaking your script:
        – added OS-detection (Windows/Linux(Debian)) for auto-detecting COM-port
        – the dot-trick didn’t work correctly, it resends the last bitpattern, added an isNumeric-check so it only sends the new bitpattern after Scratch sends the dot.

        Can you provide me with some information about the analog pins: why did you comment it out?
        Maybe I can fix it also.

        • cymplecy says:

          Re sonar – never say never 🙂 We will just have to add to Firmata 🙂
          I have not been working on ScA for a few months – I’ve been busy on Scratch GPIO for Raspberry Pi.
          I think I commented out Analogue as getting too much data and swamping serial link but can’t really remember :0

          Please carry on until I’ve finished my Scratch GPIO V2 🙂

          Simon

  22. kannan says:

    how shall i enable the analog pin as like digital pin in scratch

  23. kannan says:

    hi, i apologies to interrupt again on your work time .would you please send a stuffs about arduino controlled by scrach, Because now i am focusing on robot control via scratch.if you would send me the details it could be useful for me to step up my projects.it’s very important on my side, indeed.

Leave a Reply to kannan Cancel reply

Your email address will not be published. Required fields are marked *