Pages

Sunday, 1 March 2015

Arduino IDE on the Rapsberry Pi

As part of my experiments with tworse (the Twitter to Morse project) I needed to install the Arduino IDE on a Raspberry Pi and use it to upload a sketch to a Shrimp. The Shrimp is a low-cost Arduino clone which uses a CP2102 as its programmer.

To my surprise and delight everything just worked out of the box. A couple of people have asked me what I did.

Here's what:

Installing the IDE

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install arduino

Since I normally work at the command line, I needed to fire up X-windows

startx

The menu included a category electronics, and the Arduino IDE was located there.

Uploading a sketch

Shrimp and Pi
I started up the IDE with the Shrimp plugged into a USB port.

I configured the IDE to use the appropriate board type (normally Arduino UNO for a Shrimp) and selected /dev/ttyUSB0 as the port.

I opened and uploaded the examples/blink sketch. The IDE compiled it (which took about a minute) and uploaded it successfully. Then I watched the blinkenlight, as Liz Upton would say :)

Update

This morning I repeated my experiment with an Arduino Uno. Everything worked without problem. The only difference was that I needed to select /dev/ttyACM0 as my port in the IDE.

One thing I forgot to mention yesterday: on the Pi I used, the pi account was a member of the dialout group, which I suspect is a requirement.



Shrimp and Raspberry Pi run the Morse Twitter Display

Yesterday I outlined my plans for a Morse Twitter display.

Tworse (the Twitter Morse Code display) is now running on the Shrimp + Pi as well as on an Arduino + Pi.

The Raspberry Pi monitors a twitter stream - in this case, it's looking for  tweets with the hashtag #morsetweeter.

It converts each tweet to upper case, removes any non-ascii characters, and sends it over a serial link to the Arduino or Shrimp.

The Shrimp reads lines using the Serial interface and flashes them in Morse Code. It then sends a text version of the Morse-coded line back to the Pi which displays it on the console.

Running the app on the Pi

The sketch for the Shrimp and the Python Script for the Pi are now on github.

The sketch is  a bit long for a blog post, but here is the Python code on the Pi.

import time
from twython import Twython
import serial


def parse(filename, comment_char='#', separator='='):
    options = {}
    with open(filename) as f:
        for line in f:
            start = line.split(comment_char)[0]
            if separator in start:
                option, value = map(lambda x: x.strip(),
                     start.split(separator, 1))
                options[option] = value
    return options


class ArduinoSerial():
    def __init__(self):
        self.ser = serial.Serial('/dev/ttyACM0', 9600)

    def send(self, text):
        self.ser.write(self.ascii_only(text))

    def receive(self):
        return self.ser.readline()

    @staticmethod    def ascii_only(text):
        return ''.join(i for i in text if ord(i)<128)


def get_twitter():
    ini = parse('secrets/twitter.ini')
    key = ini['KEY']
    secret = ini['SECRET']
    tw = Twython(key, secret, oauth_version=2)
    return Twython(key, access_token=tw.obtain_access_token())


if __name__ == '__main__':
    arduino = ArduinoSerial()
    time.sleep(1.0)
    twitter = get_twitter()
    tweets = twitter.search(q='#morsetweeter')
    for status in tweets['statuses']:
        line = (status['text']).upper()+'\n'        print line,
        arduino.send(line)
        print arduino.receive(),

Saturday, 28 February 2015

Tweeting Morse Code with Raspberry Pi and Arduino

I'm stuck at home and have seized the opportunity to prepare for a workshop that will link the Shrimp and the Raspberry Pi.

I love reusing previous projects. This one combines two bits of software that I prepared earlier :)

Twitter client meets Morse Code flasher

The core idea is simple. The project listens to what's happening on Twitter, and displays selected tweets by flashing the contents in Morse Code.

You could do this using the Pi on its own, or the Arduino on its own, but the project is easier and more reliable if you combine the strengths of both platforms.

Why the Pi?

It's possible to run a Twitter client on the Arduino but you're pushing the hardware to its limits. I've found some Arduino Internet libraries to be unstable, and your application is likely to be using most or all of the Arduino's limited program and data memory.

The Pi's memory is roughly a million times larger than the Arduino's RAM, and Internet applications are very stable. There are several Python-based twitter clients on the Raspberry Pi to chose from. In an earlier project I picked tweepy, which was easy to use and well supported.

Why the Arduino?

You could write a morse code flasher on the Raspberry Pi but

  • you'd need some extra hardware to flash an LED, and
  • you couldn't easily ensure that the Morse code timings were correct.
The difficulty with timing comes from the fact that the Pi is running a multi-tasking operating system. This means that your application can be preempted by a more urgent task at any time.

If you've just turned the LED on, it will stay on until your program gets a chance to turn it off again. There's no way to predict how soon that will be.

By contrast the Arduino has no Operating System, so timing is much easier to predict and control.

Connecting the two

It's not hard to write a Morse Code flasher for the Arduino, and I use that as one of the exercises in Life after Blink. It took me a couple of minutes to install the code on an Arduino, and a few more to get the Arduino talking to the Pi over a serial connection using py-serial.

I already had the Twitter client code from my earlier project. The project filtered the stream of tweets, printing all those with a particular hashtag. I installed the script on the PI and modified it to send its data over the serial port.

Voila! As tweets are received the Python program  sends their text over a serial link to the Arduino. Then the Arduino converts the text to Morse Code and flashes out the content using the on-board LED.

What next

There are a few more things I plan to do. 
  • replace the Arduino with a Shrimp.
  • improve buffering so the project can handle very popular hashtags
  • make the script and sketch available on GitHub
I'll tweet when I've done them; follow @rareblog if you're interested.

Please comment below if you have any questions, or have ideas about how to improve the buffering!