Learning to program AVR micro-controllers

October 23, 2014

About a month ago, I wrote about learning to program PIC micro-controllers. Well, since then I've been learning about programming Atmel AVR micro-controllers. The Arduino Uno is actually based on the Atmel ATmega328p, so I have already been using these micro-controllers through the Arduino IDE and its simplified language and libraries, but now I'm learning to use them directly.

One of the most confusing things for me in this process was working out what the difference is between the Arduino and the AVR since it is possible to code the AVR directly using the Arduino IDE and it is also possible to put Arduino code on an AVR without using the Arduino IDE.

So it turns out that the Arduino language and libraries build on top of the standard AVR C language and libraries and makes them easier to use (which was fantastic for me when I was getting started). The Arduino hardware is just an AVR chip with an Arduino bootloader to make it easy to load software over a serial interface and have the chip communicate with a PC over a serial interface. The Arduino boards have a programmer built in whereas if you are using the chip directly you need to use an external programmer. I am using a $15 AVR pocket programmer from SparkFun. The advantage to using the chips directly is they often cost as little as $2 compared to $25 for an Arduino board.

So here is the obligatory picture of a blinking LED using an ATtiny85 (a $1.45 micro-controller that is capable of running at the same speed as an Arduino Uno, but with fewer pins and fewer features).


And here is the code.

#include <avr/io.h>
#include <util/delay.h>

int main(void) {
  DDRB |= 0b0000001;
  while (1) {
    PORTB = 0b00000001;
    PORTB = 0b00000000;
  return (0);

So, how does this compare to programming the PIC? Well, it's almost exactly the same. The C code even looks pretty much the same. All of these micro-controllers basically have the same features. They have pins which can be used as inputs or outputs. They have analog-to-digital and digital-to-analog converters built in (depending on the model) and they have timers and interrupts. It seems that if you learn one micro-controller then you are learning them all (to some extent).

AVR has the advantage that the compilers are open source and based on gcc whereas the PIC compilers have a free edition that is somewhat crippled and then expensive high end versions (resulting in many people coding them in assembler instead to work around this). I did manage to make an LED blink in assembly language but it was a painful experience to say the least.

Now that I'm over this part of the learning curve I can focus on building a real (but simple) project. More on that soon...