Projects with AVR Microcontroller

Introduction

In this page I'll try to put all my experience working with this Micros AVR...(I love this micros), and show some examples working with popular development boards and with the famous Arduino board. I write as well some articules about a tipical problems when you are a beginer in this world.

Starting with the Micro AVR

The first one ins necessary have some skills and knowledge with binary logic and understand some operations like "AND" "OR" etc.
Obviously this is not the right place to learn that, that is PRE requirement to start. 

Then... let start:
Things thaht you need for start programming a Micro AVR.
  • The Micro... :) or a Development board: Sound obvious but there are some thing that we consider about the IC or the development board. If you are starting with programming this micros I suggest that begin with a devel board, because there are solve problems related with the circuitry and power regulate needed for a each Micro. Even have resolve the problem related with the programming of the Micro, supporting the differents ways for each brand. Some examples where you could obtain a dev board. 
    1. ebay: Searching for... Developmet board atmega
    2. or searching for Arduino 
    3. or in your local store.. like www.olimex.cl or www.sparkfun.com
  • The programmer hardware: The next component that use need is a device callerd "programmer" o "debugger", in this case exist 2 types of programmer interfases ICSP (In circuit debugger) and ISP. Then you need to read the datasheet off the microcontroller for decide which one you wil buy. 

    If you buy an Arduino dev board you do not need some extra hardware, because the Arduino have a building a bootloader that help you to program (load you hex code) the microcontroller with out a extra hard programmer.

    ISP programmer (and debugger)

  • The IDE for write and build your source code (C or Assembly)
    For Atmel you need a IDE and the toolchain to build your programs.. and then you need to download the AVR Studio, whic is free form the manufacturer of ATMEGAs micros (ATMEL).

    download the software from here. http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725
    other tool that you need to download is WinAVR, that is a version of GNU GCC an utilitis modified for ATMEL micros, its work great and is very easy to use. (if you know programming in "C" already)
    download from here. http://winavr.sourceforge.net/download.html

  • Finally the manual and datasheets for the exact micro that you are programming. You could search every manual and datasheet from the web searching like "datasheet ATMEGA32"


Programming Arduino with AVR Studio and AVRdude


Arduino have it own IDE to develop and to manage the source, that is in real words a set of libraries and functions that show a "ilusion" to the user are programming in C simplified. But wrong.. it is C pure and complex.. C. This IDE of arduino y very very limited in functionalities, so you always need more, then try with AVR Studio and use the core libraries of Arduino. In the next sections we will talk about that.

Core of Arduino:

The Arduino have a lots o features and abstraction layers to make easy program with its dev board. So we need to know where are the source of that libraries. 
path the core Arduino libraries: arduino-0019\hardware\arduino\cores\arduino
In that directory exist some files .h an .c and .cpp with are the core of arduino, so then we need to add to the project all .c and .h files to could use some libraries and very useful function off Arduino.



Configure AVR Studio:

COnfguring AVR Studio is not very hard, just need to create the project and add all libs and source needed to the project. AVR manage the configuration and of create the Makefile to produce the right code and including or not the files in your project.


And important thing is relates with set the right device (for Arduino atmega328p) and the right Frequency (16000000).

Generate the HEX file:

For generate the hex file to be loaded to the atmega328p just need to make click in the follow icon in the AVR studio.


That trigger the process to compile a link the code and generate the HEX file for the micro.
The output is leaved in a directory called "default". We are interested just in the HEX file.
Look the program used for the arduino example Blink led compiled in AVR studio.

Example Program. (Blink led with Arduino)
----------------------------------------------------------------------------------------
#define F_CPU 16000000UL
#include "arduino/wiring.h"

int main(void)
{
init(); // Initialize the Arduino libs...
setup(); // execute the Arduino sketch function...
for (;;)
loop();
return 0;
}

/*
 * Blink
 *
 * The basic Arduino example.  Turns on an LED on for one second,
 * then off for one second, and so on...  We use pin 13 because,
 * depending on your Arduino board, it has either a built-in LED
 * or a built-in resistor so that you need only an LED.
 *
 * http://www.arduino.cc/en/Tutorial/Blink
 */

int ledPin = 13;                // LED connected to digital pin 13

void setup()                    // run once, when the sketch starts
{
  pinMode(ledPin, OUTPUT);

}

void loop()                     // run over and over again
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(ledPin, LOW);    // sets the LED off
  delay(1000);                  // waits for a second
}

----------------------------------------------------------------------------------------

Notes:
Important, the Arduino function Serial.print() is implemented like a C++ user class, so with this method of compiling is not possible to use in our programs. (I does implemented the similar functionality in pure C)

Load Hex file to the Arduino Board with AVRdude


Well the last part of that work is to discover how to put my program HEX into the micro. I develop my own way to do that (I think that is not the best) but work. :).
To do that we will use AVRdude that come with WinAVR already installed. Follow the next steps.

  • First : web built a .bat (.sh in linux) and put into the follow command.

    avrdude -p m328p -c arduino  -P com3  -b 57600 -F -U flash:w:default\Blink.hex

    - the -p m328p is the type of micro
    - the -P is the serial port where Arduino is connected (Virtual serial port USB-Serial driver) usually com3
    - the -c arduino is the type of programmer used
    - the flash:w:default\Blink.hex is where are my HEX program and where will be loaded.
  • I called to this file program.bat in the directory of my project C:\Blink-PJR\program.bat

  • The just double click to the program.bat and the process of program you Arduino will be done.
     <<Image>>


Using some libs of Arduino.


Well part of this was cover in above section, but wee will put some important point to have in mind.

  • All the core Arduino library is in arduino-0019\hardware\arduino\cores\arduino directory
  • The main files are C pure but there are as well a couple files that are written in C++ like the follows:
    • WString.h
    • HardwareSerial.h
    • Print.h
    • Stream.h
  • All this files (headers and implementations .cpp) are focus in the implementation of interfase RS 232 with the USART or ATMEGA328p. But really the implementation of that, is not hard so in the next section we will show how implement that and give the source code for you implementation using interrputs.
  • Then you need to include the necessary files of Arduino directory to you project for use the functions that you requiere. (except USART) see next section....

Using the UART of ATMEGA....


As we say the USART implementation in Arduino libs is implemented in classes C++ (Serial) and if we only want program in C, then we must implement the functionality in C.

Firt let's talk about the next source code of implementation.

------------------------------------------------------------------------------

#include <inttypes.h>
#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>
#include <stdio.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

volatile char buffer_in[30]; //buffer for typed characters

/*Imprime un string completo...*/

void serialPrint(char *buffer)
{
uint8_t i = 0;
uint8_t len = strlen(buffer);
while(i < len) sendByte( buffer[i++] );
}

/* Blocking Function!! */
inline void sendByte(uint8_t buffer)
{
 /* Wait for empty transmit buffer */
 while( !(UCSRA & (1<<UDRE) ) );
         UDR = buffer;
}

/* Implementación de Serial con interrupciones */

/* Initialize UART module con Interrupción */
void initUART(int baud)
{
    /*Set baud rate */
     int BAUD_PRESCALE = ( ( (F_CPU / (baud * 16UL)) ) - 1);

    UBRRH = (unsigned char)BAUD_PRESCALE >> 8;

    UBRRL = (unsigned char)BAUD_PRESCALE & 0xFF;

    /* Enable receiver and transmitter con interr RX*/

    UCSRB = (1<<RXEN) | (1<<TXEN) | (1<<RXCIE);

    /* Set frame format: 8 data bits, 1 stop bit */
    UCSRC =  ((3 << UCSZ0) | (1 << URSEL));
}

// Recibe los datos.. y los pone en una variable...global...

SIGNAL (SIG_UART_RECV)
{
sprintf(buffer_in,"%s%c",buffer_in,(unsigned char)UDR);
        sendByte(UDR); // Implements echo for the user..
}

--------------------------------------------------------------------------------------------------
void initUART(int baud)
This function is used for initialize the USART interface, for that we need to set parama about the baudrate, bits stop and data bits.
baudrate is set by assign the value of this formula baudrate = (F_CPU/(baud_required*16)) - 1)
that value is assigned to UBRR control registry in (H)igh and (L)ow positions. F_CPU is the frecuency of the CPU clock (tipically 16MHZ 16000000) the baud_required is a param for what is the baud rate that you want.
The control registry UCSRB is used for setting the bits corresponding to enable to receive (RXEN), enable to transmit TXEN and in this case enable the interrupt for receive - RXCIE.
The last line set the registry UCSRC to set the 8 bit data and 1 stop bit.

void sendByte(uint8_t buffer)
This function is very short and implement the sending byte to the port USART waiting for the empty buffer checking the bits and next put the byte to send in the data registry UDR. When you put the data in that registry immediately is send to the reception. 

void serialPrint(char *buffer)
This function use the function sendByte for send each byte present in the string buffer passed as a param.

SIGNAL (SIG_UART_RECV)
As we say the implementation is realized using interrupts, this is a (MACRO) declaration of interrupts related with the reception of characters in the data registry UDR. Each time whe a character arrive to the UDR the interrupts execute the code. In our case we push the up coming character in a global buffer and send an echo to the sender.


Then with this + the Arduino library we could build everything on top using the easy-to-use Arduino functions...

Creating a CMD interface with AVR ATMEGA 32

 
This is a project to build a command interface for a development board to control the basic operations of the microcontroller. The evaluation board is in the image (you could download the Proteus file in Files sub-menu)


This board work with a ATMEGA32 and inteface the USART with a MAX232 and Virtual Terminals, furthermore some pins are connected to control the H-driver for manage a MOTOR DC with inertia simulation.

The Virtual Terminal images shows the commands that are now implemented..

The project has being implemented in a AVR Studio with WinAVR last version, If you need to download see the Files section for the lasts actualizations....


Comments