Sunday, 11 October 2015

Simple Arduino Robots for Kids - Part 1

Simple Arduino Robots for Kids - Part 1

I want to share this series of articles on fun things to do with a simple tricycle-layout robot with two drive wheels.

I start by building a basic remote control car, then use this to engage kids' interest in adding autonomous behaviours and more components.

Simple Arduino Robot

Ask your kids what they they want to add next, they might surprise you.

The robot is based around the "Differential Drive" layout, where there are two independently driven wheels, and steering is achieved by varying wheel speed.

You see this pattern in a lot of places, for example:

  • Star Wars' R2D2
  • Roomba and imitators
  • Most small e-bay robot chassis (see below)
  • Tanks and other tracked vehicles (including WALL-E)
  • Segways and other self-balancing vehicles

The advantages of this arrangement are simplicity (only two motors, no steering linkage) and nimbleness (can turn on the spot). The disadvantage is that if the wheels aren't turning at the same speed, the vehicle will not run straight. The disadvantage can be overcome using closed loop feedback of some kind.

Simplest possible case - two motors, no feedback

You can get a long way with two well matched motors and no feedback (and if your motors aren't matched, you can maybe get away with correcting for the mismatch in software).

We will use this arrangement as a starting platform to be embellished in future articles. For now, we will build a working robot with the least number of parts.

Assemble your chassis

The chassis kit from ebay comes with decks, spacers, screws, wheels and motors. Kids can assemble it with minimal help.

Basic Chassis kit from eBay Chassis rear view Chassis Underside

You will need to solder some short wires (about 8cm) to the motors.

Begin fitting the electronics

All the electronic parts can be found at or other hobby electronics supplier.

You need an Arduino board, a Battery pack, some breadboards, a dual-channel motor controller, and a Bluetooth module. You'll also need some breadboard jumper wires. There are links to parts sources above.

Electronic Parts

Fit the motor controller

Start by connecting the motor wires to the motor controller, using a small screwdriver.

Connecting the motor drive Motor driver connected

Fit six female-to-male jumper wires to the motor controller, and secure it in place with a cable-tie. You can put it in any position that is easy to secure.

Jumper wires for motor driver

Fit the battery

Secure the battery box over the front wheel using a cable tie. Feed the wire up to the top deck through one of the holes.

Fit the battery

Connect the Arduino

Here I use a small 5x5 breadboard as a power distribution bus, but you can dispense with this, and use spare rows on a single breadboard if you prefer.

I'm using an Arduino Nano compatible, but there is room for a full-sized board such as Arduino Uno if that's what you have.

Connect the motor driver

Connect your battery to the VIN pin on the Arduino. This will use the Arduino's on board regulator to reduce the battery voltage to the 5v needed by the microcontroller.

To reiterate the power connections

  • Battery connects to ground and VIN
  • Motor controller connects to ground and VIN
  • Bluetooth connects to ground and 5v
  • Anything else should connect to ground and 5v

Program the Bitlash firmware

Install the bitlash library from Open the "bitlashdemo" example by following the Arduino IDE menus to File -> Examples -> bitlash -> bitlashdemo. Select your board and port and program the sketch.

Connect the arduino serial monitor and you should see "Bitlash Here" plus more information and a command prompt. The bitlash demo defaults to 57600 bits per second as the serial port speed. If you have trouble with bluetooth later on, try changing the bitlashdemo script to use 9600 bps.

Connect the Bluetooth Module

You won't have much fun tethered by a cable, so we are going to use a Bluetooth radio to replace the USB cable.

The Bluetooth module has 4 pins, Power, Ground, Transmit and Receive. Connect power and ground to the 5v pin on the Arduino (NOT the unregulated battery nor VIN). The TX pin on the Bluetooth goes to RX on the Arduino, and vice-versa.

If you hook up a USB cable to your Arduino, you should temporarily unplug the Bluetooth module first, so that the Bluetooth and the USB bridge do not "fight" over the TX and RX pins.

Simple Arduino Robot

Pair the bluetooth module

Start out using your PC to talk to the bluetooth module. You can use a PC, Mac, Linux or Android. Unfortunately iPhone and iPad don't have general purpose bluetooth serial connectivity; later in this series we will look at other ways to use an iPhone to control the robot.

Use your operating system's bluetooth settings to pair the device. Then use the Arduino serial monitor, or any serial terminal program to connect to it. Pair your bluetooth module

To use the terminal app on Mac or Linux, you can do

$ screen /dev/tty.HC-06.Dev-B

On windows, try Hyperterminal.

Program some simple commands in Bitlash

The motor controller will drive each motor in forward or reverse, using two pins, A and B. The motor controller lables its pins IA1 IB1 (inputs A and B for motor 1) and IA2 IB2 (inputs A and B for motor 2).


At this point, it may turn out we hooked up one of the motors backwards. If the motor runs in the wrong direction, loosen the terminal block screws and reverse the wires.

Arduino Pins 2 and 3 are the A and B outputs for the left wheel

Arduino pins 4 and 5 are the A and B outputs for the right wheel.

Later in this series we will use Pulse-width-modulation and the analogWrite function to control speed of the wheels. For now, we have stopped and full speed.

We define six basic bitlash commands to control the motors

  • lfwd - left motor forwards rotation
  • lrev - left motor reverse rotation
  • lstp - left motor stopped
  • rfwd - right motor forwards rotation
  • rrev - right motor reverse rotation
  • rstp - right motor stopped

Paste these commands into bitlash, put the robot up on a block (or disconnect the wheels) and try them out. Make sure you run 'iosetup' first. You may need to stop and rewire the motors if the wheels turn in the wrong direction.

function iosetup { d2=d3=0; pinmode(d2,1); pinmode(d3,1); d4=d5=0; pinmode(d4,1); pinmode(d5,1); }

function lfwd {d2=1;d3=0}
function lrev {d2=0;d3=1}
function lstp {d2=d3=0}

function rfwd {d4=1;d5=0}
function rrev {d4=0;d5=1}
function rstp {d4=d5=0}

Once you are satisfied that the motors are working, we can move on to some higher-level behaviours:

function fwd {lfwd;rfwd}
function rev {lrev;rrev}
function stp {lstp;rstp}
function ltr {lrev;rfwd}
function rtr {rrev;lfwd}

function navsetup {a=40; b=120}
function l90 {ltr; delay(b); stp}
function r90 {rtr;delay(b);stp}
function l15 {ltr; delay(a); stp}
function r15 {rtr;delay(a);stp}

function startup {iosetup; navsetup}

Since we are going to do without motor feedback for now, we will achieve controlled turns by guessing how long to run the motors. I arrived at 40ms for a 15 degree turn, and 120ms for a 90 degree turn. Adjust the values of variables a and b until you get good results.

Try to drive your robot around using the bitlash commands. I got quite good at this after a bit of practice.

Control the robot with an Android phone

You can replace "fast typing and crashing a lot" with an Android phone. Download the BlueTooth Serial Controller app, which lets you define buttons to send each of the commands above.

Set up Android app to control

Use the app settings (spanner icon) to name and configure the buttons as shown. Each button should send the command, plus a new line.

To connect to your robot, tap the magnifying glass icon and look for your bluetooth device. When you have connected the light on the bluetooth module will stop flashing and become solid red.

Have fun!

Now you have a robot that you can drive around.

What next?

In future articles we will look at some variations and improvements

  • Using a hobby radio control transmitter and receiver instead of bluetooth
  • Using and internet connection and an iPhone
  • Implementing closed-loop feedback for more precise steering
  • Adding sonar and infrared collision sensors
  • Adding First Person View video camera
  • Scaling up to bigger platforms
  • Becoming autonomous, and more

Saturday, 10 October 2015

Make a 5 volt battery supply for any Arduino

Make a 5 volt battery supply for any Arduino

Make a 5v battery from a 9v battery snap.

Powering your Arduino from a 9v battery and the built-in linear regulator is inefficient; 9v batteries have very low energy capacity, and
using a simple linear regulator (perhaps 60% efficient) wastes much of it. 9v batteries are also quite expensive compared to other battery types.

A switching regulator can be over 95% efficient. 14500 Lithium cells, which are the same size as AA cells, but deliver 3.7v each, are much more cost effective in the long term than disposable alkaline cells.

This project shows you how to make a regulated 5v supply that is about the same size as a 9v battery, and which you can connect direct to the 5v pin (NOT the power socket, nor the VIN pin) of your Arduino or other circuit.

Gather the parts

Tiny voltage regulator module

The core of the circuit is this regulator module which will take up to 23v in and output from 1 to 17 volts depending on adjustment (as long as the input is higher than the desired output). It costs less than a single 9v battery.

You also need a battery snap, some heat-shrink tubing, and a battery of some kind. I recommend a 2xAA holder holding two 14500 lithium cells, which are rechargeable 3.7v Lithium Ion cells and cost less than $5 a pair.

Assemble the parts

Begin by selecting some heat-shrink tubing of the appropriate size, and punching two holes for the battery connectors.

Preparing to punch holes

Punching holes

Prepare to assemble a 5v regulator

Then cut and solder the battery snap wires to the regulator.

Wiring the regulator

Connect the regulator and adjust the trimming potentiometer with a small screwdriver until the output reads 5 volts. Disconnect battery.

Adjusting the output voltage

Fit the heatshrink over the battery snap, then feed the battery snap wire and the regulator module into the heat shrink.

Fitting the regulator into the tubing

Use a heat source to shrink the tubing. You don't have to be obsessive, just shrink until snug.

Shrinking the tubing

Use your assembled battery

Make a 5v battery from a 9v battery snap.

A handy tip for when working with 9v battery snaps, when you need to switch on and off, just connect ONE pin, and rotate the snap until the snap makes contact with the outside of the other pin to turn on. You can rotate the snap to bring the pins apart to switch off.

Using a 9v battery snap as a switch

Remember, you have your own high-efficiency low-dropout regulator, so you do not need to use any regulator built into your Arduino, you can connect direct to the ground and 5 lines.

Power an Arduino from 5v

Monday, 5 October 2015

iPhone + Blynk = Keyless house entry

Blynk App to open door

Somehow I missed hearing about Blynk when it was a thing on Kickstarter in early 2015.

Fast forward 6 months and it's in the field and while it's still early days, Blynk looks like a load of fun.

I've been working on a keyless entry system for my house, because I've always wanted to be able to just push a button and come in, like modern cars. A friend gave me some leftover parts when he moved house, including a solenoid striker plate. I replaced my front door recently during a renovation, and decided to install the lock hardware at that time.

As someone who remembers how difficult and expensive electronics was in the 80s, the age of Smart Objects is exciting. You can basically plug together a selection of off-the-shelf modules without having to pick up a soldering iron. Now Blynk brings the same convenience to the software side.

While I learned to code in Assembler, and I learned electronics at the transistor level, I don't miss either.

Blynk is an app for iPhone and Android which connects Things to the Internet. It uses a cloud service to make your device accessible, or you can run your own server. The intended devices are ethernet or wifi connected microcontrollers such as the Arduino. In my case I'm using a board based on Arduino nano, tethered to a Raspberry Pi over USB. I find the combination of a Pi for brains and an Arduino for 5 volt-io-and-replaceable-if-you-smoke-it brawn is the sweet spot in robotics and automation projects.

The hardware

Home Automation Hub

PIR sensor and LED light strip

Solenoid door striker

Raspberry Pi single-board PC: This computer is my home automation hub, it connects to cameras sensors and actuators around my house.

Arduino Nano: while the Pi has its own IO pins, they're unbuffered 3v and a little too easy to blow up. I prefer to use microcontrollers of various kinds as a "hind brain" for my Pi projects.

Relay board: an inexpensive module that holds several 5 volt relays, which are controlled by outputs pin of the Arduino.

Solenoid door strikeplate when the 12v solenoid is energized via one of the relays, the door opens with a light push

Passive Infra-Red (PIR) Sensors two sensors will detect movement near the door, for automatic lighting.

LED light strips: Another relay energizes constant-current LED driver circuits that power two 8-watt LED strips.

Arduino Pin assignments

  • D2 (output) Relay A, the door solenoid
  • D3 (output) Relay B, the LED lighting array
  • D4 (input) PIR Sensor A, internal movement sensor
  • D5 (input) PIR Sensor B, external movement sensor
  • D6 (input) Reed Switch, for open door detection

Prototyping the software - Arduino plus Bitlash

Blynk keyless entry breadboard prototype

I've been using Bitlash for quick prototypes, it's an interpreted language resembling C that runs on the Arduino platform. The following bitlash functions allowed me to test and tune a working model of the system on a breadboard.

function startup {iosetup; run getpir; run lights; run lockdog };
function iosetup {pinmode(2,1); pinmode(3,1); pinmode(13,1); d2=d3=p=d=0 };

function getpir {p=d4|d5; d13=p; snooze(100) };
function lights {if (p) {d3=1; snooze(30000)} else {d3=0; snooze(250)} };
function lockdog {d2=d; if (d) d=d-1;d2=d;snooze(1000) };

function unlock {d=10 };
function lock {d=0 };

The system polls the PIR sensors every 100ms, and if the sensors detect movement the LED lights are turned on for 30 seconds, then off again. (By which time you have opened the door and turned on the house lights). If the 'unlock' command is given, the solenoid is activated for 10 seconds. (It turns out 5 is plenty).

Installed version - Arduino plus Blynk

Blynk App to open door Automated front door

The installed version of the application uses a timer to inspect the sensors 4 times per second. When a motion event is detected, the lights are activated. Every sensor is pushed to Blynk, and there are "Virtual Pins" configured for Blynk to activate the relays.

Blynk uses Virtual pins for pushing events to the cloud and also for sending actions to the Thing.

In this case the sensors, light and lock status are pushed on pins V0,V1 and V2, while the lights and lock can be actuated by writing to pins V3 and V4.

Virtual pin v5 is the "whoops, did I leave the front door open" sensor, for those moments when you get to the end of the street and think "I don't remember if I locked the door!".

Code is at github.

Saturday, 19 March 2011

Flat Mate - protect your LiPo cells from over-discharge

This project monitors the voltage of a battery and displays a 5-element bar-graph indicating battery charge state. A MOSFET can be added if desired cut off supply at low voltage, to protect the battery from over-discharge.

It is particularly applicable for multi-cell Lithium-ion Polymer (LiPo) packs, which are easily ruined if over-discharged.

It is intended for use in high power applications such as portable lighting, robotics and power tools where a charged SLA or LiPo battery is discharged in the presence of a human operator. The first deployment was for a high-power bicycle headlamp. Design was inspired by the simple state-of-charge indicators present on some electric bicycles.

The advantage over existing inexpensive "off the shelf" protection circuits is that this circuit gives a visual indication of state-of-charge, presented as an easy-to-read bar-graph. Existing protection circuits (often designed for flashlights or model aircraft) either have no display (sudden surprise cutoff), digital voltage display (requires memorizing cutoff voltages) or audio-only alert (no visual display).

An Atmel ATTiny45 microcontroller is used to sample the battery voltage and control the LED bargraph. Power for the microcontroller is derived from a 78L05 regulator connected to the main battery. Battery voltage is monitored using an analog input via a voltage divider and compared to the microcontroller's 1.1v internal voltage reference.

The bargraph will show 4 LEDs when at "full charge" and 1 LED when at minimum usable voltage. When voltage is critical a 5th "alert" LED will illuminate (and output supply can be terminated).

The circuit can be used purely as a voltage indicator by leaving off the optional MOSFET switch components. If a MOSFET is fitted this can be used to disconnect the main load when the battery is depleted.

Hardware Details

Flat Mate Schematic

The bargraph consists of 5 3mm LEDs (green, yellow and red) arranged GYYYR. The first four (GYYY) form the bargraph and the 5th (red) is the critical alert. The first three are connected to dedicated output pins, the final two share a single pin in a totem-pole arrangement. The fourth LED shares state with the output FET (if fitted), when this LED is lit, power is good and the FET is enabled. When this output pin is cleared, the fifth LED (the complementary red CRITICAL alert) is illuminated and the FET is disabled.

As the monitor circuit is indended for use in high-drain situations (0.5--10A), the approx 20mA consumed by the monitoring circuit is considered negligible. In particular the voltage divider is not isolated from supply between samples, so presents a constant drain of around 850uA. Current through the bargraph elements is limited by a 1kΩ resistor to around 3mA per element, so the bargraph consumes up to 12mA when at FULL level.

Software Details

Software is configurable for the type and number of cells. The initial application of a 3-cell (11.4v nominal) Lithium-ion Polymer (LiPo) battery will be used to describe the code.

Four voltage thresholds are configured (in millivolts), depending on battery type. For a 3S LiPo these are:

    BMV_FULL = 12.000v
    BMV_GOOD = 11.000v
    BMV_LOW  = 10.000v
    BMV_CRIT =  9.000v

The code converts these thresholds to analog sample values at compile time, defining corresponding VL_FULL..CRIT constants.

These thresholds give the following LED readouts:

    if >= FULL output GYYY_
    if >= GOOD output _YYY_
    if >= LOW  output __YY_
    if >= CRIT output ___Y_
    if  < CRIT output ____R


  • Configure analog pin as input
  • Configure LED pins as outputs
  • Strobe the LEDs for 1s to see that they all work
  • Configure timer 1 to give 4Hz interrupts
  • Configure ADC for internal 1v1 reference, selecting single-ended channel 2
  • Set ADC clock prescaler to give 125kHz, take and discard one sample

Main loop

  • do nothing, go straight to sleep mode until timer interrupt.

Timer interrupt handler

  • Read battery voltage
    • initiate conversion
    • busy-wait until conversion complete
    • read completed value
  • Update sample value
    • add sample value to accumulator
    • if 4 samples are accumulated, calculate the average and reset accumulator
  • Update the display whenver accumulator is reset
    • Clear all LEDs
    • Light the CRITICAL LED (and kill power) if level is <=VL_CRIT
    • Set the bargraph appropriately if level is >VL_CRIT (see above)

Since samples are accumulated at 4Hz, and each 4 samples are averaged, the outputs will be changed only once per second. Averaging is used to avoid falsely detecting a CRITICAL state when transient spikes such as motor start occur.


The circuit was prototyped on a solderless breadboard, with battery simulated using a 24v supply and an adjustable-output regulator (LM317T).

A selection of LEDs with one leg replaced by a current-limiting resistor have been made to simplify use of LEDs in breadboard prototypes.

For in-circuit programming I use the tuxgraphics AVRUSB500v2, as this programmer features a 5-pin SIL programming header, which is very convenient for breadboards.


Once the design was proven, a version was constructed on through-hole prototyping board with components arranged to take advantage of pin-bridging where possible. This turned out to be difficult since the chosen double-sided prototype board featured a solder mask that was VERY resistant to bridging (this would normally be a laudable feature). A plain copper single-sided protoboard would have actually been a better choice.

Flat Mate

The prototype has been deployed for use as a bicycle headlamp battery pack.

Subsequent revisions will use ATTiny25 in SMD package, and SMD components.

Flat Mate PCB

Full code and design files are available on GitHub

Update: Here is the etched and drilled PCB for the surface mount version (with through-hole headers and MOSFET), alongside a SOIC to DIL breakout board constructed to allow programming the ATTiny25:

Flat Mate PCB and breakout

Thanks to Warranty Voider for the breakout board design.

Update 2: Here is the assembled SMD prototype:

SMD Assembly

SMD Assembled

Monday, 9 November 2009

Drive an RGB led with software PWM

This project illustrates how to use an ATTiny microcontroller and an RGB LED to create a coloured light that cyles continuously through random colours, but changes colour dramatically at the press of a switch.


Why? My kids had this $2 novelty pen that did this employing a teensy circuit along with 3x3mm LEDs and some alkaline coin-cells. They broke it almost instantly, losing some critical small parts.

"Daddy, my light-up pen broke! WAAAAAAAAAAAAAAHHH!!!"

Having deprived themselves of the captivating coloured lights, they then drew on the walls with the instrument-formerly-known-as-the-light-up-pen. Then they experimented with strangling each other with the pen's narrow ribbon lanyard. I decided to replicate the pretty light without the other problems.

Circuit Overview


This circuit produces coloured light by using an 8-pin ATTiny13 microcontroller and Pulse-width-modulation (PWM) to vary the brightness of three LEDs (Red, Green and Blue) that are closely located, or share a common package. I used a common-anode 5mm RGB led, which looks just like a normal 5mm LED but has 4 leads instead of two.

Since the ATtiny13 only has one timer with 2 PWM channels, it cannot control 3 PWM channels in hardware. Instead, I do the PWM logic in software, timing the pulse modulation via a regular tick (interrupt) from the ATTiny's hardware timer. (Nowadays you can get the ATTiny45 and friends which have 3 PWM channels, but I could not obtain them when I first built the prototype for my middle child a couple of years ago). My youngest child is now 2, so I dug this project out of the mothball bunker for her to play with.

WARNING: modern multi-colour LEDs can be PAINFULLY bright. If children will play with this, choose one of the following: ensure your LED is not a superbright, or use a diffuse led, or diffuse a clear one (eg cover it with half a table tennis ball, or enclose it in resin or wax. You could also use higher-value resistors to limit current, or lower PWM_OC_MAX to limit the PWM duty-cycle (LED brightness) via software.

Source code and schematic are available as usual from

Pulse-Width Modulation provides colour choice

The microcontroller should be configured to obtain the system clock from the 8MHz internal RC oscillator. The ATTiny13 factory fuse settings include a divide-by-8 of the RC oscillator giving 1MHz, so remember to change that fuse to get the original 8MHz signal..

The overflow interrupt from the hardware 8-bit timer triggers an interrupt service routine (roughly 32000 times per second) which increments each of 3 separate 8 bit counters. These counters, and corresponding "Output Compare" (OC) values are used to generate 3 Pulse-Width-Modulated waveforms, with each counter being associated with a particular output pin. Every time a counter reaches zero, the corresponding pin is turned on. When the counter reaches its PWM_OC value it is turned off. When the counter reaches its PWM_TOP value (255) it wraps around to zero and the cycle repeats.

The effect of all this is that each of the 3 output pins is driven with a square-wave having a wave-legnth of 256 timer ticks (about 1/128 of a second), which is equivalent to a frequency of 128Hz (cycles-per-second). The OC value controls the "duty-cycle" (ratio of on-period to off-period) of the wave, with 0 giving always off, 255 always on, and any intermediate value giving a wave that is on for x/255 of a cycle and off for the remainder of each cycle. If an electric light is powered by such a square wave, with a frequency of more than about 50Hz, the human eye does not percieve any flickering---instead changes in the duty cycle are perceived as changes in brightness (this is how most household dimmers work). With 3 leds in Red, Green and Blue, and the ability to vary the perceived brighness of each, you can produce many different colours, exactly as is done in modern TVs and projectors.

So using 3 PWM outputs, we have a coloured light that we can set to any brightness and colour (denoted by a particular [R=x, G=y, B=z] tuple) that we desire.

BTW, it's not strictly necessary to use 3 separate counters. A single counter could be used with 3 different OC values to control each output pin independently. I chose to implement 3 distinct channels (rather than 1 channel with 3 Output-compare values) out of some voodoo idea that running the channels out-of-phase will lower the peak current draw and give slightly longer battery life. For example, if you set PWM_TOP to 240 and PWM_OC_MAX to 80, then if the PWM counters are initialized at 0,80 and 160, the 3 output pins will never be on simultaneously, and peak output current will never be more than 20mA. This also means you can get away with ONE resistor instead of 3.

Colour change by drifting PWM parameters

A coloured light isn't very interesting. But I have it on good (2 year old) authority that a pulsing and constantly changing light is captivating.

For each of the 3 channels, at the end of every PWM cycle (when the counter reaches 255), the duty cycle of the particular channel changes by a small amount. This causes the colour to change. The rate that each of the PWM channels changes duty-cycle is chosen semi-randomly such that an ever changing progression of colour is produced.

User interface

A pulsing coloured light is nice, but when you're 2, a BUTTON TO PUSH is best of all.

If the CHANGE button is pressed, the LEDs are reset to all off (OCx=0), and the cycle-rate of one channel is changed to a new random value, giving an abrupt change of colour, followed by a new and different progression of colour changes. Small children love this and will sit and frob the button for ages, before they break it or lose it. Then you can make them something else.

A second button acts as an "on/off switch" (actually triggering a low-power sleep mode, and waking from same).

Both buttons trigger interrupts via the pin-change interrupt facility. The buttons are "debounced" in software, by masking further interrupts for a certain interval after any button interrupt.


I prototyped this on a solderless breadboard, and programmed the ATTiny with an AVRUSB500v2 programmer, which has the useful advantage of using a 1x5 connector instead of the more common 2x3 or 2x5, allowing simple in-circuit programming of breadboarded AVRs.

Once I had the software working, I built a soldered prototype on a scrap of pad-per-hole proto-board. With only 5 data pins, and 2 power, you can just plonk the components down next to the chip socket, and either use point-to-point wiring and/or chains of bridged pads. If you're bridging pads, use the cheap phenolic protoboard, the high-end green fiberglass boards with solder masking are commendably resistant to solder bridging.

You can use any simple voltage regulator (or none). The ATTiny chips come in a 5v version that runs to 20MHz, or a low voltage version that will work off as low as 1.8v (but is limited to 4 or 10MHz) . I used an LP2950 low-dropout regulator, which will easily give you 5v from 4 alkaline cells, or 3.3v from 3 cells. If you're using a 9v battery, the cheap and common 78L05 (which needs an input of at least 7 volts) works fine too. You could even leave the regulator off entirely, if you use a 4.5v alkaline pack or a 3.7v lithium. The low-votage ATTiny13v is remarkably forgiving (but remember to set the brown-out fuses to an appropriate low-voltage cutoff).

I haven't bothered to design a PCB yet, as it wouldn't be significantly more compact than the protoboard version. I suppose an SMD version would be interesting---it could be made not much larger than the coin cells that power it, giving some interesting swallowing-hazard fun to be had.

Protoboard Light Up Thingy

Friday, 6 November 2009

A simple presence-sensing LED lighting controller

Low power LED night-light

Every time I see household lighting left on overnight for "security", I think of the coal-smoke belching into the atmosphere to power it. This kind of silliness has got to stop, besides the environmental cost it will soon become prohibitively expensive if carbon-taxing ever gets off the ground. My kids, however, (aged variously 1-7) have a habit of getting up several times in the night to bump their way to the bathroom, and they always leave every light switch they encounter on the way ON (not actually being awake enough to deal with turning them off).

We've been leaving a (low wattage) light on to give enough light to get around. Now, you can go out and buy motion-sensitive night-light devices for basically peanuts (eg,, but the motion sensors are often fake (just a visible light sensor, which does not work in darknesS). Besides, I never did like to do anything the easy way when I could make a production of it, so I designed my own. It makes a neat trainer project for the Atmel ATtiny microcontrollers. The primary design elements are:

  • Pre-built Passive-Infrared motion detector module
  • Atmel ATTiny45 Microcontroller. Also works on Arduino & variants.
  • 0.5 watt high-brightness LED (or an SMD LED-array)
  • Ability to override sensor with an on/off switch
  • Adjustable brightness via holding down on/off switch
  • Timed fade-out to allow enough time to leave the room
  • Also suitable (without PIR sensor) for fishtank lighting

LED Lighting

I orginally chose a 10mm 0.5W LED (from Oatley Electronics), because it is bright enough to light a bathroom or hallway at night, yet does not require any heatsink. A resistor is used to limit the maximum current to around 150mA at 5v.

Since I first created this project LED arrays have become stupidly cheap, typically sold as automotive interior and underbody lighting. Examples are here and here.

Arrays of 10-100 SMD leds, either in grids or strings are available pre-assembled with integrated current-limiting resistors suitable for 12v power. Typically 4 or 5 LEDs are chained with 1 resistor, and 1-20 chains are connected in parallel. The entire array consumes only tens or hundreds of milliamps at 12v, and produces a quite impressive amount of light. The version of the project presented here is capable of driving LEDs from either 5v (via regulator) or from the external voltage input (eg 12v).

PIR module

Pre-assembled Passive Infra-red sensor modules are available that combine a PIR sensor, control circuirty and lens. You simply supply power and monitor a TTL output line. One inexpensive source of these modules is

Circuit and software details

Source code and hardware files are available at GitHub.

Voltage regulator

You can power the circuit from battery, from a regulated power source (say an old phone charger), or use a regulator such as a 7805 or MCP1700 to get 5v from an unregulated supply. If you are powering your LED from the regulator (rather from the main supply), choose a regulator that can supply enough current.


An 8-pin ATTiny45 is used here, althoug it is hardly worked hard. The code can be made to run on an Arduino (or other ATmega device) easily enough. Only about 400 bytes of flash is used, and there are several pins spare. There's enough capacity left over to implement a communications interface, so your household LED lighting could be remote-controlled. I plan to work on this enhancement soon.

LED control

A transistor is used to control power to the LED. A general purpose medium power TO92 switching transistor capable of handling around 500ma (eg 2N2222, or 2n3907) is suitable.

The pads for the transistor are arranged to allow use of a TO92 or TO220 package.

A jumper selects whether the LED and transistor are powered from regulated 5v or external (12v) power.

A current limiting resitor may be fitted to the board, or replaced by a link when using a LED array with integral resistors.

The transistor itself may be used to limit LED current if operated in analog mode. I'm a digital guy, so I didn't try that. A good guide to selecting a base-current resistor value is at The Electronics Club

The microntroller drives the transistor with a Pulse-Width Modulated (PWM) signal, allowing the LED (or LED array) brightness may be varied over 256 steps from 0 to 255. This allows the main LED to be left in a low-brightness state as a night light, and also allows the light to be faded in and out gradually, which is kinder on sleep-deprived eyes.

PIR sensor interface

Aa 3 pin header provides power and ground to the PIR module, and reads the sensor's the TTL output signal. The PIR signal is connected to an input pin and monitored via a pin change interrupt.

The PIR module itself inhibits re-triggering for an interval after each trigger which can be adjusted via a trimmer pot.

If the LED array is off, and the PIR triggers, the LED array is faded on quickly. A 5 minute timer is started after which the LED array is faded off again. If a PIR trigger occurs while the array is lit, the 5 minute timer is reset. The effect of this is for the light to remain on while you are moving about, and to slowly fade off off five minutes after you leave the room. The on/off switch can override the timer for fast-off or remain-on.

Push-button Switch

Internal pullup is used to hold the button input pin high unless the push-button connects the pin directly to ground. De-bouncing is performed in software.

If the LED is off, the push button causes it to fade on quickly (over about 1 second). A release or second push while fading on freezes the light at that brightness.

If the LED is on, the push button causes it to begin fading off (over about 4 sec). A second push during fade-off freezes the light at that brighness (a dimmer). A third push resumes the fade-to-black (off).

Diagnostic LED and spare pins

There are at least 2 pins spare (more if you disable the RESET pin, or use fewer inputs). One of them has a normal LED connected to act as a power-on status light, handy for finding the on-switch in the dark if you do not employ a PIR sensor.

Headers are included for other spare pins for future use.

Some possible expansion ideas

  • a photosensor to turn LEDs off if room lighting or daylight is present

  • a communication interface (I2C, DOW or RS422) to allow remote control of lighting modules by home-automation systems, and use of the PIR sensors in as an alarm system

  • a Sonar or IR object sensor as a no-touch switch

  • a potentiometer connected to an analog input pin for setting minimum brightness level for 'night light' mode.


The circuit was prototyped and tested on a solderless breadboard, where the microcontroller was programmed in-circuit.

A version was then constructed on proto-board, of the type whose tracks are laid out like a solderless breadboard. This is a very handy way of migrating a breadboarded circuit to a soldered equivalent.

Once the design was proven to be workable, a PCB version was etched. A few shortcomings were made evident by the first PCB version - some of the tracks could have been made wider to give resistance to lifting due to component torquing. It would have been handy to run 5v to all the input jumpers, so that active sensors could be connected to any of the spare pins.

More pictures of construction and deployment in my pir-lite photoset.