Java (7)

To Build a SmartWatch… (Part 1)

Having seen the fuss around smart watche, I wondered exactly how difficult would it be to build one from scratch? All the technology usually packed in to one of the current generation of watches is widely available in breakout board form or equivalent, which brought me to another thought:

“How far can I get without building my own board?”

Thus, the Smart Watch project was born; an attempt to build a functional watch connected to a handset (in my case, a Nexus 5) and used to notify the user of incoming messages, etc. using only readily available hobby breakout boards and parts, so that as many people as possible could have a go at beating my designs!

If you, the reader, want to have a go, the rules are thus; The watch must:

  1. Only use readily available breakout boards to build it’s circuitry.
  2. Have the basic functionality of a smart watch, namely, to tell time, and show notifications from a host device.

Oh, and do let me know if you do have a go. I’d love to see the results!

The Parts

Because of the breakout board rule, I decided to base all my buying decisions around the single largest part required. As the display is likely to take up the lions’ share of the front surface of any watch, I attempted to cram all my other components behind that breakout.

The one I settled on in the end was the Adafruit 1.8″ TFT + SD Card Breakout with it’s whopping 128×160 resolution, 5v or 3.3v operation, and integrated Micro-SD card holder, it was a pretty easy choice to make – it gave me the added feature of storage, as well as providing a nice sized base to build the rest of the watch behind.

Conveniently, the stock image on Adafruit is a cat. I approve greatly.

The stock image on Adafruit’s display products is a slightly bemused looking cat. I approve greatly.

Conveniently, the processor board I had been looking to use for this project happened to be exactly the same height as the short dimension on the screen.

The Teensy 3.1 sports an ARM Cortex-M4 processor ( an MK20DX256VLH7 ), has hardware driven SPI, and has integrated USB support and handily runs a port of Arduino code, letting me use the Adafruit display libraries directly, rather than having to write my own ( although this came back to bite me later, but more on that another time ).

A Teensy 3.1! Nifty!

A Teensy 3.1! Nifty!

As this is to be a watch, it’s going to need to be battery powered, ( semi-obviously, I wasn’t keen on running about with a USB cable up my sleeve all the time ), and as small size was the main requirement when I decided on these parts, I tried to pick a battery with the largest capacity for approximately the right height available.

The 400mah LiPo battery from Sparkfun is about the right size, and should provide plenty of power for a working day ( a personal requirement of mine was that this should run for at least 8 hours )

It's a LiPo, what did you expect it would look like?

It’s a LiPo, what did you expect it would look like?

As the battery is a LiPo, it required it’s own charging circuitry, and luckily, the guy over at Pesky Products produces an ‘appallingly small’ ( their words, not mine! ) add-on board for the Teensy, which includes all the required circuitry, as well as breaking out a charge status pin and using the Teensy’s own USB connector for input power. It was perfect.

It's really tiny! Really handy too!

It’s really tiny! Really handy too! JST for scale?

Now that the device has power, a processor and something to display data on, a radio was needed to bridge to the host device. Adafruit once again provide the solution with their Bluetooth Low Energy, nrf8001 breakout which turned out to be the second largest single component to cram behind the screen ( the battery was the largest ) and proved to be quite a pain to mount sensibly.

Eventually I opted to put the board back-to-back with the display breakout, as thankfully, the radio breakout has no components on the back side, so could be simply stuck down with double sided foam ( more on the fun with sticky foam later… ). But even so, the sheer size of the breakout was – and still somewhat is – a problem.

The hilariously large - for my purposes - Adafruit nrf8001 breakout board.

The hilariously large – for my purposes – Adafruit nrf8001 breakout board.

More to come, when I can find the time to type everything up!

Calendar Arc Watch Face

Over the weekend, I hit two ‘firsts’ for me at the same time.

One; I published my first Android Wear app! and Two; I published my first paid app!

Watch face showing an 'Example Meeting' event

Oh yes, I was supposed to go to that…



I’ve owned a Moto360 for a while, and was slightly disappointed that there were no watch faces that adequately displayed what my calendar looked like for the day, so, having written a couple of minor apps for Android in the past, set to writing a new watch face which would show all events, from all my calendars (I have 11!) and present them in a visually pleasing way.

Customizable stock imagery is awesome!

Customizable stock imagery is awesome!

Events are drawn in arcs around the ‘tics’ along the outer edge of the watch. Semi-obviously, as a Moto360 owner, I designed this to look best on a round watch face, but it looks ‘acceptable’ on a square one too (if you own a square watch, get in touch and I’ll give out a free copy of the watch app – for the first person to contact me, anyway)


Fairly sparse at the moment, but it works!


At the moment, the number of options for the user to customise the look of the watch are limited, but I wanted to get the app out there so people could get and review it – there’s not much point in implementing features if people don’t want what you’re selling anyway!

For now, only the calendars to show can be changed (the arc colours are from the events in the calendar), and you can force a manual sync, but planned thus far are:

  • Tics on/off, for watches like the G Watch R which have physical tics
  • ‘Full Screen Mode’, for watches like the G Watch R which have physical tics
  • Shadows on/off
  • Inverted Mode – for OLED displays where bright pixels are both battery-expensive and can lead to burn-in.
  • Date settings – none/day/month/year/weekday/etc. formatting options.
  • Battery levels – for both watch and phone, if I can figure out a nice way of fitting it in this style.
  • Calendar event arc styles – thickness, end-caps, active/pending, etc.

If any of this lot takes your fancy, or if you just want to have a go with the app as it stands now, see the Calendar Arc Watch Face page on the Google Play store.

Arduino Batch Tool Prototype, version 1.2

I’ve been poking around in my batch tool, and have been pushing what you can do in the Processing IDE‘s add-on tool framework (turns out, not that much that’s every interesting without doing some fun Java hackery!).

With some slightly fancy trickery, the Arduino Editor now looks like this:

Stress testing the Arduino Batch Tool

Stress testing the Arduino Batch Tool

Yes, this is all loaded from an addon tool – not a rewrite of the IDE, not a custom build, just the stock editor with a single jar loaded from ~/sketchbook/tools and enabled in the menu.

Thus far, additions include:

  • A tabbed script console
  • Multiple target boards are configurable (for single-button-flash-everything functionality)
  • Multiple serial ports can be opened in their own tabs at the same time (and auto close and reopen during flash operations)

Non-visible additions include a partially implemented preferences dialog, and mutli-sketch multi-device support (flashing device A with sketch 1, flash device B with sketch 2, C with 1, etc. all from one button press, once configured).

I’ll be updating the download on the  Arduino Batch Flashing Tool page once I’m sure the tool is fairly stable.

If anyone uses this, I’d love to hear from you, especially those on Windows or Mac, as I’ve only tested this under Linux, but it should work on anything the Arduino IDE works on, as it doesn’t use any special binaries.

Arduino Batch Tool v1.1


Arduino Batch Tool 1.1 - Port configuration

Arduino Batch Tool 1.1 – Port configuration

With the addition of tabbing, multiple serial monitors can be instantiated at once – and the batch tool will manage them all during flash operations (disable, write, enable).

Arduino Batch Tool 1.1 - Embedded Serial Monitor

Arduino Batch Tool 1.1 – Embedded Serial Monitor

The tool doesn’t create its own serial monitors, but instead instantiates additional Arduino serial monitors and embeds them in the tool’s tabs.

The stock IDE serial monitor should still work, as long as you don’t try to open the same port in both at the same time!

Release should be soonish, check back in the near future!

Lions, Tigers and Site Updates, Oh My!

It’s been a while, I know, but I’ve finally got around to updating various bits on here, including and update on my RS-485 projects along with a new page for my Micro-CNC Milling Machine.


I also have uploaded a new app to the Google Play app store, CheerLights Live Wallpaper which pulls updates from the CheerLights Project, changing the colour of the home-screen wallpaper to match the current CheerLights colour (with a latency of around 15 seconds or so).

User warning: CheerLights does seem to like ‘white’ in the early hours of the morning… sadists!

Until next time!

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.