Menu

How to compile and burn the code to AVR chip on Linux/MacOSX/Windows ?

This is a quick tutorial for beginners that aims to show how to install tools, compile the code with avr-gcc and send it to the MCU with avrdude. It also introduce basics of automation of this task by putting the all instructions into Makefile. The example files (main.c, main.bin, main.hex, Makefile) has been packaged as a .ZIP file and can be downloaded here.

1. Installing avr-gcc and tools

To compile C and/or C++ source code of your firmware you will need gcc-avr compiler, the avr-libc C library and avrdude. What is extremely useful, there are complete and easy to install packages for all major platforms.

Linux, Ubuntu

Ubuntu provides packages, so you can just install them using this command.

$ sudo apt-get install gcc-avr avr-libc avrdude

Mac OSX

Download AVR MacPack. The MacPack disk image has an installer that does everything for you.

Windows

Download WinAVR, which includes everything you need and has a nice installer.

2. Compiling and burning the code

Now that you have the compiler installed, a next step is to compile simple source code into a .BIN file, then generate Intel .HEX file and finally burn this .HEX file to AVR chip using USBasp programmer.

Example code

Here is an example content of main.c file. The code does nothing except getting stuck in an endless loop but it’s always something!

int
main(void)
{
while (1);
}

Compiling

The command below will compile your code. It’s GCC so I assume it looks familiar to you and no additional explanations are needed. If you want perform compilation for some other MCU then you need specify appropriate -mmcu option.

$ avr-gcc -Wall -g -Os -mmcu=attiny13 -o main.bin main.c

After performing successful compilation, you can check program and data memory size with this command.

Generating .HEX

Most programmers will not accept a GNU executable as an input file, so we need to do a little more processing. So the next step is about converting the information form .BIN into .HEX file. The GNU utility that does this is called avr-objcopy.

$ avr-objcopy -j .text -j .data -O ihex main.bin main.hex

Burning

The utility called avrdude can program processors using the contents of the .HEX files specified on the command line. With the command below, the file main.hex will be burned into the flash memory. The -p attiny13 option lets avrdude know that we are operating on an ATtiny13 chip. In other words – this option specifies the device. The full list of supported parts can be found here. Note that full-length names are also acceptable (i.e. t13 equals attiny13).

3. Make and makefiles

Now, we can automate this process by creating a Makefile and putting our commands there. The structure of a Makefile is very simple, and more information about it can be found here. Utitlity make reads automatically a Makefile file in the folder where you launch it. Take a look at a ready-made example.