Archive for Uncategorized

Fixing the foam pads on a trackball

Problem: the trackball scratches my graphics tablet!

Solution: foam crafty adhesive shapes.

Fixed! It’s a bit slippery, but I’ll get used to it.

Leave a Comment

Drive an Arduino from a mobile phone wirelessly

A while ago I had the idea of using cheap bluetooth modules to operate an Arduino from a mobile phone, thus saving the expense of an IOIO board (or similar).  I purchased the module, but it didn’t arrive during a period of unemployment and I never got around to doing anything with it.

Someone beat me to it.

I’ll have to give it a go one day.  This will save me the trouble of doing it myself!

I wasn’t sure whether a slave device would be fine, or whether I’d have to get the bluetooth module running in master mode.  Someone has found out how to upload different firmware versions, to allow  master mode in these devices.

Leave a Comment

A very cheap AVR dev board

I bought one of these boards for about $4 on eBay.  It’s based on the USB ASP – a cheap AVR programming board.  I remember seeing a post on Hack A Day a while ago about using them as a general purpose dev board, with 5 lines broken out to the black pin header.  By removing a link on the bottom of the board, you can get 3.3V from a regulator.

First I wanted to see what the stock firmware was.  I shorted J2, which connects the reset pin to the header pins, allowing the chip to be programmed.  I dumped the data, and saw this:

00000000  00 00 01 01 02 02 03 03  04 04 05 05 06 06 07 07  |................|
00000010  08 08 09 09 0a 0a 0b 0b  0c 0c 0d 0d 0e 0e 0f 0f  |................|
00000020  10 10 11 11 12 12 13 13  14 14 15 15 16 16 17 17  |................|
00000030  18 18 19 19 1a 1a 1b 1b  1c 1c 1d 1d 1e 1e 1f 1f  |................|

It sounds like that’s what you get when the chip is locked.  I used avrdude to erase the chip, and I was able to program it again using the original firmware from the USB ASP site.  I had a quick look at the fuse bits, and they seem to be correct.  I haven’t actually tried this firmware, so no doubt some of the pins are in different places.

The pinout appears to be the same as the original. The pins themselves are different because of the chip packaging:

D+ 13, 32 PB1, PD2 (INT0)
D- 12 PB0
RST 14 PB2
SCK 17 PB5 (SCK)

The price is amazing since the AVR stick costs about $10, and contains fewer parts.  Perhaps I should retry my V-USB experiment with it.

A while ago I found some V-USB tutorials, but I haven’t gone through them yet.

Comments (1)

Add a caption to a JPEG image without reencoding

I was looking for a way to add captions to JPEG images without re-encoding them.  It turns out there’s a patch to jpegtran that overlay one JPEG image over another one, without re-encoding either.  Here’s how I built it:

  1. Download the sources of the IJG version of jpegtran (I used version 8c), and decompress it somewhere
  2. Download the “drop” patch, and copy the source files into the source extracted in the previous step
  3. configure, make (as usual)

I made a script that automatically adds a label using Imagemagick to create the label, and this version of jpegtran to put them together:



if [ $# -lt 3 ] ; then
echo "Usage: jpeglabel [label] [in] [out]" >2
exit 2

convert -type truecolor -size 256x16 "label:$1" jpg:"$LABELFILE"
"$JPEGTRAN" -drop +16-16 "$LABELFILE" -outfile "$3" "$2"


I tried making some examples to show, but it turns out the (experimental) “drop” patch is very fussy about the files you give it.  I got it to work on 320×240 pictures from my camera, but not on some other images I tried.  It requires the “sampling ratio” to be the same on both images, which is found in the advanced JPEG settings in Gimp.

Leave a Comment

Run a V-USB demo on an AVR stick (Easylogger)

This article describes how to run one of the V-USB demos on an AVR stick (which is an Easylogger clone).

V-USB is a firmware-only USB implementation for AVR 8-bit microcontrollers.  This means that it’s possible for most AVR chips to communicate via USB, even though they have no hardware support for that.

The AVR stick

The AVR stick is a tiny circuit board that contains the minimum components to get a somewhat useful USB device, based on an ATmega85.  It costs about $10, and is available in Australia from Little Bird Electronics and also from Sparkfun.

I’ll use the USB HID class, because it doesn’t require any fancy drivers to get running.

First, grab the V-USB code, (I’m using version 20100715), and extract the /examples/hid-custom-rq directory somewhere.

Let’s get the firmware working first.  The AVR stick works a bit differently to the circuit the demo is for, so we need a few changes.

The ATmega85 only has one port: port B.  The sample uses port D.  Edit these lines in /firmware/usbconfig.h:

#define USB_CFG_DMINUS_BIT      0

The LED is on PORTB1, not PORTB0, so change /firmware/main.c:

#define LED_BIT             1

Finally, we need to change the Makefile to match the ATmega85:

DEVICE  = attiny85
F_CPU   = 16500000

Where does 16500000 come from? The AVR stick uses the internal RC oscillator for its clock, which runs at about 8MHz.  The problem is, V-USB needs a clock speed of at least 12MHz to run.  ATmega5s have a fuse setting which doubles its clock speed (they call it the PLL clock or something like that).

While the internal RC clock is fairly stable, it’s not very accurate.  When V-USB starts, it uses the USB signal to calibrate the clock so it runs at the same speed as the USB bus.  Using this calibration, it’s possible to run the internal clock at 8.25MHz, which is doubled to 16.5MHz.  This is the speed the AVR stick must run at.

Since I was using the Bus Pirate to program the AVR stick, I had to change the AVRDUDE= line also.

That was it for the firmware – hopefully it compiles and uploads to the AVR stick.

Now for the software that runs on the computer.  When I compiled and ran ./set-led on, I got this message:

Could not find USB device "LEDCtlHID" with vid=0x16c0 pid=0x5df

but when I ran lsusb, I saw this line:

Bus 002 Device 023: ID 16c0:05df VOTI

“VOTI” doesn’t match “LEDCtlHID”, no wonder it couldn’t find it!  But when I ran sudo lsusb -v, I saw this instead:

iProduct                2 LEDCtlHID

OK, so “VOTI” is simply the string form of the USB vendor ID 0x16c0, and the name “LEDCtlHID” is correct after all.  What’s going on then?

I noticed that the usbOpenDevice function takes a few file descriptors, of which the final one is called warningsFp.  This is called from set-led.c; perhaps I’ll change this last parameter from NULL to stderr.

When I ran ./set-led on again, I got this:

Warning: cannot query manufacturer for VID=0x16c0 PID=0x05df: error sending control message: Operation not permitted

That’s a slightly more useful error message!  So the USB library doesn’t seem to be able to use the device.  I read that some USB devices appear under /dev/usb, so let’s have a look with ls -l /dev/usb:

crw------- 1 root root 180, 96 2011-12-14 22:50 hiddev0
crw------- 1 root root 180, 97 2011-12-16 21:33 hiddev1

Maybe that’s the problem – there’s no write permissions on the device.  To fix this, I’ll make this device writable by everyone.  Create the file /etc/udev/rules.d/90-avrstick.rules, and put this in it:

SUBSYSTEM=="usb", DEVTYPE="usb_device", SYSFS{idVendor}=="16c0", SYSFS{idProduct}=="05df", MODE="0666"

then sudo reload udev.  Remove the stick then put it back in, then look at /dev/usb again:

crw------- 1 root root 180, 96 2011-12-14 22:50 hiddev0
crw-rw-rw- 1 root root 180, 97 2011-12-16 21:42 hiddev1

That’s a bit better.  Now run ./set-led on – the white LED on the AVR stick should come on!

There’s one improvement I can think of – the C code is pretty ugly, so I had a go in Python.  I copied the USB calls from the C code.  The Python code follows:

import sys
import usb
import itertools

vid=0x16C0; pid=0x05DF;

devs = itertools.ifilter(
    lambda dev: dev.idVendor==vid and dev.idProduct==pid,
    (dev for bus in usb.busses() for dev in bus.devices)

if len(sys.argv) == 1:
    print 'Specify "on", "off" or "status"'
op = sys.argv[1]

for dev in devs:
    #print "Handling device %04x:%04x" % (dev.idVendor, dev.idProduct)
    handle =
    if op == "on" or op == "off":
            usb.TYPE_VENDOR | usb.RECIP_DEVICE | usb.ENDPOINT_OUT,
            1, # = CUSTOM_RQ_SET_STATUS
            [], # Empty payload - the data goes in the "wValue" field
            value = (op == "on" and 1 or 0 )
        data = handle.controlMsg(
            usb.TYPE_VENDOR | usb.RECIP_DEVICE | usb.ENDPOINT_IN,
            2, # = CUSTOM_RQ_GET_STATUS
            1, # How many bytes to read
        print "LED is " + (data[0] and "on" or "off")

That’s much shorter than the C code, and does the same thing (admittedly there’s much less error handling here).  I used the pyusb library version 0.4.2.  The documentation for this library is a bit thin, but I found the Python command “help(usb)” of some use, as well as the source code for the library.

Talking to the USB device is all using Control signals, which I think you need to do because it’s pretending to be an HID device.  I found it interesting that they never send data to the AVR stick – they send the desired LED status in the “wValue” field, which sounds like a 16-bit field that’s in every control message.  I don’t know much about USB, but conveniently copying the C code worked fine.

Leave a Comment

How an electric kettle knows when the water is boiling

My cheap kettle leaked.  You couldn’t press the lever down when it wasn’t on the base, so I hoped to find an electromagnet which held the switch on when it had power.  I didn’t find one (I only managed to salvage two neon lights from it), but I found out how kettles switch off when they’re boiling.

The steam is collected by this hood, which sends it down the tube into the base.

The steam then enters the base of the kettle through the hole at the bottom of this picture, where it’s deflected onto this disk.

The disk flexed when I pressed in the middle.  The part that sticks out pressed against the lever that switches the kettle on and off.  I guess that as the disk heats and expands, it flexes in the same way.

The lever that operates the kettle is like a large microswitch, in that it always snaps to one side or the other, and takes little force to change.  The disk flexes and presses lightly on the lever, but it’s enough force to trip the switch so the kettle turns off.

I didn’t find the electromagnet I was looking for.  Instead, whether the lever stays down depends on whether the kettle is sitting on its base.  If not, a pin with a strong spring on it protrudes from the bottom of the kettle.  The spring prevents the lever from staying down.

Leave a Comment

Laser printer mirror hacking

I pulled the mirror out of a laster pinter, and I had a go making it work.

I’d seen an article before that does this, but I had a datasheet for the driver chip.  Conveniently all of the pins I needed had test points on the board – that saves me having to attach something to the original plug.

It was pretty easy to drive – apply 12V, put a square wave on CLK and pull SS low.  The datasheet says that 5V is fine for the clock signal.  Apparently LD changes state once the mirror is up to speed.  The laster started spinning at 50Hz, but ran a bit rough below 500Hz.  It didn’t get any faster once the signal was at 5kHz.

To test out the relationship between the mirror and the clock signal, I made an Arduino flash a light 6 times for each clock pulse.  I saw 6 reflections in the mirror, so I guess the mirror spins 1/6 of a resolution for each clock pulse.

I tried running it at 5V, but I had no luck there.

Comments (1)

Repartitioning a computer with four primary partitions

I recently bought a HP Pavilion DM1 with Windows 7 on it. I’m obviously not happy just having Windows on it, so I have to repartition the hard disk. The problem is that it came with four primary partitions from the factory. These are:

  1. A boot partition
  2. The main parition
  3. A recovery partition
  4. A HP Tools partition

I’d like to touch only the main partition, leaving the others intact, so the recovery and tools still work.

I took an image of the disk before I booted Windows for the first time. I’d like to move the main partition into an extended partition. The plan is to shrink the boot partition slightly, leaving some room for an extended partition header for the main partition. Then I’ll add a logical partition in the same place the main partition is. Then I’ll see how happy Windows is.

Here’s sfdisk -d at the moment:

unit: sectors

/dev/sda1 : start=     2048, size=   407552, Id= 7, bootable
/dev/sda2 : start=   409600, size=121634816, Id= 7
/dev/sda3 : start=463384576, size= 24799232, Id= 7
/dev/sda4 : start=488183808, size=   211312, Id= c

I’ll fire up parted, and try to resize the boot partition:

GNU Parted 2.2
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) unit cyl
(parted) p
Model: ATA ST9250315AS (scsi)
Disk /dev/sda: 30401cyl
Sector size (logical/physical): 512B/512B
BIOS cylinder,head,sector geometry: 30401,255,63.  Each cylinder is 8225kB.
Partition Table: msdos

Number  Start     End       Size     Type     File system  Flags
 1      0cyl      25cyl     25cyl    primary  ntfs         boot
 2      25cyl     7596cyl   7571cyl  primary  ntfs
 3      28844cyl  30388cyl  1543cyl  primary  ntfs
 4      30388cyl  30401cyl  13cyl    primary  fat32        lba

(parted) resize 1 0cyl 24cyl
WARNING: you are attempting to use parted to operate on (resize) a file system.
parted's file system manipulation code is not as robust as what you'll find in
dedicated, file-system-specific packages like e2fsprogs.  We recommend
you use parted only to manipulate partition tables, whenever possible.
Support for performing most operations on most types of file systems
will be removed in an upcoming release.
No Implementation: Support for opening ntfs file systems is not implemented yet.

I didn’t notice the boot partition is NTFS!

ubuntu@ubuntu:~$ sudo ntfsinfo -m /dev/sda1
Volume Information
        Name of device: /dev/sda1
        Device state: 11
        Volume Name: SYSTEM
        Volume State: 1
        Volume Version: 3.1
        Sector Size: 512
        Cluster Size: 4096
        Volume Size in Clusters: 50943

So the filesystem is 208662528 bytes long. I want it 24 cylinders, which is 8225280 (according to fdisk) × 24=197406720.

ubuntu@ubuntu:~$ sudo ntfsresize --size 197406720 /dev/sda1

I’ll copy the output of sfdisk -d, then update the size of sda1 to 197406720÷512=385560 sectors:

/dev/sda1 : start=     2048, size=   385560, Id= 7, bootable

Now to change sda2 to be the extended partition – observe that sda2 only takes up about 1/4 of the available space – it must get resized when Windows starts. I’ll subtract 63 sectors from the start to make room for the new sda5 header, then make the end right before sda3. Then I’ll change the partition type to 5.

/dev/sda2 : start=   409537, size=462975039, Id= 5

I’ll put the Windows partition back as sda5:

/dev/sda5 : start=   409600, size=121634816, Id= 7

Now it’s the moment of truth:

ubuntu@ubuntu:/tmp$ sudo sfdisk -uS /dev/sda < sfdisk
Checking that no-one is using this disk right now ...

Disk /dev/sda: 30401 cylinders, 255 heads, 63 sectors/track
Old situation:
Units = sectors of 512 bytes, counting from 0

   Device Boot    Start       End   #sectors  Id  System
/dev/sda1   *      2048    409599     407552   7  HPFS/NTFS
/dev/sda2        409600 122044415  121634816   7  HPFS/NTFS
/dev/sda3     463384576 488183807   24799232   7  HPFS/NTFS
/dev/sda4     488183808 488395119     211312   c  W95 FAT32 (LBA)
New situation:
Units = sectors of 512 bytes, counting from 0

   Device Boot    Start       End   #sectors  Id  System
/dev/sda1   *      2048    387607     385560   7  HPFS/NTFS
/dev/sda2        409537 463384575  462975039   5  Extended
/dev/sda3     463384576 488183807   24799232   7  HPFS/NTFS
/dev/sda4     488183808 488395119     211312   c  W95 FAT32 (LBA)
/dev/sda5        409600 122044415  121634816   7  HPFS/NTFS
Warning: partition 1 does not end at a cylinder boundary

sfdisk: I don't like these partitions - nothing changed.
(If you really want this, use the --force option.)

Hmm, I don’t think it ended on a cylinder boundary before either! I’ll take a gamble – I can restore from the image if I need to – so I’ll use --force.

I’ll check that everything looks OK with the main parition:

ubuntu@ubuntu:/tmp$ sudo dd if=/dev/sda bs=512 count=100k skip=$((409600 - 63)) | hexdump -C | less

I can see the partition signature at offset 1fd as expected, and the partition at offset 7c00 – right at the start of the 63rd sector. It looks good!

To be safe, I’ll force Windows to check it:

ubuntu@ubuntu:/tmp$ sudo ntfsfix /dev/sda5

Now I’ll reboot and hope for the best!

It’s checked the disks and is “preparing your computer for first use”…

… and everything starts fine! Windows did expand the partition to fill the remaining space, but I can shrink it again later. It also claims that I left 11 MB unallocated between the boot partition and the extended partition, but that’s no big deal. The recovery partition and the HP tools still seem to work too.

Leave a Comment

Find the progress of a command

If you’re running some command that takes a while, perhaps compressing a large file, you often want to know how far along it is. This is when the /proc/pid/io file is useful.

I might have a bzip2 process running with PID 3722, so /proc/3722/io might look like this:

rchar: 1791093411
wchar: 224891624
syscr: 1308428
syscw: 2992919
read_bytes: 250478592
write_bytes: 183074816
cancelled_write_bytes: 0

The most useful are “rchar” and “wchar” – the number of bytes read and written by this process.

The kernel documentation tells you more about this file.

Leave a Comment

Download the packages for an offline Ubuntu upgrade

Well, not really offline since you’ll still have to download some files, but not all of the packages. Use this for computers with limited internet quota. I’m sure this could be done in a single script with some awk-fu.

  1. Produce a list of your current package selections:
    dpkg --get-selections | awk '{ print $1 }' > selections
  2. Get the package lists:
    for s in lucid/main lucid/multiverse lucid/restricted lucid/universe \
            lucid-updates/main lucid-updates/multiverse \
            lucid-updates/restricted lucid-updates/universe ; do \
        wget -c "$s/binary-i386/Packages.bz2" \
            -O Packages_${s/\//_}.bz2 ; \

    This grabs the package lists in filenames like this:

  3. Extract the filenames from these package lists:
    for f in Packages*.bz2 ; do bzcat $f | awk '
    /^Package/ { package=$2 } 
    /^Filename/ { print package "\t" $2 } 
    ' > ${f%%.bz2}.filenames ; done
  4. Produce a list of all filenames, making sure the updates get precedence over the other ones:
    cat `ls -1 Package*.filenames | sort` | awk '
    { files[$1] = $2 }
    END {
      for (p in files) print p "\t" files[p]
    }' | sort > all.filenames
  5. Produce a script of your selections:
    awk '
    BEGIN { while (getline < "all.filenames" != 0) filenames[$1] = $2 }
    { if ($1 in filenames) print "wget -c" filenames[$1] }
    '  < selections > downloads
  6. Take the file downloads to another computer, and run it:
    sh downloads
  7. Take the downloaded files back to the offline computer, copy the files to /var/cache/apt/archives, then do-release-upgrade.

You could probably save more quota by renaming the Package files and copying them to /var/lib/apt/lists.

Leave a Comment

« Newer Posts · Older Posts »