Tuesday 31 December 2013

Tutorial - II Basics of AVR programming

You are now set to begin programming. Before we proceed further, i would advice you to brush up your C basics, as the programming of a uC (microcontoller) involves C - embedded which closely resembles C.
Whenever we start programming we first include the header files:-

  1. #include<avr/io.h> - used for input/output through ports also known as port manipulation
  2. #include<util/delay.h> - used to create delays in the program.
Besides these there are several other header files which we will come across as we advance in our programming.
After the header files comes the main( ) function. The program begins by executing the main function.
So basically anything written in the main function is executed first.


So Till now the code looks like the following:

#include<avr/io.h>                            
#include<util/delay.h>
void  main()
{
.
.
.
}
Told you it closely resembles C!! :P
The figure below is a schematic of an atemga16. This shows us all the terminals coming out of the atmega16.

The atmega16 has four pairs of ports A, B, C, D as see in the above figure.
Each port has 8 pairs of terminals. (PX 0-7 where X is the port, eg A, B, C, D)
Now there are two important registers in AVR programming i.e the DDRx and PORTx register where x stands for A, B, C, D depending how many terminals are there.
Now what does DDR stand for and what does this register do?
Don't get baffled by the term register. A register is merely like an equivalent to data type in C. DDR is an abbrev. of Data Direction Register. It is used to set the terminal of the uC as input or output.
Firstly a register can take a value 0 or 1. To set a register we use a predefined syntax which avr studio provides us with.
 PORTS          7 6 5 4 3 2 1 0
eg DDRA= 0b 0 0 0 0 1 1 1 1;
The above is written in binary.
The above statement sets ports 0-3 as outputs ans 4-7 as inputs.
It can also be written in hexadecimal using the 0x prefix.
 DDRA=0x08;
These statements can be pretty long and it becomes tedious to set individual bits. Hence we use a new syntax. Just remember the following :-
We'll experiment with PORT A0 of the uC.
To set it as output DDRA = (1<<PA0);
To set it as input  DDRA&=~(1<<PA0);    ~ is the negation operator)

To set it as output with internal pull ups enabled we use two statements:- (Pull ups enabled is basically giving 5 V to the terminal). We use a combination of two statements:-
DDRA = (1<<PA0);  \* Setting it as output *\
PORTA = (1<<PA0);  \* To enable the pull ups *\

Suppose











No comments:

Post a Comment