Saturday, June 28, 2014

Atmel AVR Toolchain 3.4.4

Since I started developing on AVR MCUs, I've used avr-gcc, which includes avr-libc.  A few months ago I found out Atmel maintains a version of avr-libc separate from the Savannah project.  It's part of the Atmel AVR Toolchain.  I've wanted install avr-gcc 4.8 on my CentOS server, however I could only find rpms for 4.7.  The Atmel toolchain version 3.4.4 includes avr-gcc 4.8.1, so I decided to try it out.

To download the binary package I had to out an annoying form, before I could get access to the direct download link.  The binary is distribution agnostic, and can be installed in a user directory without root access.  After downloading just run tar xzf to extract the files, then update your path.  For bash, I added the following two lines to my .bashrc:
PATH=$PATH:~/avr8-gnu-toolchain-linux_x86/bin
export PATH

The AVR toolchain consists of three main parts:

  1. Compiler (gcc)
  2. GNU binutils (objdump, ld, nm, ...)
  3. avr-libc (including headers for various AVR MCUs)
As of May 2014, when AVR toolchain version 3.4.4 was released, the latest version of the gcc 4.8 branch was 4.8.2.  The toolchain includes binutils 2.24, which is the latest version.  With avr-libc it gets a bit confusing.  The latest avr-libc release on savannah.gnu.org is 1.8.0 from December 2011.  In a discussion on AVRfreaks, I found out Atmel maintains a separate branch of avr-libc, which seems to be based on the latest avr-libc from savannah plus additional fixes and MCU headers.  I checked for avr-libc bug #41519, which I submitted on 2014/02/07 and was fixed on 2014/03/18.  The fix is included in the toolchain 3.4.4.

I've previously blogged about link-time optimization, so I wanted to check the code generated by the AVR toolchain.  I used the following test program:
#include <avr/io.h>
#include <util/delay.h>

void toggle(unsigned char pin)
{
    PINB = (1<<pin);
}

#define LEDPIN 1
void main()
{
  toggle(LEDPIN);
  while (1) {
    toggle(LEDPIN);
    _delay_ms(500);
  }
}

I compiled it with -Os and -flto.  As expected, the toggle function was inlined in main() when I looked at the code using avr-objdump -D:
0000004c <main>:
  4c:   82 e0           ldi     r24, 0x02       ; 2
  4e:   83 b9           out     0x03, r24       ; 3
  50:   83 b9           out     0x03, r24       ; 3
  52:   2f ef           ldi     r18, 0xFF       ; 255
  54:   34 e3           ldi     r19, 0x34       ; 52
  56:   9c e0           ldi     r25, 0x0C       ; 12
  58:   21 50           subi    r18, 0x01       ; 1
  5a:   30 40           sbci    r19, 0x00       ; 0
  5c:   90 40           sbci    r25, 0x00       ; 0
  5e:   e1 f7           brne    .-8             ; 0x58 <main+0xc>
  60:   00 c0           rjmp    .+0             ; 0x62 <main+0x16>
  62:   00 00           nop
  64:   f5 cf           rjmp    .-22            ; 0x50 <main+0x4>

However the toggle function was still included in the binary.  After trying different compiler options, I found that adding -fwhole-program will not included the unused toggle function.  When testing a gcc-4.8.0 MinGW, I didn't have to use the -fwhole-program option.  As well, the gcc docs state, "This option should not be used in combination with -flto. Instead relying on a linker plugin should provide safer and more precise information."  In the description of -flto it also says, "When the linker plugin is not available, -fwhole-program should be used..."

When I compared the build specs (gcc -dumpspecs) between the AVR toolchain build and the MinGW build, I found the following string in the AVR toolchain: "fuse-linker-plugin:    %e-fuse-linker-plugin is not supported in this configuration"  Although there doesn't seem to be anything wrong with using -fwhole-program instead of the linker plugin, at least for simplicity of build options, the linker plugin is better.

Friday, June 20, 2014

The Science of Cheap Beer

Most guys like beer, and many like to brew their own.  Unfortunately, in many countries, beer is heavily taxed.  In the part of Canada where I live, the cheapest beers cost $42 for 24 bottles.  There's a 10c refund for the empty bottles, so after you bring the bottles back the net cost is $39.60, or $1.65 per bottle.  Each bottle is 341ml, making the cost per liter $4.84.  With homebrew kits like Coopers, 23L of beer can be brewed for <$20, or about 1/5th the retail price.  With a little more work, it's even posible to make a brew with the same ingredients as a Coopers kit for about $10, or 1/10th of the retail beer price.

The Coopers kits require adding 1kg of fermentable sugar to the malt extract and water, and the brew shops recommend corn sugar aka dextrose aka glucose, which sells for $5 for a 2kg bag.  Dextrose has about 10% moisture content, so 1kg of fermentable dextrose costs about $2.80.  Cane sugar aka sucrose sells for $2 or less for a 2kg bag, so for my first beer kit brew I tried half dextrose and half glucose.  It turned out fine.

I decided to research some of the science behind the fermentation of different sugars.  I found a paper by Labatt Breweries which shows virtually no difference in the fermentation of glucose vs. sucrose.  Glucose may actually be worse than sucrose, since the paper shows high glucose suppresses fermentation of maltose (fig 4B).  Malt extract is 30-50% maltose, so using sucrose instead of glucose means fermentation will be finished sooner.

Malt extracts are much more expensive than sucrose - about $5/kg for liquid malt extract.  The fermentable sugars do not contribute to the taste, so using a malt with less fermentable solids allows you to use more sucrose while still maintaining flavor. The Coopers kits include 1.7kg of hopped LME and recommend adding 1kg of fermentable sugar.  Using 1.5kg of a darker malt (~$7.50) and a little more than 1kg of sucrose (~$1) should give a flavor profile almost the same as the Coopers kit assuming the same hops.

Dried hops costs about $30/kg, and depending on the recipie, a 23L batch will need 20-50g of hops.  This adds about a dollar to the cost of a batch of beer.  The cheapest source of hops is to grow your own.  One homebrewer I know had a couple varieties of hops growing up a trellis attached to his back deck.

Coopers ale yeast costs just under $2 for a 7g package, but you don't need one for every batch.  I bought a Coopers kit on sale that was missing the yeast pack, and just split a package between 2 batches.  Despite some people that say the amount of yeast you pitch is important, the biochemistry of yeast seems to indicate otherwise.  It might take a bit longer for the brew to ferment, but not that I could notice.   I used 3.5g of yeast for a batch of Cooper's ale, which I uncovered and stirred after a few hours for oxygenation. After three days at 23C there was a full cover of foam from the active yeast.  Yeast from one batch can be re-used multiple times, so is's feasible to use a single 7g package for up to 10 batches.

When it comes time for priming, a number of sources, including this one, say that using sucrose gives a cidery taste to beer.  I've used sucrose and didn't notice a cidery taste.  More likely explanations for a cidery taste in beer is oxidation or incomplete fermentation.  Since only 100 to 150g of priming sugar is needed for a batch, the choice of priming sugar doesn't affect the cost much.

So how do I come up with the $10/batch number I mentioned?  Here's the breakdown:
1.5kg dark LME: 7.50
1.25kg sucrose: 1.25
30g hops:       0.90
yeast:          0.25
total:         $9.90

If you want a lighter tasting beer like mainstream beer buyers (bud light is the top selling beer in the US), then 1kg of dark LME and 1.5kg of sugar should suffice.  If you grow your own hops, then your cost for a homebrew light beer could be as little as 10c per bottle!

Sunday, June 8, 2014

Cheap battery-powered micro-controller projects

Many MCU circuits use less than 25mA of power with a 3-5V supply, making battery-powered operation not only feasible, but often cheaper than using a dedicated power supply.  Although I'm using AVR MCUs, the same concepts apply to using a PIC or MSP430.  An Arduino UNO consumes > 30mA even when the MCU is in sleep mode, so powering it from a battery is not a great idea.  For an Arduino Pro Mini or bare MCU on a breadboard, long running time on a battery can be achieved.

Disposable or re-chargeable batteries?

For projects with average power consumption in the low micro-amps range, it's hard to beat the disposable CR2032 coin cells.  Sparkfun's Adventures in Low Power Land shows how how to run an ATMega328p off a single CR2032.  JeeLabs also has some info on running wireless sensor nodes on coin cells.  Quality cells such as Panasonic cost only 25c in small quantities.  Battery holders are about 10c, or wires can be soldered directly to the cells.  For wireless sensor nodes that use bursts of more than a few mA of power, a cheap electrolytic capacitor will extend battery life, particularly with lower-quality cells.

For projects that would use more than one CR2032 per year, a rechargeable LIR2032 coin cell is another option.  Although their capacity is about 1/5th of a disposable, they can sustain higher output currents than the disposable cells.  However they are much harder to find than disposable cells.  FastTech is one place I've found that sells them for about 50c ea.  Chargers are also difficult to find, though not to hard to build according to this Hack A Day post.

Powering circuits from a 9V battery has long been popular, often with a small 5V regulator such as the 78L05.  An alkaline 9V battery has a capacity of about 600mAh, but it might last not much longer than a 220mA CR2032.  Over it's usable life, the average output voltage will be close to 7.5V, which means a linear regulator will be 66% efficient, leaving about 400mAh.  Even in low-power mode, a microcontroller will use about 50% more power at 5V than it will at 3V, meaning 267mAh at 3V would give the same battery life as 400mAh at 5V.
Once the higher cost of a 9V battery is factored in (about $1.50), the 9V battery is clearly more expensive than a 3V coin cell.  However you may have a cheap source of 9V batteries - smoke detectors.  I've found my smoke detectors start beeping to replace the batteries when the open-circuit voltage is still above 8V.

I've re-used these batteries for RF transmitter projects.  The transmitter modules I use will work with 3-12V, with more voltage providing higher power transmission.  Instead of using a voltage regulator to power the AVR, I use a LED similar to what I did for my ATtiny85 NRF24l01+ project.  Instead of a red LED, I used a green LED with a forward voltage of 3V.  With the 9V battery putting out 7.9V under load, I measured 4.9V at the input of an ATtiny84a I used.  Besides being a bit cheaper than a regulator, the LED has the benefit of working as a power use indicator - when the AVR is consuming more power the LED glows brighter.

Update: David Cook has recently posted the battery life expectancy of his Attiny lofi device.  According to Energizer's Alkaline Handbook, at 25mA drain the capacity of an AA alkaline is over 2500mAh, and under 1mA drain the capacity approaches 3000mAh.  Once self-discharge of 2-3% per year is factored in, the 12-year life expectancy David calculated is about right.  With a cost of about 25c for AA cells and 20c for CR2032 cells, 12 years of use on CR2032's would cost about $2 vs. 50c for the AA cells.

A wireless sensor node using an Atmega328p with a 32.768khz watch crystal and a nrf24l01+ module could work for >12yrs with a CR2032.  The power-down current with timer2 running is 1uA, or about 9mAh per year.  The nrf module would need to be transmitting for 0.5ms to transmit 16 bytes at 250kbps, vs 53ms for an ASK/OOK module at 2400bps, and both consume 10-15mA at 3V.  Even consuming 15mA for 2ms every 5 minutes would equate to only 0.1uA average consumption.  Adding 0.25uA for self-discharge adds up to 12mAh per year, or 16 years of battery life!

Sunday, May 25, 2014

PL-2303HX bit-bang AVR programmer

I've blogged before about PL-2303HX USB-TTL adapters.  In some ways they are even better than the expensive FTDI adapters - for example they work at 6mbps.  In conjunction with a cheap Pro Mini clone it's possible to get started with Arduino/AVR programming for $5.  For more advanced use such as burning bootloaders or directly programming AVR chips, I usually recommend a USBasp.  While writing picoboot-avrdude, I noticed avrdude supports bit-bang SPI programming not just with a parallel port, but also with a serial port.  Here's how hacked a PL-2303HX module so I could use it as a bit banging SPI AVR programmer.


The programmer type in the avrdude.conf file is "serbb".  Here's the description line from the "ponyser" programmer in avrdude.conf:
desc  = "design ponyprog serial, reset=!txd sck=rts mosi=dtr miso=cts";
I needed to break out the RTS, DTR, and CTS lines in order to make it work.  I found a pinout diagram of the PL2303HX, and marked the pins with a green star:
The modules come with a translucent shrink wrap protecting them, so I cut that off with a utility knife.  I tinned the ends of some pin headers, and attached them to the back side of the module with some contact cement - other types of glue would likely work fine as well.  Although I have the extra pins at the top of the board, it might be better to have them going out to the side so it doesn't cover the silk-screen labels for the Tx/Rx lines.  The hard part is soldering wires to the .65mm pitch pins on the SSOP-28 package.

I used 30AWG wire-wrap, and initially tried tinning the end of the wire.  I didn't have enough solder to make a good connection so I tried with a small ball of solder at the end of my soldering iron.  It was too much, and bridged a few of the pins, requiring solder wick to clean it up.  Eventually after a few more tries of tinning followed by attempts at soldering to the pin, I got a good connection.  I think it would be easier using solder paste.  Once I had the 3 wires connected, I used a multimeter to verify continuity and ensure I had no shorts.

With the hardware verified, I was ready to test it out.  I made the connections from the module to an ATtiny88 I had on a breadboard.  The USB-TTL adapter was com16, so I used the following avrdude options:
$ avrdude -C /etc/avrdude.conf -c ponyser -p t88 -P com16
But it didn't work:
avrdude.exe: ser_open(): can't open device "com16": The system cannot find the file specified.

I tried the same adapter with a pro mini with an arduino-compatible bootloader, and had no problems using the following command line:
$ avrdude -C /etc/avrdude.conf -c arduino -p m328p -P com16

A comparison of ser_win32.c and serbb_win32.c revealed some extra code at line 134 for dealing with high com port numbers.  It prepends "\\\\.\\" to the port name, so I did the same thing on the command line (I hope to clean up the avrdude serbb code in the longer term):
$ ./avrdude -C /etc/avrdude.conf -c ponyser -p t88 -P \\\\.\\com16
Now instead of "can't open device" I was getting a "device not responding" error.  I used an LED to verify that there were pulses on the SCK and MOSI lines, and could tell from the Tx LED on the module that Tx was being pulled low for the RST line.  I then remembered that TTL signals are inverted vs RS232, so I created a new programmer type in the avrdude.conf file:
programmer
  id    = "pl2303";
  desc  = "pl2303 serial, reset=!txd sck=!rts mosi=!dtr miso=!cts";
  type  = "serbb";
  connection_type = serial;
  reset = ~3;
  sck   = ~7;
  mosi  = ~4;
  miso  = ~8;
;
With that, combined with slowing down the communication speed by adding -i 500, I got it to work:

Monday, May 12, 2014

2.4 megasamples per second continuous AVR logic capture

In my last post I got an ATmega8A outputting a 6mbps serial UART data stream.  In this post I'll show how to use that as a way to sample 2 inputs (a USB data signal) at 2.4msps.  The reason the sample rate is not 6mbps/2 is due to the overhead of 1 start bit and 1 stop bit for every byte transmitted.  After accounting for that overhead, the data rate is 4.8mbps, and with 2 bits per sample, the sample rate is 2.4msps.

A look at the USBasp schematic shows USB D- and D+ connected to PB0 and PB1.  With the UART output rate of 6mbps and a 12Mhz CPU clock rate, a full 10-bit frame takes 20 cycles.  To take 4 2-bit samples every 20cycles requires taking a sample and packing those two bits into a byte every 5 cycles.  Single-cycle timing is very difficult to do in C, so I wrote the code in AVR assembler.

capture2:
in sample, PINB
out UDR, tmp
andi sample, 0x03
lsl sample
lsl sample
in tmp, PINB
andi tmp, 0x03
or sample, tmp
lsl sample
lsl sample
in tmp, PINB
andi tmp, 0x03
or sample, tmp
lsl sample
lsl sample
in tmp, PINB
andi tmp, 0x03
or tmp, sample
rjmp capture2
The output data is valid after the first loop itteration, so the first byte (4 samples) should be discarded.  I added code to capture a full 8 bits (at 600ksps), and a simple trigger that waits for the state of the input to change.  For the full code see sniffASM.S and sniff.c.  I've also posted sniff.hex if you don't want to build the code yourself.  With the Rx line (PD0) on the AVR high (idle state), 8-bit capture mode will be use.  If the Rx line is grounded, 2-bit capture mode will be used.

To be able to view the captured data, I like OLS.  It will read a simple text-based input file, which I wrote a small perl progam to output.  It takes a single argument, which is the serial port to read from.  Under windows I had problems getting perl to open high com ports (i.e. com10 or above), so I used the device manager advanced properties to change the port number to com2.  I also wrote a similar program for the 8-bit mode.  One second of samples will be recorded, although there is no technical limit to how long can be recorded.

Here's a portion of a screen shot of OLS showing a USB setup packet followed by 2 re-transmits after ~10us without receiving an ACK:


It's not as fast as the Logic Shrimp, but considering unlimited sampling length and the required hardware is a USB-TTL adapter that costs barely over $1 and a ~$3 USBasp that many people already have, now anyone can afford a basic logic analyzer.


Thursday, May 8, 2014

high-speed UART: pumping out the data at 6mbps

TTL UART communication is the most common way to send data from a micro-controller to a PC.  It is simple and requires very little code in the MCU.  It's fine for configuration and debugging, but usually limited to low-speed (<=115.2kbps) communication.  With a 16Mhz AVR, USART timing is off by > 3% at 230.4kbps.  My bit-bang half-duplex UART can go up to 460.8kbps while keeping timing within 2.1%, and even 921.6kbps with a small tweak (a nop instruction) to the code.  This is still far short of the maximum 3mbps supported by FTDI FT232 chips and the 6mbps supported by Prolific's PL2303 chips.

There is a way to transmit at 6mbps with the AVR USART - synchronous master mode with a 12MHz system clock.
Rather than building a circuit with an AVR and a 12MHz crystal, I used a cheap USBasp.  The version made by Shenzhen LC Tech has the UART Rx and Tx pins connected to the 10-pin header, and has a 12Mhz crystal.  For power, it just plugs into a USB port.

The code isn't much different than regular asynchronous UART mode.  UMSEL needs to be set in UCSRC in order to turn on synchronous mode, and the XCK pin needs to be set to output for master mode.  The XCK pin is not connected on the USBasp, but it is not needed as the UART outputs a valid frame with start and stop bits.  Here's the initialization code:
#define XCKPIN 4
#define XCKDDR DDRD

static void uartInit()
{
    XCKDDR |= (1<<XCKPIN);       // output mode for master 
    UCSRC = (1<<URSEL)|(1<<UMSEL)|(1<<UCSZ1)|(1<<UCSZ0);
    UCSRB |= (1<<TXEN);
#ifdef HALF_SPEED
    UBRRL = 1;
#endif
}
Defining HALF_SPEED will output at 3mbps, for use with FTDI chips.  I set the self-program jumper (JP2) on the USBasp, connected the 10-pin ribbon cable to another USBasp, and flashed the code.  Then I plugged the USBasp into a free USB port, and connected the Tx pin to the Rx pin of a PL2303HX module.
To test the data reception, I could tell data was being received by looking at the Rx activity LED, so I tried a terminal program.  There were no errors in the data stream, however there were lots of dropped characters.  Suspecting the problem was receive buffer overruns while updating the display, I wrote a perl program to receive the data:
#!/usr/bin/perl

# 1st argument must be port name
$port = $ARGV[0];

# open port in read/write mode
open(UART, "+<$port") or die "$port ", $!;
binmode UART;
my ($buf, $count);
$count = read (UART, $buf, 240);
print "read:\n";
print "$buf";
close(UART) or die $!;

The baud rate for the port needs to be set in advance - use mode or stty for Windows or Linux respectively.  Without the delays for displaying the characters as they are received, there were no errors:

You might ask when would you need to transmit data at such high speeds.  Using an AVR as a logic analyzer is the first thing I intend to try.  Watch for it in my next post.

Tuesday, May 6, 2014

PC storage oscilloscope and logic analyzer

A logic analyzer is a useful tool when working with micro-controllers, but when compared to the price of Arduino compatible boards, they are expensive.  While the ability to decode different protocols is a nice convenience, the key functionality of a logic analyzer is the ability to record a signal over a period of time.  For low-speed signals in the tens of kbps, a PC audio codec can perform this function.

The audio codecs in most modern PCs are capable of at least 96kbps stereo sampling at 16 bits per sample, with 192kbps/24-bit "HD audio" being relatively common.  This is enough to analyze a 38.4kbps UART signal in modest detail (5 samples per bit).  With some hardware to connect to the audio input and software to record and view the signal data it is possible to have the functionality of a basic storage oscilloscope and logic analyzer.

What's needed for the hardware is a 3.5mm stereo plug and 3 wires.  The largest tab is ground, and the smaller two are the left and right channels.  I used 24awg wire from a spool of ethernet cable since its cheap (~10c/ft), and when the ends are stripped it easily plugs into breadboards.
I initially had some problems recording from line input until I figured out I had to unplug the microphone - I guess the recording inputs are multiplexed.

For my testing, I recorded the 2kbps output of a pro mini running VirtualWire.  The pro mini is running at 5V, while line input voltages should be ~1V peak, so I used a 100kOhm resistor in series with pin 12 to limit the voltage at the line input.

For recording software, Audacity is probably the most popular free audio program, and one that I tested.  Here is a view of one of the output pulses captured at 192kbps:
The fluctuations at the corners of the square wave is something you would not see with a digital logic analyzer.  What you see above is normal, as a true square wave is a physical impossibility - all signals are summations of sinusoidal waveforms.  The straight lines audacity draws between points doesn't reflect that reality, so I tried resampling to a higher frequency (768kbps):
The corner of the signal looks much better, but the low amplitude ripple that was visible before seems to have been filtered out.  In the resampled signal the slight downward slope of the signal is more visible.  That is because the line input has a DC blocking capacitor which causes the 0-1V signal peak to drift down until it is roughly balanced around 0V.

Another program I tested is GoldWave 5.70.  I didn't find the interface very intuitive.  My first problem was getting it to record at 192kbps.  I eventually found the control properties, which indicated the default WASAPI maxed out at 96kbps.  Switching to DirectSound allowed me to use 192kbps.
Here's a capture from GoldWave using 192ksps:
I find the grid makes analyzing the signal easier than with Audacity.  I also tested resampling, which is limited to a maximum of 500ksps:
It seems to do a better job at resampling than Audacity.

I also tested Soundcard Oscilloscope.  It seems to be limited to 44ksps 16-bit samples and doesn't support viewing of recorded signals.  Visual Analyzer allows for analyzing a signal in many different ways, however I could not find a way to record at more than 96ksps.

I'll finish by pointing out that when trying to analyze faster communications, rather than getting a faster scope or analyzer, consider slowing down the transmitter.  For example it would not be practical to analyze 230.4kbps serial UART output when logging at 192ksps.  However setting the CKDIV8 fuse on an AVR MCU when running the same code would output a 28.8kbps signal, which can easily be captured with a PC audio codec.