Wednesday, 30 November 2011

Serial/UART communication between two PICs (18F and 16F)

It's taken a long time and a lot of different approaches to get even simple serial communication between two PICs working. Perhaps hampered a little by using two different PICs (a 16F and an 18F series chip) but that really shouldn't make any difference. Serial/UART communication shouldn't be platform dependent!

We've tried serial/UART, SPI, I2C and even bit-banging and each time got different (non-working) results. It's too much to go into in this blog post, so we're just going to describe how we actually got a working prototype:

The first thing to note is that although we're using one of our favoured 18F4550 PICs, we couldn't use the USB  and UART together. So for this experiment, we're reading the data back off our 18F (master) chip via serial, using the excellent PICKit2 programmer and software.

In our first (failed) attempt at creating pic-to-pic communication, we had our 16F (slave) device monitoring it's input pins and simply broadcasting the results as an 8-byte message over UART. The idea was for the 18F (master) chip to read this serial stream at intervals, find the start of the message and decode the rest of it, so that it knows the state of the slave chip.

In theory this sounds fine. In practice, sending more than about 4 bytes to the 18F (master) chip caused it to lock up on the Hserin command. We even tried connecting the PICKit2 to the RX pin on the 18F and removed our slave chip altogether. Our tests confirmed the same thing happening - if we sent one or two bytes at a time to the 18F from the PICKit2 terminal, it successfully received them and sent a response message back. If we sent more than about five bytes at a time, the 18F simply stopped responding - apparently locking up at the point where it reads in the serial data
(we proved this by switching an LED on just before the Hserin command, and turning it off again immediately after).

So it appears that we have a set-up whereby we can receive data from our slave, one byte at a time, but the master can't simply "dip in" to a serial stream being "broadcast" by the slave. After reading through the datasheet, it seems that the 18F has only a two (or was it four) byte buffer so blasting more bytes into the buffer than it can handle is causing some sort of buffer overrun error.

We need some way of getting the master chip to ask for data, one byte at a time.
This is what we came up with:

The master chip sends a pin high then requests a byte from the serial buffer.
The slave chip monitors the state of the "handshaking" line. When the line goes high, and the previous line state is low, this represents a request from the master, so send one byte.
Because we're using hardware UART on the master chip, after the line goes high, the code waits until a byte has arrived in the serial buffer. Because the slave only sends a byte on a low-to-high transition on the handshaking pin, we don't have to worry about buffer under-runs or errors in the master chip.

Slave code
'4Mhz external clock
Define CONF_WORD = 0x3f31

Config PORTB = Input
Config PORTD = Input
Config PORTC = Input
Config PORTA = Input

       Dim linestate As Bit
       Dim lastlinestate As Bit
       Dim a1 As Byte
       Dim a2 As Byte
       Dim a3 As Byte
       Dim a4 As Byte
       Dim a5 As Byte
       Dim xorval As Byte
       Dim bytecounter As Byte
       WaitMs 50
       Hseropen 9600
       WaitMs 50
       linestate = 0
       lastlinestate = 0
       bytecounter = 1
       'all the slave does is read a whole load of input pins
       'and write the response back to the master. The master chip
       'will decide which "row" is live, this chip just takes all
       'the "column" data and sends it back to the master.
       'RC0-5 (6&7 are TX/RX)
       'this should give us 6+7+6+8+3 = 30 inputs
       a1 = PORTA And 63 '(mask off bits 7+6)
       a2 = PORTB And 254 '(make off bit 0, handshake line)
       a3 = PORTC And 63
       a4 = PORTD
       a5 = PORTE And 7
       'now stream the values as a response back to the slave
       'all messages begin 255,255 (since this sequence is not
       'possible in the input stream because we bitmask bytes 1,3,5)
       linestate = PORTB.0
       If linestate = 1 And lastlinestate = 0 Then
              'the host chip has asked for another byte of data
              'create the checksum value
              xorval = 0
              xorval = xorval Xor a1
              xorval = xorval Xor a2
              xorval = xorval Xor a3
              xorval = xorval Xor a4
              xorval = xorval Xor a5
              xorval = xorval And 127

              'decide which byte of the message to send
              '(the host has to ask for each message eight times for all 8 bytes)
              Select Case bytecounter
                     Case 1
                     Hserout 255
                     Case 2
                     Hserout 255
                     Case 3
                     Hserout a1
                     Case 4
                     Hserout a2
                     Case 5
                     Hserout a3
                     Case 6
                     Hserout a4
                     Case 7
                     Hserout a5
                     Case 8
                     Hserout xorval
                     bytecounter = 0
              bytecounter = bytecounter + 1
       lastlinestate = linestate
Goto loop

Master code


       Dim a1 As Byte
       Dim a2 As Byte
       Symbol lineshake = PORTA.0
       Config PORTA.0 = Output
       Low PORTA.0
       WaitMs 200
       Hseropen 9600
       WaitMs 200

       Gosub getnextbyte
       'two 255 = start of message
       Hserout 255
       Hserout 255
       Hserout a1
Goto loop

       'to get the next byte, we send the lineshaking
       'line high - this tells the slave to "release"
       'another byte. Once we have this byte, we drive
       'the lineshaking pin low to say we're done
       High lineshake
       Hserin a1
       Low lineshake

After connecting up the slave to the master (the TX pin of the slave into the RX pin of the master, and RA.0 on the master to RB.0 on the slave) we did actually start receiving intelligible data from the master. So it looks like we've (finally) cracked pic-to-pic communication over serial.

It's probably a bit slower than it needs to be (since the master has to "poll" each byte from the slave) but it's fast enough for what we want - and once we crank the baud rate up from 9600 to about 57600, or even 115200, it should be more than quick enough to scan an entire game board (of not more than 16 x 28 = 448 squares) at a reasonable rate.

Communication between two PIC microcontrollers

We're having a bit of a nightmare getting two PICs to talk to each other.
The master is an 18F4550 which will do most of the grunt work and talks to the PC host via USB (we use Oshonsoft's excellent USB/HID library for our USB work).

The slave is a 16F877A (no reason for this particular model other than we had quite a few of these lying around). This basic idea is that the 16F reads 28 input pins and writes a four-byte value out to the serial port.
The master periodically polls the slave, reading the serial data. It looks for two specific bytes which signify the start of the message, then reads in the next four bytes that make up the message (the fifth byte is the XOR sum of the previous four bytes so we have some sort of checksum).

The problem is that while we can check the 16F using the PICKit2 UART tool - and it successfully reads the message being "broadcast" by the slave - when we try to read data using the hardware UART port on the 18F master chip, the USB comms lock up and our PC app stops working.

It seems that we aren't the first people to run into this sort of problem and there are lots of queries across the 'net asking for help with USB and serial comms together. Here's just one example:

So it looks like USB and UART together isn't going to work.
Which is a bit of a bummer.
Also, like the author of the article above, we were also hoping to use the timer1 interrupt to keep a simple clock running, which makes software-based bit-banging and no-go either. Getting a PIC to work as an I2C slave looks quite complicated too, so we're running out of ideas.

The only thing left for us to try is getting two PICs talking to either other using SPI hardware on both the master and slave chips.

Hopefully this will work with both USB and timer1 interrupts running on the master chip. But until we try, we're not going to know......

PIC16F877A resetting

This is just a general post to remind anyone like me who often forgets the basics and spends far too long trying to find faults with hardware/firmware that just aren't there. Although in my case, it's specific to my 18F877A, the same rules apply to 16F628A chips and pretty much any of the 16F range.

Here's why I'm so stupid......
I've been working a lot lately with 18F series chips.
These are great because they have loads of different "fuses" which let you set up the chip in a particular way. One of the fuses on the 18F range allows you to reclaim pin one - the MCLR/PGV (programming voltage) pin and set it to an input. I do this with pretty much all my 18F chips.

So when I came back to the old 16F series chips (the 16F877A is an old favourite that first got me interested in PIC programming) I completely forgot that you need to apply 5v to the MCLR pin to stop the chip from resetting (pulling this pin low causes the PIC to reset completely).

So during testing, while trying to read the serial message(s) being "broadcast" from my 16F chip, I kept getting blackouts - periods when the serial stream would stop. Wiggle a few wires around on the breadboard and it would come back to life. For a little while.
Everything was pointing at a hardware problem - either a dodgy wire or a loose crystal or something. I re-wrote the firmware on both the slave and master chips, stripping each down to just the bare essentials, and used a really handy tool in the PICKit2 software to monitor the serial stream

You can connect anything that uses serial comms, and set the baud rate to any of the common bps values - 1200, 2400, 4800, 9600, 19200, 38400 etc as well as your own custom baud rate (ideal for debugging MIDI devices at 31250)

Anyway, after connecting everything up, setting it running and not touching a thing, the 16F would periodically shut down. I stripped out all the wires, rewired the board with a brand new set of jumper wires, put LEDs on all kinds of output pins and so on. I checked and double-checked the fuses, made sure the watchdog timer was disabled (and even tried enabling it and littering the firmware with watchdog reset commands) and checked the brown-out option wasn't selected. I even put a few different capacitors on the power rail of the 16F, just in case the input voltage was getting a bit wobbly.

The whole thing was suddenly a lot more complicated than any other PIC project I'd ever worked on and still it kept resetting.....

.... that's when I remembered that pin one (MCLR) has to be pulled high to stop the, erm, PIC from resetting all the time. Bugger.

It was as simple as that!
A single wire from pin one to 5V and everything worked beautifully.
If I had remembered about the MCLR pin earlier, instead of assuming it was always set to behave as an in input pin I think I'd have saved myself about two hours this evening.

Hopefully this post will help others in future to avoid wasting a similar amount of time on something so trivial!

Electronic board game - Blood Bowl clone

Some interesting developments over the last few evenings as we've put together all kinds of ideas for an intelligent board for a board game (like, our old favourite Blood Bowl).
Our original proposal - based on freeing up as many pins as possible from two 40-pin PIC microcontrollers - was to allow for up to 600 squares, or a grid of 20x30

To allow for as much flexibility as possible, while at the same time making it relatively easy to understand, we've decided on a modular approach. Our board game will actually be made up of a grid of 4x2 "blocks" which can then be wired together in any arrangement. It means we've lost the flexibility of really wacky board layouts (although using the same technology it should be possible to create one-off boards with pretty much any layout as required) but does mean that we can simplify making boards of different dimensions.
(it also means that anyone who buys their copper boards in eurocard 100mmx160mm size can still make a board game, using a "patchwork" of smaller boards)

4x2 Board Piece

Each playing square in this board is marked out by a "cross" shape on the board. Small through-hole studs are soldered to this underside, so that on the playing side of the board, a small contact point is visible on the playing surface. Each playing piece has a conductive base (a copper coin glued to the bottom would suffice!) and when placed over the four points of a cross, makes a connection between the top and right contacts and the bottom/left contacts.

Using the above layout, we can place these pieces side-by-side and join the edges, while connecting each group of top/right contacts together using short pieces of (insulated) wire

Using this approach, we've designed our Blood Bowl board.
It's not quite 30 x 20, but we found that vertically connecting 7 "rows" of 4 contacts means for each row we can read back up to 28 lines of "column" data. By placing four of these smaller boards side-by-side, our board size is 28 x 16 playing squares. Not a bad compromise and certainly a sizeable playing area for a lot of different board games.

So what does it look like? In short, a nightmare!

As you can see, each smaller board is connected to the board horizontally next to it (the traces were deliberately lined up to make this bit quite easy). Every 7 vertical rows of contacts are connected via wire traces (shown in this diagram by different coloured bars) and each group of these 7x4 = 28 contacts is then connected to the slave microcontroller via a short wire (the connection points for these wires are circled in a matching colour).

There are 16 wire connect points - these go to the master PIC. The 28 traces from the bottom/left sets of contact points are connected to the slave. By flashing one of the 16 wires at a time, and reading the input values on the 28 inputs, we should be able to work out which set(s) of contacts are being bridged by a playing piece on the board.

That's the theory anyway.......

PICKit2 clone programmer alternatives

Something has happened to our faithful old PIC programmer - it was (was being the key word) a PICKit2 clone, iCP01 from and had worked tirelessly for about three years.
But for some reason, it has suddenly stopped working.
No puff of smoke or funny smell - it just stopped working.

At first it had problems recognising a 16F877A DIP, so - as we always do before wiggling wires - it was removed from the USB port (removing any power from the breadboard) and then when it was plugged in there was no "bing-bong" or any indication that the PC had recognised the USB device.

That's it. Despite stripping off the yellow shrink wrap and inspecting the components on the board (nothing seems to have blown and there's continuity across the connections where you'd expect there to be) the device simply refuses to work.

The PICKit2 software doesn't even recognise that the device is plugged in, and Device Manager fails to identify it too. So it's officially dead. The question is, do we get another one (they're great little programmers and really fast too) or try something else?

Tuesday, 29 November 2011

Multi-plexing LEDs for word clock

Having failed miserably at debugging our charlie-plexed LED array we've decided to stick to the simpler approach of using multi-plexing.

There's a subtle difference, but since we're already getting down and dirty with multi-plexing for inputs on a board game it made sense to use this same approach for outputs/LEDs. The main difference is that we'll be using a pin for each row and a pin for each column (10 rows x 9 columns = 10+9 = 19 pins).
If we move away from the 16F628A (with 18 pins) and go far a larger chip, with more i/o pins, then multi-plexing gives us a simpler, easier-to-debug solution.

With this in mind, we set about creating a new PCB to use multi-plexing.
So far we've just put a load of LEDs into a grid formation - the actual controller board will be a separate PCB mounted onto the back:

Uln2803a Driven LED array

Here's a photo of the completed board, populated with LEDs, ready for testing.

Unlike last time, testing LEDs is quite straight-forward; and already we've found some potential problems; a lot of the LEDs are re-used from the old board and by connecting a 3v coin-cell battery straight across the anode and cathode of each LED, we've found about half-a-dozen that refuse to light up.

Whether these were damaged during removal, or never actually worked on the original board, we'll never know. But at least we've an explanation as to why the charlie-plexed board didn't work. Sort of.

Anyway, we're going to pop out those duds and test each individual LED on this board before even considering wiring it up to the rest of the project!

Monday, 28 November 2011

The nerds are off to Berlin!

Ok, it's only for a week or so, but we've confirmed our tickets for early next month (December). And a quick look on tells us that there are no less than 12 hackerspaces, in Berlin alone!
We won't have time to visit all of them (unless we go to three different ones on each day we have free) so we'll have to concentrate on English-speaking spaces for now (a few of us can speak French to an ok level, but German is a whole new language!)

Woo-hoo, Europe here we come!

Sunday, 27 November 2011

Using 2 PIC micros for a huge input array

After spending some time thinking about a large board game input device - which simply tracks the position of each piece by comparing the current board state to a previously known state - we've decided that a multi-plexed approach will probably be the easiest to implement.

The problem with a multi-plexed approach is that whatever size grid is used determines the number of pins needed (so a 10 x 10 grid needs 10+10=20 i/o pins).

Rather than try the idea out with something simple, then discover it doesn't expand well for bigger/more complex games, we've decided to have a go at quite a complex game, and - if it works - scale it back for simpler board games. For now, we're concentrating on tracking the positions of "dumb" game pieces on the board throughout a game.

One of our favourite geek-games of the 80s was Blood Bowl (which thanks to a console remake being released in 2011 is seeing a bit of revival in recent months). Now, the original Blood Bowl board was a massive 15 x 26 = 390 squares in size.

Obviously, using a PIC with only about 30 spare pins is never going to cut it. So we're back to either using analogue inputs or increasing the i/o pins using shift registers. After much discussion, however, one idea really started to appeal: use two PIC microcontrollers!

This is not only cheaper than implementing a whole array of shift registers, but also gives us a bit more oomph to play with, as we could split game play up over a master and a slave controller.

We're planning on using the master to activate an entire "row" of inputs (the output Port1 in this previous port) but then to start listening on a serial RX pin for a response from the slave. The slave micro simply looks at the input state of all the pins (uC Port2 input in this previous post) and sends this back to the master via serial TX.

Because the master knows which row it activated, it can decode the value received over serial and work out which combination of buttons/inputs were activated. Now, by using 2 x 18F4550 chips, we've up to 30 pins available on each chip and a grid of 30 x 30 inputs (900 squares) is suddenly achievable.

For our Blood Bowl game, we could easily implement a 15 x 26 grid of squares and still have about 15 i/o pins freed up on our master controller (this controlling 15 rows, with the 26 inputs on each column being read by the slave controller). With this in mind, and after much more discussion (and a few more cups of tea and a whole packet of hob-nobs) we reckon we could come up with a generic board game controller which would have:

a) support for up to 600 squares (e.g. 20x30 but not necessarily in a square formation)
b) an LCD display for each player/side which can display current game status
c) built-in dice roll and other random-number generators
d) ability to calculate results/outcomes which would otherwise require dice rolls and table look-ups in the rule book

Although we've not actually built anything yet, this is quite an exciting development.
We remember Blood Bowl as being a great game, but bogged down with dice rolling, looking up results in tables, applying modifiers based on the playing piece type and so on. The Third Edition of Blood Bowl tried to do away with a lot of this by using a simpler dice system, but eventually the same thing happened: the immediate action could be resolved quickly (did a particular action succeed or fail) but when this affected another players ability, yet more dice rolls and table look-ups were necessary.

 If we could remove all this dice rolling and referring back to the rule book and introduce a simple interface - so a player could pick up a piece to identify which is being moved, then press a button to say which action they were performing - the microcontroller could do all the random number generating and issue resolving; simply displaying a message on an LCD screen to the user, to inform them of the outcome and what to do next.

Here's how our Blood Bowl game could look with the clever electronics in place:

Using a multiplexed keypad for other input ideas

After a less-than-successful show-and-tell session at the weekend (yes, the one we've been devoting so much time and effort to over the last few weeks, and putting all our own personal projects on the backburner for!) the few people who did turn up spent some time discussing the various projects we were working on.

A few old ideas were explored once again - sometimes a fresh pair of ideas on an old problem can turn up some really interesting ideas in themselves - and a few new ideas were chewed over.

One of the ideas that came up was using a keypad style matrix, not for output (lighting LEDs like we were doing with our charlie-plexed array for the word clock) but for input. It came following the announcement that some of the members of BuildBrighton were looking to set up a monthly board-game-geek meeting (ok, we left Brighton some time ago, but it's important to keep in touch and see what those crazy guys are up to every now and again!). A few of us here at Nerd Towers remember fondly playing uber-geek board games like Blood Bowl, HeroQuest and Space Crusade, as pimply-faced youths, when they were first released during the 80s.

The idea being investigated is using a microcontroller to load data about each piece (a lot of playing pieces in these role-play type games had a range of different values associated with them) and then to place them on the board in a specific sequence. Each piece will be a "dumb" token - i.e. does not contain or broadcast data about itself - but the board-game controller would keep track of each piece on the board, based on when it was placed on the board, and comparing the current board state with a previously known state, to work out which piece has been lifted off the board.

A quick search on Google turned up some interesting results, but most solutions broadly follow one of two methods - a multi-plex approach (using a pin to activate a full row of inputs, then querying each pin on the row to see if it has been activated) and an analogue approach, to reduce the number of pins required.
Because we're potentially dealing with hundreds of squares on a typical board game (even the simplest of board games, chess, uses 64 squares in an 8x8 grid) we're keen to keep the number of pins required down to an absolute minimum:

With the correct value resistors, we should be able to read which key has been pressed using a single input pin. This idea looks perfect for what we need. However, in practice this is quite a difficult method to implement. Why?

The solution above is better suited to single-key entry, such as a telephone keypad or security pad, where each key is pressed, one at a time.

To be able to detect multiple key presses using a single analogue input pin, we'd need to use resistor values in roughly base-2 increments. i.e. 200 ohms, 400 ohms, 800 ohms, 1600 ohms, 3200 ohms etc.
Now we know that 
a) resistors don't always come in exactly the value we want so we have to go for a best match
b) resistors have up to 10% error in them already
c) reading an analogue input is not accurate - you need to take an average over time, or work with "bands" or thresholds, to decide the true value of the input on the analogue pin.

In fact, to get to 16 inputs, we'd end up using really huge value resistors - the error in which could be more than some of the lowest-value resistors, further down the array. In short, calculating unique key combinations on a single analogue input pin is going to be, at best, difficult and in practice, almost impossible!

Which takes us back to the multi-plex approach:

Here, we need to strobe each of D0, D1, D2, D3 and take multiple readings to calculate which pins are pressed. So, for example, we could force Port1 (output) D0 low (since the outputs are tied to Vcc through a pull-up resistor) and then read the values on input pin D3 on the Port2 (input).
Under normal circumstances, D3 is pulled high through the pull up resistor at the top left of the circuit. If, however, D3 is LOW, we know that button 3 must be being pressed down. Now we read the value of Port2 D2. Like before, we expect it to be high (no button pressed) but if it is low, this tells us that button 2 must be being pressed. Similarly, if Port2 D1 is low, button 1 is pressed, and if Port2 D0 is low, button 0 must be being held down.

Now we sent Port1 (output) D0 high and pull Port1 D1 (output) low.
Checking the input pins again this time tells us whether buttons 7,6,5 or 4 are held down.

Although this approach uses more pins and appears more complex (in execution rather than in hardware) it does allow us to tell exactly which combination of buttons are pressed, even if two, three or more buttons are pressed all at the same time.

We're looking at the 18F4550 which is a 40-pin PIC microcontroller (and includes USB so we can easily download game data onto the chip) but when you take out all the used pins (2 x power, 2 x ground, usb etc) we're lucky if we have up to 28 pins to play with.
In a grid arrangement, this gives us not much more than a 14 x 14 matrix which is pretty small for anything but the simplest of board games......

Thursday, 24 November 2011

Fanell Blogger Outreach Program

Here at Nerd Towers, we're big fans of Farnell.
The level of service, fast delivery but most of all, their amazing website leaves the others in the shade!
Although you can sometimes save a few pence (or even a few quid) by going to competitors such as RS, Rapid, Mouser, eBay etc, you often find buying a few bits from one, and a few bits from another - just to get the best deal - means waiting ages for all your different suppliers to send stuff out.

Wherever possible we try to source all our components in one hit, from one place. And more often than not, it's from Farnell.

The reason is because their website is so easy to use!
I've never really browsed by category, or spent any time just clicking from item-to-item. I go straight for the search bar, type in what I want and then apply different filters to the results until I get what I want. Unlike some sites (*cough* RS) where even if you provide the exact part number you don't always get a match, the Farnell site has some really clever search intellegence behind it. You can even type in a vague description of the sort of thing you're after and it'll have a stab at what it thinks you mean. And then alongside each set of results, are alternatives or related components. Not Amazon-style-other-people-bought-this, but actually complimentary alternatives to what you've found.

Now we must add in a caveat to this Farnell-love-in.
But it's just another reason we put them above the others - brand loyalty.
Like most other "tech" suppliers, Farnell recently entered into the "community" arena; RS have their DesignSpark community (and their, frankly, dismal PCB design software), Instructables was recently bought up by AutoDesk - suppliers of the eye-wateringly expensive AutoCAD - just to get a community base and even gave away free versions of their CAD software, and Farnell launched element14.

In fact, element14 was one of the first to recognise that what drives geek-communities is a challenge. So they set up the Global HackerSpace Challenge. They even gave each hackspace a budget to buy stuff with. Not drop their own branded "freebies" onto them as a cheap alternative to beta-testing, but gave away real, genuine cash, and said "go buy stuff, make something with it, tell us what you made".

Now Farnell are continuing in this vein, giving away yet more stuff - but allowing the recipient to decide what to choose, not just promoting their own range of products. It's called a "blogger outreach programme".

And we think it's a great idea.
But then again, we probably would, since we're one of the lucky recipients!
It's hard, being given the Farnell catalogue to choose from, to decide what to go for. Choose something too expensive and you just end up looking greedy and getting expensive stuff for the sake of it. But then again, a handful of resistors worth 50p are hardly worth bothering with! In the end, we took a look at the projects we had on the go, and decided to grab some freebies to help complete them.

So yesterday we received 100 SMT LEDs which originally were going to be for our word clock project (using SMT means not having to drill over 200 holes on the next board!) but we might just incorporate into a full-sized light-up guitar fingerboard.

[photo here]

Since we've spent many months working on our range of miniature instruments, we've neglected what it was that first sparked the initial idea - that is a love of cool/geeky (full-sized) guitars. With a load of LEDs, we started designing an acrylic fingerboard (yup, acrylic. Not rosewood or ebony or maple - the usual choice of wood for a fingerboard, but good old laser-cuttable plastic!) The idea is to create a "learn to play" guitar neck, which can light up and show you where to put your fingers. Such guitars do exist, from places like FretLight, but they're quiet expensive!

We've a load of cheap guitars (off eBay) that play ok so we're going to try to retro-fit a light-up fretboard onto an existing instrument. But once we're done, we want the rest of the guitar to light up too!

So our second freebie from Farnell was a selection of EL (electro-luminescent) wire which we're planning on putting around the guitar body, for the ultimate glow-in-the-dark finish!

[EL wire photo]

We're really looking forward to spending a bit of time doing what we do best - just nerding out with a bunch of components and seeing what we can come up with. And, of course, posting the results on our blog.
Check back for progress updates soon!

Multi-lights controller for toy cars

As one of the younger members of HackLlan Jason was busy making LED traffic lights for his younger brother last Thursday. This week, we've been working on taking that idea to the next level.

Instead of a simple pin-on, pin-off with delay approach, we've changed the code in the microcontroller to use a single Timer0 interrupt (raising an "event" every 1ms) and a number of counters and state machines to control lots of different devices all at the same time.

Instead of the smaller 16F628A chip (used in the original prototype) we've gone to the other end of the scale and put in a massive 40-pin 18F4550. This gives us plenty of i/o options. So far, we've kept PORTB for inputs (using the internal pull-ups to reduce the final component count), put the traffic lights on PORTD and used PORTC for the servo and LED controller for the level crossing.

The what???

That's right. This controller now simultaneously handles:

  • two sets of inter-dependent traffic lights
  • two sets of alternate flashing level crossing lights
  • two servos (level crossing gates)
  • a one-shot fire-on-release ultra-bright LED (speed camera)

There are still plenty of spare i/o pins to add more to this project in the future (pelican crossing, belisha beacon etc) but we need to think about finishing off what we've got here, otherwise it'll be Xmas and we'll still have everything on a loose-wired breadboard (which let's be honest, won't be much of a final gift!)

Here's a video showing the breadboard, controlling all the different lights and servos at the same time -
well done Jason!

Note how the traffic lights continue to work independently of the other things on the board - the alternating lights work separately to the traffic lights, and the servo signals are being sent every 20ms to update the servo horn/gate positions. And all the while the speed camera goes off at periodic intervals!

Sunday, 20 November 2011

Debugging charlie-plexed LED array

All of the online tutorials that mention charlie-plexing and LED array over using shift registers list pros and cons. The pro is always few components, simpler layout etc. and the cons always include "difficult to debug".

They're not wrong!
Since getting our 90-LED charlie-plexed array soldered up nearly a week ago, there's still little improvement on getting it to work properly! We did track down a few broken traces (the black toner in the printer was a bit faint in places so a few traces over-etched and had breaks in them). But even after fixing those, and spending hours and hours with the continuity tester/multimeter, there are still six different scenarios that cause the matrix to fail.

Although we feel we're close to solving it (having identified which pins cause it to fail) the last bit - understanding our findings - is still as elusive as ever! Here's the array working as it should:

The sheet in the background is a drawing of our findings - the six scenarios that cause the matrix to fail and the LED pattern created, instead of a single LED lighting up

Every now and again, however, we get something like this result

 The LED we expected to be lit up is in the centre of the "cross" shape - and remains stubbornly unlit

Even more peculiarly, we did some measuring with the voltmeter. When an LED is lit properly (from a 5v source running through 200 ohms) the voltage across the cathode and anode pins is around 2.9V. The voltage across all the other LEDs in the same row/columns is about 0.6V which is the typical voltage drop across a diode, but not enough to cause it to light up.

When we measured the voltage across the pins of an LED that wouldn't light up (the one we expected to light up but is in the middle of the cross - and remains unlit) we got almost a full 5v across the two pins. All the other LEDs that were faintly lit measured about 2.8-2.9V. So in this case, with the dim LED in the centre of the cross, we're measuring 5V across the pins, but it does not light up.

Here's a diagram of the pins combinations which don't work, and the LED "patterns" that are lit up.
If anyone can spot a pattern or - better still - come up with an explanation, please leave a comment below (and anyone else in future having similar problems might have some idea where to begin debugging!)

Tuesday, 15 November 2011

Testing our 90-led charlie-plexed LED array

There's something not quite right with our LED array.
In the main, it works fine. By simply applying 5V across different terminals we can see individual LEDs light up. Here's an example of lighting a single LED by applying 5v across two of the 10 available terminals:

(yes, that is Jason's traffic light LED project - I just nicked the 9v battery and 5v regulated output for the sake of testing this new board!)

But every now and again - and it is just every now and again, not very often - we get a peculiar result. Instead of single, bright, LED lighting up, an entire row (and sometimes part of the column) lights up too. We're putting this down to either a dodgy LED somewhere, or an LED being soldered in the wrong way around.

At the minute there's no real pattern to which combination of terminals gives the bad response.
There's one way to get to the bottom of this - to build an LED tester:
The idea is to create something that we can control which pin takes 5v and which takes ground, and record the result in a truth table (similar to the table created at design stage). Hopefully by cross-referencing these results to our schematic, we should be able to identify which LED(s) are common to all the problem terminals.

Monday, 14 November 2011

Charlie-plexing 90 LED array for word clock

Despite somehow printing the PCB for our word clock project at about 90% (so the 0.1" pitch connector won't fit properly!) we decided that we'd put too much work into the first version just to scrap it - drilling over 200 holes by hand was over an hour's work on it's own!. We do now have a "proper" sized board, but we figured that we could use this messed up one as a proof-of-concept prototype.

So we got 100 white 3mm LEDs off eBay and set to work.

We started out with the top row of 10 LEDs - soldering the legs but NOT cutting them to length. Then after the second row of ten LEDs had been soldered in, we could bend the legs on the top row across to solder to the LEDs on the second row. This is how we're making our connections between each horizontal "row" on the PCB.

Care should be taken to make sure that all "ground" legs (i.e. the shorter, cathode leg) are clipped short enough so that the legs being bent DON'T make contact with them (effectively shorting one or more LEDs to ground).

Here's the top side of the board after the first two rows of LEDs were installed

After installing a couple of rows of LEDs, getting the snips in between all the flying legs was a bit of a problem, so we cut the cathodes of all the LEDs to length before putting them onto the board.

This made installing the LEDs much easier - less than 30 minutes later and we had a fully populated board:

The reverse side showing how the LED legs were bent in different directions, to create connections across the horizontal rails on the PCB

(note the connector is still in place but the final job will be to remove this and solder the ends of the wires from a 10-way multi-core cable straight onto the board)

The final LED matrix with current limiting resistors in place on each "column" of the matrix.

Now we're ready to hook it up to a microcontroller and start flashing those lights! Sadly, it's a little late to be starting such a thing now, so it'll have to wait until the morning......

PIC microcontrolled traffic lights

This is a set of traffic lights, created by the newest (and youngest) member of HackLlan, Llangollen's hackspace. Jason is also a member of our nerd club and his first microcontroller project was this funky set of traffic lights

He's used a PIC16F628A - the perfect "beginner" chip for starting out with PIC programming, although he's not really done much with the myriad of interfaces available on this chip (I2C, SPI, serial UART etc). Jason wired up the board, created the state machine for the lighting sequence and coded the Oshonsoft BASIC program to make the lights play out the same sequence as a real set of traffic lights.

The final result is quite impressive, with the 5mm LEDs mounted onto tiny little home-made PCBs, ready for fitting into their final enclosure.

Thursday, 10 November 2011

Microband goes live

One of the reasons there's not been much hardware activity is because we've been coding away like a troupe of monkeys to get the instrument software (and accompanying website) if not finished, at least in a state that we can use to demonstrate the instruments.

We're calling the range "MicroBand"

(micro because they're small, but also because they're driven by Microchips micro-controllers. You really couldn't get more micro than one of our micro instruments!)

The software uses an Activex DLL to raise events whenever the instrument is played. This allows us to concentrate on getting everything working, then handing a large part of it over to the community to play about with and see what they can come up with!

When a micro instrument is connected, the DLL raises a connected event, reads some data off the device and displays it as an interactive animation on the screen

(the onscreen guitar highlights which fret the user has selected at any time the instrument is held and played properly - note how the onscreen display changes to match the instrument you're holding)

The software includes a sequencer, so multiple players can collaborate on a single song. In the example below, another user has already laid down a drum track (red) and the sequencer shows the guitar track just played and recorded (yellow)

Using this multi-layered approach, other players with different instruments (bass, synth/keys, rhythm guitar, vocals etc) can come together to create tracks, using the website integration to pull everything together.
Which brings us onto the website - it's pretty straight forward and rather than spend ages discussing it with photos here, visit and see for yourself!

Having recognised my username and password, the server knows which guitar I've got, and updates the onscreen avatar to reflect my customisations. In time, we hope to have a full video creation tool, where players - having created their multi-track mp3 songs - can animate their avatars in time to their own musical creations.

We've still quite a way to go to get a "complete" working, finished product. But at the same time, we're now at the point where we need to see how people use the instruments, to see how and where we need to improve things. So the first batch of guitars have been made up and sent out.

The next job is to get some pals together, have a massive jam session one weekend and get a load of samples recorded for the website! (and of course, to record some videos to demonstrate just how cool these little instruments are to play - if a picture is worth a thousand words, one Youtube video is worth, erm, just loads of these types of blog posts - look out for a video update soon!)

Miniature instruments update

We've not really done much on the actual instrument hardware in recent days - except perhaps finally settle on a design we're happy with. Since trying numerous ways of building the instrument from layers of acrylic, we feel we never quite got the neck/fingerboard design right. Until tonight....

This latest style - the Les Paul classic shape - now has a fingerboard slightly raised from the body join. This is how a real guitar looks- the neck may be bolted flush to the body, but the fingerboard is always slightly raised (presumably to help the player to reach those tricky 22nd and 23rd frets!)

We're going to use this design on all our guitars in future, raising the fingerboard slightly proud of the guitar body. Here's how we acheived it -

Each guitar body is made of 2 layers of 5mm acrylic (with the middles cut away to create a hollow into which the electronics are places inside the guitar body). The lower layer does not include a cut away for the guitar neck to sit in. In the old design, we would glue the 5mm guitar neck onto this lower layer, so that when the fingerboard and 3mm top body layer were placed on, they were pretty much in line.

By adding a 3mm shim on top of the bottom layer, when we put the guitar neck on, it is raised above the height of the second layer. When the final (top) layer of acrylic is in place (often a different colour to the 5mm layers) the whole assembly is flush. The fingerboard is placed on top of the neck, with the end result that it stands a few millimetres above the guitar body - just like the real thing!

Word clock

Carrying on our Word Clock project, we managed to get a PCB made for it tonight.
The final PCB was drawn out in our old favourite ExpressPCB (because the free version of DipTrace has a limit on the number of pins you can use in one circuit). It took a while getting used to the rather basic interface again, but it didn't take long before it all came flooding back!

Here's the PCB design we came up with.
Charlie Plex 90 Pcb - Black

It's not really 100% complete, because we've only really run the traces in the horizontal direction. When the LEDs are in place on the board, we'll have to bend some legs over and solder an LED leg to another LED leg -  because otherwise we'd either end up with a really complex PCB layout or crossed traces somewhere:

note that the horizontal LEDs are connected where necessary (e.g. D51-D55, to D45-D50 are all connected) but the vertical LEDs (D5, D15, D25, D35 etc) need to be connected using the component legs

To connect the LED legs in the vertical directions, we'll just solder the legs together, similar to the way shown in this diagram -

Anyway, here's the board after etching and cleaning - getting ready to drill the LED holes.

Almost an hour later, after drilling over 200 holes with a hand drill, it started to look like an array of components might actually live on this board:

With the board drilled (and while we waited for the 150 LEDs we'd ordered off eBay to arrive) we lined up the plastic inserts, that we cut last week, against our PCB. Each LED should sit snugly into each "cell" in the insert -

Bugger. We're out by quite a bit. Having measured the spacing for 3mm LEDs and set the spacing in the insert grid to 8mm (that's 3mm for the LED plus 2.5mm top and bottom for the PCB traces) we're still not sure how we got this one so far out.
But the PCB is made and etched (we've another one in the making too) so it makes sense to redesign and cut the grid to better suit the PCB, rather than the other way around. Maybe it's time to fire up the laser cutter again......

Friday, 4 November 2011

Delta robot update

Here's our delta robot after gluing the "hip" joints to the servo horns and assembling the limbs.
Note that the joints are simply bits of elastic tied through the connecting pieces. We don't know yet if this is a suitable way of making joints, but they look ok so far - and allow for multiple degrees of movement, in all different directions, not just in one direction (without having to use expensive ball-and-socket type joints)

Please, no more comments about how messy the desk is or "haven't I seen that black guitar somewhere before?" - we tend to tidy up after we've finished what we're  making. Which, given the number of projects we've actually completed, explains why the place is always such a mess!

Now to let the glue dry before trying to actually move it around.
So while that's happening, let's get on with the controller board. As ever, it'll be a USB HID device, driven by a trusty PIC 18F2455

(the final robot may not be usb-driven, but putting a USB chip on during development makes it really easy to read back values for debugging and to see what's actually going on in your code!)

Miniature guitars manufacturing process

Incredibly, it's November and we're still perfecting the manufacturing process for our range of miniature instruments (starting with the micro guitars). We've got the PCBs made up and have placing and soldering the components down to quite a fine art - even if we're still doing everything by hand, until we've a working pick-and-place machine.

Soldering the multi-core cable is still quite a job to do by hand but we've got it down to about five-ten minutes per instrument, including testing and resoldering should any dry joints cause problems.

One of our bottle-necks is getting the guitar strings consistently the same length and all bent to the right angle(s). These finished guitars look ok, but if you examine them closely (around the bridge and neck positions) you'll see that on some, the guitar strings look a bit bent and wiggly.

While we had the laser cutter out, we made a simple jig for bending the wires.
We went through all the guitar designs and made sure that the holes for each lined up exactly then made a template for bending our wires.

As you can see, using the jig, all our guitar strings are now neatly lined up, all the same length, and all entering the guitar body at the same angle. Such a simple job - but it makes such a difference!

Word clock

As part of the HackLlan show-and-tell session, we're hoping to get a number of projects finally finished (or at least in a presentable form) and so we're furiously cutting and making, every time the laser cutter gets pulled out of the HackCupboard.

Here's the internal guts for a word clock.

Here it is assembled (missing the top and right-edge struts)

The idea is to place this structure over an array of LEDs (90 in total) which are charlie-plexed by a single PIC 18F2455 microcontroller.
Using the formula pins required = n(n-1) we can work out that we're going to need 10 pins to drive an array of 90 LEDs (10 * (10-1) = 10*9 = 90). It may be possible to drive this array from a cheaper, lower-spec PIC, such as the 16F628A and our chosen chip is probably a bit of over-kill for what we need, but it'll be nice to have extra i/o pins if needed, for extra functionality in future.

Here's how we're driving 90 LEDs:

And the truth-table (which pins to activate) to turn on each individual LED

How does a matrix of 90 LEDs become a clock then?
By simply placing our cell-structure over the leds (so we don't get any light-leakage) and fitting an etched piece of glass/perspex like this over the top:

Light up the LEDs depending on the time - so for half past four, we'd light up LEDs numbered 1,2,3,4,5,6,7,33,34,35,36,64,65,66,67. We'll put a watch crystal inside to keep accurate time, then just convert the current hours and minutes into a selection of LEDs to light up - and use the charlie-plexing routines to make the appropriate lights come on at the correct times. Easy huh?

Thursday, 3 November 2011

Delta robot and laser cutting

At another of our HackLlan meetings, and in preparation for the show-and-tell (provisionally booked for Sat 26th November, on the same day as the Llangollen Xmas Festival) we've had the laser cutter out, busy making and preparing a number of different projects.

First up is a simple three-servo delta-robot.
This robot will be programmed with a script to perform repetitive tasks such as pick up, move, release an object. There are no plans for any further  intelligence to be programmed into it at this stage - but perhaps could be used as a project for any follow-up workshop from the show-and-tell session.

The photo above shows the main structure with the servos mounted on it at 120 degree intervals. Slots were cut into a round disk, to allow the servo heads to move through 180 degrees, perpendicular to the base. The servos were lined up by placing their corners on top of some small cross-hairs etched into the base and stuck down with double-sided tape (in the final version we'll use permanent plastic cement, but for now we may need to move them around again as development continues!)

There are three legs, each made up of three lengths of acrylic.
The "hip" joint - the part that connects to the servo - is a single piece with a large circular head (for connecting to the servo horn). The lower part of the leg - from the "knee" to the ankle - is made up of two pieces connected either side of the top piece.

We're still thinking about how to make the joints, as the "ankle" joints need to free-moving in all axis directions. Someone suggested hobby-sized ball joints (like those found on remote control cars, helicopters etc). A cruder (but easier and cheaper) solution might be to simply use elastic bands to make the joints....