The Compiler And Support Software
And here, ladies and gentlemen, is the solution for Microchip’s ugly 8-bit compiler problem! Atmel themselves supply a gcc-based toolchain for the AVR series, and it’s readily available for most platforms. As I said a long while ago: gcc FTW!
I am, however, far too lazy to build gcc myself under OS X (let alone track down all the appropriate patches for the latest AVR parts), and Atmel doesn’t offer a bundle for the Mac; only Windows and Linux.
Enter CrossPack: it’s gcc, avrdude, and a couple of other things, all nicely bundled for you in an OS X installer package. I used the latest build, and it appears to support even the newest XMEGA chips, which is perfect. Simply download the package, double-click, and install. Piece of cake.
Oh, and you might want to add /usr/local/CrossPack-AVR/bin to your PATH; it makes life much simpler.
The Test Program
For the first time out, I really didn’t want to deal with anything complex. Like so many test hacks, the goal was simple: cause the LEDs to blink in alternating fashion. This is easy to do, and usually a good first test when you’re playing with a new MCU architecture; it provides end-to-end verification of your toolchain (software and hardware) without getting complex.
After a bit of googling on the specific workings of the AVR, I came up with this:
#include <avr/io.h>
#include <util/delay.h>
int main() {
// Set pins 3 and 4 of PORTB to output
DDRB = (1<<PB3) | (1<<PB4);
// Set the initial value for PORTB (pin3 high, pin4 low)
PORTB = (1<<PB3);
for (;;) {
// Invert bits 3 and 4 in PORTB
PORTB ^= ((1<<PB3)|(1<<PB4));
// Delay for a quarter second.
_delay_ms(250)
}
}
Piece of cake, at least mostly. The only catch is that _delay_ms() is a macro that requires the constant F_CPU, which must be set to the selected operating frequency of the AVR. I do this on the compiler’s command line, like so (for the default fuse settings of 1.2MHz):
$ avr-gcc -mmcu=attiny13a -Os -DF_CPU=1200000 -o main.elf main.c
You can readily see the command-line definition of the F_CPU constant. The -Os option causes the compiler’s optimizer to produce the smallest code possible. The meaning of the -mmcu=attiny13a option should be self-evident: it tells the compiler which AVR to target.
Boom. Compiled Program.
Right?

2 Responses to AVR For PIC People, Part 1: The Basics