AVR Programming 01: Introduction

We love looking at hardcore electronics projects with a beefy microcontroller and hundreds, if not thousands, of lines of code at its center. But everyone needs to get there somehow.

This tutorial series aims to make you comfortable programming the Atmel AVR line of microcontrollers. Whether you’ve never touched a microcontroller before, or you’ve cut your teeth with dozens of Arduino projects, this will help you get right down to the hardware and give you the confidence to build anything.

Series roadmap:

Prerequisite knowledge

Here’s the good news: I’ve set the bar quite low. You need basic knowledge of installing programs on your computer and using them. You should have some idea of how a solderless breadboard works and it is advisable that you have a multimeter and know how to measure voltage with it. And you shouldn’t be afraid of using Google to research questions that aren’t explicitly answered here.

What does a microcontroller actually do?

This is a loaded question. For the sake of understanding I’ll take this down to the most simple explanation:

  1. A microcontroller takes some type of input
  2. It makes a decision based on the software you have written
  3. The outputs are changed based on the decision in step 2.

A microcontroller does what you program it to do. It does so quickly, and reliably.

How does it work?

For this tutorial series I will be discussing digital logic. That is to say that all input and output pins will be judged based on a voltage of zero, or 5V. This produces our digital 1’s and 0’s, with 5 volts as a one, and zero volts as a zero.

So if you want to light up an LED just wire up the circuit to a pin, make that pin an output, and set it to a logic high (5 volts). If you want to add a button, connect it to a pin that is set as an input and program the chip to measure the voltage level of that pin. It really is that easy, once you learn how to write the correct commands so that the chip understands your wishes.

A look at he chip itself

I’ve decided to use an ATmega168 microcontroller. It’s a powerful chip but it’s no harder to start using than its younger brethren. It will leave plenty of room for you to grow into your projects, while remaining affordable (less than $4.50). Here’s a diagram of it:

This is often called the pinout as it shows what each of the 28 pins on the chip actually does. All of these pins have multiple functions and that’s why there’s long lines of text next to each, except for five which only have one name. These are the pins having do with voltage and ground (VCC, GND, AVCC, AREF, AGND), an important issue with microcontrollers.

Integrated circuits need a steady voltage source. This means as part of our project we’ll need to build a voltage regulator. This is an easy thing to do on a breadboard, and you should be able to get your hands on the parts locally. It is also worth noting that there is a semi-circular dimple on the top of the chip. This is something you’ll find in the plastic case of these dual-inline-package chips an it’s used to make sure you don’t plug it in backwards.

Take a look at the pinout once again and look for the pins whose names start with PD. You should see eight of them total, labeled PD0 through PD 7. This is a fantastic example of the 8-bit nature of these chips. PD stands for Port D, one of the input and output register. Everything in these chips centers around 8-bits. That’s a sequence of eight 1’s or zeros in different combination. If you want to turn on or off specific features, you change one or more bits in a 8-bit register. Every time you want to change one pin you must address all eight in the register. We’ll learn much more about this but not until the third part of the series.

Programming

The ATmega168 is a programmable microcontroller. But better yet, it’s reprogrammable. In fact, when you’re working on a project you’ll most likely reprogram it several times an hour.

This chip has a size limit of 16 kilobytes of programming space. In these modern times of 64 gigabyte iPods 16 kilobytes might sound minuscule. But in reality that’s 16 kilobytes of machine code. You can do a lot with that… trust me.

You do need some type of hardware to get the code onto these chips. Usually this comes in the form of an AVR programmer. In the second part of this tutorial we’ll look at several different programming options, then build and program a test circuit.

Do Your Homework

To get ready for the rest of this tutorial series I need you to gather some tools. You must have some type of computer, be it a Linux box, Mac, or Windows PC. This will run software that takes our code, compiles it into something the microcontroller can use, and then tells a programmer how to write it to our chip.

The compiler

We’re eventually going to be writing our own code for the AVR, which uses the RISC architecture. But we’re doing this on a computer with x86 architecture. The tool necessary to accomplish this is called a cross-compiler. This is quite possibly the best reason to choose AVR for development, there’s an excellent tool chain available that can easily be installed on multiple platforms.

  • Mac users: Install CrossPack
  • Windows users: Install WinAVR
  • Linux users: Debian and Ubuntu users should install the GCC-AVR package which includes the entire toolchain. Others may want to look at the AVR-libc toolchain page for help compiling the packages.

This is not the only option. Many Windows users swear by Atmel’s free AVR Studio software. This is the only time I’ll reference it as I don’t have a Windows machine and have never tried that package.

Programming software

Our software-of-choice to run the hardware programmer is called AVRdude. If you installed one of the toolchains above you should already have this program. Go to a terminal window or the command prompt and type the following to make sure:

avrdude -h

This will show the help screen. If you get an error, you should check to make sure you properly installed the toolchain in the previous step, or go download AVRdude yourself.

What the future holds

That wraps up the introductory installment of this series.

Part 2: In the next installment of this series we’ll take a look at several pieces of hardware that you can use to program an AVR microcontroller. I’ve written a hello world program and will walk you through building the circuit on a breadboard, connecting the chip to a programmer, and using AVRdude to write this simple firmware to the device. I don’t want to get you too excited, but this does involve a flashing LED.

Part 3: A pre-compiled HEX file was used to program the AVR microcontroller in Part 2 of the series. In this portion we’ll look at the C language source code that made up that firmware. I’ll also talk in-depth about the peripherals available on the chip and detail how to use them. We’ll finish up by adding functionality to the original program, recompile it, and reprogram the chip with the upgraded version.

Part 4: Now that you’ve acquired AVR programming skills I’ll show you how to start building cool stuff with them.

Follow me:

@szczys

69 thoughts on “AVR Programming 01: Introduction

  1. I recently decided to graduate myself from arduino to regular avrs and picked up an avr dragon. I’ve been working on my own little programs but am super excited to grab info anywhere I can. Great idea for a series, I look forward to reading the rest.

  2. I am going to keep an eye on this! :D

    I have been waiting for something like this as I keep looking at various kits (arduino, basic stamp etc) but I’d rather learn how to build up something based around a micro-controller from scratch.

  3. This is a great idea for a tutorial. I’m looking forward to the next part of the series because I plan on following it (I’m completely new to this kind of stuff). There’s only question I can’t seem to find the answer to immediately. What hardware is used for programming the ATmega168?

  4. So I’m pretty good with arduino/done some breadboard AVR work with USBtinyISP, and I’ve made we own hardware for specialized uses. Im sure this tutorial series (like the android tutorials) will have some new stuff in them so I will read every one. My question of the day: will you guys have an “in between” tutorial series? Something to bridge the gap between Microcontrollers and Integrated Electronics? Something along the lines of 32 bit MCU meets linux DIY? Maybe it’s just me, but this is the next step I would like to take… Beyond pushing digital lines, mapping analog readings, and having LED’s blink next to a nokia LCD.

  5. I’m also looking forward to the next part. I’ve been programming on picaxe’s which are fairly closed-source, but have easy cross-platform software available.. having a beginners guide on programming AVRs (in Linux) will probably convince me to switch.

  6. This is awesome! As someone who has taught myself all I know about electronics and microcontrollers, I know there are huge gaps in my understanding. I’m looking forward to gaining a better understanding of the basics!

    Thanks Guys! Looking forward to part 2.

  7. I agree with Brian: an ARM tutorial (with Linux instructions!) in the future would be great. A side-by-side comparison of ARM development boards would be great too.

    I like this AVR tutorial idea. Will it cover Makefiles? Keeping track of all the command-line incantations can get confusing, and finding/writing a good Makefile can be tricky. (I’ve been using the one that comes with V-USB as a base for a while.)

  8. For all you people bashing Arduino, yes, you can do some very cool stuff with just straight AVR C. But at the same time, it’s just so much easier to develop things with Arduino that there’s no sense in abandoning one for the other. It’s like saying that writing in C is better than BASH scripting. There is a time and a place for each. I say keep both in your toolbox and use them when appropriate. For the most part, the savings in time you get when using Processing + Arduino makes it worthwhile to have those tools available.

  9. Thank you HAD.

    I’ve needed a one stop tutorial to get me started with more advanced micro’s. I’ve been playing with basic stamps and propellers forever, and have out grown them.

    I hope you will give a tutorial in detail to set up a cross-compiler using linux tools (with examples that I can follow along with).

    Also, I have never seen a good complete howto for ethernet communication from a µc to a compiled program in a pc. I’m coveting a good tutorial which would explain the whole communications path from the microcontroller through the internet and into a program running on a pc (along with creation of a variable in a program…).

    and I want a new pony!

  10. @beaglebreath –

    Ethernet is pretty easy, but I suspect what you want is a tutorial on implementing an IP stack on one or more embedded systems, and then figuring out how to communicate with it from within a program on your PC.

    Many versions of popular microcontrollers now come with ethernet interfaces, requiring a module, and source for a complete ethernet stack with limited IP functionality.

    Ethernet isn’t that big of a conceptual leap from asynchronous serial – there’s another layer or two of housekeeping, but that’s all. You’ll need to understand buffering, but everything else is done for you.

    If you want to control them through software, you locate an IP stack or IP library for whatever language you want to use.

    In the end, you’re still just sending text and data back and forth like before – it’s just that you have to specify a few more parameters needed by the IP protocol.

    Running TCPIP does chew up resources on a microcontroller, so it was common to throw a pre-programmed ethernet “coprocessor” on it and just bit/byte bang as you would with a UART.

    However, built-in interfaces roughly equivalent to a uart started showing up a decade ago. For example, this old-timer is still around:
    http://www.microcontroller.com/news/dallas_8051_ethernet.asp

    As you guys keep moving up the rungs of design complexity, it gets pretty common to simply design a full linux system into whatever you’re building. Once you can run gcc on it, you can run anything!

  11. This is great!. I am so glad that you are starting from the beginning because I am basically clueless with this stuff but really want to learn.

    I have to admit, as far as the prerequisites go, I do not understand how a breadboard works but I will find out before lesson 2 arrives. In Jr. College I took a basic electronics cours but when it came time to reading resistor rings I lost interest because I am color blind. The instructor suggested I drop the class and I did. That was 26 years ago and I am convinced that todays electronics has a lot to learn without having to be able to distinquish colors. Besides, all I need to do is ask a friend “hey, what color is this”.

    Looking forward to the next lesson. Thank you HAD.

  12. @ bilboa bob –

    i get what you’re saying. thanks for the responce about the ethernetism.

    at the moment i’ve been able to figure out how to serin/serout ‘text’ to a wiz105cv (serial to ethernet board) from my propeller. on my linux box i set up netcat to listen for a connection. i then pipe the ‘text’ from netcat into my compiled program.

    i’ve no clue how to get the ethernet directly into my program. i’ve also tried a direct connection using vb.net but had no success.

    i’d like to see a tutorial to hold my hand step-by-step to get this done.

  13. Excellent. This is the stuff!
    AVRs are nothing new to me but I will read whole tutorial series anyways.
    Don’t leave the fuses out :)

    ARM? Sure. With some DSP topping :)

    ATMEL should designate someone titled master Yoda of electronics to write (or film) tutorials for HaD about other stuff they make because they make a whole bunch of goodies, including ARMs :P

  14. In part 2, please mention ArduinoISP! Those who are graduating from Arduino will not need to invest money in a programmer. From the environment they are already familiar with, they can upload the ArduinoISP sketch that will allow them to re-purpose their Arduino as a general AVR programmer.

  15. there is nothing wrong with using an arduino in some situations. I agree with most arduino bashers when you rage over leaving a full board or a basicstamp with a breadboard in a project. But I have no problem basing a project on an arduino, especially if i embed the chip on a custom board.

    I’ve programmed Freescale HC12’s in assembly for a class and I used ATtiny 85’s in AVR Studio C for my senior project. I never used an Atmega, but i would say based on the ATtinys that they would be extremely powerful if you knew how to control everyting.

    The problem is interfacing with things like LCD’s or extracting the exact serial staments you want from an GPS NMEA output. If your code needs to be extremly fast and efficient then go with AVR studio or even assembly. If your just building simple things for fun then i say go with arduino. I’m working on a GPS system to hunt for Geocaches. I’m going to build a custom board that will interface the Atmega328/GPS/LCD. The arduino already has prebuilt libraries for lcd and gps and makes it funner to build things like this. I I got most of the coding done in a couple hours while watching tv.

    btw its worth mentioning for part 2 that the AVRISP mkii programmers don’t work with Windows 7(not easily) the drivers don’t work. There is a work around but it took me several hours,lots of searching and many many installs/uninstalls of AVRGCC and AVRstudio

  16. @Patrick, indeed WinAVR is inactive now. But it will work with the targets it supports so-far and is nicely integrated with AVR Studio.

    I read somewhere the person responsible for WinAVR was hired by ATMEL. I wonder if it was to add C/C++ compatibility to AVR Studio.

    Can’t wait for the second part of this tutorial to see if the recommended programmer is one of those crippled nightmares from the likes of Adafruit.

    I’ll say it now – buy an AVR Dragon.

    No I don’t work for ATMEL.

    One good thing, at least people aren’t being led down the Arduino path – so far.

  17. Arduino = AVR Atmega 128/328/1280/… + USART based bootloader + FTDI FT232RL + C/C++ Libraries wrappers for AVR Libc(open source), GCC, it even has a header for programming via ICSP and utilizes AVRDUDE for uploading. (Albeit the header configuration is less than ideal). A little poking around would allow Arduino users to *gasp* follow the tutorial, maybe even using the binaries already included with their arduino ide!!! So whats the beef? There will always be a market for tools that reduce development time or lower the barriers to entry. mbed vs NXP arm, arduino vs avr atmega8 its comparing apples to apples and oranges to oranges, just a little sugar was added, we all love sugar. Most things in Python,Perl,Ruby could be done in C,C++, or Java which could be done in assembly or machine code. I rarely reach for assembly when I just want to *try* an idea. Peace and love.

  18. @Adam

    Arduino bashing? I have managed to ignore such things or they don’t bash it loud enough that it could be heard under my rock.

    But yeah, Arduino is like iPhone. I don’t mean to bash Arduino (it’s much more useful and more value for the $ than i-anything), let me explain:
    one can buy add-ons to extend its capabilities and when new version comes along you just _have_ to have it. Yet somehow their main functions become irrelevant or forgotten: new phone for calling people and Arduino for prototyping purposes.

  19. AVRstudio is the way to go on win. I never even heard of this WInAVR but by just judging the quality of the OSS projects lately I wouldn’t waste my time on it. You probably just googled it.

    You can really say a big thanks for Amtel providing all these stuffs for the hobbists, microchips, avr programmers, cables, software.

    There are a lot of different microcontrollers out there on different boards what you have no clue what they are. They use random meaningless numbers on the chips, they don’t have jtag or any programming interface, they might not even use any standard code and not RISC.

  20. WinAvr is the avr-gcc compiler to AvrStudio, without it you can only program assembly in AvrStudio, people dont even know how too take full use of an AVR but want to use one super complex ARM..

  21. @Drone, yes i know that WinAVR works with the supported device, but i am not worry about now, just a bit about the future (let’s say 1 year). avrdude (part of winavr) will be updated, so how we will have the last version? that’s why i am searching for an alternative.

  22. I’m looking forward to the next in this series. I’ve been using PICs for years have just moved to AVRs in the last few months.

    I’m gonna second absolutezero’s recommendation of ArduinoISP, if you already have an Arduino (except Arduino Uno) you have an AVR programmer.

  23. @Everyone: Thanks for the encouraging comments. Part 2 is already in the can and scheduled to post today.

    Yes, I’ll be talking about fuse bits. But not until part 3.

    ArduinoISP? Absolutely… If you own and Arduino you already own an In-System Programmer and I use that as the example for programming in Part 2.

    @Sanjay: I think Yet Another AVR Tutorial is exactly what we need. Yes, there are several out there, but different people understand things in different ways. For people that looked at all the other tutorials and kept on hitting a wall at one particular point this may be the answer for them. Or if not, whomever writes the next tutorial series might address that knowledge gap.

  24. @ARM Tutorials,
    I’ve developed both ARM and AVR series and it is far easier to build and do an AVR tutorial than an ARM tutorial… just too many pins and functions to cover.

    James

Leave a Reply to BrianCancel reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.