Tuesday, January 31, 2012

Arduino Timer Library

I have developed a simple to use library that gets around a load of problems that arise when you start trying to do much inside 'loop'. It can change pin values or run a callback function. It seems like such an obvious thing that I doubt its original, so I would like to hear of similar projects.

DOWNLOAD Thanks to Jack Christensen for hosting it and the improvements and version management he has added to it.


The library does not interfere with the built-in timers, it just uses 'millis' in a crude type of scheduler to decide when something needs doing.


The Arduino 'delay' function is both a blessing and a curse. Its great for showing beginners how to make an LED flash. But as soon as you get more complex and start slowing down your 'loop' function  you will run into problems.

A classic example is turning a relay on for 10 minutes. The 'delay'-way looks like this:

int pin = 13;

void setup()
  pinMode(13, OUTPUT);
  digitalWrite(pin, HIGH);
  delay(10 * 60 * 60 * 1000);
  digitalWrite(pin, LOW);

void loop()

The disadvantage of the delay approach is that nothing else can go on while the 'delay' is happening. You cannot update a display, or check for key presses for example.

My 'Timer' library version looks like this:

#include "Timer.h"

Timer t;
int pin = 13;

void setup()
  pinMode(pin, OUTPUT);
  t.pulse(pin, 10 * 60 * 1000, HIGH); // 10 minutes  

void loop()

The 'pulse' method takes arguments of a pin to change, the period to change it for and its initial state.

The call to t.update() will take a matter of microseconds to run, unless the appropriate period of time has passed.

Lets look at another example that uses two timer events. One to flash an LED and another that reads A0 and displays the result in the Serial Monitor.

#include "Timer.h"

Timer t;
int pin = 13;

void setup()
  pinMode(pin, OUTPUT);
  t.oscillate(pin, 100, LOW);
  t.every(1000, takeReading);

void loop()

void takeReading()

The first thing to notice is that we are using a callback function called 'takeReading'. We connect it to the Timer using the 'every' command, which in this case, will call the function every second.

We have also attached another event to the timer using the method 'oscillate'. This will cause the LED to toggle state every 100 milliseconds.

Each of the events has an integer ID associated with it, so that you can stop an event, as we do in this example below, which will write to the serial monitor every 2 seconds, flash the LED and after 5 seconds, stop the LED flashing fast, and flash it 5 times slowly.

#include "Timer.h"

Timer t;

int ledEvent;

void setup()
  int tickEvent = t.every(2000, doSomething);
  Serial.print("2 second tick started id=");
  pinMode(13, OUTPUT);
  ledEvent = t.oscillate(13, 50, HIGH);
  Serial.print("LED event started id=");
  int afterEvent = t.after(10000, doAfter);
  Serial.print("After event started id=");

void loop()

void doSomething()
  Serial.print("2 second tick: millis()=");

void doAfter()
  Serial.println("stop the led event");
  t.oscillate(13, 500, HIGH, 5);

You can attach up to 10 events to a timer.


As with all libraries, unzip the file into the 'libraries' folder in your Arduino directory, which will be in something like 'My Documents\Arduino' on Windows, 'Documents/Arduino' on Mac etc. If this is the first library you have installed, you will need to create a directory there called 'libraries'.

The library is compatible with both Arduino 1.0 and earlier versions.


int every(long period, callback)
 Run the 'callback' every 'period' milliseconds.
 Returns the ID of the timer event.

int every(long period, callback, int repeatCount)
 Run the 'callback' every 'period' milliseconds for a total of 'repeatCount' times.
 Returns the ID of the timer event.

int after(long duration, callback)
 Run the 'callback' once after 'period' milliseconds.
 Returns the ID of the timer event.

int oscillate(int pin, long period, int startingValue)
 Toggle the state of the digital output 'pin' every 'period' milliseconds. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW.
 Returns the ID of the timer event.

int oscillate(int pin, long period, int startingValue, int repeatCount)
 Toggle the state of the digital output 'pin' every 'period' milliseconds 'repeatCount' times. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW.
 Returns the ID of the timer event.

int pulse(int pin, long period, int startingValue)
 Toggle the state of the digital output 'pin' just once after 'period' milliseconds. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW.
 Returns the ID of the timer event.

int stop(int id)
 Stop the timer event running.
 Returns the ID of the timer event.

int update()
 Must be called from 'loop'. This will service all the events associated with the timer.


Have a go with the library, please let me know what you think.

About the Author
These are my books. Click on the image below to find out more about them.

About the Author
These are my books. Click on the image below to find out more about them.


Monday, January 23, 2012

A Review of SnootLab's 'Memoire' Arduino Shield

SnootLabs were kind enough  to send me one of their Memoire Shields. This useful little shield combines an SD card slot with a DS1307 Real Time Clock (RTC). If you haven't come across one before, an RTC is a hardware clock with its own battery back-up, so that when your Arduino gets turned off, it does not forget the time.

The rationale for combining SD card with a RTC is that you can read temperatures or whatever and write then to the SD card along with the date and time form the RTC.

This useful card costs about 25 USD in kit form and a bit more ready assembled. I actually enjoy this kind of thing in kit form. It is easy enough to assemble and the instructions are clear and logical. They are found on the 'downloads' tab for the product information and you will also find the schematic and Eagle files there too.

One immediately noticeable feature of the board is the prototyping area. Which gives you can solder in your own temperature sensors or whatever else you want to log along with the time.

Rather than make a logger, I decided to make myself a thick juicy Arduino sandwich and combine it with a Freetronics LCD shield and an Arduino Uno to make a clock. I reviewed LCD Shields a while back.

Its a rather expensive and over-engineered clock - but none the less a clock. You set the time by sending a string from the Serial monitor and from then on, it will keep time for you.

The three boards are shown below.

The Snootlabs shield is placed on the Arduino Uno and then the LCD shield on top of that.

The only potential conflict in pin usage between the two shields is for pin D9 that is used for a general purpose LED on the Snootshield. As the LCD shield uses this for LCD Enable, occasional flickering of  the LED was not seen as a problem.

In summary, its a useful shield with good documentation from SnootLabs.

There are other boards including this from AdaFruit. The AdaFruit version is a similar price and even a similar layout. It does however use a buffer chip for the SD interface, where as the Snootlabs design uses potential dividers to drop the SD card levels.

Correction: In an earlier version of this post, I stated that the Snootlabs device did not have its own regulator - actually it does. Its a SMD ready soldered onto the bottom of the board. 

The code for the example project was adapted from here. Its Arduinio 1.0 code.

#include "Wire.h"
#include <LiquidCrystal.h>

#define DS1307_ADDRESS 0x68
byte zero = 0x00; //workaround for issue #527
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
  Serial.println("Set date sending format: YYMMDD HHMMSS W");
  Serial.println("Where W = day of week - 1-7");
  lcd.begin(16, 2);

void loop()
  if (Serial.available())

void setTimeFromSerial()
  byte year = (Serial.read()-'0') * 10 + (Serial.read()-'0');
  byte month = (Serial.read()-'0') * 10 + (Serial.read()-'0');
  byte day = (Serial.read()-'0') * 10 + (Serial.read()-'0');
  byte hour = (Serial.read()-'0') * 10 + (Serial.read()-'0');
  byte minute = (Serial.read()-'0') * 10 + (Serial.read()-'0');
  byte second = (Serial.read()-'0') * 10 + (Serial.read()-'0');
  byte weekDay = (Serial.read()-'0');

  Wire.write(zero); //stop Oscillator


  Wire.write(zero); //start 



byte decToBcd(byte val){
// Convert normal decimal numbers to binary coded decimal
  return ( (val/10*16) + (val%10) );

byte bcdToDec(byte val)  {
// Convert binary coded decimal to normal decimal numbers
  return ( (val/16*10) + (val%16) );

void printDateTime(){

  // Reset the register pointer

  Wire.requestFrom(DS1307_ADDRESS, 7);

  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());

  lcd.setCursor(0, 0);
  if (minute < 10) lcd.print("0");
  if (second < 10) lcd.print("0");


About the Author
These are my books. Click on the image below to find out more about them.

Tuesday, January 17, 2012

DIY Coilgun

Here is one of the projects from the book '15 Dangerously Mad Projects for the Evil Genius'. You can actually download the chapter in full, free of charge, from here so I will just give an overview of it here.

Its pretty simple to make and safe. I kept the voltage low (36V), although it does pack about 100A through the coil in 10mS and it will fire a small section of nail at a maximum of about 30 mph. 


Here is the schematic.

And this is how it is wired together.

If you fancy having a go, be my guest and download the chapter and if you like it, then you might like to try some of the other projects. There is a real mixture. Some like the Trebuchet don't actually involve any electronics at all and three of them use Arduinos.

Projects List
Chapter 01. Coil Gun
Chapter 02. Trebuchet
Chapter 03. Ping Pong Ball Minigun
Chapter 04. Mini Laser Turret
Chapter 05. Balloon-popping Laser Gun
Chapter 06. Laser sight
Chapter 07. Laser Intruder Alarm
Chapter 08. Persistence of Vision **** Arduino
Chapter 09. Covert Radio Bug
Chapter 10. Laser Voice Transmitter
Chapter 11. Flash Bomb
Chapter 12. LED Strobe
Chapter 13. Levitation Machine **** Arduino
Chapter 14. Light Seeking Microbot
Chapter 15. Surveillance Robot **** Arduino

There is also a video on youtube showing the more interesting projects.

About the Author
These are my books. Click on the image below to find out more about them.

Sunday, January 15, 2012

Laser Cutting at FabLab Manchester

Manchester FabLab allows anyone to go along and use their kit for free on Fridays and Saturdays on condition that we make public what we do. So I paid them a visit on Friday to cut myself a new enclosure for my Arduino Lilypad Binary Clock.

The clock is one of the projects from my book '30 Arduino Projects for the Evil Genius'. Its a binary clock with four red LEDs indicating the hour, six blue LEDs the minute and six green LEDs the second. They all fan out from the Arduino Lilypad. A reed switch is used to advance the clock by holding a magnet close to it.

Its a little difficult to photograph, so here it is again on a white background. I quite like the effect of the white background and may fit a backing to the acrylic.

The clock was formerly housed in a picture frame. Which looked okay, but I thought it should be possible to make something nicer:

The new enclosure does not really do much enclosing. Its just a sheet of 3mm clear acrylic, cut in the shape below. This allows the LEDs to sit in the channels and allows a space in the center for the Lilypad.

The PDF for the clock face is available on the book's website in the download section.

The laser cutter is a Epilog Mini 24 Laser Cutter and I wasn't really taxing it much to cut the acrylic.

As well as a laser cutter, Fab Lab has a 3D printer, a Desktop Milling machine, a Vinyl cutter, a large CNC Router, a vacuum former and well equipped electronic workstations.

This is all backed up with a knowledgeable and helpful set of staff as well as well as lots of people around happy to help out.

About the Author
These are my books. Click on the image below to find out more about them.

Thursday, January 12, 2012

Power Over Ethernet (PoE)

Power over Ethernet or PoE is one of those things that sound difficult but actually at its simplest is very easy to use and a great way to reduce the number of cables. For all I know, when you get into more advanced PoE it does become scary, but all I wanted to do was to be able to do away with a wall-wart power supply lead for my little Altoids tin project.

If you look next to the 'L' of Altoids, you can see the lens of a Luxeon LED poking through. What I have here is a modification of my web morse flasher project described in my earlier blog about the EtherTen. The EtherTen is a combined Arduino and Ethernet board.

This project runs the EtherTen as a web server that gives you an interface like this:

And when you press 'Send' it flashes out the message on the LED in Morse code.

By using PoE I could mount my useful messenger device on the wall, with only a single wire coming out of it (the Ethernet cable). This would provide both power and network connection.

The module I used to accomplish this magic trick is the Freetronics 4-Channel Power-over-Ethernet Midspan Injector. This device costs about 25USD.

To use it, you insert it between your device and your home hub and plug it into a power adaptor. Hey presto, it then supplied power over the Ethernet cable.

I used a 12V DC power supply. SO you still need a separate power supply, but at least it and its wire can be kept out of sight.

You need to insert two jumpers on the EtherTen just behind the RJ45 socket. These are supplied with the EtherTen, but are not connected when shipped. You just bridge the top two connections together and also the bottom two connections.

Note to UK readers - you can buy Altoids in Tescos.

I cut bits out of the bottom with a Dremell - lots of sparks - wear glasses - and drilled a hole in the lid for the LED. I also had to cut a bit off the protpshield so that it fitted flat and fully into the EtherTen's sockets.

I put lots of PVC insulating tape anywhere where electronics might come into contact with metal.

The EtherTen fits perfectly into the Altoids box, making a perfect little web server.


PoE does not have to be difficult or expensive to use. If you are using an Arduino as a web server then this approach could simplfy your wiring - so consider it.

Disclosure: Freetronics gave me the Midspan Injector. I did however have to buy my own mints - and very tasty they were too!

About the Author
These are my books. Click on the image below to find out more about them.


Friday, January 6, 2012

Canine Radio Direction Finder - Part 2

Its been a long time coming, but my son Matt and I finally finished the radio direction finder project. I described part 1 (the transmitter back in November 2011. This post describes the receiver.

The basic idea is that the transmitter sends beeps and you turn the directional antenna until you get maximum signal and that is the direction of the transmitter.

It doesn't work terribly well. The reason being the antenna is quite sensitive, so even though it is directional, if the transmitter is close then you cant tell which way it is. So it only works in the sweet spot where the transmitter is far enough away for the signal to be smaller when the the antenna is pointing the wrong way but not so far away that you cannot get a signal at all. For us, this range was perhaps 30 to 100 yards.

What is really needed is some means of varying the gain of the antenna. We ran out of enthusiasm before solving this problem.

Anyway, it does work after a fashion and its quite fun and cheap to make.

This is the schematic.

Its just an audio amplifier that amplifies the signal from the RF module. The module is the other half of the transmitter module and something like this. Make sure you get an AM module - that matches the frequency of the transmitter.

If you want to use a speaker, omit R3, but we found headphones better. So in the diagram above the speaker is actually a headphone socket.

The directional antenn is made from a piece of wood, with lengths of retractable steel ruler attached to it. The design was taken from a posting on an Australian forum that I now cannot find. But I'm sure they wouldn't mind my repeating it here.

The second element takes the connection to the receiver circuit and this is made with a short length of TV antenna lead.

You can also see how the strips of ruler are just screwed onto the wood.

As I mentioned the results were a little disappointing. But then the whole project cost about 20 USD and we had some fun. Especially wandering around the neighbourhood wearing headphones and clutching what looks like a home made TV antenna. This is the kind of situation where it is best to just to cultivate a wild look in the eye and hope people don't bother you or call the police.
About the Author
These are my books. Click on the image below to find out more about them.


Sunday, January 1, 2012

Arduino Screw Shield Review

This is a review of the Freetronics Terminal Shield and the SnootLabs Power Screw Shield.

The Arduino socket strips are okay for attaching components, but sometimes, when putting together a quick prototype it would be useful to be able to have something more substantial - like a screw terminal.

These shield boards provide just such a feature.

                                  Snootlabs                                                          Freetronics

The shields are intended for the Arduino Uno and earlier versions of Arduino. They break out all the terminal sockets into screw terminals.

The Snootlabs shield costs around 21 USD as a kit and 28 USD fully assembled.
The Freetronics shiled is only available fully assembled and costs around 17 USD

In Common
Both boards use straight through headers that mean as well as having screw terminals, you can also fit another shield on top. In both cases, the designers have left enough room to easily access the screw terminals even with a big shield like an LCD shield attached.

Both boards have a reset button.

SnootLabs Power Screw Shield
This is the larger and more expensive of the two shields. It has a large prototyping area where you can solder in components. It also has special areas of the board for soldering in a SMD chip and for DIL through hole ICs.

The other noticeable difference is the power connector. This is the same type of four pin connectors that you used to find on PATA Hard Disks to supply the power.

Jumpers allow you to configure this socket to either provide the power to the Arduino, or to pass through the Vin 2.1mm socket on the Arduino to the 4 pin socket to provide power to other devices.

There is also an LED that can either be linked to an IO pin of your choice or to 5V to act as a power-on indicator.

The Snootlabs website has very good information on this shield, including a photographic style sheet of instructions for constructing the board and a useful datasheet that explains what all the jumpers do without having to start working out whats going on from the schematics.

Providing the board in kit form is a nice idea. As well as being cheaper, its a nice easy project for someone new to electronics wanting to practice their soldering.

Freetronics Terminal Shield

As with all Freetronics kit. This is a high quality board that is sold fully assembled. Its smaller and cheaper than the Snootlabs shield and does not have a dedicated IC area for SMD or 0.1inch DIL. It does exactly what it says on the tin.

The board comes with a number of surface mount components already attached to it. This includes three (red, green and blue) LEDs and their current limiting resistors. These are positioned on the back ende of the shield where they are easily visible and can be wired to any of the IO pins.


Both products are good quality and neither will dispoint.

If you need to use an SMD IC for your project then the dedicated area for this makes the Snootlabs shield a good choice. The same applies if you need all the prototyping area you can get.

If this is not a consideration then the cheaper Freetronics shield will serve you just fine.

Other Options

Other screw shields are available of course and if you do not need the prototyping area then something like the WingShield may be of use to you. http://wingshieldindustries.com/products/screwshield/

Sparkfun and Adafruit both sell shields similar to the Freetronics offering: http://www.sparkfun.com/products/9729 and http://www.adafruit.com/products/196

About the Author
These are my books. Click on the image below to find out more about them.