• High Performance, Low Power AVR ® 8-bit Microcontroller
• Advanced RISC Architecture
– 131 Powerful Instructions - Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Ope ration
– Up to 1 MIPS throughput per MHz
– On-chip 2-cycle Multiplier
• Data and Non-Volatile Program Memory
– 16K/32K/64K Bytes Flash of In-System Programmab le Program Memory
• Endurance: 10,000 Write/Erase Cycles
– Optional Boot Code Section with Independent Lock Bits
– In-System Programming by On-chip Boot Program
• Programming Lock for Flash Program and EEPROM Data Security
• 1024/2048/4096 Bytes Internal SRAM
• On Chip Debug Interface (debugWIRE)
• CAN 2.0A/B with 6 Message Objects - ISO 16845 Certified
• LIN 2.1 and 1.3 Controller or 8-Bit UART
• One 12-bit High Speed PSC (Power Stage Controller) (only ATmega16/32/64M1)
• Non Overlapping Inverted PWM Output Pins With Flexible Dead-Time
• Variable PWM duty Cycle and Frequency
• Synchronous Update of all PWM Registers
• Auto Stop Function for Emergency Event
• Peripheral Features
– One 8-bit General purpose T imer/Co unte r with Separate Prescaler, Compa re Mode
and Capture Mode
– One 16-bit General purpose Timer/Counter with Separate Prescaler, Compare
Mode and Capture Mode
– One Master/Slave SPI Serial Interface
– 10-bit ADC
• Up To 11 Single Ended Channels and 3 Fully Differential ADC Channel Pairs
• Programmable Gain (5x, 10x, 20x, 40x) on Differential Channels
• Internal Reference Voltage
• Direct Power Supply Voltage Measurement
– 10-bit DAC for Variable Voltage Reference (Comparators, ADC)
– Four Analog Comparators with Variable Threshold Detection
– 100µA ±3% Current Source (LIN Node Identification)
– Interrupt and Wake-up on Pin Change
– Programmable Watchdog Timer with Separate On-Chip Oscillator
– On-chipTemperature Sensor
• Special Microcontroller Features
– Low Power Idle, Noise Reduction, and Power Down Modes
– Power On Reset and Programmable Brown Out Detection
– In-System Programmable via SPI Port
– High Precision Crystal Oscillator for CAN Operations (16 MHz)
(1)
8-bit
Microcontroller
with
16K/32K/64K
Bytes In-System
Programmable
Flash
2. On the first engineering samples (Parts marked AT90PWM324), the ACMPN3 alternate function is not located on PC4. It is located on PE2.
The ATmega16/32/64/M1/C1 is a low-power CMOS 8-bit microcontroller based on the AVR
enhanced RISC architecture. By executing powerful ins tructions in a singl e clock cycle , the
ATmega16/32/64/M1/C1 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed.
8
7647D–AVR–08/08
2.1Block Diagram
Data Bus 8-bit
ATmega16/32/64/M1/C1
Figure 2-1.Block Diagram
Flash Program
Memory
Instruction
Register
Instruction
Decoder
Control Lines
Program
Counter
Direct Addressing
Status
and Control
32 x 8
General
Purpose
Registrers
ALU
Indirect Addressing
Data
SRAM
EEPROM
Interrupt
Unit
SPI
Unit
Watchdog
Timer
4 Analog
Comparators
HW LIN/UART
Timer 0
Timer 1
ADC
DAC
7647D–AVR–08/08
I/O Lines
Current Source
MPSC
CAN
The AVR core com bin es a rich in struction set with 32 g ene ra l p ur pos e worki ng re gisters. All the
32 registers are dire ctly c onn ec ted to the Ar ithmetic Logic Unit (ALU), al lo win g two ind ependent
registers to be accessed in one single instruction executed in one clock cycle. The resulting
architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
The ATmega16/32/64/M1/C1 provides the following features: 16K/32K/64K bytes of In-System
Programmable Flash with Read-While-Write capabilities, 512/1024/2048 bytes EEPROM,
1024/2048/4096 bytes SRAM , 27 gener al purpos e I/O lines , 32 gener al purpose wor king reg isters, one Motor Power Stage Controller, two flexible Timer/Counters with compare modes and
PWM, one UART with HW LIN, an 11-chann el 10-b it ADC with two differentia l input s tages wi th
programmable gain, a 10-bit DAC, a programmable Watchdog Timer with Internal Individual
Oscillator, an SPI serial port, an On-chip Debug system and four software selectable power saving modes.
9
ATmega16/32/64/M1/C1
The Idle mode stops the CPU while allowing the SRAM, Timer/Counters, SPI ports, CAN,
LIN/UART and interrupt system to continue functioning. The Power-down mode saves the register contents but freezes the Oscillator, disabling all other chip functions until the next interrupt or
Hardware Reset. The ADC Noise Reduction mode s tops the CPU and al l I/O modules exc ept
ADC, to minimize switchi ng nois e du ring ADC c onver s ions. In Sta ndby mo de, th e Crys tal /Res onator Oscillat or is runni ng wh ile the rest o f th e de vice is s lee ping. Thi s all ows very fa st st art-u p
combined with low power consumption.
The device is manufactured using Atmel’s high-density nonvolatile memory technology. The Onchip ISP Flash allows the program memory to be reprogrammed in-system through an SPI serial
interface, by a conventional nonvolati le memory programmer , or by an On-chip B oot program
running on the AVR core. The boot program can use any interface to download the application
program in the application Flash memory. Software in the Boot Flash section will continue to run
while the Application Flash section is updated, prov iding true Read-Whi le-Write operation. By
combining an 8-bit RISC CP U with In-System Self-Programm able Flash on a monolithi c chip,
the Atmel ATmega16/32/64/M1/C1 is a powerful microcontroller that provides a highly flexible
and cost effective solution to many embedded control applications.
The ATmega16/32/64/M1/C1 AVR is supported with a full suite of program and system development tools including: C compilers, macro assemblers, program debugge r/simulators, in-circuit
emulators, and evaluation kits.
2.2Automotive Quality Grade
The ATmega16/32 /64/M1/C1 ha ve been de veloped an d manufactu red accordin g to the most
stringent requirements of the international standard ISO-TS-16949. This data sheet contains
limit values extracted from the r esults of ex tensive charac terizatio n (Temperatu re and Voltag e).
The quality and reliability of the ATmega16/32/64/M1/C1 have been verified during regular product qualification as per AEC-Q100 grade 1.
As indicated in the ordering information paragraph, the products are available in only one temperature grade.
Table 2-1.Temperature Grade Identification for Automotive Products
TemperatureT emperature
-40 ; +125ZFull AutomotiveTemperature Range
2.3Pin Descriptions
2.3.1VCC
Digital supply voltage.
Comments
Identifier
2.3.2GND
Ground.
10
7647D–AVR–08/08
2.3.3Port B (PB7..PB0)
Port B is an 8-bi t b i- dire ctional I/O port with in terna l pul l- up res ist ors (se le cte d f or ea ch bi t). T h e
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
resistors are activated. The Port B pins are tri-stated whe n a rese t condition bec omes ac tive,
even if the clock is not running.
Port B also serves the functions of various special features of the ATmega16/32/64/M1/C1 as
listed on page 69.
2.3.4Port C (PC7..PC0)
Port C is an 8-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 pi ns are tri-stated when a res et condition bec omes active,
even if the clock is not running.
Port C also serves th e functions of special features of the ATme ga16/32 /64/M1/C 1 as listed on
page 73.
2.3.5Port 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 pi ns are tri-stated when a res et condition bec omes active,
even if the clock is not running.
ATmega16/32/64/M1/C1
Port D also serves the functions of various special features of the ATmega16/32/64/M1/C1 as
listed on page 76.
2.3.6Port E (PE2..0) RESET/
XTAL2
Port E is an 3-bi t b i- dire ctional I/O port with in terna l pul l- up res ist ors (se le cte d f or ea ch bi t). T h e
Port E output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port E pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port E pins are tri-stated whe n a rese t condition bec omes ac tive,
even if the clock is not running.
If the RSTDISBL Fu se i s p rogra mmed, PE 0 is u sed as an I/ O p in. N ote th at th e el ectri cal c haracteristics of PE0 differ from those of the other pins of Port E.
If the RSTDISBL Fuse is unprogrammed, PE0 is used as a Reset input. A low level on this pin
for longer than the minimum pulse lengt h will gen erate a Reset, ev en if the cloc k is not runn ing.
The minimum pulse leng th is g iven in T able 7-1 on page 47. Sho rter pul ses a re not guarantee d
to generate a Reset.
Depending on the cloc k sel ec tio n fus e s etti ngs , PE1 c an be us ed as i npu t to the inv ert ing O s ci llator amplifier and input to the internal clock operating circuit.
Depending on the clock selection fuse settings, PE2 can be used as output from the inverting
Oscillator amplifier.
XTAL1/
7647D–AVR–08/08
11
ATmega16/32/64/M1/C1
The various special feature s of Port E are ela borat ed in “Alter nate Fu nctions of Po rt E” on pag e
79 and “Clock Systems and their Distribution” on page 30.
2.3.7AVCC
AVCC is the supply voltage pin for the A/D Con verter, D/A Conv erter, Curren t source. It should
be externally connected to V
be connected to V
2.3.8AREF
This is the analog reference pin for the A/D Converter.
2.4About Code Examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. These code examples assume that the part specific header file is inc luded before
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details.
, even if th e ADC , DA C ar e n o t us ed . If th e AD C is used, it should
CC
through a low-pass filter.
CC
12
7647D–AVR–08/08
3.AVR CPU Core
3.1Introduction
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
3.2Architectural Overview
Figure 3-1.Block Diagram of the AVR Architecture
ATmega16/32/64/M1/C1
Data Bus 8-bit
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
Direct Addressing
Indirect Addressing
Status
and Control
32 x 8
General
Purpose
Registrers
ALU
Data
SRAM
EEPROM
Interrupt
Unit
SPI
Unit
Watchdog
Timer
Analog
Comparator
I/O Module1
I/O Module 2
I/O Module n
7647D–AVR–08/08
I/O Lines
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buse s for program and data. Instructi ons in the p rogram memory ar e
executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the p rogram memory . This concep t enabl es i nstruct ions to be ex ecute d
in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
13
ATmega16/32/64/M1/C1
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 r egisters can be used as three 1 6-bit i ndirect address register pointer s for Dat a
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports ar it hme tic a nd log ic o perati on s betwe en r egisters or between a cons tan t an d
a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whol e addres s space. Mo st AVR instru ctions hav e a single 16 -bit word format. Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program sec tion and the
Application Prog ram sect ion. Both se ctions ha ve dedicate d Lock bits for write and rea d/write
protection. The SPM (Store Program Memory) instruction that writes into the Application Flash
memory section must reside in the Boot Program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is e ffec ti ve ly al lo ca ted in the general data SRA M, a nd co nse que ntl y the Sta ck
size is only limited by th e total SRAM size a nd the usage of the SRAM . All user p rogram s mus t
initialize the SP in th e Re set routi ne (bef ore s ubrou tine s o r int errup ts are e xecut ed ). The Sta ck
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible inter rupt modul e has its cont rol registe rs in the I/O s pace with a n additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. T he in terr up ts h av e pri or ity in ac co rd ance wi th t hei r Interr up t Ve cto r pos ition. The lower the Interrupt Vector address, the higher is the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F. In addition, the
ATmega16/32/ 64/M1/C1 h as Exten ded I/O spac e from 0x60 - 0xFF in SR AM where onl y the
ST/STS/STD and LD/LDS/LDD instructions can be used.
3.3ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single c lock cycle, arithmetic operat ions between general purpose
registers or between a register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a po werful mult iplier suppo rting both sig ned/unsig ned multipl ication
and fractional format. See the “Instruction Set” section for a detailed description.
14
7647D–AVR–08/08
3.4Status Register
ATmega16/32/64/M1/C1
The Status Register contains information about the result of the most recently executed arithmetic instruction. This information ca n be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Re gis ter i s no t au tomat icall y s tored w hen enteri ng a n in ter rupt routi ne a nd r estor ed
when returning from an interrupt. This must be handled by software.
The Global Interrupt Enable bit must be set to enable d the interrupts. The in dividual interru pt
enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are ena bled independ ent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instr uctions BL D (Bit LoaD) and BST (B it STore) us e the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a regi ster in the Register File by the
BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H ind icate s a Hal f Carry in s ome ari thmetic operati ons. Ha lf Carry Is usefu l
in BCD arithmetic. See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N
⊕ V
The S-bit is always an exclusive or between the negative flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
7647D–AVR–08/08
15
ATmega16/32/64/M1/C1
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
3.5General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 3-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 3-2.AVR CPU General Purpose Working Registers
…
R260x1AX-register Low Byte
R270x1BX-register High Byte
R280x1CY-register Low Byte
R290x1DY-register High Byte
R300x1EZ-register Low Byte
R310x1FZ-register High Byte
Most of the instructions operati ng on the Regis ter File have d irect access to all register s, and
most of them are single cycle instructions.
As shown i n Figure 3-2, each register is also assigned a data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
3.5.1The X-register, Y-register, and Z-register
The registers R26..R31 have s ome adde d functi ons to their gen eral purpose us age. Thes e registers are 16-bit address poin ters for indirec t addressing of the data space. The three indi rect
address registers X, Y, and Z are defined as des cri bed in Figure 3-3.
16
7647D–AVR–08/08
3.6Stack Pointer
ATmega16/32/64/M1/C1
Figure 3-3.The X-, Y-, and Z-registers
15XHXL0
X-register7070
R27 (0x1B)R26 (0x1A)
15YHYL0
Y-register7070
R29 (0x1D)R28 (0x1C)
15ZHZL0
Z-register7070
R31 (0x1F)R30 (0x1E)
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses aft er interrupts and subroutin e call s . The S tack Pointer Register alway s poi nts
to the top o f t he S t ac k. N ot e t h at t h e S tack is implemented as growing from higher mem o ry l o ca tions to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Point er points to the data SRAM S tack area wh ere the Su broutine a nd Interrupt
Stacks are located. Thi s Stac k space i n the data S RAM mus t be defin ed by the pr ogram be fore
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be s et to
point above 0x100. The Stack Pointer is decremented by one when data is pushed onto the
Stack with the PUSH instruction, and it is decremented by two when the return address is
pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one
when data is popped from the Stack with the POP instruction, and it is incremented by two when
data is popped from the Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clk
chip. No internal clock division is used.
, directly generated from the selected clock source for the
CPU
7647D–AVR–08/08
17
ATmega16/32/64/M1/C1
Figure 3-4 shows the parallel instructio n fetches an d instruc tion ex ecutions enable d by the Ha r-
2
T1T2T3T4
T1T2T3T4
vard architecture and th e fast- access Register File con cept. Thi s is the bas ic pipel ining conce pt
to obtain up to 1 MIPS per MHz with the cor respondi ng unique res ults for func tions per cos t,
functions per clocks, and functions per power-unit.
Figure 3-4.The Parallel Instruction Fetches and Instruction Executions
clk
CPU
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
Figure 3- 5 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two regi ster ope rands is executed , and the result is stored bac k to the de stination register.
Figure 3-5.Single Cycle ALU Operation
Total Execution Time
egister Operands Fetch
ALU Operation Execute
Result Write Back
3.8Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate program vector in the program memory space. All interrupts ar e
assigned individual enable bits which must be written logic one together with the Global Interrupt
Enable bit in the Status Re gister in or der to ena ble the int errupt. De pendin g on the Prog ram
Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12
are programmed. This feature improves software security. See the section “Memory Program-
ming” on page 295 for details .
The lowest addresses in the p rogram memory space are by default defined as the Reset a nd
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on pag e 57. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the hig hes t prior it y, and next is ANACOMP0 – the Analog Comparator
0 Interrupt. The Interr upt Ve ctor s can be moved to t he start of the B oot Flas h secti on by settin g
the IVSEL bit in the MCU Control Register (MCUCR). Refer to “Inte rrupts” on p age 5 7 for more
information. The Reset Vector can also be moved to the start of the Boot Flash section by pro-
clk
CPU
18
7647D–AVR–08/08
gramming the BOOTRST Fuse, see “Boot Loader Support – Read-While-Write Self-
Programming ATmega16/32/64/M1/C1” on page 276.
3.8.1Interrupt Behavior
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user softw are c an write lo gic one to the I-bit to enab le nes ted i nterrup ts. Al l ena bled
interrupts can then interrupt the current interrupt routine. The I-bit is automa tically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
interrupt flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execut e the int errupt ha ndlin g routine , and hardware clears the cor respon ding inte rrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be
cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared,
the interrupt flag wi ll be set an d remembe red u ntil th e interr upt is enabl ed, or th e flag is c leared
by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable
bit is cleared, the c orrespond ing interru pt flag(s) wil l be set and reme mbered unti l the Globa l
Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessa rily hav e in ter rupt fl ags . If the interr up t con dit ion disapp ear s befo re the
interrupt is enabled, the interrupt will not be triggered.
ATmega16/32/64/M1/C1
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatic ally stored when entering an in terrupt rou tine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruct ion to disable interrupts, the interrupt s will be immedia tely disab led.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence..
Assembly Code Example
in r16, SREG; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMWE; start EEPROM write
sbi EECR, EEWE
out SREG, r16; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG;/* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1<<EEMWE); /* start EEPROM write */
EECR |= (1<<EEWE);
SREG = cSREG; /* restore SREG value (I-bit) */
7647D–AVR–08/08
19
ATmega16/32/64/M1/C1
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example.
Assembly Code Example
C Code Example
3.8.2Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine
is executed. During this four clock cycle pe riod , the Prog ram Co unter is pu shed o nto the Stack.
The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If
an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed
before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt
execution response time is increased by four clock cycles. This increase comes in addition to the
start-up time from the selected sleep mode.
sei; set Global Interrupt Enable
sleep; enter sleep, waiting for interrupt
; note: will enter sleep before any pending
; interrupt(s)
_SEI(); /* set Global Interrupt Enable */
_SLEEP(); /*enter sleep, waiting for interrupt */
/* note: will enter sleep before any pending interrupt(s) */
A return from an inter rupt handli ng routine takes four clock cycles. During the se four c lock
cycles, the Program Cou nter (two bytes ) is popped back fr om the Stack, the Sta ck Pointer is
incremented by two, and the I-bit in SREG is set.
20
7647D–AVR–08/08
4.Memories
FF
Program Memory
This section describes the different memories in the ATmega16/32/64/M1/C1. The AVR architecture has two m ain memor y spaces , the Data Mem ory and the P rogram Me mory space. In
addition, the ATmeg a16/32/64/M 1/C1 fe atures an EEP ROM Memo ry for data stor age. All three
memory spaces are linear and regular.
4.1In-System Reprogrammable Flash Program Memory
The ATmega16/32/64/M1 /C1 co ntai ns 16K/32K /64 K by tes On-chi p In-Sy ste m Reprog r amm abl e
Flash memory for p rogram storage . Sin ce all A VR i nstru ction s are 1 6 or 32 bit s wide , the Fl ash
is organized as 8K x 16 , 16K x 16 , 32K x 16. For software securit y, th e Flas h Pro gr am m emo ry
space is divided into two section s, Boo t Prog ram sec ti on and App li ca tio n Pro gram section.
The Flash memory has an endurance of at least 10,000 write/erase cycles. The
ATmega16/32/64/M1/C1 Program Counter (PC) is 14/15 bits wide, thus addressing the
8K/16K/32K progr am me mor y lo ca tio ns. The operation of Bo ot P ro gram section and associ ate d
Boot Lock bits for software protection are described in detail in “Boot Loader Support – Read-
While-Write Se lf-Pro gramm ing ATme ga16/3 2/64/M1 /C1” on pa ge 276. “Memory Programming”
on page 295 contains a detailed description on Flash programming in SPI or Parallel program-
ming mode.
Constant tables can be allocated within the entire program memory address space (see the LPM
– Load Program Memory.
ATmega16/32/64/M1/C1
Timing diagrams for instruction fetch and execution are presented in “Instruction Execution Tim-
ing” on page 17.
Figure 4-1.Program Memory Map
0x0000
Application Flash Section
7647D–AVR–08/08
Boot Flash Section
0x1FFF/0x3FFF/0x7
21
ATmega16/32/64/M1/C1
4.2SRAM Data Memory
0F
Figure 4-2 shows how the ATmega16/32/64/M1/C1 SRAM Memory is organized.
The ATmega16/32/64/M1/C1 is a complex microcontroller with more peripheral units than can
be supported within the 64 locations reserved in the Opcode for the IN and OUT instructions. For
the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD
instructions can be used.
The lower 2304 data memory locations address both the Register File, the I/O memory,
Extended I/O memory, an d the intern al data SRAM . The first 32 lo cations address the Register
File, the next 64 location the sta ndard I/O memory, then 160 locations of Exte nded I/ O memor y,
and the next 1024/2048/4096 locations address the internal data SRAM.
The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Ind irect with Pre- decrement , and Indirect with Post-inc rement. In the Re gister
File, registers R26 to R31 feature the indirect addressing pointer registers.
The direct addressing reaches the entire data space.
The Indirect with Displacement mode reaches 63 address locations from the base address given
by the Y- or Z-register.
When using register indirect addressing modes with automatic pre-decr ement and post-incre-
ment, the address registers X, Y, and Z are decremented or incremented.
The 32 general purpose working registers, 64 I/O Registers, 160 Extended I/O Registers, and
the 1024/2048/4096 bytes of internal data SRAM in the ATmega16/32/64/M1/C1 are all accessible through all these addressing modes. The Register File is described in “General Purpose
Register File” on page 16.
Figure 4-2.Data Memory Map for 1024/2048/4096 Internal SRAM
4.2.1SRAM Data Access Times
This section describes the general access timing concepts for internal memory access. The
internal data SRAM access is performed in two clk
Data Memory
32 Registers
64 I/O Registers
160 Ext I/O Reg.
Internal SRAM
(1024x8)
(2048x8)
(4096x8)
0x0000 - 0x001F
0x0020 - 0x005F
0x0060 - 0x00FF
0x0100
0x04FF/0x08FF/0x1
cycles as described in Figure 4-3.
CPU
22
7647D–AVR–08/08
Figure 4-3.On-chip Data SRAM Access Cycles
A
T1T2T3
clk
CPU
ddress
Compute Address
Data
ATmega16/32/64/M1/C1
Address valid
4.3EEPROM Data Memory
The ATmega16/32/64/M1/C1 contains 512/1024/2048 bytes of data EEPROM memory. It is
organized as a separate data space, in which single bytes can be read and written. The
EEPROM has an en duranc e of at least 100,000 wr ite/era se cycles. The access betwee n the
EEPROM and the CPU is described in the following, specifying the E EPROM Address Regi sters, the EEPROM Data Register, and the EEPROM Control Register.
For a detailed description of SPI and Parallel data downloading to the EEPROM, see “Serial
Downloading” on page 311 , and “Parallel Programming Parameters, Pin Mapping, and Commands” on page 299 respectively.
4.3.1EEPROM Read/Write Access
The EEPROM Access Registers are accessible in the I/O space.
WR
Data
RD
Memory Access Instruction
Write
Read
Next Instruction
The write access time for the EEPROM is given in Table 4-2. A self-timing function, however,
lets the user software detect when the next byte can be written. If the user code contains instructions that write the EE PROM, some precau tions must be taken. In he avily filtered power
supplies, V
is likely to rise or fall slowly on power-up/down. This causes the device for some
CC
period of time to run at a vo ltag e lo wer tha n sp ec ifi ed as mi ni mum for the clo ck frequ enc y u se d.
See “Preventing EEPROM Corruption” on page 28.for details on how to avoid problems in these
situations.
In order to prevent unintentional EEPROM writes, a specific write procedure must be followed.
Refer to the description of the EEPROM Control Register for details on this.
When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is
executed. When the E EPROM is writ ten, the CPU i s halted for tw o clock cycles before t he nex t
instruction is execute d.
23
7647D–AVR–08/08
ATmega16/32/64/M1/C1
4.3.2The EEPROM Address Registers – EEARH and EEARL
Bit15141312111098
–––––EEAR10EEAR9EEAR8EEARH
EEAR7EEAR6EEAR5EEAR4EEAR3EEAR2EEAR1EEAR0EEARL
76543 2 10
Read/Write RRRRRR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
Initial Value00000XXX
XXXXX X XX
• Bits 15.11 – Reserved Bits
These bits are reserved bits in the ATmega16/32/64/M1/C1 and will always read as zero.
• Bits 9..0 – EEAR10..0: EEPROM Address
The EEPROM Addre ss Registers – EEARH a nd EEARL specify the EEPR OM address in the
512/1024/2048 bytes EEPROM space. The EEPROM data bytes are addressed linearly
between 0 and 511/1023/2047. The initial value of EEAR is undefined. A proper value must be
written before the EEPROM may be accessed.
For the EEPROM write operation, the EEDR Register contains the data to be written to the
EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the
EEDR contains the data read out from the EEPROM at the address given by EEAR.
The EEPROM Programming mode bit setting defines which programming action that will be triggered when writing EE W E. It is possible to prog ra m data i n o ne ato mic o peration (erase the old
value and program the new value) or to split the Erase and Write operations in two different
operations. Th e Programming ti mes for the diffe rent modes ar e shown in Tabl e 4-1. While
24
7647D–AVR–08/08
ATmega16/32/64/M1/C1
EEWE is set, any write to EEPMn will be ignored . During rese t, the EEP Mn bits will be r eset to
0b00 unless the EEPROM is busy programming.
Table 4-1.EEPROM Mode Bits
Programming
EEPM1EEPM0
003.4 msErase and Write in one operation (Atomic Operation)
011.8 msErase Only
101.8 msWrite Only
11–Reserved for future use
• Bit 3 – EERIE: EEPROM Ready Interrupt Enable
Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set. Writing
EERIE to zero disables the interrup t. The E EPROM Rea dy inter rup t generates a cons tant inte rrupt when EEWE is cleared. The interrupt will not be generated during EEPROM write or SPM.
• Bit 2 – EEMWE: EEPROM Master Write Enable
The EEMWE bit determines whether setting EEWE to one causes the EEPROM to be written.
When EEMWE is set, setting EEWE within four clock cycles will write data to the EEPROM at
the selected address If EEMWE is zero, setting EEWE will have no effect. When EEMWE has
been written to on e by soft ware, ha rdwar e cle ars th e bit to z ero aft er fo ur cl ock c ycles . See th e
description of the EEWE bit for an EEPROM write procedure.
• Bit 1 – EEWE: EEPROM Write Enable
TimeOperation
The EEPROM Write Enable Signa l EEWE is the write strobe to the EEPROM. When address
and data are correctly set up, the EE WE bit must be written to one to write the value into the
EEPROM. The EEMWE bit mu st b e written to one befor e a log ical one is written to E EWE, otherwise no EEPROM write tak es pla ce . Th e follow ing procedure should be followe d when writing
the EEPROM (the order of steps 3 and 4 is not essential):
1. Wait until EEWE becomes zero.
2. Wait until SPMEN (Store Program Memory Enable) in SPMCSR (Store Program Memory
Control and Status Register) becomes zero.
3. Write new EEPROM address to EEAR (optional).
4. Write new EEPROM data to EEDR (optional).
5. Write a logical one to the EEMWE bit while writing a zero to EEWE in EECR.
6. Within four clock cycles after setting EEMWE, write a logical one to EEWE.
The EEPROM can not be programmed during a CPU write to the Flash memory. The software
must check that the Flash programming is completed before initiating a new EEPROM write.
Step 2 is only rele vant if the soft ware cont ains a Boo t Load er allow ing the CPU to progr am the
Flash. If the Flash is never being updat ed by the CPU, step 2 ca n be omi tted . See “Bo ot Loa der
Support – Read-While-Write Self-Programming ATmega16/32/64/M1/C1” on page 276 for
details about Boot programming.
Caution: An interrupt between step 5 and step 6 will ma ke the write cycle fail, since the
EEPROM Master Write E nable will time-out. If an i nterrupt routi ne accessi ng the EEPROM is
interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the
interrupted EEPROM access to fail. It is recommended to have the Global Interrupt Flag cleared
during all the steps to avoid these problems.
7647D–AVR–08/08
25
ATmega16/32/64/M1/C1
When the write access time has elapsed, the EEWE bit is cleared by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEWE has been set,
the CPU is halted for two cycles before the next instruction is executed.
• Bit 0 – EERE: EEPROM Read Enable
The EEPROM Read Enable S ignal EE RE is the re ad strobe to the EE PROM. Whe n the corr ect
address is set up in the EEAR Register, the EERE bit must be written to a logic one to trigger the
EEPROM read. The EEPROM read access takes one instruction, and the requested data is
available immediatel y. When the EEPRO M is read, the CPU is halted for four cycles before the
next instruction is executed.
The user should poll the EEWE bit before starting the read operation. If a write operation is in
progress, it is neither possible to read the EEPROM, nor to change the EEAR Register.
The calibrated Osci llat or i s used t o tim e the EEP ROM acce sses. Table 4-2 lists the typi cal programming time for EEPROM access from the CPU.
Table 4-2.EEPROM Programming Time.
SymbolNumber of Calibrated RC Oscillator CyclesTyp Programming Time
EEPROM write
(from CPU)
The following code examples show one assembly and on e C function for writin g to the
EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also
assume that no Flash Boot Loader is present in the software. If such code is present, the
EEPROM write function must also wait for any ongoing SPM command to finish.
263683.3 ms
26
7647D–AVR–08/08
ATmega16/32/64/M1/C1
Assembly Code Example
EEPROM_write:
; Wait for completion of previous write
sbic EECR,EEWE
rjmp EEPROM_write
; Set up address (r18:r17) in address register
out EEARH, r18
out EEARL, r17
; Write data (r16) to data register
out EEDR,r16
; Write logical one to EEMWE
sbi EECR,EEMWE
; Start eeprom write by setting EEWE
sbi EECR,EEWE
ret
C Code Example
void EEPROM_write (unsigned int uiAddress, unsigned char ucData)
{
/* Wait for completion of previous write */
while(EECR & (1<<EEWE))
;
/* Set up address and data registers */
EEAR = uiAddress;
EEDR = ucData;
/* Write logical one to EEMWE */
EECR |= (1<<EEMWE);
/* Start eeprom write by setting EEWE */
EECR |= (1<<EEWE);
}
7647D–AVR–08/08
27
ATmega16/32/64/M1/C1
The next code e xampl es sho w ass embly and C funct ions for r eading the EEPR OM. Th e ex amples assume that interrupts are controlled so that no interrupts will occur during execution of
these functions.
Assembly Code Example
EEPROM_read:
; Wait for completion of previous write
sbic EECR,EEWE
rjmp EEPROM_read
; Set up address (r18:r17) in address register
out EEARH, r18
out EEARL, r17
; Start eeprom read by writing EERE
sbi EECR,EERE
; Read data from data register
in r16,EEDR
ret
C Code Example
unsigned char EEPROM_read(unsigned int uiAddress)
{
/* Wait for completion of previous write */
while(EECR & (1<<EEWE))
;
/* Set up address register */
EEAR = uiAddress;
/* Start eeprom read by writing EERE */
EECR |= (1<<EERE);
/* Return data from data register */
return EEDR;
}
4.3.5Preventing EEPROM Corruption
During periods of low V
too low for the CPU and the EEPROM t o operate prop erly. These is sues are the s ame as for
board level systems using EEPROM, and the same design solutions should be applied.
An EEPROM data corruption can be caused by two situations when the voltage is too low. First,
a regular write sequence to the EEPROM requires a minimum voltage to operate correctly. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltage is too low.
EEPROM data corruption can easily be avoided by following this design recommendation:
Keep the AVR RESET ac tive (low) du ring per iods o f insu ffici ent power supp ly vo ltage. Th is ca n
be done by enabling the internal Brown-ou t Detect or (BOD ). If the de tectio n leve l of the in terna l
BOD does not match the needed detection level, an external low V
be used. If a reset occurs while a write operation is in progr ess, the write ope ratio n will be completed provided that the power supply voltage is sufficient.
28
the EEPROM data can be corrupted because the supply v oltage is
CC,
reset Protection circuit can
CC
7647D–AVR–08/08
4.4I/O Memory
ATmega16/32/64/M1/C1
The I/O space definition of the ATmega16/32/64/M1/C1 is shown in “Register Summary” on
page 355.
All ATmega16/32/64/M1/C1 I/Os and peripherals are placed in the I/O space. All I/O locations
may be accessed by the LD/L DS/LDD an d ST/STS /STD i nstruc tions, tr ansferr ing data be tween
the 32 general pur pose work ing regis ters and the I/O space . I/O register s within the address
range 0x00 - 0x1F are d irectl y bit-ac cessi ble usi ng the S BI and CBI in structi ons. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. Refer to
the instruction set section for more details. When using the I/O specific commands IN and OUT,
the I/O addresses 0x00 - 0x3F must be used. When addressing I/O registers as data space
using LD and ST instructions, 0x20 must be added to these addresses. The
ATmega16/32/64 /M1/C1 is a complex mi crocontrol ler with mor e periphera l units than ca n be
supported within the 64 location re served in Opcode for the IN and OUT ins tructions. For the
Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used.
For compatibility with future devices, rese rved bits should be wr itten to zero if acces sed.
Reserved I/O memory addresses should never be written.
Some of the status flags are cleared by writing a logical one to them. Note that, unlike most other
AVR’s, the CBI and S BI inst ruction s will onl y operate on the spe cified bi t, and ca n theref ore be
used on registers con tai nin g s uch s tatus fl ags. T he CBI a nd S BI ins truc ti ons work with re gisters
0x00 to 0x1F only.
The I/O and peripherals control registers are explained in later sections.
4.5General Purpose I/O Registers
The ATmega16/32/64 /M1/ C 1 con t ains fou r Gener al P urpos e I/O Re gis ters . T h ese regi s ter s ca n
be used for storing any information, and they are particularly useful for storing global variables
and status flags.
The General Purp ose I/O Reg isters, within the address range 0x00 - 0x1F, are directly b itaccessible using the SBI, CBI, SBIS, and SBIC instructions.
Figure 5- 1 presents the principal clock systems in the AVR and their distribution. All of the clocks
need not be active at a given time . In order to re duce power consu mption, the clocks to unuse d
modules can be halted by using different sleep modes, as described in “Power Management and
Sleep Modes” on page 41. The clock systems are detailed below.
Figure 5-1.Clock Distribution
Fast Peripherals
CLK
PLL
PLL Input
Multiplexer
General I/O
Modules
PLL
clk
I/O
ADCCPU CoreRAM
clk
ADC
AVR Clock
Control Unit
Clock
Multiplexer
Source Clock
clk
CPU
clk
FLASH
Reset Logic
Watchdog Clock
Watchdog Timer
Watchdog
Oscillator
Flash and
EEPROM
5.1.1CPU Clock – clk
CPU
The CPU clock is routed to parts of the system concerned with operation of the AVR core.
Examples of such module s are the General Purpo se Regis ter File , the Stat us Regi ster an d the
data memory holding the Stack Pointer. Ha lti ng the CP U c lo ck i nhi bi ts the co re fr om pe rfo r min g
general operations and calculations.
5.1.2I/O Clock – clk
I/O
The I/O clock is used by the majority of the I/O modules, like Timer/Counters, SPI, UART. The
I/O clock is also used by the External Interrupt module, but note that some external interrupts
are detected by asynchronous logic, allowing such interrupts to be detected even if the I/O clock
is halted.
30
External Clock
(Crystal
Oscillator)
Calibrated RC
Oscillator
7647D–AVR–08/08
Loading...
+ 342 hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.