Hatherly.com

Blog



Raspberry Pi – More fun with Lego Motors!

Posted on May 2, 2016 by Adam under Uncategorized

In a previous blog post I talked about using the Raspberry Pi with the PiFace digital board to control some Lego motors (using the two on-board relays). This worked well, but there was a small problem – the motors could only go in one direction.

In order to make the motors be able to go both forwards and backwards I needed to find a way to reverse the polarity of the 9v current. To do this, we need to use something called a “H bridge”. There are lots of clever ways of building a H bridge, but my electronic skills aren’t up to much, so I decided to go with a solution I found on this page – which is nice and simple as it uses just relays and no other components.

This is nice and simple, but it introduces a new problem… each motor now needs two relays (one for forwards and one for backwards), and our PiFace Digital board only has two relays on it. I wanted to drive two lego motors (one on each wheel of my robot), so I needed to add more relays.

Luckily, simple relay boards can be bought online very cheaply – there are loads available, for example this one from amazon.

In terms of connecting the relay board, I found a really useful forum post here explaining the easiest way of connecting it to the PiFace outputs (see the comment from nickhills at Mon Apr 15, 2013 11:23 pm). This requires a separate 5v power feed for the relays, so I butchered a USB cable to provide me with 5v. To keep the wiring neat I re-used an old floppy drive cable which plugs nicely into the header pins on the relay board, and I then connected the relevant wires into the PiFace screw terminals:

02-05-2016 08-56-21_0004

Now, all I needed to do was to follow the wiring from the relay H-bridge article, and connect the lego motors to the relay screw terminals. I also connected the lego buttons (see previous post) to act as inputs for controlling the robot:

02-05-2016 09-27-49_0001

Now, we can use scratch (making sure you follow the instructions on the PiFace site for setting up and starting the piface scratch handler) to create a simple script to process the inputs (from the Lego buttons) and send the relevant signals to the relays (and on to the motors):

LegoRobotScript1

And here it is in action!

Finally, Laura had some fun creating another script in scratch to programme a sequence of actions (a bit like a home-made BigTrak!):

LegoRobotScript2



  |  
Leave a comment


MythTV and “Cypress” remote control that emulates a keyboard

Posted on by Adam under MythTV, Ubuntu

Some time ago I bought a new home theatre PC case for my mythtv box, and it came with an in-built IR remote control. I didn’t use it at first, preferring to use a pulse-eight CEC adapter with my normal TV remote, but when that stopped working the other day I thought I would see if I could get the case remote working with MythTV.
02-05-2016 08-49-28_0003
I had assumed it would just be a case of configuring lircd (the usual Linux infra-red remote control daemon, but it turned out it was actually showing up as a keyboard and mouse – as you can see from the output from running xinput list:

⎡ Virtual core pointer                    	id=2	[master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer              	id=4	[slave  pointer  (2)]
⎜   ↳ Cypress Cypress USB Keyboard / PS2 Mouse	id=14	[slave  pointer  (2)]
⎜   ↳ MCE IR Keyboard/Mouse (saa716x)         	id=17	[slave  pointer  (2)]
⎜   ↳ Pulse-Eight USB-CEC Adapter             	id=15	[slave  pointer  (2)]
⎜   ↳ Logitech USB Receiver                   	id=9	[slave  pointer  (2)]
⎜   ↳ Logitech USB Receiver                   	id=10	[slave  pointer  (2)]
⎜   ↳ SONiX USB Device                        	id=11	[slave  pointer  (2)]
⎣ Virtual core keyboard                   	id=3	[master keyboard (2)]
    ↳ Virtual core XTEST keyboard             	id=5	[slave  keyboard (3)]
    ↳ Power Button                            	id=6	[slave  keyboard (3)]
    ↳ Video Bus                               	id=7	[slave  keyboard (3)]
    ↳ Power Button                            	id=8	[slave  keyboard (3)]
    ↳ Cypress Cypress USB Keyboard / PS2 Mouse	id=13	[slave  keyboard (3)]
    ↳ saa716x IR (TurboSight TBS 6280)        	id=16	[slave  keyboard (3)]
    ↳ SONiX USB Device                        	id=12	[slave  keyboard (3)]

The device we are interested in is “Cypress Cypress USB Keyboard / PS2 Mouse”. The first job is to see what keyboard events the remote is generating when we press keys. To do that, use xev, which will show you a whole load of keyboard and mouse events (each key press includes a keydown event and a keyup event). For example, when we press the “Back” button on our remote, we get this:

KeyPress event, serial 37, synthetic NO, window 0x4800001,
    root 0xe4, subw 0x0, time 48537039, (150,532), root:(150,584),
    state 0x0, keycode 22 (keysym 0xff08, BackSpace), same_screen YES,
    XLookupString gives 1 bytes: (08) "
    XmbLookupString gives 1 bytes: (08) "
    XFilterEvent returns: False

The keycode from our remote we want to remap is “keycode 22”, currently mapped to a key event of “Backspace”. I want this button to actually send an Escape key rather than Backspace, so on my main keyboard I press Escape to see what the action is:

KeyPress event, serial 38, synthetic NO, window 0x4c00001,
    root 0xe4, subw 0x0, time 48697777, (492,-51), root:(492,1),
    state 0x0, keycode 9 (keysym 0xff1b, Escape), same_screen YES,
    XLookupString gives 1 bytes: (1b) ""
    XmbLookupString gives 1 bytes: (1b) ""
    XFilterEvent returns: False

So, the action we want is called (unsurprisingly) “Escape”.

This page show how to remap keys globally, but we only want to remap it for this device so we don’t also remap the keys on the keyboard! So this link can help us do that.

So, using the link in the above page we can map our keycode 22 to an XKB code of <BKSP>. Now, we can make a script like the one in the above article to remap this key (and others we want to remap). The line in the script for our back key will look like this:

    key <BKSP>  { [ Escape ]       };

Which maps the <BKSP> key to the “Escape” key event. I was able to remap other keys in the same way to get keypresses I could use in MythTV.

One challenge I had was with some of the buttons on the remote that send multiple keypresses. For example, the menu button sends Alt+Super+Enter. This caused me some head-scratching as I couldn’t get MythTV to properly process any keypresses with Alt, Ctrl or Super (a.k.a. the Windows key) pressed (I suspect Gnome was intercepting them). In the end I remapped both Alt and Ctrl to Shift, and rather sneakily I mapped Super to “m” (the key for opening the Menu in MythTV), which works quite nicely for my purposes. I few tweaks to the MythTV keyboard bindings (which you can do in MythWeb) and I now have a fully working remote!

This is the full script to remap the keys:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
# Find the ID of our keyboard (using the name "Cypress")
remote_id=$(
    xinput list |
    sed -n 's/.*Cypress.*id=\([0-9]*\).*keyboard.*/\1/p'
)

# Remap our keys:
mkdir -p /tmp/xkb/symbols
cat >/tmp/xkb/symbols/custom <<\EOF
xkb_symbols "remote" {
    key <BKSP>  { [ Escape ]       };
    key <COMP>  { [ i ]       };
    key <LCTL>  { [ Shift_L ]       };
    key <LALT>  { [ Shift_L ]       };
    key <LWIN>  { [ m ]         };
};
EOF

setxkbmap -device $remote_id -print | sed 's/\(xkb_symbols.*\)"/\1+custom(remote)"/' \
 | xkbcomp -I/tmp/xkb -i $remote_id -synch - $DISPLAY 2>/dev/null

And I added this script as 99remapRemoteControlButtons.sh in /etc/X11/Xsession.d so it runs when X11 starts.



  |  Leave a comment


Lego and Raspberry Pi – Simple Simon Memory Game

Posted on April 19, 2015 by Adam under RaspberryPi

Following on from my last blog post where I used a simple touch sensor to trigger a robot moving, controlled by the Raspberry Pi, I thought we would try something a bit more complex this time. This time we have used three lego touch sensors for buttons, and three of the digital outputs to drive three different coloured LEDs. Putting it all together, with a bit of fun lego construction, we were able to create a simple simon memory game!

This time rather than using Scratch to control it, we went for Python, and we used some code provided on the piface web site to control the game itself.

Unfortunately I only had three different coloured LEDs handy, so our simple simon game only has three buttons rather than the traditional four, but it is still lots of fun! We had to tweak the code to make sure it worked with three inputs rather than four (instructions on the piface page above).

This is how we created the coloured buttons using our lego touch sensors:
Touch Sensor Button

The LEDs were inserted into some clear lego blocks which glow nicely when they are lit up. Simple jumper wires were used to connect the LEDs to a breadboard, and from there to the outputs on the PiFace digital card. Two of the LEDs ran on 5v (which is what the Pi outputs), with the third needing a resistor to bring the voltage down:
Connecting it all up

The touch sensors are connected to the inputs in the same way as the project from my previous blog post, and it was all ready to go!
Ready to play!

Then, we pulled down the code, tweaked the number of inputs, ran it, and tested our memory!

I did look into adding some sounds to make it more authentic, but ran out of time – maybe next time…



  |  Leave a comment


More Lego Raspberry Pi and Scratch fun – adding some inputs

Posted on September 21, 2014 by Adam under RaspberryPi

In a previous post I talked about a simple method of controlling Lego motors using a raspberry Pi with the PiFace digital card. I decided to see if I could extend this slightly to include some inputs so we can control our Lego creations (with a bit of help from my kids of course!).

After some investigations I came across some great little touch sensors, which you can get for less than a pound each using sellers on bricklink. I also took the opportunity to get some more wires too, with yellow connector blocks on the end so I can easily tell my inputs apart from my outputs.
21-09-2014 13-47-18_0004_small

Getting them working was as simple as wiring the connector block wires into the input screw terminals on the PiFace card.

Now we just needed a fun project to try it out. We decided to create a simple game with a marble and a robot who talks when you get the marble into the goal. The touch sensors are quite sensitive, but we did struggle with a design which registered the marble reliably when it rolled into the goal. In the end we built a platform which pivoted, so any small weight on the platform would push the touch sensor quite firmly, and trigger the input into the Raspberry Pi.
21-09-2014 13-57-07_0007_small

All that was left then was to create the robot’s head to go on top of the goal and “talk” when the marble is successfully rolled into the goal. The motor controlling the robot’s mouth is connected to the output on the PiFace card (in the same way as I described in my previous post).
21-09-2014 13-47-39_0005_small

Finally, a nice simple scratch script to make it all work, and to keep score!
MarbleRobotScript

And here is a video of it in action:



  |  3 Comments


Raspberry Pi Controlling Lego Motors Using Scratch

Posted on February 5, 2013 by Adam under RaspberryPi

I recently bought a Raspberry Pi and have been having great fun finding fun things to do with it. One great thing about the Pi is the GPIO port which allows other things to be easily connected to the Raspberry Pi. One great add-on that I have also bought is a PiFace Digital [link]. This fits nicely on top of the Pi and gives you 8 digital inputs and 8 digital outputs (2 of which can drive relays on the board).

I decided to use this to drive some Lego motors, so I could make a simple robot and control it from the Pi.

The first step after plugging the PiFace board into the Pi was to download a customised Raspian image. You can find links to this and other useful documents here. Once I booted the image I was able to switch the LEDs on the PiFace on and off from Python by typing:

$ python
>>> import piface.pfio as pfio
>>> pfio.init()
>>> pfio.LED(1).turn_on()
>>> pfio.LED(1).turn_off()
>>>

I then decided to see if I could control some lego motors, and control them from Scratch. I had two old 9v lego motors with connectors, so I started by connecting the positive wire from a 9v battery to the middle connector on each of the two relays, connected longer wires to the “Normally open” connector on each of the relays, and connected the negative battery wire to the other connector on both motors:

Raspberry Pi and PiFace board with 9v battery connected to relays to control Lego motors

Raspberry Pi and PiFace board with 9v battery connected to relays to control Lego motors

I then opened up Scratch. The next step is to enable a “mesh” connection. To do this, within Scratch Shift-Click the Share menu and click “Host Mesh”.

Now, go back to the desktop and double click the “Scratch Mesh Handler”. This will start listening to the inputs and outputs on the PiFace and relay them to Scratch.

Next, I made a simple “robot” – which was just a simple car with two motors and some gears to slow them down to a more manageable speed.

Lego Robot Controlled by Raspberry Pi

Lego Robot Controlled by Raspberry Pi

Mext, I created a simple script in Scratch to make the robot move forward, turn around and then come back again. First, you need to create some variables for the outputs. Create two variables called piface-output1 and piface-output2, you can then use these to control the two motors. This is the full script:

Scratch Script

Scratch Script

Simple as that!

Here is a video of it in action:



  |  3 Comments


MythTV Tips: Auto Restart Script

Posted on February 25, 2012 by Adam under MythTV, Ubuntu

MythTV has got a lot more stable in recent releases, but I have found that there is still occasional crashes, with MythMusic being the main offender. I have found that if you pause a song as it is just about to end, it invariably hangs and needs to be restarted. To do this I use the “power” button on my remote to kill mythtv, and use another script to automatially restart it.

To kill mythtv you will need irexec installed, then you can add the below to your ~/.lircrc file:

begin
    remote = mceusb
    prog = irexec
    button = KEY_POWER
    config = /usr/bin/pkill mythfrontend
    repeat = 0
    delay = 0
end

So far so good, but we need to make mytvtv restart itself too. I am sure there are many ways of doing this, but I settled on a utility called daemontools. You can install daemontools and daemontools-run from the Ubuntu repositories.
Create an /etc/service/mythfrontend directory, and within that directory create a script called “run”:

#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MYPROCESS=/usr/bin/mythfrontend

if [ -x $MYPROCESS ]
then
        su -c /home/adam/Scripts/startMyth.sh adam
fi

I keep the actual startup script in the scripts directory in my home folder for ease of maintenance – this is the script:

#!/bin/bash
export DISPLAY=:0.0 && /usr/bin/mythfrontend 
   -l /var/log/mythtv/mythfrontend.log

As soon as you make the /etc/service/mythfrontend/run script executable (chmod +x run), mythfrontend should start. There are some more tips on using daemontools here.
I use a similar script to automatically restart “irexec” if it crashes. Create an /etc/service/irexec directory, with a “run” script:

#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

if pidof -x /usr/bin/irexec > /dev/null; then
        # Do nothing - already running
        echo ""
else
        su -c /home/adam/Scripts/startIRExec.sh adam
fi

And the startIRExec.sh script:

#!/bin/bash
DISPLAY=:0 ~/.local-display-coordinates.sh
DISPLAY=:0 irexec

In recent versions of Ubuntu there has been some changes to the way that scripts can connect to the active X session, so the line at the start of this script:

/home/adam/.local-display-coordinates.sh

calls a script that is generated automatically when the X session starts. This is created by adding the following to your ~/.profile script:

case $DISPLAY in
  :*) export | grep -E ' 
  (DISPLAY|XAUTHORITY)=' 
  >~/.local-display-coordinates.sh;;
esac

This is based on the advice on this page.



  |  Leave a comment


MythTV Tips: Universal Volume Control

Posted on by Adam under MythTV, Ubuntu

I have done a fair bit of tinkering with my MythTV box over the last year or two, and I thought I would share a couple of handy tips with the world.

One of the things I always found annoying about MythTV was the fact that I could not alter the volume unless I was in the music or video playback screens. Myth allows you to keep music playing in the background, for example while you browse some news feeds in MythNews – but if you do this you can no longer alter or mute the volume, which is annoying…

To get around this I decided to ditch Myth’s own internal volume controls and create a script that can alter the master volume control directly. This can be launched directly as a result of keypresses on the remote control thanks to a handy app called irexec. This allows me to control the volume even if MythTV is not running.

So, to begin with we need a script to alter the volume. The other problem is that we want to have some visual indication of the volume level as we alter it, so we need to use an OSD (On Screen Display) library of some sort. Initially I used the gnome notification library that ships with recent gnome versions, but I had a strange issue with it not updating quickly enough if I send a few updates in quick succession, so I tried a few others. In the end I settled on osd_cat. The script is loosely based on this one:

#!/bin/bash

/home/adam/.local-display-coordinates.sh

#####################
# Config
CHANNEL='Master'
FONT='10x20'
DELTA_VAL_UP=3+
DELTA_VAL_DOWN=3-

####################
# Code
action=$1; shift

# Unmute the volume and increase/decrease it
# Arg 1: volume change to set (1+ or 1-)
set_volume() {
    amixer sset $CHANNEL unmute &> /dev/null &
    volume=$(amixer sset $CHANNEL $1 unmute | 
             grep "Mono: Playback" | 
             grep -o "[[0-9]*%]" | 
             tr '[%]' ' ')
}

# Get the current volume %
# No args
get_volume() {
    volume=$(amixer sget $CHANNEL | 
             grep "Mono: Playback" | 
             grep -o "[[0-9]*%]" | 
             tr '[%]' ' ')
}

# Toggle Master volume mute on/off
# No args
mute_volume() {
    status=$(amixer sset $CHANNEL toggle | 
             grep "Mono: Playback" | 
             grep -o "[on]|[off]" | 
             tr '[]' ' ')
}

show_volume() {
    killall -9 -q osd_cat
    (osd_cat --font="$FONT" --shadow=1 --color=green 
    --pos=bottom --align=center --delay=2 
    --text "$( [ "z$2" = "z" ] && 
    echo Volume: $1% || echo $2 )" 
    --barmode=percentage --percentage=$1 )&
}

case "$action" in
    show)
        get_volume
                show_volume $volume
        ;;

    up)
        delta=$DELTA_VAL_UP
        set_volume $delta
        show_volume $volume
        ;;

    down)
        delta=$DELTA_VAL_DOWN
        set_volume $delta
        show_volume $volume
        ;;

    mute)
        mute_volume
        case "$status" in
            off)
                show_volume 0 "Muted"
                ;;
            on)
                get_volume
                show_volume $volume
                ;;
        esac
        ;;
    *)
        echo "Usage: $0 {up|down|mute|show}"
        ;;
esac

In recent versions of Ubuntu there has been some changes to the way that scripts can connect to the active X session, so the line at the start of this script:

/home/adam/.local-display-coordinates.sh

calls a script that is generated automatically when the X session starts. This is created by adding the following to your ~/.profile script:

case $DISPLAY in
  :*) export | grep -E ' 
  (DISPLAY|XAUTHORITY)=' 
  >~/.local-display-coordinates.sh;;
esac

This is based on the advice on this page.

You can test your script by running it from an xterminal using ./setVolume.sh up or ./setVolume.sh down to alter the system volume. You should see the volume displayed at the bottom of the screen in green.

The final step it to configure lirc to run your script when the volume buttons are pressed.
Make sure you have irexec installed, and add it to your startup applications so that it is always running (I will do a subsequent post about auto-restarting mythtv which will also cover auto-restarting lircmd in case it crashes).
You can now edit your .lircrc file to launch you script using irexec when the volume keys are pressed – add the following to your .lircrc file:

begin
    prog = irexec
    button = KEY_VOLUMEUP
    config = /home/adam/Scripts/setVolume.sh up
    repeat = 2
end
begin
    prog = irexec
    button = KEY_VOLUMEDOWN
    config = /home/adam/Scripts/setVolume.sh down
    repeat = 2
end

Make sure you remove the existing mythtv volume entries so you don’t end up controlling both volume controls whenever you press the button on the remote.
Restart lircd, and hopefully everything should work! You may have to restart your gnome session to make sure the script is able to pick up the active X session correctly.



  |  1 Comment


Multi-room audio (the easy way)

Posted on July 3, 2010 by Adam under Uncategorized

I have a mythtv box in the lounge that I use for playing music and videos, but for a while now I have been looking into ways of extending the audio into additional rooms in the house (primarily the kitchen). I looked into running speaker cables (or a fibre optic cable) across the room but didn’t want to start pulling up the carpet or having unsightly wires everywhere, so I started looking into other options. I looked into software options using my existing powerline or wireless network, but with all of them there were synchronisation issues – the overhead of network streaming means getting the audio in the lounge and kitchen sychronised was impractical.

Then I stumbled on a much simpler option. I already have a good quality DAB and FM radio in the kitchen. It occurred to me that I could use an FM transmitter like the ones used in cars for mp3 players to transmit audio to the car radio. I found a basic FM transmitter on amazon for £6.99 – link.

I didn’t want to run it on batteries, and obviously I don’t have a cigarette lighter socket behind my PC, so I cut the cigarette lighter plug off the end of the cable and replaced it with a USB plug from Maplin for £1.39 – link. You can use this page to find out which pins provide the 5v output – the transmitter works fine on 5v.

FM Transmitter

Then, all I had to do was plug a splitter into the audio output from the myth box so it feeds into the speakers in the lounge as well as the FM transmitter. It works like a charm now and the music is perfectly in sync between the lounge and kitchen. Range is pretty good too – I can even tune in the radios upstairs and listen in there too!



  |  Leave a comment


Open source desktop search – and indexing Freemind maps

Posted on December 11, 2009 by Adam under Java

I am always keen to investigate open source solutions to everyday problems I face, and my preference is for apps that run in a JRE. This is for two primary reasons:

  • They don’t generally require “installing” by which I mean I can use them on a windows machine without requiring admin rights or permission to update the registry
  • They are portable, so once I have figured out how to best use them to support my day-to-day tasks, I can easily transfer that solution to my Linux PC or Windows laptop

I have been using Freemind for organising all my notes as mindmaps for some time, and I am very pleased with it.

Another area I have been looking into recently is desktop search. The basic offerings in Linux are generally very good, but the Microsoft search solutions are very poor in comparison. I have used Google desktop before – which is very good, but it doesn’t meet the criteria above. To that end I did a bit of searching, and came across a nice pure java desktop search application called DynaQ. It uses various other best-of-breed java libraries to do the extraction and indexing, so is a very powerful search tool. It makes use of Catweasel and Aperture to trawl files and extract content, then uses Apache Lucene for indexing.

One problem I did come across however was that DynaQ did not seem to index my Freemind mind maps. After a bit of digging I discovered that this was because when Freemind saves it’s maps it does not include the standard XML header at the start of the file to identify it as an XML file. As a consequence, when Aperture looks at the file it cannot identify what type of file it is, and does not index it.

There are a few simple steps to remedy the problem:

  • Go to the DynaQ config directory and extract the contents of the apertureMimeConfiguration.xml.jar file
  • Edit the apertureMimeConfiguration.xml file, and amend the content of the XML section so it looks like this:
  • <description>
      <mimeType>text/xml</mimeType>
      <extensions>xml,xsl,xslt,wml,mm</extensions>
      <magicString>&lt;?xml</magicString>
      <magicString>&lt;map</magicString>
    </description>
    
  • Re-add the file to the jar and put it back in the config directory
  • Re-index the directory containing your Freemind files. NOTE: If the directory had been indexed previously you will probably need to update the timestamps on the files to force the indexer to re-index them

You should now be able to search on the contents of your mind maps.



  |  Leave a comment


Random Freezing in Amarok, Banshee, Rhythmbox

Posted on June 19, 2009 by Adam under Ubuntu

I am a big fan of Amarok – as a music application I think it is the best there is (much better than iTunes).

I have for some time however had problems with it freezing up on a regular basis. It seemed to happen with no particular pattern, even if I opened the application and left it on screen without playing any music or touching the mouse or keyboard, after a few minutes it would freeze up. It generally didn’t freeze for very long – maybe 10 seconds or so, but seemed to be doing it quite regularly every few minutes.

I eventually got so fed up with it that I tried switching to Banshee, but had exactly the same issue. I then tried Rhythmbox and had the same issue yet again, so decided it had to be a common library in Ubuntu rather than the apps themselves.

I have tried various things to get to the bottom of the problem. I stumbled across quite a few posts relating to issues with ESD (Enlightenment Sound Daemon) causing problems in all sorts of applications, but switching to OSS or ALSA didn’t seem to improve matters.

So, for now I have still not found a solution – please let me know if you have any suggestions!



  |  1 Comment