All posts by admin

Send pre-filled tweets using tweetyourmp.com

Rather excitingly my little side project tweetyourmp.com was mentioned by pukka chef Jamie Oliver as part of his campaign for healthy eating:

Big yellow sign
Big yellow sign

After my panic that I might not have enough bandwidth subsided, I thought it might be a good moment to give Tweety our MP a bit of love, so I’ve added the option to pre-fill tweets.

The tweet text is passed across using a custom URL – this can be done as follows:

Pre-filling in the postcode and tweet message:

Make sure you use the URL http://tweetyourmp.com/index.php

The URL needs to be in the format:

http://tweetyourmp.com/index.php?postcode=SW2 2AX&tweetmsg=twitter message&[email protected]

the parts being:

http://tweetyourmp.com/index.php

?postcode= the postcode for constituency lookup

&tweetmsg= the twitter message

&sentvia= the twitter handle for the sender (default is @tweet_your_mp)

You can leave out the postcode (or the tweet message!):

http://tweetyourmp.com/index.php?tweetmsg=twitter message&[email protected]

Passing values to tweetyourmp.com in this way works with spaces, but safer to encode the message and postcode parts using http://andrewu.co.uk/tools/uriencoder/ to replace characters with %20 for a space.

so the above becomes:

http://tweetyourmp.com/index.php?postcode=SW22AX&tweetmsg=twitter%20message&[email protected]

This example generates:

hello @ChukaUmunna your twitter message via @kimondo

as the tweet.

Important note on using hashtags

I had to use a bit of a hack to make it possible to have a pre-filled tweet with a hashtag. As # is used to denote an anchor link when you stick it in a URL the rest of the URL gets ignored by the bit of the code that reads the tweet from it.

To get round this use an asterisk * in place of a hash # – the code then puts the hash back in when it sends the tweet:

http://tweetyourmp.com/index.php?postcode=SW22AX&tweetmsg=twitter%20message%20*hashtag&[email protected]

This hashtag example generates

hello @ChukaUmunna your twitter message #hashtag via @kimondo

The salutation is fixed as ‘Hello’ but can be changed – is important not to begin the tweet with the @handle as it reduces its visibility and ‘Hi’ is a bit American sounding hence the hello.

Next on the list is building some sort of Raspberry Pi based tweet totaliser. You can download the (very simple) code that runs Tweet your MP on GitHub – a couple of interesting options are to use the code in a thankyou email after a supporter has completed an action to give it a bit more impact, or to sort through your data and merge in constituency contacts in an email.

Note that some MPs don’t consider twitter an ‘official’ communication format so this is best combined with an email or letter to an MP.

tweetyourmp.com is made possible thanks to the theyworkforyou.com API – this is free for charitable use up to 50,000 queries.

Update: I’ve now added a page that automates this process and builds a bit.ly link with the correct address!

Indiana Jones Idol Swap party game

My sister in law does epic children’s parties (a couple of years back I had a lot of fun playing Snape and being mean to all the kids who weren’t in Slytherin) and this year I was given a request to build a game for an upcoming Indiana-Jones themed party.

Remember that bit at the very beginning of Raiders of the Lost Ark where Indy has to balance the idol with a bag of sand to avoid the traps going off?

“Can you build a game that does that?”

So I started thinking along the lines of using an Arduino coupled with a weight sensor which triggers an attached Raspberry Pi to play a tune when the idol is balanced, all packaged up inside a suitably rock looking biscuit tin:

I've got a bad feeling about this
I’ve got a bad feeling about this

The idea would be the idol would be swapped, the Arduino would detect the swap, determine if the weight was different and then set off an alarm and rumble motor if it was. If it was the same weight it would play the Indiana Jones music.

The Arduino has lots of analogue pins that can read changes in voltage, and the Pi can take care of the music and sound effects – it would also be possible to  hook it up to a TV to play the appropriate bit of the film, as chasing down seven year olds with a giant boulder / dart traps / snake pits might not go down well with their parents.

Initially I looked at using a load cell sensor similar to what’s found in electronic scales, however I discovered that the resistance generated by these sensors to be really tiny, and it’s not just a simple matter of hooking them up to an Arduino. Note – since I built my initial version Sparkfun have actually brought out a handy load-cell amplifier kit that should make this possible for version 2!

So instead I opted for a much simpler force sensor – these are widely available and their resistance can be easily measured, but they’re also a bit inaccurate. For the purposes of the game and to add a bit of random variability I decided to go with this simpler route.

My arduino circuit is as follows – it includes an LED to indicate if the pressure sensor is detecting the idol properly. The Arduino communicates with the Pi over serial to then trigger the appropriate sound file. I ran out of time to include the rumble motor but it would be quite easy to add one.

Adafruit have a tutorial along with some suitable code which can be used to send the force sensor output to the Raspberry Pi  via serial:

/* FSR testing sketch. 
 
Connect one end of FSR to 5V, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground
Connect LED from pin 11 through a resistor to ground 
 
For more information see www.ladyada.net/learn/sensors/fsr.html */
 
int fsrAnalogPin = 0; // FSR is connected to analog 0
int LEDpin = 11;      // connect Red LED to pin 11 (PWM pin)
int fsrReading;      // the analog reading from the FSR resistor divider
int LEDbrightness;
 
void setup(void) {
  Serial.begin(9600);   // We'll send debugging information via the Serial monitor
  pinMode(LEDpin, OUTPUT);
}
 
void loop(void) {
  fsrReading = analogRead(fsrAnalogPin);
  Serial.print("Analog reading = ");
  Serial.println(fsrReading);
 
  // we'll need to change the range from the analog reading (0-1023) down to the range
  // used by analogWrite (0-255) with map!
  LEDbrightness = map(fsrReading, 0, 1023, 0, 255);
  // LED gets brighter the harder you press
  analogWrite(LEDpin, LEDbrightness);
 
  delay(100);
}

This also lights up an LED to give useful visual feedback – the Pi then just listens on the serial input and triggers the according sound effect.

Assembled the sensor looks like this (the force sensor is under the lid of the coffee tin):

Indiana Jones style trap game
Indy was out so Han stepped in

Inside my ‘Idol’ (which was a papercraft model printed on shiny paper), was a counterweight made from a stack of pennies – this is reasonably heavy and I was able to adjust the sensitivity of the circuit to detect the presence (and absence) of the Idol.

To build the pedestal I used an octagonal quality street plastic box, covered in paper mache and spray-painted with stone effect spray paint. The arduino and pressure sensor were contained inside a metal coffee tin.

On detecting the Idol being removed, the Pi plays the sound sample “It belongs in a museum” from Raiders of the Lost Ark, if the sensor is successfully fooled it plays the Indiana Jones theme!

After a bit of play testing we found that balancing the idol was very hit and miss – although a handy rock nearby seemed to do the job most of the time. Ideally this would use the much more accurate load cell to measure the weight of the idol and compare it to the bag of sand after a button press. I still have all the parts, so I’m just waiting for the next time someone in my family holds an Indiana Jones themed birthday party.

Indiana Jones Idol Swap game
Here it is (running off a USB battery)

Raspberry Pi powered General Election Swingometer

In the UK it’s election time again and the BBC are preparing to wheel out the latest version of their Swingometer. The BBC Swingometer dates back to 1959, and was a visual device for displaying the balance in seats won by the two main political parties. The Swingometer coined a whole load of phrases along the lines of a ‘swing away’ or ‘swing towards’ a particular party or candidate, and was well suited towards the simple days of two party politics.

Here’s version 1.0 back in 1959:

There's a chap with a pipe behind controlling the arrow
There’s a chap with a pipe behind moving the arrow (photo BBC)

The BBC have more or less stuck to the same device for every election since, although sadly in the same way that CGI ruined the Star Wars films, Swingometers have recently become more and more complicated. This is perhaps also a consequence of the UK moving to multi-party politics where working out who exactly in power after polling day is getting a bit complicated.

Here’s version 14.0 from 2010:

There's just a big green room
There’s just a big green room (photo BBC)

In a tribute to the original, the charity I work for – Concern Worldwide have been using a Development Swingometer, which pays homage to the original 1959 version and tracks the number of candidates who have signed up to support Concern’s 5 pledges on fighting global poverty and protecting international aid (you can tweet them on that page with some code I mashed up using TheyWorkForYou.com and YourNextMP.com).

Building a Raspberry Pi powered Swingometer

As our low-budget version is a bit simple, for a bit of fun I thought I’d build a slightly more technical version that updates itself automatically. My updated Swingometer uses a servo to move the arrow, and a Raspberry Pi to fetch the ‘swing value’ from a web page when you push the big friendly button. The code I’ve used can be edited to fetch more or less any numerical value from a web page and turn it into a ‘swing’ so It should be possible to repurpose this into a political swingometer, or something that displays anything with a value of 1-180 (the angle of swing possible with a servo).

Push the button for results
Just push the button for the latest results

The back of the frame (£5 from Wilko) shows the Raspberry Pi model A and a little slice of Pi board I soldered up. There are two buttons – the big friendly update button for the front and a safe shutdown button on the back, so I can run this without a screen and keyboard.

Here's the back with an arcade machine button and the wiring to the servo
Here’s the back with an arcade machine button (white wires) and the wiring to the servo (brown – red – yellow wires)

The method I’ve used to control the servo is similar to RaspiTV’s Raspberry Pi flag waving post – although I opted for the version detailed in the Raspberry Pi cookbook over Adafruit’s single servo control. For my power supply I used a D-link powered USB hub to supply both the Pi and the Servo via separate USB cables. This results in a slightly wobbly update of the Swingometer arrow, which suits me fine. For more precise control you can use a dedicated servo control hat which can control up to 16 separate servos.

For the code I modified the Raspberry Pi cookbook tutorial code to fetch a value from a web page using Beautiful Soup. You can install this on the pi using:

sudo apt-get install python-beautifulsoup

Note that this installs version 3 – but you’re still able to do lots of clever things to grab content from web pages. If you want to build a political swingometer I’d suggest grabbing values from the election forecast page. There’s a lot more information about using Beautiful Soup on the web page here.

Here’s the code I’ve used to update the swingometer:

import RPi.GPIO as GPIO
import time
from BeautifulSoup import BeautifulSoup
import urllib2

#change this bit
url="http://www.kimondo.co.uk/swingometer-control/"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())

value = soup.find('span',{'style':'color: #99cc00;'})
value = value.next
value = float(value)

print value

GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 100)
pwm.start(5)
t_end = time.time() + 1

while time.time() < t_end:
        print value
  angle = value/100.0 * 180
  print angle
        duty = float(angle) / 10.0 + 2.5
        pwm.ChangeDutyCycle(duty)

exit()

An alternative I considered was using the Sentiment 140 twitter sentiment tracker API – this tracks positive and negative sentiment towards keyword searches on twitter – although it seems to get fooled by ironic tweets.

If you’ve been inspired to build a Swingometer please share it in the comments! One day I’d quite like to build something like the Weasley clock.

You can ask your election candidates to support Concern’s 5 pledges to fight global poverty and support development here and my fantastic blog about the Development Swingometer on Concern’s website.

5 geeky DIY Christmas gift ideas

With Christmas rapidly approaching, one of my aims this year is to at least attempt a bit of DIY Christmas gifting. So if you know me, there are potential spoilers ahead and stop reading this right now. So here are five ideas I may or may not be considering as part of my Christmas gift ideas. These really are quite geeky, but then so are most of my friends and family.

1. 3d printed jewellery

We don’t all own 3d printers (yet) particularly ones that can print in precious or semi-precious metals. But head over to Shapeways – a website with a name that sounds like it’s straight from an episode of the Hitch-hikers Guide to the Galaxy and you can print more or less anything you can practically design provided it’s in a format they support. You can also order a printed version of your idea in cheaper plastic before committing to a more expensive material.

For a less daunting project you can contact some of the designers to create customised versions of their work. Lots of designs are available on Thingiverse for you to download and edit (including the ring shape below).

http://www.thingiverse.com/thing:7354
Thingiverse Ring, it’s a thing.

2. Make your own lego brick shaped bath bombs

So slightly less technical but fun nevertheless is to make your own bath bombs or fizzies. These are compacted cubes of Sodium Bicarbonate and Citric Acid that bubble Carbon Dioxide when you chuck them in the bath:

C5H7O5COOH + NaHCO3 → C5H7O5COONa+ + H2O + CO2

Here’s a nice recipe from Busy City Mum’s blog for Bath Fizzies which goes into detail about what quantities and ingredients you need. You can now buy silicon moulds in lots of shapes including Lego brick (lookalikes, not official) and the Death Star (not a moon).

In Japan it’s tradition to include a figure inside the bath bomb, so a Lego minifigure would seem appropriate!

3. A custom Raspberry Pi

A very neat little computer

 

I had to include a Raspberry Pi based project – there are lots to choose from including Media players and retro computer emulators – but for this I wanted to find something that would be suitably difficult to purchase. One possibility is the Raspberry Pi magic mirror which is detailed on it’s creator’s blog – this is something you simply can’t buy, and looks amazing – although you’ll need a monitor and a mirror for the full effect.

My simpler project is to build a Raspberry Pi audio streamer. Audio streamers are generally very expensive and although the Pi’s default audio output is fairly basic it’s possible to add a DAC to provide really high quality sound output. Thanks to Carla at busycitymum.com for sending me a Wolfson Pi I was able to build a fairly decent Pi Music Box with Airport support.

The recipe for this is as follows – I’ve confirmed this to work with the original Wolfson Pi Audio Card and a Raspberry Pi model A – there is a new version of the Wolfson card available for the newer Raspberry Pi models.

  • Download the custom version of Raspbian from www.element14.com/PiAudioCard – on the Mac the custom version of Raspbian unpacks best if you use Stuffit Expander and then Apple Pi Baker to copy the iso file to an SD card.
  • Install Shairport using these instructions from Drew Lustro
  • For a final bit of polish (particularly if your running a Raspberry Pi as a headless server) you can include a web based shutdown control panel – follow the instructions on the forum here. You can edit the web page to include a nice message to your gift recipient as well!
IMG_2679
Raspberry Pi Airport speaker

DIY projects that work with Apple products go down quite well.

4. Bake!

Baking is a much appreciated gift – and given the diversity of cookie cutting shapes available it’s possible to give a nerdy spin on even the most traditional recipes.

Firebox do a nice line in Tetris Cookie cutters – combined with a Gingerbread recipe these make for a pleasing tessellating gift.

I’ve tried a few different gingerbread recipes and Delia’s is by far the best. Thanks to the additional spoon of black treacle the gingerbread is sufficiently biscuity – and you can vary the cooking time if you want a more chewy gingerbread. Other recipes don’t work as well since they opt for either golden syrup or black treacle. Cowards.

Combine with an original Gameboy (search for DMG1) for added wow factor. Works particularly well on millennials.

Gingerbread Tetris
Gingerbread Tetris

5. Give a DIY gift

So technically cheating, but you can also give the gift of DIY. I recently reviewed the StoneTurners DIY microscope

finished USB microscope
I was a little heavy with the glue gun

which can take awesome pictures of things, and works with the Raspberry Pi.

If you want to spend a bit more the DIY projects from Technology will save us are worth a look.  Although they’re more expensive than shopping around and buying the parts, the packaging is lovely and they make quite complicated projects accessible. Plus angry birds on the Arduino is very addictive…

ASCII camera with the Holga 120d

So now I’ve finished my digital Holga project, one of the things I wanted to do was to get a bit creative with it – so here’s my first attempt at an ASCII art generating camera.

Holga 120d ASCII text image
High contrast images work best.

This uses the ASCII art script written by Steven Kay, please visit his blog to find out more – I’ve modified the original script to use the python picamera library – this helps speed up the image resize. There’s also a timestamp added to the text file which uses the same script I wrote about in my previous Holga post.

If you just want to run Steven Kay’s script you’ll need the python imaging tools – install with

sudo apt-get install python-imaging

Here’s my modified script:

'''
ASCII Art maker
Creates an ascii art image from an arbitrary image
Created on 7 Sep 2009

@author: Steven Kay
'''

import time
import picamera
from PIL import Image
import random
from bisect import bisect

# greyscale.. the following strings represent
# 7 tonal ranges, from lighter to darker.
# for a given pixel tonal level, choose a character
# at random from that range.

greyscale = [
            " ",
            " ",
            ".,-",
            "_ivc=!/|\\~",
            "gjez2]/(YL)t[+T7Vf",
            "mdK4ZGbNDXY5P*Q",
            "W8KMA",
            "#%$"
            ]

# using the bisect class to put luminosity values
# in various ranges.
# these are the luminosity cut-off points for each
# of the 7 tonal levels. At the moment, these are 7 bands
# of even width, but they could be changed to boost
# contrast or change gamma, for example.

zonebounds=[36,72,108,144,180,216,252]


#take photo

with picamera.PiCamera() as camera:
                        camera.capture('image.jpg');

# open image and resize
# experiment with aspect ratios according to font


im=Image.open(r"image.jpg")
im=im.resize((160, 75),Image.BILINEAR)
im=im.convert("L") # convert to mono

# now, work our way over the pixels
# build up str

str=""
for y in range(0,im.size[1]):
    for x in range(0,im.size[0]):
        lum=255-im.getpixel((x,y))
        row=bisect(zonebounds,lum)
        possibles=greyscale[row]
        str=str+possibles[random.randint(0,len(possibles)-1)]
    str=str+"\n"

print str

date_string = time.strftime("%Y-%m-%d-%H:%M:%S")

text_file = open('image' + date_string + '.txt', "w")
text_file.write(str)
text_file.close()

There are lots of settings to tweak – the image above was generated by the script – and bear in mind this is designed to be viewed with black text on a white background. Perhaps I’ll see if I can dig out an old dot matrix printer from somewhere.

For a blog of ‘photos’ updated whenever I take them and am in range of WiFi check out:

http://holga120d.blogspot.co.uk/

This emails the ASCII art in HTML format to blogger whenever I take a photo (and the Pi Holga is in range of the internet).

For more about the Digital Holga check out my previous blog posts on the hardware and building the case.

How to find a Raspberry Pi on your network

Here’s a quick tip to finding a Raspberry Pi (and anything else) on your network using the nmap network scanning security tool.

Quite often you might want to run a ‘headless’ Raspberry Pi without a screen or keyboard, using SSH to connect. SSH can be enabled in the config menu when you first boot the Pi. You can then find the IP address of your Pi when you’re initially setting it up using the ifconfig command in the terminal. Normally this works like this – on the Pi you want to connect to, type into the terminal:

ifconfig

Note the value next to “inet addr” – which usually looks like 192.168.1.(a number) – Then from another machine you can SSH to your Pi to allow for remote control

ssh [email protected][the ip address of your pi]

This is fine, but most home networks use something called DHCP – ‘dynamic host configuration protocol’ – local IP addresses are temporarily assigned to the computers by your router (the DHCP server). Although these addresses often don’t change, they can. You can assign a static IP address which is something i’ve used in the past, or install a service like no-ip that tracks your Pi’s IP address (and makes it available over the internet as well). You also need to be able to connect a screen to the computer you’re attempting to connect to!

A simpler method is to use a tool called nmap (network map)- there are versions available for windows and mac, and it works from a Raspberry Pi. It’s also free.

For instance, you might have a Raspberry Pi setup on your network with a monitor and keyboard, and you’ve plugged a second Pi in that’s running SSH.

Install nmap with:

sudo apt-get install nmap

and then use the following command:

sudo nmap -sP 192.168.1.*

Returns a list of ips and hostnames – just look for the one called Raspberry Pi – This takes about 30 seconds.

Just like the matrix
Just like the matrix

Nmap does a lot of other things as well – and it’s the program of choice whenever movies attempt to depict computer hacking, or if you want to hack into Matt Damon’s brain.

If you’re looking for a more portable version there’s a (paid for) tool called Scany which is available for the iPhone and iPad or Fing which is free.

 

 

Controlling Lego motors with the Ryanteck Raspberry Pi board

I’ve reviewed a few Raspberry Pi add on boards before, including the PiFace which includes a multitude of inputs and outputs, and the minimalistic LEDborg which has a very bright single multicoloured LED.

The Ryanteck Raspberry Pi Motor Controller Board Kit is a GPIO add on board that allows you to control 2 motors with your Raspberry Pi. Although it’s much simpler than the PiFace it’s cheaper (about £12) and is easy enough to assemble yourself. In fact it makes a nice introduction to soldering, and is an ideal project if you want to take the plunge and have a go at making your own hardware.

With the motor controller board you can build a simple Raspberry Pi based rover – you just need 2 motors driving side by side sets of wheels or tracks. Driving the motors in opposite directions allows you to turn on the spot. The Ryanteck board can control motors up to 12 volts to you could always re-purpose a toy or build your own.

There’s some documentation available here, but I thought I’d share my build guide. If you’ve never soldered before check out the Soldering is Easy guide, and try to buy some leaded cored solder. Lead has (quite rightly) been removed from the solder used in commercial products to prevent it ending up in landfill when electronics are thrown away. However lead-free solder is much harder to work with (it’s fine if you’re a robot) and for hobbyist applications it’s easier to work with the leaded variety. Just make sure you don’t throw your electronics projects away once you’ve finished with them.

Build guide

In the kit are 3 sets of 2 pin headers, 3 sets of blue terminal blocks, a GPIO connector pin header and a chip carrier and controller chip.

Don't panic.
Don’t panic.

 

Holding everything in place when you’re soldering is tricky – so my tip here is to use the GPIO header block to hold the parts in place while you solder them. So first we have the set of 3 2 pin headers:

The spacing is just right!
The spacing is just right!

Next we’ll solder the chip holder into place, using the GPIO header plugged into one of the sets of 2 pin headers – orientate the cut out to the left hand side of the board:

Chip holder next, held in place with the GPIO header
Chip holder next, held in place with the GPIO header

Next comes the blue terminal pins. These are a tighter fit so easier to just rest the board on the blocks and solder away. Finally comes the GPIO header. Remember to solder this facing down – you’ll need something to rest the board on. Fortunately I discovered this was exactly one lego minifigure knee in height, so I used the lego workman as a rest:

Soldering is Awesome!
Soldering is Awesome!

 

Finally comes connecting it all up and testing. The board is rated for a range of motor voltages. Surprisingly as I seem to have a lot of Lego around I thought I’d test it with a vintage Lego technic motor. Lego motors come in different voltages – the very old ones are 4.5v and the newer ones tend to be 9v. My motor is 9 volts but I’m running it off a 5 volt USB power supply, which I’m using in my Lego rover project. The motor runs a bit slower but is fine for my purposes. Attach the power supply for the motor to the J1 blue terminal with positive on the left hand side.

It lives!
It lives!

There’s a test program included in the instructions to switch the motor on, and change it’s direction for a set period of time.

Create the program with:

sudo nano motortest.py

 

copy the following code:

##Simple motor script for the RTK-000-001
import RPi.GPIO as GPIO
import time
#Set to broadcom pin numbers
GPIO.setmode(GPIO.BCM)
#Motor 1 = Pins 17 and 18
#Motor 2 = Pins 22 and 23
GPIO.setup(17, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
#Now loop forever turning one direction for 5 seconds, then the other
while (True):
#Sleep 1 second then turn 17 on
 GPIO.output(18, 0)
 time.sleep(1)
 GPIO.output(17, 1);
 time.sleep(5);
#And now the other way round
 GPIO.output(17, 0)
 time.sleep(1);
 GPIO.output(18, 1);
 time.sleep(5);
 #And loop back around
#And final cleanup
GPIO.cleanup()

 

and then run it using:

sudo python motortest.py

 

You’ll need to use sudo as you’re using the GPIO pins.

Finally here’s a picture of the almost completed Lego Rover: all that’s to do next is to write some software and add a PiCam:

Curiosity killed the cat..
Curiosity killed the cat..

The Ryanteck Raspberry Pi board is a nice kit, easy to put together and get going straight away, and works with Lego motors so there’s quite a range of interesting things you can try. Ryanteck has now launched a complete robot kit that includes a chasis as well. For more info check out their GitHub project page. It’s a bargain way of making your Pi control things.

New year, new server

Well I always like to celebrate a New Year in style, so to celebrate 2014 (the busiest year for this website ever) I’ve finally upgraded my legacy Supanames web package to something a bit faster.

The really-quite-handy-I-can’t-believe-it’s-free Uptime Robot tells the story better than I can, but hopefully things will start to work a bit faster and fall over less often.

It probably also helped that I had a bit of a script spring clean at the same time...
It probably also helped that I had a bit of a script spring clean at the same time…

Next step is to sort out the design again…