Professional Documents
Culture Documents
My Experience in Programming Avr Microcontroller
My Experience in Programming Avr Microcontroller
WINAVR/AVRGCC
by
BIBIN JOHN
Signatu
re Not
Verified
Bibin
John
Digitally
signed by
Bibin John
DN: cn=Bibin
John, c=IN
Date:
2006.04.28
11:08:52 Z
Reason: I am
the author of
this document
Location:
Ernakulam
NOTICE
This book is for newbies for programming AVR
microcontroller using WinAVR. This is mainly for those who want to make robots
using Atmel's AVR.Here i am writing this because I want to include troubleshooting
tips and simple working examples for newbies. The main reason for choosing AVR
microcontroller is because of its facilities and support from Linux compilers and cheap
cost programmers. Here i am using WinAVR and BSD AVRDUDE programmer. All
the codes in this book are tested with WinAVR2006. Before starting this you should
read my other books(it will be good) because I refer to that books for some parts.All
books are available on yahoo group-booksbybibin
I thank my teachers of MNNIT and my
colleagues Anil K.M,O.Praveen Kumar Reddy, M. Satish,Vigith Maurice, J
Rajashekhar Reddy,Athul Sona,Sanjo Sebastin . So i feel this book can guide you
through troubleshooting AVR microcontrollers. I thank my teachers of THSS Muttom,
Thodupuzha from where i learned the very basics of electronics.If you find any
problems put a post in yahoo groupbooksbybibin.
I am providing this book free of cost. You can use this
book as a study material. I don't want my book to be used as a material for business
without my permission. You are not allowed to upload this book in any other sites.
e-mail:njbibin@yahoo.co.in
website:www.geocities.com/njbibin
forums for AVR microcontrollers:
www.avrfreaks.net
www.avrbeginners.net
Www.roboticsindia.net
www.edaboard.com
Yahoo group:
avrclub
avrbooks
magazine:Circuit Cellar
BIBIN JOHN
INDEX
Why AVR???..................................................................................................5
As a beginner what i need to know???....................................................5
Softwares Required.....................................................................................5
Hardwares Required...................................................................................5
Difference between atmega32 and atmega32L.......................................5
GETTING STARTED.................................................................................6
LET'S START...............................................................................................6
Makefile.........................................................................................................9
What you had done in first program??...................................................15
PROGRAMMER HARDWARE...............................................................15
COMMON ERRORS IN AVR PROGRAMMING..............................20
TROUBLESHOOTING.............................................................................21
MOST IMPORTANT TIP.........................................................................22
FUSE BITS..................................................................................................24
DISABLING JTAG................................................................................27
DISABLING JTAG AND USING INTERNAL 8Mhz CLOCK..........29
INTERFACING LCD WITH AVR...........................................................30
SOME IMPORTANT COMMANDS USED
FOR PROGRAMMING.............................................................................34
L293D INTERFACING WITH AVR........................................................35
BIPOLAR STEPPER MOTOR DRIVING USING AVR.....................38
UNIPOLAR STEPPER MOTOR INTERFACING................................41
KEY ENCODER INTERFACING(74922)................................................43
7-SEGMENT DISPLAY INTERFACING WITH AVR.........................46
MULTIPLEXED 7-SEGMENT DISPLAYS.............................................48
IC TESTER....................................................................................................49
UART of AVR..............................................................................................51
Troubleshooting...............................................................................51
SERIAL PORT OF COMPUTER..............................................................52
BIOS SETTINGS.........................................................................................53
SERIAL PORT INTERFACING WITH COMPUTER..........................54
HYPER TERMINAL................................................................................58
Device Manage COM Properties..........................................................60
Why AVR??????
AVR microcontrollers are popular because of their Linux support and their softwares
like AVRGCC and AVRDUDE. If you start learning with any microcontroller the cost
you have to pay is the microcontroller cost+software+programmer. If you compute
this then AVR is the best. Atmega8 is available with Rs.75 and programmer cost is just
a printer cable costs Rs.40 with some wires and AVRGCC for Linux and WinaVR2006
for Windows.It has facilities like inbuilt ADC which is not there in 8051, which will be
advantageous for robotics. Software are easily available for other microcontrollers but
they have a limit of maximum 2K program memory. The project 'embedded ethernet'
have around 10K program memory usage while WinAVR have no such limitations.
The programmer cost of 8051 and pic are above Rs.400(as far as I know). See
http://www.electricstuff.co.uk/picvsavr.html
As a beginner what i need to know???
Here I am going to talk about microcontroller just like a computer running on parallel
port and a C program. I am using the same examples. Basic thing you have to know
how to program the chip and writing programms for the chip. If you know 8085 then
it will be easy to understand. Anyway I am writing codes in C so that it will be easy to
understand.
Softwares Required:
WinAVR2006,AVRDUDE(if you are using AVRStudio)
www.winavr.sourceforge.net
atmega32,atmega8 datasheet(see in atmel.com)
You better make logins in www.avrfreaks.net so that when you have doubt, you can
put it there.
Hardwares Required:
atmega32 or atmega 8 (atmega32 costs from Rs.200 to Rs.350 and atmega8 from Rs.75
to Rs.120)
Breadboard
Printer Port cable
Serial port cable
Crystal(3.6864Mhz)
Difference between atmega32 and atmega32L:
Both are same only difference in frequency and voltage limitations. I prefer atmega32L
because of its low cost and easy availability. Atmega16 also serve same purpose except
its Flash is 16KB(sufficient) and difference in memory capacities. The remaining
hardware portion are same for both.
GETTING STARTED
First you should require a compiler which
converts your program into the hex code of the avr microcontroller. If you use C for
programming Avr then you can use WinAVR, CodeVision AVR, ImageCraft AVR,
BASCOM AVR for programming in BASIC, AVRStuidio for programming in
assembly. But here I am talking about C programming. I use WinaVR2006 for all these
programms compilation. Same code is valid for AVRGCC in Linux. Second
requirement is a programmer which transfers the . Hex code(machine code for AVR)
into the chip. That is a programmer which burns the chip. I use BSD programmer for
that.
LET'S START
Install WinaVR2006 to C drive. Then you
can see that your desktop has the following programs.
The main program we use is the programers Notepad. So let's start with first program.
10
11
Now save the Makefile in the folder where your program is. Better you use the
Makefile in the code I had given
Now open Makefile using Notepad and do the following.
12
13
Here I made CPU frequency to 1Mhz because when you buy the chip, the default
frequency is 1MHz with JTAG enabled. They use internal RC oscillator to generate
1Mhz. I will explain more about it in fuse settings
14
This is valid for all microcontrollers of AVR which are supported by AVRDUDE
programmer. See how to do it for atmega32
15
See my programmer.
16
17
Instead of using Vcc of supply you can use any pin on the data port(D0) for Vcc of
AVR.I am using breadboard instead of a ready made PCB for programmer.So the
connections in the breadboard as shown
NOTE:
Here I am not using crystal because I am thinking that you bought a new atmega32
or you are having an atmega32 which is not using external crystal(not done fuse
bits). If your microcontroller had done fuse bits then you have to use a proper
crystal. I will explain about it in Fuse Bits section.
18
19
20
21
22
If you are not working with WinAVR2006 and you are using AVRStudio, then you can
use the same programmer. Only difference is that you have to work in text mode.
Install AVRDUDE then execute install_giveio.bat for acessing ports. Now change to
the avrdude\bin> directory and do the following shown
Here f.hex is the hex file we had to load into the chip. If you installed WinAVR2006
then change the director to C:\WinAVR\bin> and execute the above command. See
the AVRDUDE documentation for more about it.
Now check the program loaded into the memory. Remove the Reset pin and connect
Reset pin to VCC because the value at Reset pin is LOW by default and chip is reset
( i am talking about the parallel port voltage).
You can see that all ports except PORTC pins C2,C3,C4,C5 are not blinking. This is
because your chip's JTAG has been enabled. If you want to use PORTC pins further
then you have to disable JTAG. This is done by using fuse bit settings.
23
FUSE BITS
You have to do fuse bits to disable JTAG,lock the
microcontroller, change the clock frequency of the microcontroller. So let's study
AVRDUDE in terminal mode. First enter in the terminal mode and see the fuses.See
page 255 of atmega32 datasheet, then you will get some ideas about fuse bits.
24
25
26
DISABLING JTAG
After disabling JTAG you can use PORTC properly. Pins C2,C3,C4,C5 are properly
used for other applications. i.e, we got one port for other applications. When I brought
my new microcontroller for the first time I thought that the microcontroller was not
good because PORTC pins are not working, then I later came to know that it is due to
JTAG only.
27
See what happened when I removed the RESET pin of the microcontroller . Here I
downloaded blinking program to see whether PORTC is working and I removed the
RESET pin connection with parallel port, that is why the fuse read as 0xff
28
In the first case after changing the fuse bits I removed the RESET pin to see whether I
got 8Mhz. It worked according to the previous program: blink.c, I got fast blinking.
Don't remove the programmer before you leave the terminal mode of
AVRDUDE.That is what happened in the first case.
29
This is the simple schematic without using backlight and contrast pins. Here control
pins are connected to PORTD and datapins to PORTA. See the figure below.
30
31
32
Folder:lcd
/*----------------------------------------------------------------------------CONNECTION BETWEEN LCD AND ATMEGA32---------------------------------------------------------------------------------*/
#define DATA_DDR
DDRA
#define DATA_PORT PORTA
#define CONTROL_DDR
#define CONTROL_PORT
#define Enable_Pin
#define RegSelect_Pin 4
#define ReadWrite_Pin 5
#define CONTROL_MASK
DDRD
PORTD
6
0X70
Here are the declaration I am using. Here CONTROL_MASK is used so that remaining
pins can be used for other purpose. Change the port settings here so that you can use
same code for all ports. When you program you should program in such a way that
port pins are not wasted and same program can be used irrespective of ports. So do
this at the beginning of the program for better understanding of the program and
portability. Practice this when you do programming. Rest program remain same as
that I had given my previous book for parallel port.
33
34
35
This figure shows connecting a motor to L293D. Here I applied 12V from adapter to
the pin8 of L293D. I used a normal 12V,250mA DC motor.
36
37
38
39
40
41
42
FOLDER:74922
43
44
FOLDER:74922_LCD
45
46
47
I am using 74126, tristate buffer to give power supply to the 7segment. You can use
transistors in case of common cathode display. But here I am using common anoder
displays.
FOLDER:2-7seg
48
IC TESTER
Try to make one IC TESTER. In the previous book I made one which requires atleast 56 IC's. Suppose if you use a 40 pin AVR then you can make it with a single AVR. The
advantage is that the individual pins can be set for input as well as output. There are
3 i/o ports which is connected directly to the IC to be tested. For each IC pin diagram
will be different. That is we have to configure those 24 pins as input port or output
port as per the IC number. This can be divided into three categories, DDR (data
direction register in atmega32), data out and data in. We are using only one port to
communicate with computer. Therefore we have got at max 8 pins. In that one nibble
is used for data transfer only and the other nibble for determining the following things
49
Of which port is the data in the most significant nibble of porta. That is portb
lowest nibble, portb highest nibble, portc lowest nibble, portc highest nibble,
portd lowest nibble or portd highest nibble.
What kind of data is in the least significant nibble. That is value to be stored in
DDR (data direction register of atmega32), PORTA/B/C (value to be outputted
to data register of PORTB/C/D) or PINB/C/D (value to be inputted from pins
of PORTB/C/D).
Now its clear that there are three combinations for what kind of data is available
in most significant nibble. Also 6 nibbles are to be controlled. So total we need
18 different kind of data to be transferred through most significant nibble.
Remaining number of bits to control this is only four. With four using usual
convention only 16 combinations can be made. For this, the strategy we
implemented is as follows,
D0-D3 of PORTA is first four the least significant bits, ie least significant nibble.
Now, initially we will set this to 0000. The first bit which becomes high will
decide what kind of data is in the bits D4-D7 of PORTA. Suppose first D3
becomes high, then the data in the bits D4-d7 of PORTA is DDR. Suppose first
D2 becomes high, then the data in the bits D4-d7 of PORTA is PORTB/C/D.
Suppose first D1 becomes high, then the data in the bits D4-d7 of PORTA is
PINB/C/D. After this what we want to know is, of which nibble should the
data in the bits D4-D7. This is determined by the remaining bits, ie suppose first
D1 becomes high, then the remaining bitw D3,D2,D0 will determine that. If
D3,D2,D0 is 010, it means data in the bits D4-D7 belongs to most significant
nibble of PORTB, ie D4-D7 of PORTB. And since first D1 becomes high it
implies PINB/C/D. So the value in D4-D7 of PORTA is the value from D4-D7 of
PORTB. In this way we can get and write values to all 24 pins.
50
UART of AVR
51
52
BIOS SETTINGS
First set the bios then only do any other operations like programming the
microcontroller and serial port. See the Port numbers correctly. Then only use the
COM1, COM2 or lpt1,lpt2 repectively. This is the most important step. AVRDUDE
programmer sometimes won't work for some parallel port. It does not worked for
INTEL965GV motherboard. So see my previous book on parallel port before doing
these steps.
53
54
Figure shows the connections with serial port of computer. You can use a 1uF
capacitor instead of 10uF.
55
56
57
HYPER TERMINAL
Hyper Terminal is used to see the serial port data. It
will show only the received data. All the data is show in ASCII. Go to
Start_Programs_Accessories_Communicatin_Hyper Terminal. If you are using serial
port for your internet you have to disconnect it for acessing serial port. Run Hyper
Terminal then some screen come for asking area codes, put some garbage value and
press OK and in the next page press OK, then you will come to this page.
58
If you use some USB to RS232 converter, then I can't say that Hyper Terminal will
work.
59
60
Now connect serial port to max232, then short circuit the Rx and Tx of max232 ie pin
11 and pin 12 and type something in hyperterminal, see what you are getting. If you
are getting the alphabets you typed then your connections are proper. Max232 is
working fine. By default the TTL output is 5V. See the RS232 output corresponding to
5V input, it should be mostly in the range -8V to -10V. See these conditions properly
otherwise your microcontroller will get burned because voltage greater than 5V is
damagerous to the microcontroller.
61
FOLDER:serial_computer
Here this code will send back next ASCII you type. See the error in baud rates for
different clock frequencies. Here I am using 2400 8 N 1 with 1Mhz internal crystal. If
you want more speed then go for internal 8Mhz crystal. But still error is around .2%,
so if you want 0% error in baud rate go for crystal 3.6864Mhz or crystals given in the
datasheet which is having 0% error in baud rate
TransmitByte(ReceiveByte()+1);
You can use terminal program inbuilt in WinXP or Bray's terminal for serial port
interfacing with computer. Bray's terminal is a free software with more options than
hyperterminal. Hyperterminal won't show the transmitted data, it shows only the
received data.
SERIAL PORT TROUBLESHOOTING AND ERRORS:
62
63
64
FOLDER: serialport_lcd
65
66
67
//lcd initializations
Init_Ports();
Init_Lcd();
InitUART( 25 ); /* Set the baudrate to 2400 bps using a 1MHz crystal */
for(;;)
/* Forever */
{
a=ReceiveByte();
Lcd_Send(a);
TransmitByte(a); /* Echo the received character */
}
First initialising LCD ports and start initialising baud rates. First we receive the data
from serial port and send it to LCD first then it is again send back to serial port. But
this process will be having some delays because of the delays inserted in the LCD
functions.
68
69
FOLDER:lm_2-7seg
See the problem with persistance of vision. Here the temperature varies with time and
it is shown on LED i.e, it is shown a non decimal value.
ADCSRA|=_BV(ADSC); //start conversion
while(!((ADCSRA&_BV(ADIF))>>ADIF));
return ADCH;
Here I am using single conversion mode. I am waiting for the conversion to end and
we are using 8 bit conversion mode. The 8 bit converted value is there in ADCH
register and we are returning the values.
70
71
if(a!=b)
{
//first delete the previous values for uart
for(i=0;i<2;i++)
{
TransmitByte(del[i]);
}
//for LCD we require initialiatization
Init_Lcd();
for(i=0;i<12;i++)
Lcd_Send(str[i]);
j=a%10;
k=a/10;
k=k%10;
Lcd_Send((k+0x30));
TransmitByte((k+0x30));
Lcd_Send((j+0x30)); //since both will display ASCII values, we convert decimal to
ASCII
TransmitByte((j+0x30));
b=a; //for next value
//delay sometime (1s) otherwise LCD display will run
delay(1000);
we are seeing for any change in the temperature reading, if any change occurred then
it is send it to the LCD and serial port. We are using 'BACKSPACE' to delete the
previous values in case of serial port. Here I am clearing LCD and writing to it , but
you can do other way by selecting the instruction register and moving to location 0x8c
and 0x8d to write the temperature on that locations.
72
TROUBLESHOOTING:
1. Always remember about the fuse settings and frequency of the crysal you are
using. Set the baud rate according to it.
2. See the baud rate errors. Better to use a maximum error of .2%,better don't go
for baud rates of errors 8.3%.
3. Refer datasheet for the baud rate before setting it.
4. Put noise cancellation capacitance in the AREF pin.
5. See the Hyper Terminal settings, about the port is it COM1 or any other port,
see the bios settings.
73
TIMERS
void main()
{
InitUART(25);
TCCR0|=(_BV(CS02)|_BV(CS01));
do
{
TransmitByte(TCNT0);
delay_ms(500);
}
while(1);
}
Here I am using external clock for running the timer. The clock is set falling edge. But
if you keep T0 pin open then the counter will run counting. Better connect T0 pin to
Vcc or ground. Include serial.c for serial port transmission.
Which one should I choose Atmega32 or Atmega32L??
I prefer Atmega32l because its low power consumption and cost. Cost difference is
around Rs.50 or more and second thing it works on low power which is very
adavantegous in robotics because the power supply won't be consumed much.
Suppose if you make a robot using some transistors and OPAMP's then the power
consumption of that circuit will be more and motor will draw more current which will
sometimes cause the control circuit to improper working. But atmega32l works from
2.7V 5V and with even low voltage. You might have noticed that it works with the
voltage from the parallel port without connect any Vcc to the chip. After
programming the chip, switch off the adapter then also avr works with the voltage
from parallel port. This shows how less is the power required to run the chip. This is
the main advantage of using microcontroller instead of normal transistors and
OPAMPS for robotics. I don't think clock frequency does not matter much for us since
atmega32l maximum frequency is 8MHz. The sensitivity of a sensor is in the range of
milliseconds or 100 uSec not more than that and we are mainly processing the sensor
signals,still we are getting 8000 cycles for processing. This much time is more than
enough for us.
74
1. Always see that the voltage (Vcc) to the microcontroller should not be greater
than 5V.
2. See your parallel port and serial port settings on BIOS before starting with
microcontrollers.
3. Always keep a screenshot of the fuse bit settings you are doing.
4. Main reasons which cause AVR to burn:
microcontroller voltage>5V
fuse bits had done wrongly(lock bits especially)
5. Before doing fuse bits, be thorough with what you are doing. Enable the proper
modules only. Suppose if you use external clock then before doing fuse bits you
should have a proper crystal.
6. Always see the register settings. Don't waste a full port for the use of a single
input or output. Do proper commands,mainly _BV();
7. Apply proper noise cancellation. Use proper capacitance values.
8. See for the baud rate error corrections. Better use maximum possible error to
.2%.
9. See the breadboard problems. This is a serious problem.
10. See my previous books for more troubleshooting.
75
IR led identification
http://roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1438
sonar
http://www.robot-electronics.co.uk/htm/srf04tech.htm
http://www.robot-electronics.co.uk/htm/srf08tech.shtml
http://hamjudo.com/sonar/
http://www.rdrop.com/~cary/html/ultrasonic.html
http://www.leang.com/robotics/info/articles/minison/minison.html
http://www.robot-electronics.co.uk/htm/srf04tech.htm
http://www.interq.or.jp/japan/se-inoue/e_pic6_6.htm
ir vs sonar
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1189
sms
http://www.riccibitti.com/tinyplanet/tiny_article.htm
sharp sensor
http://www.blueink.com/CLASS/physcom1/SharpGP2D12.htm
http://neil.fraser.name/software/lpt/
cro
http://www.roboticsindia.com/modules.php?name=News&file=article&sid=112
lcd
http://www.roboticsindia.com/modules.php?name=News&file=print&sid=75
http://www.beyondlogic.org/parlcd/parlcd.htm
http://www.eio.com/lcdintro.htm
http://home.iae.nl/users/pouweha/lcd/lcd0.shtml#hd44780
http://ee.cleversoul.com/lcd_project.html
76
speech
http://www.vbip.com/miscellaneous/Speech-Recognition.asp
http://roboticsindia.com/modules.php?name=News&file=article&sid=115&mode=&
order=0&thold=0
7segment
http://www.iguanalabs.com/7segment.htm
general
http://homepage.hispeed.ch/peterfleury/
avrfreaks user projects
http://www.avrfreaks.net/index.php?module=FreaksAcademy&func=viewProjects&
startnum=76
software
http://www.avrfreaks.net/index.php?module=FreaksAcademy&func=viewProjects&
startnum=76
tachometer
http://www.xdesignlabs.com/digitaltach/
remote control
http://home.earthlink.net/~henryarnold/page33.html
http://scv.bu.edu/GC/shammi/ir/
http://www.ustr.net/infrared/sony.shtml
http://www.ustr.net/infrared/infrared1.shtml
http://www.ustr.net/
good link
http://www.sbselektronik.com/devreler.asp
http://www.geocities.com/stampic/links.htm
77
fuse bits
http://www.roboticsindia.com/modules.php?name=Forums&file=viewtopic&t=1412
&p=7120
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=207381#
207381
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=36235
programmers
http://www.tuxgraphics.org/electronics/200510/article05101.shtml
http://www.users.on.net/~symes/Mega32/CandMega32.htm
good tutorials
http://www.users.on.net/~symes/CwithAVR/IntrotoCwithAVR.htm]
www.avrbeginners.net
mmc card interface
http://www.avrrepository.com/samplecode/sd_breakout/doc/index.html
avrdude problem
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1318
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1327
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1332
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1332
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1241
78
ir
http://roboticsindia.com/modules.php?name=News&file=article&sid=35&mode=&o
rder=0&thold=0
http://www.techgeek.com/subpage/index.phtml?topic=998&subtopic=996&item=10
17
http://www.acroname.com/robotics/info/articles/irlinear/irlinear.html
http://www.roboticsindia.net/modules.php?name=Forums&file=viewtopic&t=1427
&p=7184
79