Saturday, June 13, 2009

Version Control for Dummies

Version Control is one of those things that once you have it you wondered how you ever lived without it. A version control system (like CVS, Subversion, Perforce, etc.) runs on a server and holds all the versions of the files you put into it.

Daily Development with version control works like this:
First, you do an update of the files you're working on. This will get the latest version of each file from the server and copy it onto your local hard drive. Obviously, if you're the only developer you probably won't need to do it very often.
Then, when you come to a good stopping point (usually when you get something working or make a substantial change) you check-in the files to the server.
Now, let's say you're working on something and you screw something up, can't get the code to compile, etc. With a version control system in place, you can just revert the file back to the last good version.

I put all my firmware and software into the version control system and many of my PCB design files too. Oftentimes I'll put in other documents too if I'm working with multiple developers.

I use a hosted SVN solution from - they have plans starting at $3.95 per month, and they're very good. For client side, I use RapidSVN on the mac which isn't very good but I haven't found anything better yet, or TortoiseSVN in Windows which is a very nice shell extension.

Electrical vs. Mechanical

This week I delivered five electrical prototypes to a world renowned industrial designer. Here's a few lessons I learned:

Get the mechanicals as soon as you can. I have yet to see a product where the first mechanical and electrical prototypes fit together perfectly. Have the mechanical guy there when you first assemble them together to discuss any problems right away.

Mechanical guys like datasheets but they love datasheets plus samples. Give them samples of everything, particularly switches, connectors, displays, light pipes, etc.

Better yet, have the mechanical guy pick out the switches, connectors, displays, etc. based on the requirements you give them.

Good things to have on-hand for modifications to the enclosures: Dremel, hot-glue gun, and strong double-sided tape.

For tight designs, some of the higher-end PCB layout programs (Altium, for example) will produce a 3D model of the PCB from the layout. This is very useful, and then creates a 3D space contract between electrical and mechanical. But be sure that your heights are all correct! Even better, have someone else double-check your design.

When determining how much space you'll need, don't forget to take into account space for wiring etc.

For a prototype, try to get as much space as you can. There will always be surprises.

For components that are very tall, try to find lower height components, even just as a backup. One of the prototypes I just delivered had a speaker that was about 2" in diameter and 1" tall. The mechanical guy screwed up and the space for it was nowhere near large enough, a good 0.2" too short. But, I found a couple other speakers that were similar but thinner, and I swapped one of those in and looked like the hero.

Speaking of Heroes and Villains, at some point both you (the electrical guy) and the mechanical guy will screw up something, so don't be too hard on each other. Be nice when they screw up and chances are they'll be nice to you when you screw up.

Spare, Spares, Spares: if you're working on a product for a demo, get extra enclosures and make extras of everything. On one of my prototypes a stupid little $0.20 battery holder prevented the a system of 3 devices from working. Of course it worked fine in the lab and failed when I got over to the client. Unfortunately I didn't have any spares so I had to troubleshoot it and fix it there on the spot. Doh!

Tuesday, June 9, 2009

Bringing up Baby (or at least a new PCB)

A few words of advice when bringing up a new board.

Idiot Check - I first take a blank PCB and do continuity between Vcc and Gnd as a simple idiot-check. You never know if DRC or ERC missed something, or the PCB vendor screwed up somewhere.

Start with the micro - Next, I put down the bare minimum required to get the microcontroller up and running - usually just the micro, crystal, and JTAG port.

Work outward - Then work your way outward from there, adding peripherals, testing them as you go along. When you power up the board, keep an eye on current consumption - if it inexplicably spikes then you may have a problem.

This being said, if I'm working on a new circuit where I'm not sure if part of the circuit is correct, I'll just populate that part and leave the rest of the PCB unpopulated. For example, a recent project had a DAC feeding an audio output to a speaker; something that I haven't done much before. I populated the audio filter and PA and tested that before I put down anything else.

The art of the prototype

Here's a few things I've learned to make prototype hardware. This mainly applies to low-speed (<100mhz)>
  • Use a processor with more Flash and RAM than you think you need. It's always easier to downgrade later than upgrade now.
  • Give yourself a debug serial port. It doesn't have to be much, and you could bit-bang it if need be, but this will make your life much easier. For complicated designs where I know I'll need to rely on it I'll go ahead and put an RS-232 level converter IC and DB-9 connector to make life easier. If I'm not sure whether or not I'll need it then I'll just leave it as a header with Tx,Rx,Gnd, and Vcc.
  • Don't route traces under ICs, if you can. I learned that the hard way recently. Why? because if you need to cut/jump that trace you now need to remove the IC first. I use both, but through-hole parts (in particular resistors and caps) tend to be more flexible than surface-mount. I like to use through-hole parts for power resistors or large (>100uF) decoupling caps because it makes it much easier to swap parts.
  • Use zero-ohm resistors liberally to give yourself options. On one board I made, I wasn't sure if I would need to power the audio amp from 3V or 6V. So, I put a zero-ohm resistor tying the audio power rail to both 3V and 6V rails. Of course I only populated one of them, but it allows you to change things easily.
  • Give yourself space. If possible, don't bunch components tightly together. The one that's in the middle of them all will be the one you need to replace. Also, I try to use the larger SMT components (0805+) to make it easier to rework.
  • Use "full-size" JTAG connectors, preferably polarized. Make life easy on yourself and prevent mistakes. Nothing's worse than having to replace your processor IC because the firmware guy reversed the JTAG connector, frying it.
  • Use the silkscreen to label liberally. Every connector/switch, etc should be labeled. A little thinking now can save a lot of time later on.
  • Bring out unused pins to headers. I like to use 0.100" single-row headers because it makes it easy to route. On each header be sure to put Vcc & Gnd just in case.
  • Idiot Lights - give yourself a power LED and also connect one LED to an output pin on your micro. Makes life a lot easier when troubleshooting.
  • DIP Switches - if you have space, put on 2 or 4 DIP switches. Very handy for when you have customers who can't make up their mind. I write the firmware to do a couple different things and then I can change things on the fly easily.
  • If you are working on a power-critical project, then run each subsection through a zer0-ohm resistor so you can do a good power analysis. There's nothing worse than populating a board, putting the micro to sleep, and then finding out that the PCB is still consuming a huge amount of current.
  • Use decoupling capacitors liberally. I use a ton of 0.1uF caps, putting them near Vcc pins on ICs. A few designs I've worked on recently controlled very power-hungry devices (high brightness LEDs, speakers) and I used a few large electrolytics.
  • Get extra PCBs made. They're very handy to test out different parts of the circuit, or even just to look at as a visual reference.
  • Speaking of PCBs, if your design is very simple and you're only making 1-2 then you might be able to use a development board and just connect everything point-to-point by soldering wires around. If your design is not trivial or you have to make more than 1-2 of them then by all means make a PCB. They're really inexpensive nowadays.
  • And finally, connectorize. I don't like to have lots of cables soldered directly to the PCB; if possible use connectors instead. They don't have to be fancy; I use a lot of simple 0.100" headers and mating connectors because they're easy to work with.

Thursday, June 4, 2009

The Joy of Bit-Banging, part 1: TX

Need a good bit-bang?

Sometimes you need one more UART than what your microcontroller has. In that case you need to bit-bang it out. "Bit-banging" sounds much more vulgar than it actually is - it just means that instead of using the built-in shift peripheral, you are manually turning on/off the bits. For this example I could implement it using a blocking method, so I just delay the microcontroller inbetween bits. A better implementation would be to use a timer to generate the bit timings.

The most common UART data format is 8N1: 8 start bits, no parity bits, one stop bit. This only tells part of the story. Actually there are a total of 10 bits: (see wikipedia)
  • One start bit (a "1")
  • Eight data bits
  • One stop bit (a "0")
For 9600 baud, bit spacing is 104uSec. To perfect the bit spacing I first just twiddled a bit on and off with the delay loop inbetween until I got exactly 104uSec.

On the hardware side, I ran the output of this through a simple level converter and then into an RS-232 port on a PC to verify that everything was working ok. One level shifter I like is available from here.

* Bit-Bang UART transmit
* Transmits one byte out the specified pin
* Baud rate is 9600 (104uSec bit timing)
* 8-N-1: 8 data bits, no parity, 1 stop bit
* Line is nominally at '1' (high)
* 1 Start bit = '0'
* Data, MSB first, LSB last. '1' = line high, '0' = line low
* 1 Stop bit = '1' (idle, or high)
* PRECONDITION: LINE IS high (idle) and port/bit configured for output!

#define BIT_LENGTH_9600 160
void bitBangOutput(unsigned char byte)
//start bit - pull line down
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT0)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT1)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT2)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT3)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT4)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT5)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT6)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

if (byte & BIT7)
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //'1' = line high
BIT_BANG_TX_PORT &= ~BIT_BANG_TX_BIT; //'0' = line low
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

//Stop bit
BIT_BANG_TX_PORT |= BIT_BANG_TX_BIT; //let line go high
for (unsigned int i = 0; i < BIT_LENGTH_9600; i++) ; //104uSec delay

For receive, see The Joy of Bit-Banging, part 2: RX

Wednesday, June 3, 2009

PWM on a microcontroller, the Hard Way

On a project I had to implement nine PWM outputs for an LED dimming application. Up to eight is easy on an MSP430 - use TimerB outputs TB 1..6 and TimerA outputs TA1,2. But I needed nine. So, I had to do this the hard way, in code. Here's how I did it.

This example "fades up" an LED:
unsigned int onTime = 0; //periodsPerStep;
unsigned int offTime = 0; //PWM_PERIOD - onTime;

#define PWM_PERIOD 0xFF //period for PWM wavelength - 0xFF = 8kHz or so
#define CROSSFADE_STEPS 0xFF //how many intervals of intensity. 16 looks choppy
#define PERIODS_PER_STEP 0x3F//0x7F //how much time to wait at each intensity interval: 0xFF = 6 secs

unsigned int perStepInterval = PWM_PERIOD / CROSSFADE_STEPS;

for (int step = 0; step < CROSSFADE_STEPS; step++)
onTime = perStepInterval * step;
offTime = PWM_PERIOD - onTime;

//PWM periods:
for (int periodCounter = 0; periodCounter < PERIODS_PER_STEP; periodCounter++)
P1OUT = 0x01;
for (unsigned int counter = 0; counter < onTime; counter++) ; //on interval

P1OUT = 0x00;
for (unsigned int counter = 0; counter < offTime; counter++) ; //off interval

White Noise on a Microcontroller

I recently finished a project where I had to make a white noise generator using a microcontroller. It was a lot harder than I thought it would be. What didn't work: wavetable with 100-1000 random numbers. The human ear can detect aural patterns, and at an 8kHz sample rate, the 1000 number pattern repeats itself about 8 times per second which is noticeable. What does work: a Linear Feedback Shift Register. (Wikipedia) Using a 16 bit LFSR you can get a 16*16 = 65535 pseudorandom number sequence. In my tests the pattern could not be detected, which is perfect.

I implemented this on an MSP430F2618 using its internal DAC and the internal timer; though an MSP430F169 could work too. It uses TimerA0 to generate a constant period. When the timer interrupt occurs, the LFSR generates a new value and sends it out via the DAC.

Setting up the DAC:
void setupDac()
ADC12CTL0 = REF2_5V + REFON; // Internal 2.5V ref on
// Delay is 17mSec for caps to charge, [from code] 13600 at 1MHz, or 0x1A900 at 8MHz
// At 8000 cycles/Msec, need 0x21340 clock cycles to get 17mSec
// for safety, we'll delay a little longer, or 0x22000 clock cycles
#define SEVENTEEN_MS_AT_8MHZ 0x22000
for (long j = SEVENTEEN_MS_AT_8MHZ; j; j--); // Delay for needed ref start-up.
DAC12_1CTL = DAC12IR + DAC12AMP_5 + DAC12ENC + DAC12OPS; // Int ref gain 1, DAC12OPS = output select for DAC12_1 on P6.5
Setting up TimerA0
void setupTimerA()
TACCTL0 = CCIE; // TACCR0 interrupt enabled
TACCR0 = 200; //starting interval, gets changed at first interrupt
TACTL = TASSEL_2 + MC_2; // SMCLK, up mode
And finally, the TimerA0 interrupt service routine (ISR):
* White Noise Generator
* Galois Linear Feedback Shift Register implementation
#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A (void)
TACCR0 += 0x3FF; // Timer interval, Add Offset to TACCR0
lsb = lfsr & 1; //Get lsb (i.e., the output bit).
lfsr >>= 1; //Shift register
if(lsb == 1) //Only apply toggle mask if output bit is 1.
lfsr ^= 0xB400u; //apply toggle mask, value has 1 at bits corresponding to taps, 0 else where.
DAC12_1DAT = lfsr;
That's it. In your main code, be sure that you enable interrupts, or else it won't work.