Processing 2.1 + Oracle Java + Raspberry Pi + Serial + Arduino = ☺

Hey! This is very old and there’s an officially supported version out now coming out very soon.

Update for Raspberry Pi 2/Processing 2.2.1/Processing 3.0.5: Raspbian now ships with Java 8, and Processing only likes Java 7. oracle-java7-jdk is still in the repos, so install that, and follow the instructions below. It’s a bit flakey, but when it runs, runs quite fast on the Raspberry Pi 2. You might have more luck running Processing.js or p5.js in the browser.

With Sun Oracle hardfloat Java now available, Processing now runs at a decent clip on the Raspberry Pi. My old instructions are now very obsolete. Here are current, tested instructions for installing it under Raspbian.

[This is a particular solution to installing a Serial/Firmata-enabled Processing 2.1 distribution on a Raspberry Pi. Processing still has issues with other aspects of visual programming (particularly video) that I’m not addressing here.]

A lot of software is installed here, and much of it depends on previous steps. Don’t jump in mid-way and expect it to work.

Update the system

Always a good plan if you’re doing major upgrades:

sudo apt-get update
sudo apt-get dist-upgrade

Install Sun Oracle Java

sudo apt-get install oracle-java7-jdk

Check if the right version is installed as default: java -version should give

java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) Client VM (build 24.0-b56, mixed mode)

If you get anything else, you need to make Sun Oracle’s version the default:

sudo update-alternatives --config java

Download & Install Processing

Go to Download \ Processing.org and get the Linux 32-bit version.  It’s big; about 100 MB. I’m going to install it in my home directory, so the base path will be ~/processing-2.1. Extract it:

tar xvzf processing-2.1-linux32.tgz

Now you have to remove the included x86 Java runtime, and replace it with the Raspberry Pi’s armhf one:

rm -rf ~/processing-2.1/java 
ln -s /usr/lib/jvm/jdk-7-oracle-armhf ~/processing-2.1/java

You should now have a Processing installation that will run, but there’s some more we need to get serial and Arduino support.

Install the  java Simple Serial connector

Download jSSC-2.6.0-Release.zip and extract it:

unzip jSSC-2.6.0-Release.zip

Now overwrite the jssc.jar that ships with Processing with the one you just downloaded:

mv jSSC-2.6.0-Release/jssc.jar ~/processing-2.1/modes/java/libraries/serial/library/

(You can remove the jSSC folder now: rm -r jSSC-2.6.0-Release)

Test Processing’s serial support

You’re almost there! Fire up Processing:

~/processing-2.1/processing

and try Perhaps the World’s Most Boring Processing Sketchâ„¢:

// Example by Tom Igoe

import processing.serial.*;

// The serial port
Serial myPort;

// List all the available serial ports
println(Serial.list());

Screenshot from 2014-01-07 20:08:32When this runs (it’s a little slow), you should get a single line of output, which should start /dev/tty___:

/dev/ttyACM0

(I have an Arduino Leonardo attached, which usually appears as an ACM device.)

Installing Arduino/Firmata support

(I’m not going to go into uploading Firmata onto your Arduino here. All I can recommend is that you use the newest version at firmata/arduino, rather than the old code bundled with your Arduino distribution.)

Exit Processing, and download processing-arduino.zip from firmata/processing. Extract it into your Processing sketchbook:

unzip processing-arduino.zip -d ~/sketchbook/libraries/

For tedious reasons, you also have to rename one of the files:

mv  ~/sketchbook/libraries/arduino/library/Arduino.jar  ~/sketchbook/libraries/arduino/library/arduino.jar

Start up Processing again, and  save Most Probably the World’s Second Least Interesting Processing Programâ„¢:

import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13;

void setup()
{
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(ledPin, Arduino.OUTPUT);
}

void draw()
{
  arduino.digitalWrite(ledPin, Arduino.HIGH);
  delay(1000);
  arduino.digitalWrite(ledPin, Arduino.LOW);
  delay(1000);
}

Screenshot from 2014-01-07 21:13:54
What this sketch does is emulate the µC’s “Hello World” program, Blink. It flashes the board’s LED once per second. Boring? Yes. But if it worked, you have a working Processing 2.1 installation on your Raspberry Pi. Go forth and make more interesting things.
(Props to bitcraftlab/wolfing for the basic outline for installing Processing, and for samaygoenka for the prodding needed to update and test the Processing installation process. If you’re still stuck, the Processing 2.0 Forum and the Raspberry Pi Forum are good places to ask.)

python + Arduino + Tk: Toggling an LED

Whoa! This is so old I don’t even know where to start!

  • It’s using Python 2, so if it works at all it probably won’t for much longer, and Tkinter is something completely different under Python 3
    (grrreat planning there, Python guys …)
  • pyfirmata is likely ancient history too.

Phil sent me a note last week asking how to turn an LED on or off using Python talking through Firmata to an Arduino. This was harder than it looked.

It turns out the hard part is getting the value from the Tkinter Checkbutton itself. It seems that some widgets don’t return values directly, so you must read the widget’s value with a get() method. This appears to work:

#!/usr/bin/python
# turn an LED on/off with a Tk Checkbutton - scruss 2012/11/13
# Connection:
# - small LED connected from D3, through a resistor, to GND

import pyfirmata
from Tkinter import *

# Create a new board, specifying serial port
# board = pyfirmata.Arduino('/dev/ttyACM0') # Raspberry Pi
board = pyfirmata.Arduino('/dev/tty.usbmodem411') # Mac

root = Tk()
var = BooleanVar()

# set up pins
pin3 = board.get_pin('d:3:o') # D3 On/Off Output (LED)

def set_led():  # set LED on/off
    ledval = var.get()
    print "Toggled", ledval
    pin3.write(ledval)

# now set up GUI
b = Checkbutton(root, text = "LED", command = set_led,
                variable = var)
b.pack(anchor = CENTER)

root.mainloop()

This is explained quite well here: Tkinter Checkbutton doesn’t change my variable – Stack Overflow. I also learnt a couple of things about my previous programs:

  • You don’t really need to set up an Iterator unless you’re reading analogue inputs
  • My “clever” cleanup-on-exit code actually made the script hang on Mac OS.

Servo Control from pyfirmata + arduino

Hey! This article is really old! So old, in fact, that I clearly thought that saying (ahem) “w00t w00t” was a good idea. Information here may be misleading and possibly wrong. You probably want to be using a newer client library and you definitely want to use an Arduino IDE ≥ 1.6 and not the ancient one that comes with Raspbian.

pyFirmata‘s documentation is, to be charitable, sparse. After writing Raspberry Pi, Python & Arduino *and* a GUI (which should be making an appearance in The MagPi soon, w00t w00t yeet!), I looked at pyFirmata again to see what it could do. That pretty much meant digging through the source.

Firmata can drive hobby servos, and if you’re not driving too many, you can run them straight from the Arduino with no additional power. I used a standard cheapo-but-decent Futaba S3003, which gives you about 180° of motion. The particular one I tried started to make little growly noises past 175°, so in the example below, that’s hardcoded as the limit.

#!/usr/bin/python
# -*- coding: utf-8 -*-
# move a servo from a Tk slider - scruss 2012-10-28

import pyfirmata
from Tkinter import *

# don't forget to change the serial port to suit
board = pyfirmata.Arduino('/dev/tty.usbmodem26271')

# start an iterator thread so
# serial buffer doesn't overflow
iter8 = pyfirmata.util.Iterator(board)
iter8.start()

# set up pin D9 as Servo Output
pin9 = board.get_pin('d:9:s')

def move_servo(a):
    pin9.write(a)

# set up GUI
root = Tk()

# draw a nice big slider for servo position
scale = Scale(root,
    command = move_servo,
    to = 175,
    orient = HORIZONTAL,
    length = 400,
    label = 'Angle')
scale.pack(anchor = CENTER)

# run Tk event loop
root.mainloop()

The code above makes a slider (oh, okay, a Tkinter Scale widget) that moves the servo connected to Arduino pin D9 through its whole range. To set the servo position, you just need to write the angle value to the pin.

I haven’t tried this with the Raspberry Pi yet. It wouldn’t surprise me if it needed external power to drive the Arduino and the servo. This might be a good excuse to use my Omega-328U board — it’s Arduino code compatible, runs from an external power supply, and has Signal-Voltage-Ground (SVG) connectors that the servo cable would just plug straight into.

Raspberry Pi, Python & Arduino

Hey! This article is really old! So old, in fact, that it really only exists to track down content farms that like to knock off my articles (oh hai, CircuitDigest!). Information here may be misleading and possibly wrong. You probably want to be using a newer client library and you definitely want to use an Arduino IDE ≥ 1.6 and not the ancient one that comes with Raspbian.

After the other night’s wonderfully slow detour into Processing, I thought I’d try the Raspberry Pi’s “native” language of Python to control an Arduino. This worked rather well, though I don’t have a slick GUI for it yet.

pyFirmata is the magic that allows an Arduino running Firmata to talk to Python. It’s fairly easy to install under Raspbian:

  1. Get the required packages:
    sudo apt-get install python-serial mercurial
  2. Download the pyFirmata code:
    hg clone https://bitbucket.org/tino/pyfirmata
    cd pyfirmata
    sudo python setup.py install

    (If this succeeds, you can delete the pyfirmata folder.)

Using pyFirmata is a bit different from other Arduino applications:

  • Analogue reads and PWM writes are normalized to a 0 .. 1 range, and not the standard Arduino 0 .. 255 and 0 .. 1023.
  • You really need to start a separate iterator thread to stop old readings overflowing the serial buffer
  • Since the Arduino is read asynchronously, make sure that the pyFirmata connection is fully initialized before reading from ports. Otherwise, None values ensue.

Here’s some code that uses the same hardware as before, but simply reports the temperature and ramps the brightness of the LED up in 10% steps.

#!/usr/bin/python
# -*- coding: utf-8 -*-

# simple test of pyfirmata and Arduino; read from an LM35 on A0,
#                                       brighten an LED on D3 using PWM
# scruss, 2012-08-14 - tested on Arduino Uno & Raspberry Pi (Raspbian)

import pyfirmata

# Create a new board, specifying serial port
board = pyfirmata.Arduino('/dev/ttyACM0')

# start an iterator thread so that serial buffer doesn't overflow
it = pyfirmata.util.Iterator(board)
it.start()

# set up pins
pin0=board.get_pin('a:0:i')             # A0 Input      (LM35)
pin3=board.get_pin('d:3:p')             # D3 PWM Output (LED)

# IMPORTANT! discard first reads until A0 gets something valid
while pin0.read() is None:
    pass

for i in range(10):
    pin3.write(i/10.0)                  # set D3 to 0, 10%, 20%, ... brightness
    print "PWM: %d %% Temperature %.1f °C" % (i * 10, pin0.read() * 5 * 100)
    board.pass_time(1)                  # pause 1 second

pin3.write(0)                           # turn LED back off
board.exit()

The output from this might look like:

PWM: 0 % Temperature 24.9 °C
PWM: 10 % Temperature 24.9 °C
PWM: 20 % Temperature 24.9 °C
PWM: 30 % Temperature 25.9 °C  <-
PWM: 40 % Temperature 26.9 °C    |
PWM: 50 % Temperature 28.3 °C    | I was holding the LM35 here
PWM: 60 % Temperature 28.8 °C    | to make the temperature rise
PWM: 70 % Temperature 29.8 °C    |
PWM: 80 % Temperature 29.8 °C    | 
PWM: 90 % Temperature 29.8 °C  <-

If this doesn’t work, check the output of dmesg to see if you’re using the right port. You could try this little test script

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pyfirmata

PORT = '/dev/ttyACM0'           # change this to suit
board = pyfirmata.Arduino(PORT)
print 'pyFirmata version:\t%s' % pyfirmata.__version__
print 'Hardware:\t\t%s' % board.__str__()
print 'Firmata firmware:\t%i.%i' % (board.get_firmata_version()[0],
                                    board.get_firmata_version()[1])
board.exit()

which should generate something like

pyFirmata version:    0.9.4
Hardware:        Arduino /dev/ttyACM0 on /dev/ttyACM0
Firmata firmware:    2.3

Next time, I’ll try to wrap this in a tkinter GUI. But for now, pyFirmata is a much quicker way than Processing to talk to an Arduino. But there is hope of a faster Java for the Raspberry Pi

Controlling an Arduino from Raspberry Pi using Processing

Hey! This article is really old! The code might still work, but I’ve updated the installation instructions for Processing 2.1 and Sun Oracle Java here: Processing 2.1 + Oracle Java + Raspberry Pi + Serial + Arduino = ☺.

This might not look like much, but it was a lot of work to get here. It’s the display from a small Processing sketch, running on a Raspberry Pi, talking to an Arduino controlling the brightness of an LED with the slider, and reading from an LM35 temperature sensor.

I wanted to see if I could get graphical control of an Arduino on the Raspberry Pi. I wrote about the simplest sketch in Processing that combined output (to control a small green LED through a resistor) and input (from an LM35, that simplest of sensors). This is how it looks running on a slightly faster machine than the Raspberry Pi:

LED at half brightness, LM35 showing 25°C

LED off, sensor at 26°C

LED full on, LM35 warmed up

I had the same results on the Raspberry Pi; just much, much slower. The sketch is below the fold.

Running Processing on Raspberry Pi

Processing is both written in and generates Java, so there’s some hope that it can run on most platforms. Up-to-date installation instructions. These instructions are modified from Processing sur Raspberry Pi, for which thanks are given to the original author:

  1. Install the JDK and Java serial library: sudo apt-get install librxtx-java openjdk-6-jdk
  2. Download the Linux version of Processing, and unpack it to somewhere permanent in your home directory
  3. Delete the java folder in the Processing directory; for me, that was processing-1.5.1/java
  4. Replace that java folder with a link to your system’s installation: ln -s /usr/lib/jvm/java-6-openjdk-armhf java
  5. In the Processing folder, remove or rename modes/java/libraries/serial/library/linux32/librxtxSerial.so; it’s an x86 binary, and will fail
  6. In the Processing folder, also remove modes/java/libraries/serial/library/RXTXcomm.jar, and replace it with a copy of /usr/share/java/RXTXcomm.jar
    (If you don’t do this, you’ll get a warning: “WARNING:  RXTX Version mismatch”, and any serial comms will fail.)
  7. Download and install the controlP5 library for Processing
  8. Download and install the Arduino library for Processing
  9. Program your Arduino with Firmata; the version that comes with the Arduino software is fine a bit old.
  10. Connect your Arduino to the Raspberry Pi with a USB cable; it may require external power.

Now fire up Processing. It will used to take a while to start up, and will throw the following warning:

Despite this, it should eventually should start up fine:

Now, this is slow. It takes tens of seconds to start up. It might not be the most practical development tool, but Processing sketches are very portable, so you can develop on one machine, and then run on the Raspberry Pi.

The code at the end of this article expects:

  • an Arduino running the Firmata DAQ sketch attached to a USB port;
  • a small LED connected from digital pin 3, through a 1kΩ resistor to ground;
  • an LM35 with the following connections: +Vs → +5V, Vout → analogue pin 0, and GND → GND.

If you run this, after about half a minute, the blank sketch window appears, and about half a minute later, the slider and temperature reading appears. If it doesn’t, there’s a good chance that the serial libraries are wrong. Try this sketch:

import processing.serial.*;
import cc.arduino.*;

Arduino arduino;
println(Arduino.list());

This should return a number and a serial port where the Arduino was found; something like ‘[0] /dev/ttyACM0’.

What I really want to do now is get this same hardware running with Python and tkinter. It’s not that Python’s my favourite language; it’s just that the Raspberry Pi Foundation chose Python as the official language for the board. I’d rather work to further the aims of this educational foundation rather than work against it. Processing’s pretty much unworkably slow on the Raspberry Pi — but it does work!