0% found this document useful (0 votes)
2K views30 pages

Fig. 1: Block Diagram Showing Architecture of AVR Microcontroller

The document discusses the AVR microcontroller architecture. It begins by explaining that AVR microcontrollers are single-chip computers that include peripherals like RAM, EEPROM, and timers to perform predefined tasks. It then provides a brief history of AVR, describing its development in 1996 and some of the early models. Finally, it details key aspects of the AVR architecture, such as its RISC design, 32 general purpose registers, separate memory buses for program and data, and features of common AVR models like the ATmega16.

Uploaded by

Pranav Pr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views30 pages

Fig. 1: Block Diagram Showing Architecture of AVR Microcontroller

The document discusses the AVR microcontroller architecture. It begins by explaining that AVR microcontrollers are single-chip computers that include peripherals like RAM, EEPROM, and timers to perform predefined tasks. It then provides a brief history of AVR, describing its development in 1996 and some of the early models. Finally, it details key aspects of the AVR architecture, such as its RISC design, 32 general purpose registers, separate memory buses for program and data, and features of common AVR models like the ATmega16.

Uploaded by

Pranav Pr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

EC509 Advanced Microcontrollers Unit 2

Unit - 2: AVR microcontroller

Internal Architectural –
Microcontroller: Microcontroller can be termed as a single on chip computer which includes
number of peripherals like RAM, EEPROM, Timers etc., required to perform some predefined
task.

Fig. 1: Block Diagram Showing Architecture of AVR Microcontroller

The computer on one hand is designed to perform all the general purpose tasks on a single
machine like you can use a computer to run a software to perform calculations or you can use a
computer to store some multimedia file or to access internet through the browser, whereas the
microcontrollers are meant to perform only the specific tasks, for e.g., switching the AC off
automatically when room temperature drops to a certain defined limit and again turning it ON
when temperature rises above the defined limit.

There are number of popular families of microcontrollers which are used in different applications
as per their capability and feasibility to perform the desired task, most common of these
are 8051, AVR and PIC microcontrollers. In this article we will introduce you with AVR family
of microcontrollers.
History of AVR
AVR was developed in the year 1996 by Atmel Corporation. The architecture of AVR was
developed by Alf-Egil Bogen and Vegard Wollan. AVR derives its name from its developers and
stands for Alf-Egil Bogen Vegard Wollan RISC microcontroller, also known
as Advanced Virtual RISC. The AT90S8515 was the first microcontroller which was based
on AVR architecture however the first microcontroller to hit the commercial market was
AT90S1200 in the year 1997.

AVR microcontrollers are available in three categories:


1. TinyAVR – Less memory, small size, suitable only for simpler applications
2. MegaAVR – These are the most popular ones having good amount of memory (upto 256
KB), higher number of inbuilt peripherals and suitable for moderate to complex applications.

Dr.J.C.Vijayshree 1
EC509 Advanced Microcontrollers Unit 2

3. XmegaAVR – Used commercially for complex applications, which require large program
memory and high speed.
The following table compares the above mentioned AVR series of microcontrollers:

Series Name Pins Flash Memory Special Feature


TinyAVR 6-32 0.5-8 KB Small in size
MegaAVR 28-100 4-256KB Extended peripherals
DMA , Event System
XmegaAVR 44-100 16-384KB
included

Importance of AVR
What’s special about AVR?
They are fast: AVR microcontroller executes most of the instructions in single execution cycle.
AVRs are about 4 times faster than PICs, they consume less power and can be operated in
different power saving modes. Let’s do the comparison between the three most commonly used
families of microcontrollers.

8051 PIC AVR


SPEED Slow Moderate Fast
MEMORY Small Large Large
ARCHITECTURE CISC RISC RISC
ADC Not Present Inbuilt Inbuilt
Timers Inbuilt Inbuilt Inbuilt
PWM Channels Not Present Inbuilt Inbuilt

AVR is an 8-bit microcontroller belonging to the family of Reduced Instruction Set Computer
(RISC). In RISC architecture the instruction set of the computer are not only fewer in number
but also simpler and faster in operation. The other type of categorization is CISC (Complex
Instruction Set Computers). Click to find out differences between RISC and CISC. We will
explore more on this when we will learn about the architecture of AVR microcontrollers in
following section.

AVR Atmega16 is a 40-pin IC and belongs to the megaAVR category of AVR family. Some of
the features of Atmega16 are:
· 16KB of Flash memory
· 1KB of SRAM
· 512 Bytes of EEPROM
· Available in 40-Pin DIP
· 8-Channel 10-bit ADC
· Two 8-bit Timers/Counters
· One 16-bit Timer/Counter
· 4 PWM Channels
· In System Programmer (ISP)
· Serial USART

Dr.J.C.Vijayshree 2
EC509 Advanced Microcontrollers Unit 2

· SPI Interface
· Digital to Analog Comparator.

Architecture of AVR
The AVR microcontrollers are based on the advanced RISC architecture and consist of 32 x 8-bit
general purpose working registers. Within one single clock cycle, AVR can take inputs from two
general purpose registers and put them to ALU for carrying out the requested operation, and
transfer back the result to an arbitrary register. The ALU can perform arithmetic as well as
logical operations
over the inputs from the register or between the register and a constant. Single register operations
like taking a complement can also be executed in ALU. We can see that AVR does not have any
register like accumulator as in 8051 family of microcontrollers; the operations can be performed
between any of the registers and can be stored in either of them.

AVR follows Harvard Architecture format in which the processor is equipped with separate
memories and buses for Program and the Data information. Here while an instruction is being
executed, the next instruction is pre-fetched from the program memory.

Fig. 3: Block Diagram Of memory architecture In AVR

Since AVR can perform single cycle execution, it means that AVR can execute 1 million
instructions per second if cycle frequency is 1MHz. The higher is the operating frequency of the
controller, the higher will be its processing speed. We need to optimize the power consumption
with processing speed and hence need to select the operating frequency accordingly.

There are two flavors for Atmega16 microcontroller:


1. Atmega16:- Operating frequency range is 0 – 16 MHz.
2. Atmega16L:- Operating frequency range is 0 – 8 MHz.
If we are using a crystal of 8 MHz = 8 x 106 Hertz = 8 Million cycles, then AVR can execute 8
million instructions.

Naming Convention.!
The AT refers to Atmel the manufacturer, Mega means that the microcontroller belong to
MegaAVR category, 16 signifies the memory of the controller, which is 16KB.

Dr.J.C.Vijayshree 3
EC509 Advanced Microcontrollers Unit 2

Fig. 4: Naming Convention Of AVR Microcontroller

MegaAVR Family
Various microcontroller of MegaAVR series:
ATmega8 and Atmega32 are other members of MegaAVR series controllers. They are quite
similar to ATmega16 in architecture. Low power version MegaAVR controllers are also
available in markets. The following table shows the comparison between different members of
MegaAVR family:

Operati
I/0
Part RO RA EEPR Tim Interru OperationVol ng Packagi
Pi
Name M M OM er pts tage frequen ng
ns
cy
ATmega 8K 1K 0-16
512B 23 3 19 4.5-5.5 V 28
8 B B MHz
ATmega 8K 1K 0-8
512B 23 3 19 2.7-5.5 V 28
8L B B MHz
ATmega 16K 1K 0-16
512B 32 3 21 4.5-5.5 V 40
16 B B MHz
ATmega 16K 1K 0-8
512B 32 3 21 2.7-5.5 V 40
16L B B MHz
ATmega 32K 2K 0-16
1KB 32 3 21 4.5-5.5 V 40
32 B B MHz
ATmega 32K 2K 0-8
1KB 32 3 21 2.7-5.5 V 40
32L B B MHz

Block diagram of controller (Atmega 8) –


AVR is a family of microcontrollers developed by Atmel beginning in 1996. These are modified
Harvard architecture 8-bit RISC single-chip microcontrollers. The Atmel AVR core combines a
rich instruction set with 32 general purpose working registers. All the 32 registers are directly

Dr.J.C.Vijayshree 4
EC509 Advanced Microcontrollers Unit 2

connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be
accessed in one single instruction executed in one clock cycle. The resulting architecture is more
code efficient while achieving throughput up to ten times faster than conventional CISC
microcontrollers. Here we go through ATmega8 pin diagram, block diagram, sleep mode and
features. But before talking about ATmega8 pin diagram, let’s first go through the Atmega8
block diagram.

ATmega8 Block Diagram

Dr.J.C.Vijayshree 5
EC509 Advanced Microcontrollers Unit 2

The ATmega8 provides 8 Kbytes of In-System Programmable Flash with Read-While-Write


capabilities, 512 bytes of EEPROM, 1 Kbyte of SRAM, 23 general purpose I/O lines, 32 general
purpose working registers, three flexible Timer/Counters with compare modes, internal and
external interrupts, a serial programmable USART, a byte oriented two wire serial interface, a 6-
channel ADC (eight channels in TQFP and QFN/MLF packages) with 10-bit accuracy, a
programmable Watchdog Timer with Internal Oscillator, an SPI serial port, and five software
selectable power saving modes.

Features

 Advanced RISC Architecture


o 130 Powerful Instructions – Most Single-clock Cycle Execution
o 32 × 8 General Purpose Working Registers
o Fully Static Operation
o Up to 16MIPS Throughput at 16MHz
o On-chip 2-cycle Multiplier
 High Endurance Non-volatile Memory segments
o 8Kbytes of In-System Self-Programmable Flash program memory
o 512Bytes EEPROM
o 1Kbyte Internal SRAM
o Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
o Data retention: 20 years at 85°C/100 years at 25°C (1)
o Optional Boot Code Section with Independent Lock Bits
o In-System Programming by On-chip Boot Program
o True Read-While-Write Operation
o Programming Lock for Software Security
 Peripheral Features
o Two 8-bit Timer/Counters with Separate Prescaler, one Compare Mode
o One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and
Capture Mode
o Real Time Counter with Separate Oscillator
o Three PWM Channels
o 8-channel ADC in TQFP and QFN/MLF package (Eight Channels 10-bit
Accuracy)
o 6-channel ADC in PDIP package (Six Channels 10-bit Accuracy)
o Byte-oriented Two-wire Serial Interface
o Programmable Serial USART
o Master/Slave SPI Serial Interface
o Programmable Watchdog Timer with Separate On-chip Oscillator
o On-chip Analog Comparator
 Special Micro-controller Features
o Power-on Reset and Programmable Brown-out Detection
o Internal Calibrated RC Oscillator
o External and Internal Interrupt Sources
o Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down,
and Standby

Dr.J.C.Vijayshree 6
EC509 Advanced Microcontrollers Unit 2

 I/O and Packages


o 23 Programmable I/O Lines
o 28-lead PDIP, 32-lead TQFP, and 32-pad QFN/MLF
 Operating Voltages
o 2.7V – 5.5V (ATmega8L)
o 4.5V – 5.5V (ATmega8)
 Speed Grades
o 0 – 8MHz (ATmega8L)
o 0 – 16MHz (ATmega8)
 Power Consumption at 4Mhz, 3V, 25C
o Active: 3.6mA
o Idle Mode: 1.0mA
o Power-down Mode: 0.5µA

Let’s look at the ATmega8 pin diagram in detail.

ATmega8 Pin diagram and description

ATmega8 Pin Diagram


Detailed description of the ATmega8 pin diagram:

VCC: Digital supply voltage.


GND: Ground.
Port B (PB7…PB0) XTAL1/XTAL2/TOSC1/TOSC2

Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up

Dr.J.C.Vijayshree 7
EC509 Advanced Microcontrollers Unit 2

resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even
if the clock is not running.

Port C (PC5…PC0)

Port C is a 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port C output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port C pins are tri-stated when a reset condition becomes active, even
if the clock is not running.

PC6/RESET

If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that the electrical
characteristics of PC6 differ from those of the other pins of Port C.
If the RSTDISBL Fuse is unprogrammed, PC6 is used as a Reset input. A low level on this pin
for longer than the minimum pulse length will generate a Reset, even if the clock is not running.

Port D (PD7…PD0)

Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit).
The Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even
if the clock is not running.

RESET

Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset.

Vcc

Vcc is the supply voltage pin for the A/D Converter, Port C (3…0), and ADC (7…6). It should
be externally connected to Vcc, even if the ADC is not used. If the ADC is used, it should be
connected to Vcc through a low-pass filter. Note that Port C (5…4) use digital supply voltage,
Vcc.

ARef

ARef is the analog reference pin for the A/D Converter. ADC7…6 (TQFP and QFN/MLF
Package Only) In the TQFP and QFN/MLF package, ADC7…6 serve as analog inputs to the
A/D converter. These pins are powered from the analog supply and serve as 10-bit ADC
channels.

Dr.J.C.Vijayshree 8
EC509 Advanced Microcontrollers Unit 2

Configuration of Two 8-bit and One 16-bit Timers and Counters –


Generally, we use timer/counter to generate time delays, waveforms or to count events. Also, the
timer is used for PWM generation, capturing events etc.
In AVR ATmega16 / ATmega32, there are three timers:

 Timer0: 8-bit timer


 Timer1: 16-bit timer
 Timer2: 8-bit timer

Basic registers and flags of the Timers


TCNTn: Timer / Counter Register
Every timer has timer/counter register. It is zero upon reset. We can access value or write
a value to this register. It counts up with each clock pulse.
TOVn: Timer Overflow Flag
Each timer has Timer Overflow flag. When timer overflows, this flag will get set.
TCCRn : Timer Counter Control Register
This register is used for setting the modes of timer/counter.
OCRn : Output Compare Register
The value in this register is compared with the content of the TCNTn register. When they
are equal, OCFn flag will get set.

Let us see Timer0 to understand the timers in ATmega16 / ATmega32

Timer0
First, we need to understand the basic registers of the Timer0

1. TCNT0: Timer / Counter Register 0

It is an 8-bit register. It counts up with each pulse.


2. TCCR0: Timer / Counter Control register 0
This is an 8-bit register used for the operation mode and the clock source selection.

Bit 7- FOC0: Force compare match


Write only bit, which can be used while generating a wave. Writing 1 to this bit causes the
wave generator to act as if a compare match has occurred.
Bit 6, 3 - WGM00, WGM01: Waveform Generation Mode
WGM00 WGM01 Timer0 mode selection bit

0 0 Normal

0 1 CTC (Clear timer on Compare Match)

Dr.J.C.Vijayshree 9
EC509 Advanced Microcontrollers Unit 2

WGM00 WGM01 Timer0 mode selection bit

1 0 PWM, Phase correct

1 1 Fast PWM

Bit 5:4 - COM01:00: Compare Output Mode


These bits control the waveform generator. We will see this in the compare mode of the
timer.
Bit 2:0 - CS02:CS00: Clock Source Select
These bits are used to select a clock source. When CS02: CS00 = 000, then timer is
stopped. As it gets value between 001 to 101, it gets clock source and starts as the timer.
CS02 CS01 CS00 Description

0 0 0 No clock source (Timer / Counter stopped)

0 0 1 clk (no pre-scaling)

0 1 0 clk / 8

0 1 1 clk / 64

1 0 0 clk / 256

1 0 1 clk / 1024

1 1 0 External clock source on T0 pin. Clock on falling edge

1 1 1 External clock source on T0 pin. Clock on rising edge.

3. TIFR: Timer Counter Interrupt Flag register

Bit 0 - TOV0: Timer0 Overflow flag


0 = Timer0 did not overflow
1 = Timer0 has overflown (going from 0xFF to 0x00)
Bit 1 - OCF0: Timer0 Output Compare flag
0 = Compare match did not occur
1 = Compare match occurred
Bit 2 - TOV1: Timer1 Overflow flag
Bit 3 - OCF1B: Timer1 Output Compare B match flag
Bit 4 - OCF1A: Timer1 Output Compare A match flag
Bit 5 - ICF1: Input Capture flag
Bit 6 - TOV2: Timer2 Overflow flag
Bit 7 - OCF2: Timer2 Output Compare match flag

Dr.J.C.Vijayshree 10
EC509 Advanced Microcontrollers Unit 2

Timer0 Overflow
Normal mode: When the counter overflows i.e. goes from 0xFF to 0x00, the TOV0 flag is set.

Creating Delay Using Timer0

Steps to Program Delay using Timer0


1. Load the TCNT0 register with initial value (let’s take 0x25).
2. For normal mode and pre-scaler option of the clock, set the value in TCCR0 register. As soon
as clock prescaler value gets selected, the timer / counter starts to count, and each clock tick
causes the value of timer / counter to increment by 1.
3.Timer keeps counting up, so keep monitoring for timer overflow i.e. TOV0 (Timer0 Overflow)
flag to see if it is raised.
4. Stop the timer by putting 0 in the TCCR0 i.e. the clock source will get disconnected and the
timer / counter will get stopped.
5. Clear the TOV0 flag. Note that we have to write 1 to the TOV0 bit to clear the flag.
6. Return to the main function.

Program for Timer Delay

/*
Generating delay using ATmega16 Timer0
*/

#include <avr/io.h>

void T0delay();

int main(void)
{

Dr.J.C.Vijayshree 11
EC509 Advanced Microcontrollers Unit 2

DDRB = 0xFF; /* PORTB as output*/

while(1) /* Repeat forever*/


{
PORTB=0x55;
T0delay(); /* Give some delay */
PORTB=0xAA;
T0delay();
}
}

void T0delay()
{
TCNT0 = 0x25; /* Load TCNT0*/
TCCR0 = 0x01; /* Timer0, normal mode, no pre-scalar */

while((TIFR&0x01)==0); /* Wait for TOV0 to roll over */


TCCR0 = 0;
TIFR = 0x1; /* Clear TOV0 flag*/
}

The time delay generated by above code


As Fosc = 8 MHz
T = 1 / Fosc = 0.125 μs
Therefore, the count increments by each 0.125 μs.
In above code, the number of cycles required to roll over are:
0xFF - 0x25= 0xDA i.e. decimal 218
Add one more cycle as it takes to roll over and raise TOV0 flag: 219
Total Delay = 219 x 0.125 μs = 27.375 μs

Example
Let us generate a square waveform having 10 ms high and 10 ms low time:
First, we have to create a delay of 10 ms using timer0.
*Fosc = 8 MHz
Use the pre-scalar 1024, so the timer clock source frequency will be,
8 MHz / 1024 = 7812.5 Hz
Time of 1 cycle = 1 / 7812.5 = 128 μs
Therefore, for a delay of 10 ms, number of cycles required will be,
10 ms / 128 μs = 78 (approx)
We need 78 timer cycles to generate a delay of 10 ms. Put the value in TCNT0 accordingly.
Value to load in TCNT0 = 256 – 78 (78 clock ticks to overflow the timer)
= 178 i.e. 0xB2 in hex

Dr.J.C.Vijayshree 12
EC509 Advanced Microcontrollers Unit 2

Thus, if we load 0xB2 in TCNT0 register, the timer will overflow after 78 cycles i.e. precisely
after a delay of 10 ms.
*Note - All calculations are done by considering 8 MHz CPU frequency. If you are using another
value of CPU frequency, modify the calculations accordingly; otherwise the delay will
mismatch.

Program for 10 ms Delay Using Timer0

/*
Generating a delay of 10 ms using ATmega16 Timer0
*/

#include <avr/io.h>

void T0delay();

int main(void)
{
DDRB = 0xFF; /* PORTB as output */
PORTB=0;
while(1) /* Repeat forever */
{
PORTB= ~ PORTB;
T0delay();
}
}

void T0delay()
{
TCCR0 = (1<<CS02) | (1<<CS00); /* Timer0, normal mode, /1024 prescalar */
TCNT0 = 0xB2; /* Load TCNT0, count for 10ms */
while((TIFR&0x01)==0); /* Wait for TOV0 to roll over */
TCCR0 = 0;
TIFR = 0x1; /* Clear TOV0 flag */
}

Timer Interrupt
TIMSK: Timer / Counter Interrupt Mask Register

Dr.J.C.Vijayshree 13
EC509 Advanced Microcontrollers Unit 2

We have to set TOIE0 (Timer0 Overflow Interrupt Enable) bit in TIMSK register to set the
timer0 interrupt, so that as soon as the Timer0 overflows, the controller jumps to the Timer0
interrupt routine.

Timer0 Interrupt Program

/*
Generating 10 ms delay pulse on PORTB using ATmega16 Timer interrupt
*/

#include <avr/io.h>
#include <avr/interrupt.h>

/* timer0 overflow interrupt */


ISR(TIMER0_OVF_vect)
{
PORTB=~PORTB; /* Toggle PORTB */
TCNT0 = 0xB2;
}

int main( void )


{
DDRB=0xFF; /* Make port B as output */

sei();
TIMSK=(1<<TOIE0); /* Enable Timer0 overflow interrupts */

TCNT0 = 0xB2; /* Load TCNT0, count for 10ms*/


TCCR0 = (1<<CS02) | (1<<CS00); /* Start timer0 with /1024 prescaler*/
while(1);
}

6-channel ADC Working –


ADC (Analog to Digital converter) is most widely used device in embedded systems which is
designed especially for data acquisition. In AVR ATmega series normally 10-bit ADC is inbuilt
in the controller.
Let us see how to use the ADC of AVR ATmega16 / ATmega32.
ATmega16/32 supports eight ADC channels, means we can connect eight analog inputs at a
time. ADC channel 0 to channel 7 are present on PORTA. i.e. Pin no.33 to 40.

Dr.J.C.Vijayshree 14
EC509 Advanced Microcontrollers Unit 2

ADC Pins of ATmega 16/32


The controller has 10 bit ADC, means we will get digital output 0 to 1023.
i.e. When input is 0V, digital output will be 0V & when input is 5V (and Vref=5V), we will get
highest digital output corresponding to 1023 steps, which is 5V.
So controller ADC has 1023 steps and

 Step size with Vref=5V : 5/1023 = 4.88 mV.


 Step size with Vref=2.56 : 2.56/1023 = 2.5 mV.

So Digital data output will be Dout = Vin / step size.


ATmega16/32 ADC

 It is 10-bit ADC
 Converted output binary data is held in two special function 8-bit register ADCL (result
Low) and ADCH (result High).
 ADC gives 10-bit output, so (ADCH : ADCL) only 10-bits are useful out of 16-bits.
 We have options to use this 10-bits as upper bits or lower bits.
 We also have three options for Vref. 1. AVcc (analog Vcc), 2. Internal 2.56 v3. External
Aref. Pin.
 Total conversion time depends on crystal frequency and ADPS0 : 2 (frequency devisor)
 If you decided to use AVcc or Vref pin as ADC voltage reference, you can make it more
stable and increase the precision of ADC by connecting a capacitor between that pin
and GND.

Dr.J.C.Vijayshree 15
EC509 Advanced Microcontrollers Unit 2

ADC Register
In AVR ADC, we need to understand four main register -

1. ADCH: Holds digital converted data higher byte


2. ADCL: Holds digital converted data lower byte
3. ADMUX: ADC Multiplexer selection register
4. ADCSRA: ADC Control and status register

ADCH : ADCL register


First two register holds the digital converted data, which is 10-bit.
ADMUX Register

Bit 7 : 6 – REFS1 : 0: Reference Selection Bits


Reference voltage selection for ADC
REFS1 REFS0 Vref to ADC

0 0 AREF pin

0 1 AVCC pin i.e. Vcc 5 V

1 0 Reserved

1 1 Internal 2
Bit 5 – ADLAR : ADC Left Adjust Result
Use 10-bits output as upper bits or lower bits in ADCH & ADCL.

Bits 4 : 0 – MUX4 : 0 : Analog Channel and Gain Selection Bits


We can select input channel ADC0 to ADC7 by using these bits. These bits are also used to
select comparator (inbuilt in AVR) inputs with various gain. We will cover these comparator
operations in other part.
Selecting channel is very easy, just put the channel number in MUX4 : 0.
Suppose you are connecting input to ADC channel 2 then put 00010 in MUX4 : 0.
Suppose you are connecting input to ADC channel 5 then put 00101 in MUX4 : 0.

Dr.J.C.Vijayshree 16
EC509 Advanced Microcontrollers Unit 2

ADCSRA Register:

 Bit 7 – ADEN : ADC Enable

Writing one to this bit enables the ADC. By writing it to zero, the ADC is turned off. Turning the
ADC off while a conversion is in progress, will terminate this conversion.

 Bit 6 – ADSC : ADC Start Conversion

Writing one to this bit starts conversion.

 Bit 5 – ADATE : ADC Auto Trigger Enable

Writing one to this bit, results in Auto Triggering of the ADC is enabled.

 Bit 4 – ADIF : ADC Interrupt Flag

This bit is set when an ADC conversion completes and the Data Registers are updated.

 Bit 3 – ADIE : ADC Interrupt Enable

Writing one to this bit, the ADC Conversion Complete Interrupt is activated.

 Bits 2 : 0 – ADPS2 : 0 : ADC Prescaler Select Bits

These bits determine the division factor between the XTAL frequency and the input clock to the
ADC

Dr.J.C.Vijayshree 17
EC509 Advanced Microcontrollers Unit 2

We can select any divisor and set frequency Fosc/2, Fosc/4 etc. for ADC, But in AVR, ADC
requires an input clock frequency less than 200KHz for max. accuracy. So we have to always
take care about not exceeding ADC frequency more than 200KHz.
Suppose your clock frequency of AVR is 8MHz, then we must have to use devisor 64 or 128.
Because it gives 8MHz/64 = 125KHz, which is lesser than 200KHz.

Circuit Diagram
LCD16x2 is used to show digital converted value from channel 0.

Circuit Diagram For Using ADC0 Of ATmega 16/32

Dr.J.C.Vijayshree 18
EC509 Advanced Microcontrollers Unit 2

Steps to Program ADC

1. Make ADC channel pin as input.


2. Set ADC enable bit in ADCSRA, select the conversion speed using ADPS2 : 0. For
example, we will select devisor 128.
3. Select ADC reference voltage using REFS1 : REFS0 in ADMUX register, for example
we will use AVcc as reference voltage.
4. Select ADC input channel using MUX4 : 0 in ADMUX, for example we will use channel
0.
5. So our value in register ADCSRA = 0x87 and ADMUX = 0x40.
6. Start conversion by setting bit ADSC in ADCSRA. E.g.ADCSRA |= (1<<ADSC);
7. Wait for conversion to complete by polling ADIF bit in ADCSRA register.
8. After ADIF bit gone high, read ADCL and ADCH register to get digital output.
9. Notice that read ADCL before ADCH; otherwise result will not be valid.

Program

#define F_CPU 8000000UL


#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include "LCD_16x2_H.h"
void ADC_Init()
{ DDRA=0x0; /* Make ADC port as input */
ADCSRA = 0x87; /* Enable ADC, fr/128 */
ADMUX = 0x40; /* Vref: Avcc, ADC channel: 0 */

int ADC_Read(char channel)


{ int Ain,AinLow;

ADMUX=ADMUX|(channel & 0x0f); /* Set input channel to read */

ADCSRA |= (1<<ADSC); /* Start conversion */


while((ADCSRA&(1<<ADIF))==0); /* Monitor end of conversion interrupt */

_delay_us(10);
AinLow = (int)ADCL; /* Read lower byte*/
Ain = (int)ADCH*256; /* Read higher 2 bits and
Multiply with weight */
Ain = Ain + AinLow;
return(Ain); /* Return digital value*/
}

int main()

Dr.J.C.Vijayshree 19
EC509 Advanced Microcontrollers Unit 2

int main()
{
char String[5];
int value;

ADC_Init();
LCD_Init(); /* Initialization of LCD */
LCD_String("ADC value"); /* Write string on 1st line of LCD */

while(1)
{

LCD_Command(0xc4); /* LCD16x2 cursor position */


value=ADC_Read(0); /* Read ADC channel 0 */
itoa(value,String,10); /* Integer to string conversion */
LCD_String(String);
LCD_String(" ");
}
return 0;
}

Bootloader Circuit –
The BootLoader is a code which executes when a microcontroller is powered ON or reset. It
basically sets an environment for the application code to execute. It is the Boot-Loader that sets
the hardware and loads the application code from any storage medium or received through
external communication and let the application to execute. Thus a Boot-Loader has to perform
the following basic function : Initialize the controller peripherals,
Initialize the devices in the board,
Allow an option for the user to select from the available applications to load,
Load the selected application,
Let the application code to execute.
Apart from the above mentioned functions some Boot-Loaders can perform many other functions
and there are Boot-Loaders which don’t perform all these functions like provide option to select
the required application etc. The Boot-Loader codes in microcontrollers are actually very small
and simple compared to the Boot-Loaders in advanced devices like PC. In most of the
microcontroller the functionality of a Boot-Loader is limited only to set the initial clock and
other settings for the microcontroller, load an application binary from the serial port etc.
In an AVR microcontroller writing a Boot-Loader code is comparatively easy, since any code
which is written to the BLS section of the flash memory can have complete access to the
hardware of the microcontroller. The flash memory of the AVR microcontroller is divided into
two sections; an Application flash section and a Boot-Loader section (BLS).
Any code which executes from the BLS can use Self Programming Mode (SPM). Using the SPM
feature a code from the BLS section can read or write the entire flash memory including the BLS
section where the code is running from. This feature can be used to load any application code

Dr.J.C.Vijayshree 20
EC509 Advanced Microcontrollers Unit 2

binary to the flash memory and let it execute. The required initialization of the controller
peripherals like USART, port bits etc. and the initialization of the external devices like LCD etc.
can be done from the BLS itself before loading the application code.
In this project discuss how to write a simplest Boot-Loader code for the AVR microcontroller
which can initialize the peripherals like USART, LED port and initialize a 4 bit LCD connected
to the controller and then load any application which has been flashed into the built-in EEPROM
of the microcontroller. The microcontroller used in this project is ATMEGA16, and the
programmer used is USBASP. The AVR studio 4 is used as the IDE and the burner software
used is AVR-BURNO-MAT.

The AVR flash memory is divided into two sections namely the application section and the
Boot-Loader section (BLS). In case of the ATMEGA16 it has 16 KB of flash memory of which
the 15KB is application section and the remaining 1KB is BLS. The memory architecture of the
ATMEGA16 is shown in the following figure;

Dr.J.C.Vijayshree 21
EC509 Advanced Microcontrollers Unit 2

Fig. 2: Flash Memory Architecture of ATMEGA16


The code for both the BLS and application section can be written as normally does and there is
no much difference. The only thing to be careful about is the size of the code binary. It should
not be more than 1KB, otherwise it won’t be able to code programmed into the BLS.
The project on AVR BLS coding discusses how to program a simple code into the BLS of
ATMEGA16 microcontroller with the help of AVR studio as IDE, USBasp as the programmer
and AVR-Burnomat as the burner software.
In this particular project the Boot-Loader is coded to perform UART initialization along with a
simple LED pin initialization and also an external hardware initialization of the 4 bit LCD.
Hence the application codes does not require those codes in them, still they works because before
executing the application codes the initialization functions will be executed by the Boot-Loader.
The BLS code has the initialization functions which should not be there in the application codes.
The initialization functions used in the Boot-Loader code for this project are given below;
Function Description
void lcd_init ( void ) Initialize the LCD in 4 bit mode
void usart_init ( void Initialize the usart in 9600 baud rate with transmission and reception
) enabled
DDRD |= 0x80; Initialization of the LED pin as output
Fig.3 :Initialization functions used Boot-Loader code of AVR

Dr.J.C.Vijayshree 22
EC509 Advanced Microcontrollers Unit 2

Any application code can directly use the following function calls to access the USART, LCD
and LED without their initializing functions anywhere in their code.
Function Description
lcd_clear () Clear the LCD
Display a string in the
lcd_string ()
LCD
usart_send_string () Send a string via usart
PORTD &= 0x7F; Turn ON the LED
PORTD |= 0x80; Turn OFF the LED
Fig. 4: Function calls used by application code to access peripherals in AVR
The hardware initialization before executing the application code is explained in detail in
a project on Initializing hardware from AVR BLS.
The major function of the Boot-Loader is load a code binary form storage medium or which can
be received through the external communication with other devices to the flash memory. The
SPM feature available for the code executing from the BLS helps in loading an application code
binary to the flash memory. The task of writing the BLS code with SPM has been made simple
by the APIs available in the header file <avr/boot.h>. The following are the important APIs
available in the header file which helps in the SPM.
FUNCTION DESCRIPTION PARAMETER
Erase the flash page that is referred A byte address in
boot_page_erase (address)
by address flash
Fill the Boot-Loader temporary The address is a byte
boot_page_fill (address,
page buffer for flash address with address. The data is a
data)
data word word
Write the Boot-Loader temporary
boot_page_write (address) page buffer to flash page that Byte address in flash
contains address
Fig. 5: Important APIs in AVR
The steps required to do the SPM on the application flash memory is explained in a project on
using SPM in AVR flash to flash programming.
In this particular project the Boot-Loader is coded in such a way that it will try to load any
application code binary which has been loaded into the built-in internal EEPROM of the AVR
microcontroller. The APIs available in the <avr/eeprom.h> is used to read the data bytes from the
EEPROM and with the help of APIs from the <avr/boot.h> the data bytes are stored into a
temporary buffer and then flashed into the application section of the flash memory.
The API provided by the <avr/eeprom.h> to read the data bytes from the built-in EEPROM of
the AVR microcontroller is;
uint8_t eeprom_read_byte (const uint8_t *p)

FUNCTION DESCRIPTION PARAMETER


uint8_t The function returns one data byte The pointer refers to the
eeprom_read_byte which is stored in the EEPROM EEPROM address from which
(const uint8_t *p) address referred by the pointer p the data byte need to be read
Fig. 6: API <avr/eeprom.h> to read data bytes from in-built EEPROM of AVR microcontroller

Dr.J.C.Vijayshree 23
EC509 Advanced Microcontrollers Unit 2

With the help of the above discussed APIs from both <avr/boot.h> and <avr/eeprom.h> one can
use the SPM feature of the AVR microcontroller to write a Boot-Loader code which can load an
application which has been programmed into the built-in EEPROM of the AVR microcontroller.
For that one should follow the steps mentioned below which are explained in a project on using
SPM in AVR EEPROM to flash programming.
Step: 1 Erase the flash page which is about to write into
Step: 2 Store the code binary which are read from the EEPROM into a temporary buffer before write
into a flash page
ode section and let the newly programmed application to execute.

Flash the Boot-Loader code to the BLS first any small sized application code to the EEPROM
memory using the steps explained in the previous project on LED blinking from BLS of AVR.
Once the EEPROM programming has completed and when the controller resets the Boot-Loader
will start executing. Once can observe that it is performing the initialization functions and is
loading the application from the built-in EEPROM.

Fig. 7: Burning BLS code into BLS of AVR circuit on breadboard

Dr.J.C.Vijayshree 24
EC509 Advanced Microcontrollers Unit 2

Fig. 9: LCD Display initialized by BLS code in AVR setup on breadboard

Dr.J.C.Vijayshree 25
EC509 Advanced Microcontrollers Unit 2

Fig. 10: USART initialized at 9600 baud rate by BLS of AVR setup on breadboard

Dr.J.C.Vijayshree 26
EC509 Advanced Microcontrollers Unit 2

ISP of Atmega

Dr.J.C.Vijayshree 27
EC509 Advanced Microcontrollers Unit 2

Dr.J.C.Vijayshree 28
EC509 Advanced Microcontrollers Unit 2

Dr.J.C.Vijayshree 29
EC509 Advanced Microcontrollers Unit 2

Dr.J.C.Vijayshree 30

You might also like