Odd Software for Odd Jobs

Grotto Time, part 5

Upload to my website is finally working again - it only took my website just over three weeks to tell me what they changed that stopped it working (despite me telling them what I was trying to send and the exact minute it stopped working). Anyway …

So, it's allowed me to start working on it again.

I've added dew point estimation - this uses the temperature and relative humidity to estimate the dew point. It's a good measure of how humid the day feels. Also, when the ambient temperature is within a few degrees of the dew point, fog will form. It's sometimes nice to photograph the sunrise when it's foggy! So this will help warn me when it might be a foggy morning.

This information is now also uploaded to my website.

In addition, I've also added approximate sunrise & sunset times for my location in Sydney. The times are displayed on the LCD and change during the day - if it's after sunrise, then it will display today's sunset and tomorrow's sunrise. If it's after sunset, then it will display both times for tomorrow.

This is also uploaded to my website.

2016-03-06 19.18.44-1

Grotto Time - Arduino sketch

Here's the code for my little Grotto Time project.

I make no claim that it is perfect or written to excellent coding standards. It has accreted over the years as I've experimented and changed my mind.

It's built with three main components:

  • Freetronics EtherMega - needed due to the sketch size)
  • Freetronics ProtoShield Mega - sandwiched between the EtherMega & LCD, where all the sensors are connected
  • Freetronics LCD & Keypad Shield - so I can see the time

Additionally, I'm using a DHT22 sensor for temperature/humidity, BMP085 for pressure, an LDR to measure ambient light, a PIR to automatically control the LCD backlight and a DS1307RTC real-time clock. I might add a UV light sensor later - I need to figure out how to house it as it needs direct sunlight for the best reading.

The code works roughly like this (not necessarily in this order):

  1. Get an IP address
  2. Try to sync time via NTP and store this to the RTC
  3. If it can't sync via NTP, then read the time from the RTC - note, this assumes/requires that the time is synched via NTP the very first time it's powered up, maybe I can change this to get the time from the computer when the sketch is loaded?
  4. Check if max/min readings are stored in EEPROM - it currently keeps track of the max/min weekly, resetting every Sunday midnight, by storing in EEPROM I don't lose them if I restart the Arduino for some reason (updating the code, connecting serial monitor, etc.)
  5. Startup the sensors
  6. Store the startup time so we can track uptime

Now the main loop starts:

  1. Calculate the local Sydney time, including if DST is active
  2. If it's Sunday midnight, reset the max/min readings
  3. Cycle through each display of information every 5s
  4. Check the sensors every 2s
  5. Check the PIR - if there is movement then flick back to the time/date display and activate the LCD backlight for 5s
  6. Try to post the sensor data to a PHP script on my website every minute (customise the PHP_PAGE_LOCATION and SERVER_ADDRESS)
  7. Check buttons on the LCD shield - the select button takes us back to the time/date display, for example

And that's it.

Bike Sonar, part 5

I've been working on a "Mark 2" version of my Bike Sonar project.

I'm trying a MaxBotix ultrasonic sensor:

2016-02-11 17.01.46-1

I've also thought of using a wireless beeper. My original idea was to have it mounted on my helmet, but when I was fiddling around, I added an LED to the receiver circuit. Then I thought, what about mounting it on my handlebars?

After some tinkering, I managed to get the breadboard prototype working. You can see the transmitter (with MaxBotix ultrasonic sensor) on the right (with a yellow wire being used as an antenna):

2016-02-22 08.33.39

It's a pretty simple circuit - the 433MHz receiver will take a max of 5.5V so I'm using a diode to drop the (nominal) 6V from the 4xAA to less than that. This feeds the Vcc on the Rx board. I've got a 1µF electrolytic capacitor across the Vcc and DATA pins on the receiver - without it, the signal was VERY noisy (Instagram video). The DATA pin is connected to the base of an NPN transistor via a 100KΩ resistor. The emitter of the transistor is connect to ground and the collector is connected to the negative pin of a piezo transducer. The positive pin is then connected to the positive side of the battery pack.

Now this is my very-first "own designed" circuit, simple as it may be. I still haven't figured this out yet, but I had to add an LED between the transistor's collector and ground for the piezo buzzer to sound (and the LED lights at the same time).

When I replaced the transducer with a different type, I had to remove the LED. So I'm a bit confused. But this is why I'm doing all this - to learn and figure things out myself.

Anyway, I ended up using a different piezo transducer when I moved to veroboard. This is what I ended up with:

2016-02-25 17.59.34-1

The strange thing (for me) is that the LED/buzzer remain lit/buzzing if the power is on but no signal is being received by the Rx. So I've obviously screwed up somewhere in my simple design. But, it works enough for my purposes!

The next step will be to figure out how to mount this on my handlebars. I need to also implement the MaxBotix sensor on a new prototyping board, with an antenna for the transmitter. Then I'll be able to give my Bike Sonar, Mk. 2 a test run.

Replacement Sony MiniDisc remote, part 2

The RM-MZ3R MiniDisc remotes I ordered on eBay arrived today so I got to work pulling one apart to start figuring out how to emulate one so I could have a nice large control box rather than a fiddly little remote.

MD remote2

It's simply a bunch of resistors (and one capacitor), with the audio L/R channels passed through.

MB remote1

The audio uses three wires - ground (brown), left (white), right (red). The controls use two wires - grey (KEY) and yellow (+B). Two remaining wires were cut short and not terminated on the circuit board - these, I assume, are for the display information (the RM-MZ3R doesn't have a display).

The resistor values are:

  • R1 = 1KΩ
  • R2 = 1.3KΩ
  • R3 = 1.3KΩ
  • R4 = 47Ω
  • R5 = 1.5KΩ
  • R6 = 62Ω
  • R7 = 2KΩ
  • R8 = 1.3KΩ
  • R9 = 1.5KΩ
  • R10 = 2KΩ
  • R11 = 2.4KΩ
  • R12 = 2.4KΩ

There are ten switches:

  • S101 = hold switch
  • S102 = reverse, select left
  • S103 = FF, play, select right
  • S104 = pause, CAPS
  • S105 = stop, ENTER
  • S106 = VOL -
  • S107 = VOL +
  • S108 = TMARK
  • S109 = DELETE
  • S110 = EDIT

Various combinations of the resistors lead to the MD unit understanding what command was sent. This is what I'm working on now (yes, I can just find it on the Internet but I learn more this way).

To make it easier, I've removed the wires from the circuit board and replaced them with headers. I've also soldered the tiny wires onto a breadboard in preparation for tinkering with an Arduino. I used a hot glue gun to try to make the wires a bit more robust - let's see!

You can see the two shorter wires on the right - these are for the display information. Should be interesting to figure out how that works.

2016-02-15 20.32.23

I'm almost ready to start tinkering …

MD remote3

GameBoy Camera to iPhone, part 2

A very quick 'n' dirty test of the whole concept - the GameBoy Camera 'printing' to an Arduino, and the Arduino passing the output onto an iOS device. In this case I simply used the demo RedPark app on an iPad.

The picture below shows the data being received on the iPad from the GameBoy via the Arduino … the INIT string of 0x88 0x33 0x01 etc.

2016-02-09 07.34.21

So the next step is customising the code on the Arduino and on iOS. Probably I'll get the Arduino to filter out the control sequences and only pass the raw image data on to the iOS device.

One concern I have is that maybe the printer output is lower resolution than the actual image stored on the GameBoy Camera.

If so, I have a backup plan. A clever fellow, Alex/Alejandro at insideGadgets.com has created an Arduino shield for reading GameBoy cartridges.

2016-02-09 07.46.53

If the quality of the 'printed' images isn't as good as I was hoping then plan B is to read the image data from the SRAM of the GameBoy Camera cartridge using the Arduino, and then still pass it to my iOS program via the RedPark serial cable.

Anyway, let's see. It'd be interesting to try Bluetooth instead of the serial cable but I'm not too sure if Apple have imposed some artificial restriction.

GameBoy Camera to iPhone

This is a little project I started on a few years ago.

I thought it might be "cool" to take photos on my GameBoy Camera and upload them to Instagram on my iPhone.

To do this, I'd need an Arduino to emulate a GameBoy Printer. It would capture the image data "printed" by the GameBoy and then upload it to my iPhone's Camera Roll.

2016-02-06 14.34.23

This would give me experience in implementing arbitrary serial protocols, interfacing the Arduino with my iPhone (originally by RedPark serial cable, but maybe using Bluetooth instead?), and writing a simple iOS application.

I got started on it - cutting a GameBoy serial cable in half and creating a little breakout board. I'd done my research and found people had done something similar, but using a GameBoy Printer on the Arduino rather than using the Arduino as the printer. So I had somewhere to start.

Using my oscilloscope, I could confirm the INIT sequence being sent by the GameBoy but I got stuck trying to send the ACK. So I lost interest.

2016-02-07 07.18.42

But after being re-invigorated in my tinkering and inventing (maybe my family won't be forced to emigrate?!?), I'm having another crack at it.

Doing some more research today, I found someone who implemented something similar to what I want … roughly around the time I was working on it!

Of course, the serial protocol is very similar to SPI. That simplifies things!

Let's see how I go …

Grotto Time, part 4

The sensor data upload to this website now seems to be running quite smoothly - the 'clock' uploads its data every minute or so, and the page auto-refreshes every 30s.


I've also revised the shield I made with the sensors - I've removed the DHT22 temperature/humidity sensor as I thought it was probably too close to the WizNet chip on the Arduino board, thereby skewing the readings. I had another one lying around from my very early Arduino experimenting - it was already on a length of wire so was perfect. I could move the sensor away from the board and place it somewhere else.


With the space freed up by removing the sensor from the board, I added a light-dependent resistor. This would both give additional data to upload as well as controlling the LCD backlight. When it's dark in the garage (i.e. lights are off and I've gone to bed) then the backlight will automatically switch off - video testing it. I've also added an additional screen of information showing the RTC's battery level and the LDR/ambient light level.

2016-02-04 16.54.04

So, this project is pretty much complete - two-three days in total, both hardware and software! The Arduino code is a bit messy and not optimised, but it works! Cleaning it up will be the next step. But first, I just need to figure where I'm going to mount it in my workspace. And come winter time, I'll be able to check the temperature outside on my phone whilst still hiding under the covers!

Grotto Time, part 3

There's one small design flaw I can see already.

The AM2302/DHT22 temperature sensor (white one on the right below) is not far from the WizNet chip that handles the Ethernet connectivity on the Arduino.

GrottoTime shield

This chip generates a bit of heat, and so will probably be skewing the temperature measurements.

Not a big deal - I can move the sensor off the shield and place it a short distance away, connected via wires. This should give a more accurate reading. And it will free-up space on the shield for a light-dependent resistor, perhaps, to automatically switch the LCD backlight off when I've switched the lights off and gone to bed … ? At the moment I can toggle the backlight on/off with the keypad select button.

Before I sort that out though, I've incorporated the web upload code again … and it appears to be working … intermittently. Still need to iron the kinks out.

And I'm working on adding some automatic DST handling too - here in NSW, DST starts on the first Sunday in October and finishes on the first Sunday in April. So shouldn't be too hard to come up with a routine to decide whether it's on or not.

But you can check the current-ish weather in my garage, aka Nerd Grotto, by visiting the page here:


Grotto Time, part 2

I started my GrottoTime project a few years ago - I wanted a clock for my "Nerd Grotto" (i.e. workspace in the garage). I figured it would be a good project to learn how to use a real-time clock (RTC) and Ethernet connectivity.

So I came up with something that would initially poll the time from an NTP server and store it to the battery-backed RTC. It would also check the current temperature/humidity/pressure. This would be displayed on the seven segment LED displays. Additionally, it would upload the sensor data to my website … the thinking was I could wake up in the morning during Winter and quickly check the outside temperature on my phone.

Anyway, the breadboard version worked. The harder part was coming up with a hardwired version.

This is what I settled on - I would use a Freetronics EtherTen board (Arduino Uno with Ethernet & SD card). I shaped a vero-strip board to fit around the Ethernet port of the EtherTen. This would be a shield that would have all the components.

Anyway - this was the result:

Grotto Time Mk. 1

Unfortunately, there appears to be a hardware. The DHT22 temperature sensor (the white thing) fails to start up. The connections look good for it look good.

So it looked like I'd have a lot of frustrating hours fault-finding.

But … as I'd recently figured out how to use LCDs (yeah, simple), I decided to start from scratch. The EtherTen had problems with a lack of memory - it just couldn't fit all the code I wanted it to do … polling the time via NTP, uploading the sensor data, etc.

Thus, here is Mark 2. Much better looking, yes?

  • Changed the EtherTen for an EtherMega (more code space),
  • Used a Freetronics LCD + keypad shield,
  • Used a prototyping shield sandwiched between for the sensors - RTC, barometric pressure, temp/humidity

GrottoTime Mk. 2

Here it is working - I've got a few screens of information working that can be scrolled through using the keypad buttons.

2016-02-02 21.56.04

I've been slowly bringing my original code across to a new sketch, replacing the LED code with LCD code.

The time is initially synched via NTP. This is stored to the RTC. Thus it can then run offline or online. Of course, to upload the data to my website it needs to be online. The idea is that it'll be on the wall in the garage connected to a cheap WiFi access point via an Ethernet cable.

The code is a bit of a mess at the moment, but it works. I'm currently working on adding some automatic DST setting.

Project Idea: Replacement Sony MiniDisc remote

A project idea to exercise the brain - replace the RM-MC38EL remote control on my Sony MiniDisc recorder with a larger unit.

2016-02-01 06.47.07

It would use a larger and easier to read 16x2 LCD and buttons controlled by an Arduino. This will make it more like a component unit and make it easier to use in my workshop than the fiddly little controls it has now.

Sony never made a component HiMD.

The hardest bit will be the plug - either cannibalise a remote or somehow simulate it? Two pins are used to send commands to the MD (different resistance for each command) and the other two for sending data to the remote's display (will need to figure that out!). It does appear easy to acquire Sony RM-MZ3R remotes on eBay, giving me access to a source of the plugs. It would be nice to have just the four-pin plug, leaving the headphone socket free.

I did find a similar project that pre-dates Arduino. In this case it was to allow the use of infra-red remote controls.

Might turn out to be another dead-end ... but it is fun to experiment!

DarcyBot, Mk. 2

This is the second iteration of the first 'robot' I ever built with my eldest son Darcy.

The first was a fairly bog-standard robot - it had two bumper-switches at the front. Move forward until one or both are triggered. Back-off, turn a bit, then proceed.

That was fun. We learned how to use H-bridges to control motors and how to make simple decisions.

We figured a new challenge would be to understand how to interface discarded bits of electronics - in this case, we had the transmitter and receiver of a broken remote controlled police car.

You can see the final result below - we even kept the flashing red/blue lights.

2016-01-31 21.16.40

The transmitter/controller was re-housed in a new box. Pretty simple - just wire up new buttons for forward/reverse/left/right to the circuit board and add a new battery holder:

2016-01-31 21.15.17

The robot itself is built upon a tracked chassis (Jaycar KR-3130, seems discontinued). In the picture below you can see the separate parts:

2016-01-31 21.09.58

The brain is a Freetronics Eleven (Arduino Uno compatible). There are then two shields plugged into the Arduino. The first shield, sandwiched in the middle between the Arduino & the top shield, is the H-bridge. We used a pair of L6202 full-bridge drivers, one for each side of the robot.

2016-01-31 21.10.22

On top of this is another shield that is used to interface the Arduino with the receiver from the broken toy car. The receiver is attached with some double-sided tape (high-tech). The black & red wires are for the flashing lights and the yellow wires are the control signals received from the transmitter - backwards, forwards, left, right.

2016-01-31 21.11.04

The control signals are fed into the Arduino via the analogue inputs. These are simply read and the motors controlled appropriately.

So, from this exercise we learned:

  • What are H-bridges and how they're used to control the direction of motors
  • How to program simple intelligence into a robot to allow it to make decisions based on stimuli
  • How to interface discarded bits of electronics to allow wireless control of completely different devices
  • To never throw away remote control stuff - it can be re-used for simple, one-way wireless communication (i.e. a weather station sensor)

The next iteration of the DarcyBot will probably be some sort of line or light follower - this will teach us how to use visual inputs.

Average Speed Calculator, part 3

Took my little average speed calculator for a quick field-test around the local streets. Seems to be doing the job I wanted it to. Need to enlist the wife's help to do a proper test at highway speeds.

Field test

I also added a sixth screen of information - the maximum speed recorded and the timestamp:


I still need to sort out the localisation of the date from the UTC date received. And also tidy up the code - add some more functions instead of just replicating the code (I feel terrible about it!).

Average Speed Calculator, part 2

I have got my prototype ready for field-testing, i.e. driving around in a car.

The final parts list is:

  • Freetronics Eleven (Arduino Uno compatible)
  • GPS module using a u-blox NEO-6M (board is labelled "GY-GPS6MV2")
  • 16x2 LCD display (labelled "JHD162A")
  • Two SPDT microswitches that I've soldered onto the prototyping area of the Eleven (Jaycar SM-1036)
  • 10kΩ potentiometer to control the LCD contrast
  • 1 x 4.7kΩ, 3 x 10kΩ, 1 x 220Ω resistors

The 4.7kΩ & one 10kΩ resistor are used for the GPS module's Tx pin to the Arduino (the GPS module uses 3.3V).
The 220Ω resistor is connected between the LCD display's pin 15 (LED+), the backlight anode, and the Arduino's 5V supply.
The final two 10kΩ resistors are connected between the switches and the Arduino.

One of the buttons is used to switch between five screens of information:

Screen #1 - current speed and altitude


Screen #2 - when speed averaging is activated (i.e. when you pass under the first point-to-point camera), it shows the duration since it started and the current calculated average. The asterisk indicates whether the average is currently being updated (asterisk) or is from the previous activation (no asterisk)


Screen #3 - current latitude and longitude


Screen #4 - number of visible satellites and the current HDOP


Screen #5 - finally, the current date & time - the date/time is received in UTC so I've hardcoded +11 hours to compensate for current Sydney DST


Oh, bugger - I haven't bothered compensating the date either. Okay, still some polishing to do.

Anyway, the Freetronics Eleven can be run off 5V via the micro-USB or 7-12V so I have the option of wiring up a cigarette lighter plug to power it or simply use a cigarette light -> USB plug.

If it seems to be accurate - I'll measure against my TomTom - then I'll move to the next step and create a proper hardwire prototype in a jiffy box.

Here's the current Arduino code if anyone is interested - I used Mikal Hart's 'kitchen-sink' example from his TinyGPS++ library as the basis.

Temperature & Humdity

This is one of my very early experiments with Arduino that succeeded in the move from idle breadboard tinkering into a "manufactured product".

I built a thermometer for my son. It comprises:

  • an Arduino Micro,
  • a DHT22 temperature & humidity sensor (labelled "AM2302"),
  • a two-digit, seven-segment LED display (labelled "CA15621BS", common anode),
  • a 10kΩ resistor for the DHT22,
  • seven 680Ω resistors for the LED display,
  • a SPST temporary action pushbutton,
  • a 9V battery,
  • and an iPod touch case

The result can be seen below:

Temperature Gauge 1

Temperature Gauge 2

(Probably could've made the black negative wire from the switch to the circuit board a little longer)

Why a momentary action switch? I didn't trust that my young son would remember to switch it off after quickly checking the temperature - so you need to hold the button down to check the temperature. So far I've never had to replace the 9V battery!

The LED display alternates between temperature and humidity. As I live in Sydney and the display is limited to two digits, there is no expectation that negative temperatures are needed. Actually, checking the code I wrote, it seems that I don't bother checking the temperature result at all - I think I assumed that the temperature returned by the DHT22 will always be above freezing point (0 Celsius)! Maybe I need to do some cold weather testing, or at least add some sanity checking! Anyway, it's safe for Sydney usage at least.

The code is here.

Here's a short video of it in action.

Bike Sonar, 2nd test run

Took it for a quick test run this morning. No traffic around so I couldn't properly test it, so I rode past some parked cars instead!

Here's a screen grab from the Fly6 video.

Fly6 screengrab

An idea for a different implementation - replace the LED display with a Bluetooth module and feed the data to an app on my phone. This would be an opportunity to both figure out how to implement BT in my Arduino projects and also how to write an iOS app.

Anyway, refinement continues. I will probably replace the LeoStick with an Arduino Nano clone so I can run it off a 9V battery and thus enclose the ultrasonic sensor, Arduino and battery in a more-waterproof Jiffy box or similar. I could probably do the Bluetooth version at the same time so the whole sonar would be in a single box - much less fiddly.

I'm having fun regardless of how useful this may turn out to be!

Bike Sonar, Arduino code

Here's the Arduino code of the prototype I've got running on my bike after a bit of cleanup.

// Simple "bike sonar" ... aka rear parking sensor for a bicyle Winking
// Version 1.1, Brett Hallen, 2016
// Uses: HR-SC04 ultrasonic sensor,
// MAX7219 LED driver,
// four-digit LED display,
// and a piezo buzzer (Jaycar AB-3459)
// Implemented on my bike using a Freetronics LeoStick - requires 5V
// so powered with a "USB battery bank"

// http://playground.arduino.cc/Main/LedControl
#include "LedControl.h"

// http://playground.arduino.cc/Code/NewPing
#include "NewPing.h"

/* ---------------> Sonar Stuff <--------------- */
#define triggerPin 7
#define echoPin 6
#define maxDistance 400 // the HR-SC04 has a max range of about 450cm
#define triggerDistance 100 // when to trigger buzzer, in cm
#define pingDelay 50 // pause between sonar pings
NewPing sonar(triggerPin,echoPin,maxDistance);

/* ---------------> LED/MAX7219 Stuff <--------------- */
#define Din 8
#define CS 9
#define CLK 10
LedControl lc = LedControl(Din,CLK,CS,1);

/* ---------------> Speaker Stuff <--------------- */
#define speakerPin 12

void setup()
int i = 0;

// for verification of ping result to serial monitor

// initialise the LEDs
// Intensity between 0 (lowest) and 16 (highest)

// Bit of fancy "I'm powering on, running setup()" indication
// print 0123 on LED
for (i=0;i<=3;i++)
lc.setChar(0,i,' ',false);
// print 3210 on LED
for (i=3;i>=0;i--)
lc.setChar(0,i,' ',false);

// initialise speaker output
pinMode(speakerPin, OUTPUT);

// setup done

void loop()
// pause between sonar pings

// send a ping
int uS = sonar.ping();

// calculate distance in cm
int distance = uS / US_ROUNDTRIP_CM;

// print distance on the LED

// object closer than minimum distance?
if (triggerDistance > distance)
// closer the object, the faster the 'beeps'
int toneDelay = distance * 5;
// turn on LEDs
playTone(toneDelay,500); // beep
delay(toneDelay); // pause
playTone(toneDelay,500); // beep
else if (250 < distance)

void printDistanceOnLED(int distance)
int metres = distance / 100;
distance = distance - metres * 100;
int cms_tens = distance / 10;
int cms_ones = distance % 10;

// only display digits if non-zero
// no need for thousands digit
lc.setChar(0,0,' ',false);

// display hundreds digit?
// yes if it is non-zero
if (metres)
lc.setChar(0,1,' ',false);

// display tens digit?
// yes if it is non-zero or we already have displayed the hundreds digit
if ((cms_tens) || (metres))
lc.setChar(0,2,' ',false);

// display ones digit?
// yes if it is non-zero, or we already have displayed the hundreds or tens digit
if ((cms_ones) || (cms_tens) || (metres))
lc.setChar(0,3,' ',false);

// for verification to serial monitor
Serial.print(metres); Serial.print("."); Serial.print(cms_tens); Serial.print(cms_ones); Serial.println("m");

// duration in milliseconds, frequency in Hertz
// http://michael.thegrebs.com/2009/03/23/playing-a-tone-through-an-arduino-connected-piezo/
void playTone(long duration, int freq)
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
delayMicroseconds(period / 2);
digitalWrite(speakerPin, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);

Bike Sonar, part 4

So this is what I've ended up with for mounting on my bike - bit of wood, a lot of cable ties, a bit of galvanised steel and some bolts (that has holes that perfectly lined up with where my red reflector was).

2016-01-16 15.17.33

Bike Sonar

2016-01-16 15.18.05

The display is mounted so that the distance is captured on video by my Cycliq Fly6.

I made the mistake of running the LeoStick from a 9V battery - whoa, that smelt bad when it blew! Silly mistake - I'd earlier used an Arduino Nano clone that happily ran off a 9V and had assumed the LeoStick was the same (when you assume, you make an ass out of u and me … but just me in this case).

So down to Jaycar to grab another LeoStick. But how to power it? There's no 5V batteries - could I used 6V directly? Probably not - I'd have to add a voltage regulator to my circuit to knock it down to 5V - a bit of a re-design after all that fiddly soldering I did!

But then got the idea to use one of those USB battery banks you can recharge your phone with.

Unfortunately, the battery bank I got is too clever … it can tell a phone isn't plugged in and so switches off. As a workaround, I have to plug my phone into the second USB output socket (shaking head).

I took it for a test ride … and it worked! Unfortunately, the cycling infrastructure around where I live is pretty good - lots of bike paths, so I didn't really get a chance to ride on the road. But I simulated by riding up close to parked cars.

First thing I realised … an LED display is not much use in the middle of the day! Not bright enough. Anyway, made some tweaks and did a static test after I got home.

Bike Sonar, part 3

Now, the idea seems to work on a breadboard.

To properly test it, I need to move it to something that can be attached to a bike and powered off a battery.

My original idea was to have the Arduino, ultrasonic sensor, LED display driver mounted on one circuit board at the back of the bike and the LED display mounted remotely on the handlebars.

Bike sonar, original plan

Slept on it, then decided to use a Freetronics LeoStick with the ultrasonic sensor mounted above it on a ProtoStick. The piezo buzzer, LED display and driver IC would then be mounted separately and I'd use my Cycliq Fly6 to record the results.

Bike sonar, new plan

This is what I ended up with - my original breadboard prototype at the top and the bike-ready prototype at the bottom:

2016-01-16 11.53.52

I had an old DSLAM serial-port cable handy with a handy ten-pin connector so I used that to link the two circuit boards.

Moving to the LeoStick required some port changes … note to self … solder the components to the ProtoStick first … and THEN solder in the male header pins (damn amateur).

Anyway, it worked pretty much straight away! Phew.

Next step - somehow mounting it on my bike!

Bike Sonar, part 2

The Arduino is coded up and it seems to be working!

Here's the Arduino code - pretty simple.

(sorry, I don't know how to display code all fancy-like at the moment!)

#include "LedControl.h"
#include "NewPing.h"

/* ---------------> Sonar Stuff <--------------- */
#define triggerPin 12
#define echoPin 10
#define maxDistance 400
NewPing sonar(triggerPin,echoPin,maxDistance);

/* ---------------> LED Stuff <--------------- */
#define Din 7
#define CLK 8
#define CS 9
LedControl lc = LedControl(Din,CLK,CS,1);

/* ---------------> speaker Stuff <--------------- */
#define speakerPin 11

#define triggerDistance 100 // cm
int i = 0;

void setup()

// LEDs
for (i=0;i<=3;i++)
lc.setChar(0,i,' ',false);
for (i=3;i>=0;i--)
lc.setChar(0,i,' ',false);

pinMode(speakerPin, OUTPUT);


void loop()
int uS = sonar.ping();
int distance = 0;
int toneDelay = 0;

distance = uS / US_ROUNDTRIP_CM;
toneDelay = distance * 4;

if (triggerDistance > distance)

void printDistanceOnLED(int distance)
int metres = 0;
int cms = 0;
int cms_tens = 0;
int cms_ones = 0;

metres = distance / 100;
distance = distance - metres * 100;
cms_tens = distance / 10;
cms_ones = distance % 10;

// only display digits if non-zero
if (0 != metres)
{lc.setDigit(0,1,' ',false);}

if ((0 != cms_tens) || (0 != metres))
{lc.setDigit(0,2,' ',false);}

if ((0 != cms_ones) || ((0 != cms_tens) || (0 != metres)))
{lc.setDigit(0,3,' ',false);}

lc.setDigit(0,0,' ',true);

Serial.print(metres); Serial.print("."); Serial.print(cms_tens); Serial.print(cms_ones); Serial.println("m");

// duration in mSecs, frequency in hertz
// http://michael.thegrebs.com/2009/03/23/playing-a-tone-through-an-arduino-connected-piezo/
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
delayMicroseconds(period / 2);
digitalWrite(speakerPin, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);

Bike Sonar

Hi! This is my first attempt at a blog, so bear with me!

The easiest way I find of learning something new is to have an idea of something you want to create and then go about implement it, learning the pitfalls and how to solve them. I've never been any good at just reading a book and then creating some software.

So where I live in Australia, the government is introducing new laws this year regarding safe passing distances for cars & bicycles. Simply, allow a 1m gap. It's obviously not something you need to get out a ruler and measure but rather to get the mindset that pedestrians are a lot easier to kill than cyclist, and cyclists are a lot easier to kill than motorists. So just think and be courteous to other road users, regardless of their means of transport … no one person owns the road or has any greater rights.

Anyway, this gave me an idea to implement a simple little sonar for my bike. Essentially it's just a 'rear parking sensor' for a bike! The idea is if a car gets too close then an audible warning can be given to the cyclist. It also has a display so that the actual distance can be captured by a video camera, like the Cycliq Fly6.

Maybe this will be of interest to someone else. Like I said, it's pretty simple. And there's no doubt similar things already out there - this was just something so I could practise going from initial idea to prototype and then refine.

Step one. Get all the parts and put it together on a breadboard for testing to see if it'll actually work.

I used the following:

  • Adafruit USB-Boarduino
  • HR-SC04 ultrasonic sensor
  • four-digit seven-segment LED display (labelled "CPS02841AR", common cathode)
  • Maxim MAX7219 LED display driver (plus 68kΩ resistor, 10μF electrolytic and 100nF ceramic capacitors)
  • Freetronics piezo buzzer

First step was just wiring it all up. Here is the result:

Bike Sonar, prototype 1

Next step is to write the code for the Arduino to run it all and test.