It's been another few weeks of traveling and client work so I haven't had any chance to tinker. Apologies to those subscribers expecting the frenetic pace of my SQL blog - ain't gonna happen. I'm at home for a few weeks now though, so should have spare cycles to get back to the Arduino.

I'm very impressed with the kit - the instructions are *excellent* - totally suitable for a novice, but easily digestable by someone more advanced without being annoyingly simple. The packaging is great too - with all components packed and labeled separately - not something I expect, but a nice time saver.

The kit took me about 4 hours of soldering and neat lead-snipping to put together. I powered it on and it worked first time. However, it's supposed to work in the dark and I couldn't get anything out of it. The board looked perfectly put together so I contacted Evil Mad Science. Windell replied within 90 minutes with some suggestions. I replied that I've got a degree in electronics so talk techie - smileys ensued and we troubleshooted (troubleshot?). I'd hooked up a spare IR LED and shown that the phototransistors were working, but obviously the IR LEDs on the board weren't - with only about 10mV foward voltage across each. The whole IR LED circuit has 24V through it, so something was sucking down the power. I traced it to a broken IR LED with very high resistance both ways, and taking 18V - no wonder it wasn't working. I swapped out the broken LED and put in another, and hey presto! Great technical support!

Great kit to put together and I'm going to build a wall tile to hang in the house somewhere!

It's been a couple of weeks since I've been able to play hands-on with electronics because I've been busy with client work and out-of-town traveling.

To continue satisfying my must-be-tinkering-with-something urges, I hit upon the idea of using some old Windows code I had lying around to allow me to program LED matrices, without the LED matrices or an Arduino. This means I can effectively be developing code for the Arduino while on the road (we travel around 50% of the year seeing our clients around the world). The old code was for a life simulator (creatures running around fighting, breeding, etc) but it had all the code to display a bitmap on screen and update it already worked out. I figured that I could use it to simulate an 8x8 LED matrix - so off I went.

What it turned into is a couple of classes that simulate a maze and an 8x8, 16x16, or 32x32 LED display. I thought the code would be useful to a bunch of you so I've zipped it up for you to download and play with. The cool thing is that I can work on the maze processing code while on the road and then come home and drop it into the Arduino environment to compile and use. As long as I have LED matrix driving code on the Arduino, it should work like a charm.

Here's a screenshot of the simulator running:

Black 'dots' are on LEDs, spaces are off LEDs, the lighter colored dot is supposed to be a different color LED to represent a person. The simulator can switch between 8x8, 16x16, and 32x32 displays by pressing the Page Up and Page Down keys. Movement is through the arrow keys. The display mode can either be static with screen changes when the person crosses a window border (i.e. the person moves around on the screen) or scrolling, where the person stays still and the maze moves around. Pressing S switches between the two modes.

The code is in a zip file: Maze021710.zip (12.1k) and I've been using VS 2005 Professional to develop and debug.

There are plenty of comments in the code and I'm happy to answer questions about it.

In the last post I figured out how to drive a 74HC595 shift register to control 8 LEDs from only 3 digital outputs of the Arduino. Now I've taken that a step further and cascaded (sometimes called daisy-chained) four 595s together to drive 7-segment displays and also added code to accept input from the PC.

Instead of using 10-LED bar graphs like I did last time, I've moved on to 7-segment displays - which are more challenging and provide a more meaningful output. The 7-segment displays I have are common-cathode, wired as shown below:

The code to illuminate decimal digits on a 7-segment display is pretty straightforward. I assigned each of the 7 segment-pins on the display to an output on the 595, from QA through QG (see the circuit diagram below). Each pin from QA to QG is assigned a binary value of 2 ^ pin#, so figuring out which pins to make high to produce each decimal digit is just a matter of adding together the binary values representing each pin necessary to light up the right segments. You can see this array being initialized in the setup() function.

I've also moved to a proper coding style, with g_ prefixing each global variable to distinguish them from local variables inside functions and methods. It's a good practice to define unchanging variables as const to allow the compiler to optimize the code around them - this also prevents mistakes where the code accidentally tries to change the value - the compiler won't allow it as the variable is effectively read-only and a difficult-to-debug bug is avoided.

To daisy-chain 595s together is really simple - connect the serial output (pin 9) of the 'lowest' 595 to the serial input (pin 14) of the next one in the chain, and connect all the latch (pin 12) and clock (pin 11) inputs together. When the first 595 accepts a new bit, the highest bit in the register will be pushed out of it's serial line as input to the next 595 in the chain. Enough bits must be pushed to fill all the 595s with new data correctly. In the previous post I only had a single 595 so I only had to push 8 bits of data from the Arduino. With two 595s I need to push 16 bits, with the first 8 bits effectively flowing through the first 595 and into the second. And so on with more 595s in the chain.

Care must be taken to push the 8-bit values in the correct order - the 8 bits for the 595 furthest from the Arduino must be pushed first, and the 8 bits for the 595 nearest the Arduino in the chain must be pushed last. I do this in the code in the sendSerialData() function by passing in the number of registers in use, plus a pointer to an array of bytes. Each element in the array has the byte to be pushed to the corresponding register - with the highest register number the furthest away from the Arduino. The code then iterates backwards through the away, pushing each byte in succession.

Rather than doing the obvious count-from-0-to-9999 code, I decided to figure out how to read input from the PC. This is done in the readNumberFromPC() function. If it detects that something has been sent from the PC, it reads each character, with a 10ms delay between each character read to ensure that all characters are received from the PC. Without the delay, the Arduino executes so fast that it may read the first character from the input stream, try again, and the next character hasn't made it over the slow (compared to the Arduino!) link from the PC - resulting in the input being chopped into two parts. This delay doesn't cause a problem with the 595s as their outputs are latched, and so stay the way they were set until the next update - preventing any display flickering.

In the loop() function, the logic to put the correct digit-byte in the register array is hard-coded. In the next rev I'll make this register-count agnostic.

As far as the circuit is concerned, I've got one 220ohm resistor on each 7-segment common cathode going to ground, which produces a bright enough display. I've also added a 100nF decoupling capacitor on the Vcc pin of each 595 to forestall any noise problems.

The complete circuit diagram is as below (click for a larger version):

Here's the breadboard layout, with a close up of IC2 (click for larger versions):

Once I'd figured out the wiring for one of the displays, adding the other three was pretty easy. At this point I ran out of 595s so I couldn't take the experiment any further, but I do have a bunch more on the way from Jameco.

I took a short (40s) video of the board in action - check it out here on YouTube.

And all the code is below(to download as a text file click here). Drop me a comment if you find this stuff useful!

[Edit: 12/19/10 - here's a link to someone who built a clock based on my code below.]

Next up - replacing some of the shift registers with transistors to allow a bigger fan-out from the Arduino.

// Simple function to send serial data to one or more shift registers by iterating backwards through an array.
// Although g_registers exists, they may not all be being used, hence the input parameter.
void sendSerialData (
byte registerCount, // How many shift registers?
byte *pValueArray) // Array of bytes with LSByte in array [0]
{
// Signal to the 595s to listen for data
digitalWrite (g_pinCommLatch, LOW);

// Read a number from the PC with no more digits than the defined number of registers.
// Returns: number to display. If an invalid number was read, the number returned is the current number being displayed
//
int readNumberFromPC ()
{
byte incomingByte;
int numberRead;
byte incomingCount;

One of the parts that makes possible the scrolling message kit I built over the weekend (see Kit building: Hansen Hobbies mini-scrolling LED sign kit) is a shift register. This is a very neat device that uses at least 2 inputs to load 8 parallel outputs. The idea is to pulse a clock input for each bit of data in the 8-bit register, loading each bit in succession until all 8 bits have been loaded. The shift registers in the kit I made are 74HC164s, which means that the outputs immediately go high or low to relfect the bits as they're loaded into the shift register and shifted along into their desired positions. Many people prefer a latched shift register, where the outputs reflect a steady-state of the register until all 8 new bits have been loaded, and then the outputs change to the new bits in the register (i.e the latched register has two registers - a true shift register and a storage register).

The simple algorithm to load a latched shift-register is:

pull the latch pin low

pull the clock pin low
pull the data pin high or low to reflect bit 1
pull the clock pin high

<repeat for bits 2 through 8>

pull the latch pin high

It's up to you whether you load the 8-bit value as MSB (most-significant-bit) first or LSB (least-significant-bit) first - you'll soon work out if you've got it the wrong way around!

I'm going to use a 74HC595 shift register that can source 35mA per output - perfect for driving the LEDs in my 10-bar LED arrays.

There are two ways to implement the logic above - using the Arduino shiftOut function or writing one yourself. I played around with both to make sure I fully understood what's going on - and I like bit-twiddling in C/C++. The Arduino site has a good language reference on shiftOut (see here) and also a tutorial on using the 74HC595 (see here). I decided to figure out how to use the chip myself so I internalized how to do it in future - but I'm not trying to be a purist and re-inventing the wheel.

The code I used is below, with the two different functions to push data out to the shift register. I had a problem with the code where I originally had the counter variable in the loop() function as a byte and the LEDs counted to the end and then stopped. I put in the serial output to do some testing and connected up with Windows HyperTerminal - so much easier to do it with this than when trying to debug code I'd written in the storage engine of SQL Server :-) Of course as soon as the counter value reached 256, it overflowed and was stored as 0, so no more LEDs being lit up. If you do this, don't forget to hangup before trying to upload a sketch to the Arduino otherwise it won't be able to grab the COM port.

My aim while building all these cool circuits is to re-learn all the electronics theory I knew when I got my electronics degree, but have forgotten in the intervening 15 years!

The kinds of circuits I'm most interested in right now are those that drive large arrays of LEDs from an Arduino. To do that, I'm going to have to create multiplexer circuits using transistors and shift registers, as the Arduino doesn't have enough IO pins to drive, say, 64 LEDs. The trouble is, I've forgotten how to do things like calculate the value of a base resistor and the algorithm for loading bits into a shift register.

First things first - refresh memory on Ohm's Law - Voltage = Current x Resistance. Now I can properly calculate the resistor required to put in series with an LED. The 10-bar red LED arrays I'm playing with have a 2.0V drop across the LED at 20mA current - so I need a resistor to take up the other 3.0V of my 5.0V supply and give me 20mA. R = V/I = 3V / 0.02A = 150ohms. This resistor is said to be limiting the current through the LED - without it the LED would burn out.

Now on to selecting a transistor that can switch the current. My electronics textbooks explain what to do, and I found various web pages that explained things in different ways, some of them contradictory! Kind of hard to find the right thing though - Googling for 'Arduino transistor LED' or 'transistor LED driver' and the like didn't turn up anything simple and useful - hence this post.

I want to switch on the current through the LED when the Arduino's output pin is high, so I'm going to use an NPN transistor in common-emitter mode. If I wanted to switch it on when the output from the Arduino is low, I'd use a PNP transistor.

I need a transistor that has:

1) a maximum collector current (IC) greater than my desired load current of 20mA

2) a minimum current gain (hFE) that allows me to comfortably source a base current IB from the Arduino pin that will give me the collector current I need. When the Arduino pin goes high, current flows into the transistor base, turning it on and allowing current to flow through the collector to the emitter - lighting up the LED. I don't want too much current flowing into the transistor base otherwise it will damage it.

I want an IC of 20mA, and the maximum output current from the Arduino pin is 40mA. The hFE should be at least IC/IB * a safety factor (e.g. 10). In this case, that works out to be (20mA/40mA)*10 = 5. This isn't really a concern here. If I was trying to drive 600mA from an IC that could only source 5mA through a transistor with a gain of 100, that would be a problem.

On hand I have some BC337 transistors with a minimum current gain of 100 @ 150mA - perfect!

Now I need to calculate the right base resistor value so the transistor will be fully on (saturated) and act as a switch rather than acting as an amplifier (where collector current is proportional to base current). The required base current IB = IC/hFE = 20mA/100 = 0.2mA. This is way lower than I need to be careful of. If I go for a 4.7K resistor, this will give me IB = (5V-0.7V)/4.7K = ~1mA - plenty to make sure I get the load current I want. The 0.7V is the voltage drop across the base-emitter junction when the transistor is on.

Amazing how all the theory comes flooding back - now I don't feel like I'm groping in the dark picking resistor values!

Now I've figured out the circuit to use, I'm going to draw a circuit diagram. I found a freeware tool from ExpressPCB that allows you to draw circuit diagrams really simply (and if I ever want to get PCBs made, I won't need to learn another tool). I'd like to start making a habit of this so it's easier for others to understand my circuit, and for my future reference. The circuit is below, with a photo (click for larger image):

The Arduino code to test the circuit is very simple, using pin 5 to drive the transistor switch:

I finally had some time over the last two days to play with the Arduino board I picked up late last year. The Arduino is a pretty neat concept - wrapping a microcontroller up in a neat board that makes playing with sensors, displays, motors, etc and prototyping very simple. It's all open source and you can read more about it on their homepage (http://www.arduino.cc/) which also has a freeware IDE to use for programming. The board I have uses Amtel's ATmega328P processor, with 32K of flash memory and can do 20MIPS. They're very popular and opening up electronics and gadget hacking to non-techies.

Here's the 2009 rev of the Arduino Duemilanove board (image from their website, click for larger version):

They cost about $30 - I got mine as part of a kit from the Nuts'n'Volts magazine store but loads of online stores have them. I just picked up some accessories yesterday from SparkFun who have the full range, including the Arduino Mega which has 54 IO pins - can't wait for that to arrive!

The possibilities for this are just endless. The IDE provides a full C++ environment with a bunch of helper classes already defined, which takes a lot out of the tedium of programming microcontrollers. If you're going to play with this, I recommend using some of the samples that come with the IDE and on their very extensive web site.

My current interest is with making things light up in clever ways so I thought I'd start off by writing a simple program to play with an LED array. The circuit's very simple: pins 2-11 from the Arduino connected to the LED array, which is connected through 220ohm resistors to ground on the other side. First time I goofed and put the resistors into the breadboard on the Arduino side of the circuit, to no effect whatsoever. Future, more complex projects will include a circuit diagram (once I find a nice freeware program to do it), and of course, correct resistor positioning :-)

Here's a photo of the board connected up and a close up of the very simple circuit (click for larger versions):

Don't try to use pin 1 as a digital output, it won't work.

I put together two easy programs - one to move the lit LED from right-to-left and back again and one to move the lit LEDs from the middle out to the two sides and back in again. Kind of Knightrider-esque, but also the way the old SUN machines I used at university had their status lights on the back of the machine.

The code for the first one is:

/*
10-bar LED array

Connect the LED array to pins 11-2 and through a 220R resistor to ground on the other side.
01/14/2010
*/

Note there's no main() function - it's all taken care of. The wrapper calls your setup() function and calls the loop() function in an infinite loop. You only have to provide these functions and you can use all the C++ programming constructs (if you want to) or keep it pretty simple.