Tag Archive : avr

/ avr

Atmel Studio 6 and Arduino

December 11, 2015 | Article | No Comments

Atmel Studio, formerly known as AVR Studio, is a good development application to create program for Atmel’s processor (Atmel’s AVR and Atmel’s ARM). The 6th version promises to be better, faster, and easier to use than before. Here, we will discuss about the way to set up the platform for the use with Arduino.

In this article, I use:

  1. Windows 8.1 64-bit
  2. Atmel Studio 6.2
  3. Arduino 1.5.8 (BETA)

Our objective:

  1. Successfully create binary file for Arduino
  2. Successfully flash the image to Arduino
  3. Know some of Arduino core library

It is recommended that we install both Atmel Studio and Arduino IDE.

Introduction to Atmel Studio 6

This Integrated Development Platform is a rich feature development platform for developing and debugging Atmel ARM Cortex-M and Atmel AVR microcontroller (MCU) based application.

Atmel Studio 6 is released in 2011 and based on Microsoft Visual Studio. The latest version at the time of writing this article is Atmel Studio 6.2 which can be downloaded from here.

Atmel studio 6 is free of charge and is integrated with the Atmel Software Framework (ASF), a large library of free source code with 1600 ARM and AVR project examples. In summary, what Atmel Studio 6 offers in addition to creating new software for MCU:

  1. Facilitates reuse of existing software and, by doing so, enables design differentiation.
  2. Supports the product development process with easy access to integrated tools and software extensions through Atmel Gallery.
  3. Reduces time to market by providing advanced features, an extensible software eco-system, and powerful debug integration.

Why Switching from Arduino IDE to Atmel Studio 6?

Arduino is a great tools. But, it does so much under the hood that it can actually be quite limiting for experienced programmers. The lacks of compiler warnings and debugging capabilities make life hard when working on advanced projects. And here Atmel Studio comes to the rescue.

Atmel Studio is a huge step up from those limitations. If you have a big project, porting the entire thing to pure C can be a daunting task. Plus, some of those Arduino libraries are just so darn convenient.

So, why not have the best of both worlds? Arduino is basically a wrapper on top of C/C++, technically it’s possible to combine any Arduino sketch or library with your own custom code (and that it is). The trick is in setting up your project properly. Once accomplished, you can keep access to the huge Arduino user-contributed code library, but enjoy all the features of advanced AVR and a real IDE.

Arduino Core Library

Arduino is an open-source physical computing platform based on simple I/O board. Stripped the IDE part, Arduino has a library which consists of seberal things like: EEPROM, Esplora, Ethernet, Firmata, etc. But down to the innermost, Arduino has a set of library known as the Arduino core. This Arduino core is the software library which is compiled to any board of Arduino and make Arduino as Arduino.

The Arduino core can be found at “<ArduinoPath>\hardware\arduino\cores\arduino\” where <ArduinoPath> is the path you install Arduino IDE. Well, if you don’t install Arduino IDE, you can clone it from git

git clone git://github.com/arduino/Arduino

and head to “hardware\arduino\cores\arduino”. You can read the content of Arduino core library in the appendix A below.

In order to build Arduino projects, we need to grab the arduino core library. Normally, the Arduino IDE compiles this for us whenever we compile a sketch. To use it in Atmel Studio we need to compile it first.


  1. Open Arduino IDE. Open preferences (File -> Preferences) and check on “compile” next to “Show verbose output during:”.
  2. Make sure Arduino IDE is set to whichever chip you want to use with Atmel Studio.
  3. Compile any example sketch, for example “01.Basics\Blink”. In output window at the bottom of the IDE window you should see information on where the IDE put the temporary build output. It will look something like this: “C:\Users\{Your User}\AppData\Local\Temp\build1249632912679374352.tmp”
  4. Copy the “core.a” file and paste it as “libcore.a” so Atmel Studio (and GCC toolchain) can recognizes it as a standard library.

Converting the Sketch

Now the sketch part. There are two things you can do:

  1. If you are converting an existing sketch called Sketch, open the Sketch.cpp file from temporary build directory in text editor. You can then simply copy-paste the code into AVR Studio project. This file is generated by Arduino from our sketch. Arduino automatically fix the messes for us, for example we can define function anywhere in the sketch but Arduino would make appropriate function prototype for us. This is a solution if you are compiling the sketch via Arduino IDE.
  2. Copy and paste the source code from sketch file into the project’s main .cpp file. You can also copy-paste the source from Arduino .pde sketch. If you do this, you should define the function prototypes by yourself. Adding function prototypes is easy actually. Remember to incluse prototypes for setup() and loop() and then add #include “Arduino.h” to the very beginning.

Compiler and Linker Setup

In this section we will setup the compiler and linker setup for any of our project. Our objective:

  • Define Symbols for compilation, especially F_CPU and Arduino software version.
  • Point additional Include directory.
  • Set some Optimization
  • Set Linker to include our libcore
Picture 1


  1. Open the Project Properties (Project -> <ProjectName> Properties or press Alt+F7), then click on “Toolchain”. We need to setup a bunch of compiler options here. Select “All Configuration from the Configuration drop-down menu to modify both release and debug configuration at same time.
  2. Click on “Symbols” in the left-hand “AVR/GNU C++ Compiler” dropdown menu (see number 1 on picture 1). We need to tell some symbols to our compiler. To do it, click the green plus icon and then enter the symbol. Here is what you need to enter:
    • F_CPU=16000000L
    • ARDUINO=158
  3. Click on “Directories” in the same C++ Compiler menu (see number 2 on picture 1). We need to add the include directories, the directories that contain our Arduino core code and libraries. For any Arduino project, we’ll need to tell the compiler where to find “Arduino.h” and “pins_arduino.h”. In my case I install Arduino on C:\Arduino so the library should be on “C:\Arduino\hardware\arduino\cores\arduino” and “C:\Arduino\hardware\arduino\variants\standard”.
  4. Click on “Optimization” immediately after “Directories” (see number 3 on picture 1). Choose “Optimize for size” under “Optimization Level”. Add “-fdata-sections” to “other optimization flags” and check the box for “prepare functions for garbage collection”.
  5. Next click on “Miscellaneous” (see number 4 on picture 1). Add “-fno-exceptions” to the “Other flags” field.
  6. Now we will move to the linker. Click on “Libraries” in the left hand “AVR/GNU Linker” dropdown menu (see number 5 on picture 1).
    1. In the Libraries section you should already see an entry for “m” which is the AVR math library. Add an entry called core, which is our libcore.a file that we grabbed earlier.
    2. We also need to tell where to find the libcore.a, so add that directory path under “Library search path”
  7. Click on “Optimization” (see number 6 on picture 1) and check the box for “Garbage Collect unused sections (-Wl,-gc-sections)”. This tells the linker to leave out unused portions of each library, which reduces the final code size.

Build Project

Building process is similar like other project. Hit the “F7” button to build our solution and watch the output window.

AVRDude and Flashing

The instruction in this section is similar to other “Adding ISP Programmer to Atmel Studio”.

Once you have build the project, we need to upload it. We can achieve this using the similar method as the Arduino IDE. Arduino uses the avrdude utility to flash via serial, and we will do the same.

picture 2
picture 3

Ignore entries other than Arduino on picture 3.


  1. Open External Tools by clicking Tools -> External Tools (see picture 2)
  2. When the window popups, click “Add” (see number 1 on picture 3)
  3. Note which COM port Arduino uses and make the title like “Arduino on COM24” for easy identification (see number 2 on picture 3)
  4. In the “Command field” (see number 3 on picture 3), put the path to avrdude.exe in Arduino installation. For example in my case: “C:\arduino\hardware\tools\avr\bin\avrdude.exe” without the quotes.
  5. In the “Arguments” (see number 4 on picture 3), paste this line.
-CC:\arduino\hardware\tools\avr\etc\avrdude.conf -patmega328p -carduino -P\\.\COM24 -b57600 -D -Uflash:w:"$(ProjectDir)Debug\$(ItemFileName).hex":i

Edit the path to Arduino installation and change the COM port, chip target, and baud rate if necessary.


Appendix A: Arduino Core Library files

The Arduino core library is consists of following file:

utility function


CDC communication.


Human Interface Device (HID) communication.


Hardware serial, for serial communication capability.


Internetwork connection.




Stream oriented communication


USB serial communication.


Tone Generator.


Wiring project


Linux udev Rule for AVR USB Programmer

December 11, 2015 | Article | No Comments

In previous article, we have discussed about AVR development in both Linux and Windows. As you might see, we are using software avrdude to write our binary code to avr chip.

Now, when executing avrdude on Linux, it may give an error such as

avrdude: error: usbtiny_transmit: error sending control message: Operation not permitted.

This problem arise when we run avrdude without root privilege.

We can quickly fix this by run avrdude as root or doing sudo. The other choice we have is creating an udev rule for certain programmer. And that’s what we will discuss in this article.

Create udev Rule

First, what is udev?

Any device attached to Unix (and its derivation) will be represented as a node in /dev directory.For each device, it will receive a (major, minor) pair of integers. In the old school way, we can call “mknod” to create device. Starting from kernel version 2.6, Linux use udev to provide a userspace solution for dynamic /dev directory with persistent device naming. With udev we won’t have hard time to manage all device.

We use udev to give us enough privilege to access to device node.

It’s easy to use udev. We need to create a file containing udev rule and save it to /etc/udev/rules.d/

Create file “/etc/udev/rules.d/99-avrprogrammer.rules” and write following this:

# /etc/udev/rules.d/99-avrprogrammer.rules
# Udev rules to make AVR programmers user-accessible

# USBtinyISP Programmer rules
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1781", ATTRS{idProduct}=="0c9f", GROUP="users", MODE="0666"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="0479", GROUP="users", MODE="0666"

# USBasp Programmer rules http://www.fischl.de/usbasp/
SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05dc", GROUP="users", MODE="0666"

# Mdfly.com Generic (SiLabs CP2102) 3.3v/5v USB VComm adapter
SUBSYSTEMS=="usb", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", GROUP="users", MODE="0666"

#Atmel AVR Dragon (dragon_isp) rules
SUBSYSTEM=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2107", GROUP="users", MODE="0666"

SUBSYSTEM=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2103", GROUP="users", MODE="0666"

#Atmel Corp. AVR ISP mkII
SUBSYSTEM=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2104", GROUP="users", MODE="0666"

The above rules describe about six hardware programmers.

Introduction to AVR Registers

December 11, 2015 | Article | No Comments

What is Register?

Micro controller operations mostly involve processing data. Registers is used to do operations in CPU.

Registers are special storages in CPU with capacity of certain bits. In 8-bit AVR, a register is 8 bits wide which can hold data of 8-bits (1 byte). In nutshell, they do like this:

7 6 5 4 3 2 1 0

Note the numeration of these bits: the least significant bit starts with zero (20 = 1).

A register can either store numbers from 0 to 255 (positive number, no negative values), or numbers from -128 to +127 (whole number with a sign bit in bit 7), or a value representing an ASCII-coded character (e.g. ‘A’), or just eight single bits that do not have something to do with each other (e.g. for eight single flags used to signal eight different yes/no decisions).

The special character of registers, compared to other storage sites, is that

  • they can be used directly in assembler commands,
  • operations with their content require only a single command word,
  • they are connected directly to the central processing unit called the accumulator,
  • they are source and target for calculations.

Registers are commonly divided into three categories:

  1. General purpose registers
  2. Control & Status registers
  3. Segment registers

A general purpose registers are registers which is used to hold data for operations. They can be used as operand which will be operated by ALU (Arithmetic & Logic Unit), or as result of the operations.

The Control and Status registers are used to control the micro controller. They are used to determine the control flow of the program. Many instructions involve comparisons and mathematical calculations. Those operations will changes some part of flags. Other conditional instruction test the value of these status flags to take the control to other location.

Segment registers are registers which is used to point different segment in the memory. Segments are specific areas defined in a program for containing data or instruction.

Registers in AVR

General Purpose Register

AVR micro controllers have 32 general purpose 8-bit registers, named R0 to R31. All arithmetic operations operate on those registers, only load and store instructions access RAM. A limited number of instruction operate on 16-bit register pairs. The lower-numbered register of the pair holds the least significant bits and must be even-numbered. The last three register pairs are used as pointer registers for memory addressing. They are known as X (R27:R26), Y (R29:R28) and Z (R31:R30). Postincrement and predecrement addressing modes are supported on all three. Y and Z also support a six-bit positive displacement.

Instructions which allow an immediate value are limited to registers R16–R31 (8-bit operations) or to register pairs R25:R24–R31:R30 (16-bit operations ADIW and SBIW). Some variants of the MUL operation are limited to eight registers, R16 through R23.

Control and Status Register

In addition to those 32 general-purpose registers, the CPU has a few special-purpose registers:

  • PC: 16- or 22-bit program counter
  • SP: 8- or 16-bit stack pointer
  • SREG: 8-bit status register

The status register bits are:

  1. C Carry flag. This is a borrow flag on subtracts.
  2. Z Zero flag. Set to 1 when an arithmetic result is zero.
  3. N Negative flag. Set to a copy of the most significant bit of an arithmetic result.
  4. V Overflow flag. Set in case of two’s complement overflow.
  5. S Sign flag. Unique to AVR, this is always N⊕V, and shows the true sign of a comparison.
  6. H Half carry. This is an internal carry from additions and is used to support BCD arithmetic.
  7. T Bit copy. Special bit load and bit store instructions use this bit.
  8. I Interrupt flag. Set when interrupts are enabled.

The Carry flag is used for shift and rotate instructions.

If the Global Interrupt Flag is set, the mcu will perform the Interrupt Service Routine corresponding to the interrupt that occurred.

Just remember: They are important for mathematical operations, and changing them between calculating a value and comparing it with something else might be fatal. That’s why Interrupt Service routines should preserve the SREG and any other registers they use (unless these registers are unused in normal code). An interrupt might occur between comparing two values with each other and a following branch – the ISR might change status flags and corrupt the flags the branch relies on.

Segment Registers

AVR micro controller has some 8-bits segment registers, named: RAMPX, RAMPY, RAMPZ, RAMPD, and EIND. These registers are prepended to 16-bit addresses in order to form 24-bit address; only available in parts with large address spaces.

You should remember that AVR use modified Harvard architecture which separate the instructions and the data.It is different to Intel x86 where instruction and data are stored in same memory.

Gentle Introduction to AVR Assembly

December 11, 2015 | Article | No Comments

What is Assembly Language?

Assembly language is a low-level programming language for programmable device. It is an alphanumeric representation of machine code. In contrast to high-level programming language which are generally portable across multiple systems, assembly language is very architecture specific. Assembly language is very strong correspondence between the language and the architecture’s machine code instruction.

Assembly consists of a list of instructions that are in no way comparable to anything you might know from C, Basic or Pascal. It does not have structure like high-level language does (like for or while)

Let’s see the example below. The code below is an example of a AVR assembly code written in assembly language. Each line of the code is an instruction telling the micro controller to carry out a task.

            ADD     R16, R17       ; Add value in R16 to value in R17
            DEC     R17            ; Minus 1 from the value contained in R17
            MOV     R18, R16       ; Copy the value in R16 to R18
END:        JMP     END            ; Jump to the label END

As we stated before, the instruction or mnemonic are note general but specific. Each company provides a set of instructions for their micro controllers. Also note that not all instructions are available to all micro controllers. We should consult datasheet for each AVR microcontroller.

Why Assembly?

Assembler or other languages, that is the question. Why should I learn another language, if I already learned other programming languages? The best argument: while we live in France we are able to get through by speaking English, but we will  never  feel  at  home  then,  and  life  remains  complicated.  We can  get  through  with  this,  but  it  is  rather inappropriate. If things need a hurry, we should use the country’s language.

Many people who dwelling in higher-level language start diving into AVR assembly. The reasons are sometimes similar to people who come to assembly language in x86, such as:

  • to know the architecture better
  • analyze bug
  • use hardware features which aren’t supported by higher-level language
  • need time-critical code
  • just for fun

It is necessary to know assembly language, e.g. to understand what the higher-level language compiler produced. Without understanding assembly language we do not have a chance to proceed further in these cases.

High Level Languages and Assembly

High level languages insert additional nontransparent separation levels between the CPU and the source code. An example for such an nontransparent concept are variables. These variables are storages that can store a number, a text string or a single Boolean value. In the source code, a variable name represents a place where the variable is located, and, by declaring variables, the type (numbers and their format, strings and their length, etc.).

For learning assembler, just forget the high level language concept of variables. Assembler only knows bits, bytes, registers and SRAM bytes. The term “variable” has no meaning in assembler. Also, related terms like “type” are useless and do not make any sense here.

High level languages require us to declare variables prior to their first use in the source code, e. g. as Byte (8-bit), double word (16-bit), integer (15-bit plus 1 sign bit). Compilers for that language place such declared variables somewhere in the available storage space, including the 32 registers. If this placement is selected rather blind by the compiler or if there is some  priority rule used,  like  the  assembler  programmer carefully  does  it,  is  depending  more  from the  price  of  the compiler. The programmer can only try to understand what the compiler “thought” when he placed the variable. The power to decide has been given to the compiler. That “relieves” the programmer from the trouble of that decision, but makes him a slave of the compiler.

The instruction “A = A + B” is now type-proofed: if A is defined as a character and B a number (e. g. = 2), the formulation isn’t accepted because character codes cannot be added with numbers. Programmers in high level languages believe that this type check prevents them from programming nonsense. The protection, that the compiler provides in this case by prohibiting your type error, is rather useless: adding 2 to the character “F” of course should yield a “H” as result, what else? Assembler allows us to do that, but not a compiler.

Assembler allows us to add numbers like 7 or 48 to add and subtract to every byte storage, no matter what type of thing is in the byte storage. What is in that storage, is a matter of decision by the programmer, not by a compiler. If an operation with that content makes sense is a matter of decision by the programmer, not by the compiler. If four registers represent a 32-bit-value or four ASCII characters, if those four bytes are placed low-to-high, high-to-low or completely mixed, is just up to the programmer. He is the master of placement, no one else. Types are unknown, all consists of bits and bytes somewhere in the available storage place. The programmer has the task of organizing, but also the chance of optimizing.

Of a similar effect are all the other rules, that the high level programmer is limited to. It is always claimed that it is saver and of a better overview to program anything in subroutines, to not jump around in the code, to hand over variables as parameters, and to give back results from functions. Forget most of those rules in assembler, they don’t make much sense. Good assembler programming requires some rules, too, but very different ones. And, what’s the best: most of them have to be created by yourself to help yourself. So: welcome in the world of freedom to do what we want, not what the compiler decides for us or what theoretical professors think would be good programming rules.

High level programmers are addicted to a number of concepts that stand in the way of learning assembler: separation in different access levels, in hardware, drivers and other interfaces. In assembler this separation is complete nonsense, separation would urge us to numerous workarounds, if we want to solve your problem in an optimal way.

Because most of the high level programming rules don’t make sense, and because even puristic high level programmers break their own rules, whenever appropriate, see those rules as a nice cage, preventing us from being creative. Those questions don’t play a role here. Everything is direct access, every storage is available at any time, nothing prevents your access to hardware, anything can be changed – and even can be corrupted. Responsibility remains by the programmer only, that has to use his brain to avoid conflicts when accessing hardware.

The other side of missing protection mechanisms is the freedom to do everything at any time. So, smash your ties away to start learning assembler. We will develop your own ties later on to prevent yourself from running into errors.

What is Really Easier in Assembly?

All words and concepts that the assembler programmer needs is in the datasheet of the processor: the instruction and the port table. Done! With the words found there anything can be constructed. No other documents necessary. How the timer is started (is writing “Timer.Start(8)” somehow easier to understand than “LDI R16,0x02” and “OUT TCCR0,R16”?), how the timer is restarted at zero (“CLR R16” and “OUT TCCR0,R16”), it is all in the data sheet. No need to consult a more or less good documentation on how a compiler defines this or that. No special, compiler-designed words and concepts to be learned here, all is in the datasheet. If we want to use a certain timer in the processor for a certain purpose in a certain mode of the 15 different possible modes, nothing is in the way to access the timer, to stop and start it, etc.

What is in a high level language easier to write “A = A * B” instead of “MUL R16,R17”? Not much. If A and B aren’t defined as bytes or if the processor type is tiny and doesn’t understand MUL, the simple MUL has to be exchanged with some other source code, as designed by the assembler programmer or copy/pasted and adapted to the needs. No reason to import an nontransparent library instead, just because you’re to lazy to start your brain and learn.

Assembler teaches us directly how the processor works. Because no compiler takes over your tasks, we are completely the master of the processor. The reward for doing this work, we are granted full access to everything. If we want, we can program a baud-rate of 45.45 bps on the UART. A speed setting that no Windows PC allows, because the operating system allows only multiples of 75 (Why? Because some historic mechanical teletype writers had those special mechanical gear boxes, allowing quick selection of either 75 or 300 bps.). If, in addition, we want 1 and a half stop bytes instead of either 1 or 2, why not programming your own serial device with assembler software. No reason to give things up.

The Instruction Set

Instruction Set or Instruction Set Architecture (ISA) is set of instruction for computer architecture, including native data types, instructions, registers, addressing modes, memory architecture, interrupt and exception handling, and external I/O. In simple word, it is the set of instruction we use to program the device.

Every instruction is actually a number. These numbers are stored in flash memory and when the chip is powered, the CPU then start to fetch instruction from storage and executed what the instruction want. The instructions are 16-bit number. But there is no need for us to learn that binary code and pattern, because in assembler those codes are mapped to human-readable instruction. The so called mnemonics are machine instruction represented as human-readable text.

Still, the CPU understands instruction expressed in 16-bit word. The mnemonics only represents those instruction.

Instruction Set can be divided into some categories:

  • Data handling and memory operations: set register to a fixed value, move data from memory location to register or vice.
  • Arithmetic and logic operations: add, subtract, multiply, divide, bitwise operations, comparison.
  • Control flow operations: branch, conditionally branch, function call.

You can see the complete AVR instruction set here: Download

The Directives

Apart from the microcontroller instruction set that is used in writing an AVR assembly code the AVR Assembler support the use of assembler directives. Assembler Directives are used as instruction to the AVR assembler and are in no way translated to machine language during the assembly process.

Assembler Directives are use by the programmer to assist in adjusting the location of the program in memory, defining macros and so fort. A list of the AVR assembler directives available to the AVR assembler is given below.

[table “9” not found /]

Each assembler directives in an AVR assembly program must be preceded by a period “.” as shown below where the directives INCLUDE and ORG are used.

.include "m8515def.inc"
.org $00

begin:     ADD R16, R17      ; Add R17 to R16
           MOV R17, R18      ; Copy R18 to R17

Installing USBasp Drivers on Windows 8.1

December 11, 2015 | Article | No Comments

When we are dealing with AVR programming, after create the codes in our development machine we should write the code into the device. For this purpose, we need a tool which we called Downloader or Programmer. This tool will “burn” the code into AVR CPU using spesific port.

One popular tool is USBasp (http://www.fischl.de/usbasp/). This tool is a USB in-circuit programmer which consists of an ATMega88 or an AtMega8 and a couple of passive components. In short, we need no special USB controller anymore.


Sometimes, we might face a problem installing usbasp drivers on Windows 8.1. But, this article will discuss about how to install those drivers.


The method described here will require machine to restart. Make sure you have write down the steps before proceeding.

Identify The Problem

The main problem is that Microsoft doesn’t allow us to install drivers which are not ‘digitally signed’ directly (or easily) on Windows Vista and later version (7, 8, and also 8.1). To get around this, we must temporarily disable the signature verification process.

Phase 1: Disable Driver Signature Enforcement

  1. Enter “start screen” and open “PC Settings”
  2. Choose “Update and recovery” option in the left panel.
  3. Choose “Recovery” option in the left panel
  4. Click on “Restart now” button, below the “Advanced startup” section then click “reset” button to begin resetting.
  5. Once machine is restarted, we will face several options which we can choose by pressing F1-F9. Choose F7 for “Disable driver signature enforcement”

Now, the machine will boot with no driver signature enforcement. We can then install the driver to our machine.

Phase 2: USBasp Driver Installation

Download the driver fro Windows from USBasp (http://www.fischl.de/usbasp/). The latest version is version 2011-05-28.zip which can be downloaded here. Read the readme first. Because I use WinAVR version 20100110, i will extract the libusb_0.1.12.1 folder as D:\libusb_0.1.12.1.

Plug the USBasp in to USB port. Windows will try to recognize the device. It should be recognized but it lacks of driver so the process is not finish.

Open “Device Manager” on “Control Panel”. Look for Other devices. We have USBasp device there.


Right click on it and click on “Update Driver Software…”


Click on “Browse my computer for driver software”.


Type the location of folder “D:\libusb_0.1.12.1” and then click “Next”.


Windows will give warning as it can’t verify the publisher of the driver. Just ignore it and select “Install this driver software anyway”


Let the installation proceed and wait until it finish.



Creating Simple AVR Program: “Running” LEDs

December 3, 2015 | Article | No Comments

In the previous article we have discussed about AVR microcontroller programming in Linux environment and Windows environment. The term program in this case is downloading / store a binary program to your microcontroller using usb programmer and avrdude. If you haven’t read the article I recommended you to read it. It’s not a long article so it would be fine to skim it.

Now, in this article we will discussed about writing a simple program for our AVR microcontroller. What we will need:

  1. Host Operating System, (you can use GNU/Linux or Microsoft Windows Operating System)
  2. AVR microcontroller, embedded as board. In this case I use atmega32
  3. avrdude, this tool is for writing our program to microcontroller
  4. avr-gcc, this tool is for compiling the code
  5. A USB programmer

Now, let’s configure the chip. I have assembly my AVR as follows:

  1. ATMega32 chip
  2. External clock with 16MHz frequency
  3. Eight active low LEDs connected to PORT A
  4. A port for ISP programming connected to PORT B

Well, actually there are more in my board but for this article we will just need those informations.

Please note that I use PORT A for LEDs. You may use other port but you must adjust your configuration with this article. The one I used are active-low LEDs which can only emitted light if we give low voltage. Also note that I use PORT B for ISP programmer and this is the only one PORT to program AVR microcontroller.

I assume we all have prepared the tools. See article for preparing tools in Windows and Linux.

Writing the Codes

When writing the codes, you can use any text editor. For simplicity, we use notepad in Windows and Geany in Linux (remember, any text editor will do).

What I want is some turn on and off some LEDs in a pattern. For every second, I will switch the condition for every LEDs and shift the series to the left. This will give impression like the LEDs are running :3

OK, let’s get to actual code. Write this codes and save it as avr-leds.c

#define F_CPU 16000000UL

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

/* our entry point */

int main() {
   /* we used PORT A for LEDs so we will give a little setup */
   DDRA 	= 0xFF;
   PORTA	= 0b11000101;
   /* used for shifting */

   int tmp;

   /* our main loop. The execution goes here */
   while(1) {
      /* setting the running speed. It's a simple delay in 800 miliseconds */

      /* get the least significant bit, in this case is the most right position
         on binary number but it is the most left position on leds */
      tmp = PORTA & 1;

      /* shift the number to the right */
      PORTA >>= 1;

      /* grab the saved bit and shift it to the most right position */
      PORTA |= tmp << 7;
   return 0;

It’s short and simple code. We only write what we need, not completely set other parts.

In this code, we only use port A as output. To do so, we set all the 8 bits to 1 (which has value of 0xFF or 255 in decimal). Port A is then connected to 8 LEDs and I give initial pattern of 0b11000101. Remember that I use active low LEDs, so it will turn on when we give low logic.

To access individual bit of a byte, we use bitwise operation.

The statement:

tmp = PORTA & 1

will give me the least significant byte of PORTA and store it to tmp variable.

Then the statement:

PORTA |= tmp << 7;

will write the most significant bit by the value of tmp variable.

Here you see some


OK, next we will compile the code. To do so open your terminal and invoke this command:

avr-gcc -g -Os -mmcu=atmega32 -c avr-leds.c

That command tell the compiler to compile a single file avr-leds.c but do not link it yet. It’s useful if you have bigger project you can compile each source code separately.

What you need to know is -mmcu switch. It tells compiler what chip we are using now. In this case we are using ATMega32.

The previous command will compile the file into an object file with filename avr-leds.o.

Now, invoke this command:

avr-gcc -g -mmcu=atmega32 -o avr-leds.elf avr-leds.o

This will produce a binary file called avr-leds.elf, which is a GNU executable file. The file format is ELF (Executable and Linkable Format) which is similiar to linux program. However, this is not what we need. We need hex file for AVR.

Now invoke this command:

avr-objcopy -j .text -j .data -O ihex avr-leds.elf avr-leds.hex

This will produce the file we want, an intel hex file. Let me explain what switches we gives

When we write -j switch we tells the avr-objcopy to only copy from that section. In this case we only copy data from section .text and .data. If you have program in assembly before, then you might know what is section.

A -O switch tells the avr-objcopy to produce file with following format. And in our case it is intel hex format (ihex).

The next arguments are the .elf file and .hex file respectively. It means that our input would be avr-leds.elf and will be processed to avr-leds.hex.

Burn the Program to the Device

We use avrdude to do so. Make sure you have connected the device with the downloader and connect it to PC. The downloader I use is USBasp.

avrdude -c usbasp -U flash:w:avr-leds.hex -p atmega32

And we are done!

AVR Microcontroller Programming in Windows

December 3, 2015 | Article | No Comments

AVR or Alf & Vegard RISC, is a single chip microcontroller developed by Atmel. AVR is a modified Harvard architecture 8-bit RISC (Reduced Instruction Set Computer) which is famous microcontroller.

AVR microcontrollers has many categories or we will say family. Family basically a group or category based on similiar characteristic and properties. There are six family and fortunately, AVR microcontrollers have same architecture so programming in any kind of family can be guaranteed work on other family. It is only limited to physical limitation such as different amount of flash storage, etc. This is also an advantage using AVR while variety options can be found while developing microcontroller project.

This article will be covering preparation and setting up environment in Linux to develop AVR program.

What you will need:

  1. Microsoft Windows Operating System
  2. avrdude
  3. avr-gcc
  4. avr-binutils
  5. A programmer (will be described later)
  6. AVR Microcontroller, with it’s development board if any, in this case I use AVR ATMega32

Program in Microcontroller

Before I start, let’s talk about program. What is program? A program is simply set of instructions written using machine language so it can be executed by machine. It is also called “binary” which mean to be not human-readable file (but can be understood by machine). For microcontrollers, binary files have type .hex (Intel Hex Format). You can imagine it as .exe in windows application. There are other forms, but in this article we will focus on .hex.

AVR has a small amount of memory in it. It is a storage where program is actually saved. And yes it is small compared by computer. Just some Kilobytes. When the chip starts up, microcontroller will start running whatever program written in flash.

Compiler and Cross Compiling

Compilation for microcontroller is basically similar to compiling program for PC. However, the difference between those two is in term of product of compilation. Compiler for AVR is run in our PC (developer machine), compile source code, and then produce machine language which is specific for the microcontroller (not our PC). This process is called cross compiling.

There are many cross compiler for AVR. I use AVR-GCC for this purpose (in this article and other similar articles, unless told otherwise).

Other tools we need are collectively known as avr-binutils. The binutils packages provide all the low-level utilities needed in building and manipulating object files. In this package, we have AVR assembler (avr-as), linker (avr-ld), and librarian (avr-ar and avr-ranlib). In addition, we get tools which extract data from object files (avr-objcopy), dissassemble object file information (avr-objdump), and strip information from object files (avr-strip).

The last thing to mention is the libc or standard c library. This is library designed for AVR microcontroller, or in other word it is different with our library used for PC programing.

Fortunately, avr-gcc, avr-binutils, avr-libc, and avrdude (later) are already ported into Windows. These Windows version tools are collectively called WinAVR. We can download WinAVR for free from sourceforge site (http://sourceforge.net/projects/winavr/). Download the latest version.

Download / Burn the Program to the Chip

To program microcontroller we need a downloader. It is a special chip that can connect your microcontroller with our computer and write our program into our chip. Every AVR has a set of pins that are programming pins. You have to verify you chip pins and connect the programmer to those pins in the right order.

So what programmer can be used? In this article I used USBasp. Of course you can have other programmers, but I will only talk about this programmer. For information about USBasp, you can visit this link http://www.fischl.de/usbasp/

Now we have know our programmer (USBasp I mean) but then, how to write our program to microcontroller? Relax! We will cover now.

We will use avrdude, a small application to do that. This tool is already included in WinAVR.

Let’s take a peek of avrdude by give this command on our terminal:


Let’s see what we have got. You will get something like this:

Usage: avrdude [options]
-p <partno>                Required. Specify AVR device.
-b <baudrate>              Override RS-232 baud rate.
-B <bitclock>              Specify JTAG/STK500v2 bit clock period (us).
-C <config-file>           Specify location of configuration file.
<strong>-c <programmer>            Specify programmer type.</strong>
-D                         Disable auto erase for flash memory
-i <delay>                 ISP Clock Delay [in microseconds]
-P <port>                  Specify connection port.
-F                         Override invalid signature check.
-e                         Perform a chip erase.
-O                         Perform RC oscillator calibration (see AVR053).
-U <memtype>:r|w|v:<filename>[:format]
 Memory operation specification.
 Multiple -U options are allowed, each request
 is performed in the order specified.
-n                         Do not write anything to the device.
-V                         Do not verify.
-u                         Disable safemode, default when running from a script.
-s                         Silent safemode operation, will not ask you if
fuses should be changed back.
-t                         Enter terminal mode.
-E <exitspec>[,<exitspec>] List programmer exit specifications.
-x <extended_param>        Pass <extended_param> to programmer.
-y                         Count # erase cycles in EEPROM.
-Y <number>                Initialize erase cycle # in EEPROM.
-v                         Verbose output. -v -v for more.
-q                         Quell progress output. -q -q for less.
-?                         Display this usage.

avrdude version 5.10, URL: <http://savannah.nongnu.org/projects/avrdude/>

Woah, that’s too much. But our interest is only in few options. I’ve bold the text which will get our attention. We only interests in -p, -U, and -c options as this is a minimum command we need to invoke along with avrdude.

  • -c : We specify the programmer we type. We are using usbasp so can be replaced with usbasp. Of course if you are using other programmer you must specify. For a complete list about supported programmer, invoke command: avrdude -c asdf. Because asdf is not a valid programmer, avrdude would complaint and print out list of supported programmer to you. Read it and verify your programmer is supported.
  • -U :r|w|v:[:format]: This is the most important command. is either flash or eeprom which is destination where our program will be stored. Next is r (read), w (write), or v (verify) option that you must choose one (only one). Next is which you have to replace with your program path and name. Next is optional format flag [:format] that specify our program format.
  • -p : Specify microcontroller series. Or simply what microcontroller we willl program. For example I will use ATMega32 so i will replace with atmega32.

With these three, we can program in minimal. In this case when I want to program ATMega32 using USBasp with filename avr_leds.hex, the command I use will be:

avrdude -c usbasp -U flash:w:avr_leds.hex -p atmega32

Wait until process is finish and then you can see you microcontroller is programmed now.

Next time I will write some actual writing program for AVR.

Social Share Buttons and Icons powered by Ultimatelysocial