Code (21)

PCIDevices Update

  • March 7, 2012
  • C, Code, ...

Fixed some bugs in the files I posted before, and included the commented-out sections.

Again, if anyone does anything interesting with this, let me know!


Internet Radio – Part 2

  • February 1, 2012
  • C, Code, ...

I said I would put some more photographs of the clock, so here we go. These were taken after the radio board and power connectors were completely removed.

The clock module is entirely mechanical, save for the constant-speed motor that ran the mechanism (now defunct, and 110v, yeesh.) but doesn’t it look nice!

The front of the clock module through the plastic cover

The dial on the left is the alarm rotor, which is a simple stepped cam triggering a microswitch on the back of the module – see the later photographs. The split-flap digits are perfect, no damage at all, and the action is smooth and constant.

The sleep timer, which rotates a cam past a second microswitch.

The Sleep timer rotates a small cam against a second switch on the top of the module. Nice! I spy an interrupt pin input!

The back of the clock module, showing the alarm microswitch and the back of the alarm display spindle

The alam rotor moves the metal arm shown on the right of the photograph above, and triggers quickly at ‘alarm time’ then slowly re-presses the arm against the switch over the course of approximately an hour, I spy another interrupt!


The switches along the top of the radio

The switches along the top of the radio are simple nPnT type, one with four position – the On/Off/Wake to music/Wake to alarm switch – and the other with two positions – the current AM/FM switch.

The four position switch will remain unchanged, both in function and device, but the AM/FM switch is obviously redundant now, and I will *probably* repurpose that as a stream/saved selector.

The switches actuate small plates behind the front panel with white markers in appropriate places.

The front panel includes a thin section along the top above the tuning gauge containing various basic indicators, composed of holes in the front panel with a sliding plastic indicator with white splotches at the appropriate position.

It is my intention to keep this top section intact for the final build, (as it covers the back of the switches!)  and all but two of the indicators make sense for the final build’s features.

The rest of the case is wholly uninteresting, and is mainly open space, leaving plenty of room for new electronics, and currently only contain the new power socket (a basic barrel-jack socket and two wires hot-glued in place over the existing grommet hole for power) and a medium-sized speaker with no markings (which will be investigated in a future post).

Until next time.

Internet Radio – Part 1

I recently started working on a project I’ve been meaning to do for a long time.

I listen to a lot of internet-based radio stations, mainly Shoutcast or Icecast stations, and tend (at the moment) to do this on my phone, as I can leave it on the bedside table and listen with it charging.

But the sound quality from such a tiny speaker is… well… terrible, to be honest. While phone manufacturers are getting better at building half-decent speakers into their devices, they simply cannot compete with the much better dynamic response of a larger speaker, so the want for a better device to play music arose.

Further to this, my Fiance really hates my current alarm clock, (which displays time in binary, octal, roman numerals and boring old normal decimal) due to it’s hideous alarm, and having attempted to remedy this by cracking the case to see what could be done, I gave up due to the components mainly being surface mount and resin-blob type :'(

So. Half-decent sounding clock radio, that satisfies the Fiance-test and actually wakes me up. That doesn’t exist! Time to build it then!

I’ve started with a donor clock-radio, as shown here:

The donor clock-radio, how innocent it looks here, so unsuspecting...

It has a split-flap display! Excellent! (I love these things, and miss them from stations – they had a nice self-announcing quality as the noise they made when refreshing caught everyone’s attention without being irritating… but I digress) and the large tuning area to the right is perfect for a display of some variety!

The existing electronics were dead-on-arrival, so have been discarded (I wouldn’t feel right removing working parts from a ‘vintage’ radio) along with the 240v gear motor for the split-flap display. The power cord and connector were also discarded, and replaced with a barrel-jack socket on the back (photo tomorrow) ready for the 5v mains power adapter to drive the new electronics.

The existing speaker has been kept for the moment, until I build the amplifier I won’t know how good the sound is, but it is easy to remove, and the area it covers is easily large enough (and the new electronics small enough) to support larger drivers if required.

Unfortunately I didn’t have my camera with me during the disassembly, but photographs will be taken tomorrow and appended to this post.

So… it begins.

Enumerating PCI Devices

In a fit of ‘getting stuff done’ at 6am today, I wrote a basic PCI enumeration class, allowing my research OS to display what it has found along the PCI bus.

QEMU diplaying a list of PCI devices and their respective ID's

Acinonyx Jubatus running in QEMU, displaying the connected virtual PCI devices.

The actual enumeration itself is pretty straightforward, just a bit of indirect addressing and you get a nice structure back (sequentially) with the vendor and device IDs.

The awkward part was gleaning any meaning from those – obviously I can match an ID to a driver, but it’d be nice to output some human readable stuff so that we show that specific hardware has been recognised.

VirtualBox's PCI devices enumerated in my research OS

To this end, I enlisted the help of which provide an open list of PCI device and vendor IDs, as well as a C header (yay!).

Except that I’m using C++, and a fairly trimmed-down version of C++ at that, with the String libraries missing (I haven’t written them yet!) so the header won’t work without modification.

Thus, after many a minute of search/replacing, I’ve altered the header into a object/header pair (to avoid linker errors) that works with a stripped-down compiler.

In case this is useful for anyone else (god knows who) I’m attaching it here – PCIDevices.tar.gz – do let me know if anyone finds any use for it! I’d love to know what for…



Allocation and Deallocation Times for Varying Size Chunks

Black-box profiling the Linux memory manager


I’ll just leave this here…

A massive rocky outcropping

Avatar-Style Worlds in Minecraft


Having had my feet wet a little with Android development, I decided to have a go at a bigger project – hence; uLaunch.

uLaunch is a very basic home screen replacement, with the intent to design for usability rather than fancy graphics (Oh, and I suck as an artist!).

Anyway – progress on Rev.0 continues thus:

Android ‘R’ Class

Just putting this up here in case anyone else falls into the trap I just did.

If you’re writing an Android application, and add a new Activity, you might want to refer to a generated class (from XML) using the ‘R’ class.

In Eclipse, it automagicly imports “android.R” as soon as you use it to attempt to access R.layout for a setContentView( R.layout.something ) call – this then breaks the class!

This is because the class is included as part of your project, but can be accessed via static calls from the Android API, causing a fun name conflict.

Simple workaround – remove the import line! Then your local copy will be used over the static methods of the class described in the API, fixing the issue.


Written for part of my university coursework, so vaguely well structured for once!
It can be downloaded here: GA.tar.gz
What follows is taken directly from the included readme.txt.

This program attempts to solve the Travelling Salesman problem using
a Genetic Algorithm approach.

The basic sequence of events is as follows (omitting special cases and
display code of any kind);

generation = new RandomGeneration( size );
    iteration = 0;
    while( iteration < maxGenerations ){
        Perform ERO on quads from top half of ‘generation’.
        Randomly select ‘n’ children{
            For each child{
                Randomly swap city positions in its genome ‘X’ times.
        //Sort the generation by path length (shortest first)
        if( not changed in X generations )

If the ‘–attempt_autocorrection’ (or -ac) flag is set upon starting the
program, the following sequence is executed immediately following the
mutate stage;

//Child Mutate
    Randomly select ‘n’ children{
        For each child{
            Randomly swap city positions in its genome ‘X’ times.

In this implementation, genes are stored as array offsets, allowing very
fast manipulation of data without extensive memory access.
Additionally, this allows modifications to the agents to be made without
details on the search space, allowing very generic representations of

Edge Recombination is used to breed new agent sequences from a
pair of parents. This has the advantage of only creating offspring
which are very similar to their parents, keeping ‘good’ sequences in the
gene pool and allowing them to spread to other agents genome in the next
breeding cycle.

The Edge Recombination Operator (ERO) is defined thus;

For each parent{
        Generate adjacency matrix for their genome.
    Combine the matrices to one, removing any duplicated entries.
    Start from a parent‘s first point.
    Remove all instances of the current point from the matrix
    While( Matrix not empty ){
        if( Points exist on this row )
            Select next point from matrix.
            Choose a random point on the matrix.
        Remove all instances of the current point from the matrix
    Return new child( from points );

Selection is simple, the entire generation is ordered by how close to
zero they are, and the bottom half are removed. The top half then breed
with their ‘rightmost’ neighbours, stepping twice for each breed
( 1&2&3&4, 3&4&5&6, 4&5&6&7, etc. ) and populate the generation with
pairs of children.

Once they have bred, the breeders then move into the next generation
themselves, such that they can persist unless better candidates are

The algorithm will exit if the best solution has not changed in a set
number of generations, as determined by the –stagnate (or -st)

While this is not a brilliant metric for completion, it works most of
the time as the GA tends to plateu after a while as the probability of
it finding a better solution reduces the closer it gets to the perfect


With javac and javadoc on your PATH, simply calling;


which will generate both the binaries and the java documentation in
./bin and ./docs respectively.

To perform a clean build;

make clean && make

Logs of example runs can be found in ./logs, and are stored such
that the short parameter names follow their values; ie.

150 agents, 25 cities = 150a25c.txt
300 agents, 100 cities = 300a25c.txt

Logs are in CSV with the column order of:

Best Length
Worst Length
Average Length
SteveScore Best
SteveScore Worst
SteveScore Average

USAGE: java GeneTest
            [–width=X | -w=X]
            [–height=X | -h=X]
            [–agents=X | -a=X]
            [–cities=X | -c=X]
            [–mutate=X | -m=X]
            [–mutate_factor=X | -f=X]
            [–simple | -s]
            [–stagnate=X | -st=X]
            [–noreturn | -nr]
            [–stevescore | -ss]
            [–show_worst | -b]
            [–seed=X | -se=X]
            [–manual | -e]
            [–log=FILE | -l=FILE]
            [–attempt_autocorrection | -ac]
    –width=X | -w=X
        Sets the width of the search space to X.

    –height=X | -h=X
        Sets the height of the search space to X.

    –agents=X | -a=X
        Sets the number of agents in each generation to X.

    –cities=X | -c=X
        Sets the number of cities to pathfind through.

    –mutate=X | -m=X
        Sets the number of agents to run mutations on.

    –mutate_factor=X | -f=X
        Sets the number of mutations to occur in a mutated agent.

    –stagnate=X | -st=X
        Will halt the GA after no better route is found after X generations.

    –noreturn | -nr
        Performs calculations without a return path – gives open-ended routes.

    –stevescore | -ss
        Displays the scores in ‘steve’ format, for benchmarking purposes.

    –simple | -s
        Uses simple random mutation rather than edge recombination breeding.

    –show_worst | -b
        Displays the worst path in red on the search space window.

    –seed | -se=X
        Sets the random seed for city position generation.

    –manual | -e
        Allows you to tweak the best route produced for each generation.
        ‘swap [a] [b]’ swaps two points in the tour array, and
        ‘skip [generations]’ skips edits until ‘n’ generations have passed.

    –attempt_autocorrection | -ac
        Attempts to reduce the number of small, crossed over routes by
        an additional form of mutation. This takes the form of selectively swapping
        the points in edges with very short lengths.
        This uses the mutate factor to determine where to start reassembling
        edges in the generation (distance from best).

    –log | -l
        Sets the log file and starts logging to that file

        Prints this help.

OS Development

I’m working on a hobby OS to keep my C skills sharp, I’ll document stuff about it here when I remember


So far, I have a bootable kernel, with ISRs, IRQs, working, no memory manager yet, and no multitasking!

Grub on my bootable ISO

Grub on my bootable ISO