Aug 14

Arduino and code efficiency

The thing I love about programming for Arduino is that, unlike programming in most other environments nowadays, you are forced to think about memory footprint, memory allocation, and how your code relates to the hardware.

That’s great for people like me who don’t really consider themselves coders at all, because “perfect code” is less about something that’s mathematically beautiful and conceptually elegant, and more about getting the job done. In fact the code is often more efficient if you spell it out line-by-line in a bunch of nested if statements, rather than abstracting it into a pre-written processing function that may do the job in fewer lines of code but end up costing more in storage space because the function itself is general purpose.

Take for example this code. Horrendous to mathematicians I’m sure, but lovely for electronics engineer types;

void callback(char* topic, byte* payload, unsigned int length) {

Serial.println("Volume Callback");

if (length == 1) { output = payload[0] - 48; Serial.println(output); }
else if (length == 2) { output = ((payload[0] - 48) * 10 + (payload[1] - 48)); Serial.println(output); }
else if (length ==3) { output = 100; Serial.println(output); }


In the above you can see I have a byte array, each location in the array is an ASCII representation of a digit that forms a number. I know that number coming in from the payload will only ever be between 0 and 100, AND have considered in what situations that might not be the case and what would happen. So it will have a maximum of 3 digits. Indeed if it does have 3 digits the number must definitely be exactly 100. And so rather than using expensive string to integer manipulation functions which add 2k (yes, 2k!) to my sketch it is cheaper to write it out in if statements that calculate it in a “units – tens – hundreds” way working on the basis that the characters 0 to 9 are represented in the ASCII table consecutively.

So oftentimes it’s more computationally efficient to write more lines of code than fewer, which is great for idiots like me who tend towards wanting to put everything in terms of flow charts and IF statements!

There are so many examples of the above I’ve discovered so far, e.g. using a switch statement, whilst looking a little clearer on the page, is worse than using IF statements unless you have over at least 4 cases. The exact detail depends on your sketch and how variables are stored of course.

Arduino helps us by showing us how many bytes your sketch is at compile time. Great for keeping an eye on things as you progress your project.

Aug 14

Arduino, MQTT, OpenHAB and the Ultimate Room Control Panel

Little demo video of the project so far below!

My idea for a room control panel came about after seeing the vastly expensive options on the market, and because we are building a new home!

Lovely! But I can do *far* better, right?

Lovely! But I can do *far* better, right?


I love the brushed stainless steel precision-cut panels they offer – so I plan to make my own.

Not only are the options available a little* over budget, more importantly they don’t come close to addressing my ideals:

* a lot

  • Combine lighting and audio control into one panel. Soft dimming of multiple lighting channels with advanced / user-friendly audio control.
  • Field nodes small enough to be placed in wall back-boxes and controls flush-mounted in the wall.
  • Accessible but autonomous. Should not require changing batteries or worrying about someone hacking the RF wireless protocol. CAT6 and mains powered. RF options with secured MQTT an option, but we have a blank slate with cabling so prefer to go wired.
  • All control to communicate with an automation server (Windows laptop / RPi / whatever) which provides rules that integrate audio, lighting, security, and give me access from out of the home. Must be resilient to server outage; lighting must still work using physical switches.

The audio control aspect is particularly close to my heart:

  • I have always used Squeezebox. Whilst Sonos is more “user friendly” it doesn’t cut the mustard for me!
  • Hardware controls for audio in every room. Physical dials and buttons with tailor-made visual feedback and ergonomic design.
  • Audio to be controlled from anywhere and any device, therefore control panel must show updated volume and status. Volume display using LED ring around a knob (muted colours, no “chav-blue”!)
  • Backlit display showing current artist / track.
  • Discreet display which lights up when you walk past, or move within e.g. 1m of the panel (distance sensors).
  • Presence sensing for added convenience.

You’ll see I have shunned wireless communications and touchscreen control devices. Whilst they might seem sexier, to me nothing beats the reliability of cables and the hard, fast, robustness of a physical knob. Especially when we are controlling digital devices, it’s so hard to get that lovely “feel” when turning things up and down, but we must try!

(Also I have a huge surplus of CAT6 cable 🙂

My budget includes laser cutting some screwless faceplates, and even with this custom work, it’s looking very likely it will still be around 5-10 times cheaper than anything else I’ve seen… and SO much better.

Check out my progress so far!

In this video I’m perhaps unfairly harsh about OpenHAB and provide no detailed information about MQTT, but I’ve spent a great deal of time assessing OpenHAB vs. alternatives like Domoticz, and I’m sold. I believe it will become the glue that will hold the increasingly disparate world of automation together. It provides persistence, data access layers, and a binding for pretty much any automation device or system you care to think of.

It’s true that OpenHAB is daunting for the non-coder, but v2 is set to address these problems. Most importantly for me, OpenHAB has an advanced rule engine and a lovely array of software control interfaces.

MQTT as a transport protocol is a winner; HTTP is clearly not appropriate for sensor networks and REST is for sleeping. I may post about MQTT in more detail later but I’m really satisfied by how sophisticated and simple it is, and I find it highly intuitive. I like the mindset behind MQTT which you can read about here.


Aug 14

A world of home automation opening up

So I became pretty obsessed with home automation. You know, the type where your home detects you walked through the door, turns the lights on, and says through the speakers, “Hello Mat, did you have a nice day?”

Actually the above, whilst it sounds a bit sci-fi, is something I already tested out in my home to great success. My home automation system can now speak to me and tell me things. It’s a fine line tweaking it to only communicate useful things, such as “I see you are getting ready to go out, don’t forget your kitchen window is open”, but it’s important that the automation system doesn’t become a gimmick. For example, and this is something I tested, using a combination of cheap wireless sensors in different rooms allows me to write rules: bedroom door shut, lights off, bathroom detects movement, front door opens, BANG – he is leaving the house. Automatically check windows and if any are left open then speak a message through the home network audio system using Google’s voice servers. Then send a notification to my iPhone.

Sounds far too neat to be true, but it works a treat, and reliably too. It really is “set and forget” once you get the rules right.

Whilst I ditched the “hello Mat” bit spoken through the speakers (it got annoying after a while), you must agree the hallway lights coming on when you enter the home is a rather warm and lovely thing you might want to keep.

Using a combination of cheap and free bits of tech, it’s rather easy to do this*.

* I say easy. It’s easy for the geek or the technically-minded, but sadly out of reach for the technically-challenged at the moment. No doubt this may change in the coming years.

First of all you need to replace your lightswitches with the lovely RF controlled dimmer types available from manufacturers such as Z-Wave / Fibaro, or closer to home, an English company called LightwaveRF who make very cheap multi-way multi-gang dimmer switches that pair with controllers also manufactured by LightwaveRF. These were until recently found in B&Q, I think stock may come back shortly. After playing with those for a while you can stop using the LightwaveRF handheld radio remotes (they are radio, not infrared. That means they work anywhere in the house), lovely as they are, and for £80 buy an RFXtrx which is a little USB device you plug into your laptop or server or Raspberry Pi and it transmits and receives signals and talks to your lights.

Now hook the RFX with a computer running one of the excellent open source automation products, all free of course, and hey presto – you can now control your lights from the nearby park from your iPhone! One-touch access to moods, scenarios, dimmer sliders, you name it.

A lightswitch is an “actuator”. LightwaveRF – and many others – also sell “sensors”, such as PIRs to detect movement in a room, or door sensors, which feed into the system too.

Many home automation products – the one I have settled on is called OpenHab – allow you to integrate with a number of systems you might already own. Network home audio? You bet! OpenHab has a binding for Sonos and Squeezebox. They integrate with Google Voice. No extra cost and only a bit of extra playing to get it working. The world of opportunities now opens up – you can now control your music AND your lights from your light switches…

Actually it turns out that of course the LightwaveRF switches only receive signals, they don’t send them out. They ship with remote controls that can be re-purposed for controlling your volume and play / stop etc., but the lightswitches themselves will clearly need upgrading to the more expensive Z-Wave RF types which have 2-way communications in order to do such a thing. Well I don’t plan to do that because I’m a cheapskate, and more importantly I love the challenge of building my own room audio controller. This gives me a chance to integrate a pretty flush-mount digital display into my walls showing the current playlist.

Next post: the new home.

Aug 14

Arduino – the beginnings of a journey

Warning: geek post to follow.

Anyone who has been unlucky enough to know me over the last 3 weeks will realise my obsession with all things Arduino has got out of hand. From the initial buzz of realising “I can do ANYTHING with one of these things” to the late-night shopping sprees with Amazon sellers who distribute from warehouses in Hong Kong (I placed my 18th Ardunio order in 3 weeks yesterday night at 4am … gladly most of these purchases come in around a quid per unit so it’s not even that expensive a hobby so far), it has been a fun journey so far.

My first stop was to give myself a brief refresher in electronics and coding in C, so I followed some excellent examples from the Arduino “getting started” book. Right, after 13 minutes of making a little circuit that pulses an LED at the speed set by a knob and a few other beginner projects, I thought I should dive right in and do something serious.

I mean *REALLY* serious. A piezo tune generator. #sarcasm

The key array basically sets out the diatonic notes of a scale for 8 notes. The ones following those 8 notes are a random selection of semitones that I snuck in just so that I could program “You are my sunshine”. Musos will understand why.

Next instalment: how to control your hi-fi volume using an Arduino, RF signals, and a rotary encoder!

Here’s the sketch:

// Whack a piezo between 8 and GND
// Comment or uncomment the tune array definitions

int key[] = {261,294,330,349,392,440,494,523,587,622,659,698,784,880,987,1046};

// "You're Just Too Good To Be True"
// int tune[] = {5,5,5,6,5,3,5,0,5,5,5,6,5,3,5,0,5,5,5,6,5,3,5,0,5,5,4,5,4,5,4,0,4,4,3,5,4,3,4,0,4,4,4,4,3,2,3,0,3,3,3,3,2,1,2,0,2,2,2,2,1,1,1,0};

// "You are my sunshine"
int tune[] = {5,8,9,11,0,11,0,0,11,10,11,8,0,8,0,0,8,9,11,12,0,14,0,0,14,13,12,11,0,0,0,0,8,9,11,12,0,14,0,0,14,13,12,11,0,8,0,0,5,8,9,11,0,0,12,9,9,0,11,8,0,0,0,0};

int tunelength = sizeof(tune) / sizeof(int);
void setup() {

void loop() {
int currentnoteindex = 0;
while (currentnoteindex < (tunelength)) { if (tune[currentnoteindex] == 0) { delay(180); currentnoteindex++; } else { tone(8,key[tune[currentnoteindex++]-1],90); delay(180); } } currentnoteindex = 0; }