Features
High Performance, Low Power AVR® 8-bit Microco ntroller
Advanced RISC Architecture
124 Powerful Instructions - Most Single Clock Cycle Execution
32 x 8 General Purpose Working Registers
Fully Static Operation
Up to 1 MIPS Throughput at 1 MHz
Nonvolatile Program an d Da ta Memories
40K Bytes of In-System Self-Progra mmable Flash, Enduran ce: 10,000 Write/Erase
Cycles
Optional Boot Code Section with Independent Lock Bits
In-System Programming by On-chip Boot Program
True Read-While-Write Operation
512 bytes EEPROM, Endurance: 100,000 Write/Erase Cycles
2K Bytes Internal SRAM
Programming Lock for Software Security
On-chip Deb ugging
Extensive On-chip Debu g Support
Available through JTAG interface
Battery Management Features
Two, Three, or Four Cells in Series
Deep Under-voltage Protection
Over-current Protection (Charge and Discharge)
Short-circuit Protection (Discharge)
Integrated Cell Balancing FETs
High Voltage Outputs to Drive Charge/Precharge/Discharge FETs
Peripheral Features
One 8-bit Timer/Counter with Separate Prescaler, Compare Mode, and PWM
One 16-bit Timer/Counter with Separate Prescaler and Compare Mode
12-bit Voltage ADC, Eight External and Two Internal ADC Inputs
High Resolution Coulomb Counter ADC for Current Measurements
TWI Serial Interface for SM-Bus
Programmable Wake-up Timer
Programmable Watchdog Timer
Spec ia l Micr oc ontroller Features
Power-on Reset
On-chip Voltage Regulator
External and Internal Interrupt Sources
Four Sleep Modes: Idle, Power-s ave, Power-down, and Power-off
Packages
48-pin LQFP
Operating Voltage: 4.0 - 25V
Maximum Withstand Voltage (High-volt age pins): 28V
Temperature Range: -30°C to 85°C
Speed Grade: 1 MHz
8-bit
Microcontroller
with 40K Bytes
In-System
Programmable
Flash
ATmega406
Preliminary
2548F–AVR–03/2013
22548F–AVR–03/2013
ATmega406
1. Pin Configurations
Figure 1-1. Pinout ATmega406.
1.1 Disclaimer Typical values contained in this datasheet are based on simulations and characterization of
other AVR microcontrollers manu factured on the same process technology. Min and Max values
will be available after the device is characterized.
1
2
3
4
5
6
7
8
9
10
11
12
36
35
34
33
32
31
30
29
28
27
26
25
SGND
(ADC0/PCINT0) PA0
(ADC1/PCINT1) PA1
(ADC2/PCINT2) PA2
(ADC3/PCINT3) PA3
VREG
VCC
GND
(ADC4/INT0/PCINT4) PA4
(INT1/PCINT5) PA5
(INT2/PCINT6) PA6
(INT3/PCINT7) PA7
PVT
OD
VFET
OC
OPC
BATT
PC0
GND
PD1
PD0 (T0)
PB7 (OC0B/PCINT15)
PB6 (OC0A/PCINT14)
48
47
46
45
44
43
42
41
40
39
38
37
13
14
15
16
17
18
19
20
21
22
23
24
RESET
XTAL1
XTAL2
GND
(TDO/PCINT8) PB0
(TDI/PCINT9) PB1
(TMS/PCINT10) PB2
(TCK/PCINT11) PB3
(PCINT12) PB4
(PCINT13) PB5
SCL
SDA
NNI
NI
PI
PPI
VREFGND
VREF
NV
PV1
PV2
PV3
PV4
GND
Top View
3
2548F–AVR–03/2013
ATmega406
2. Overview The ATmega406 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC
architecture. By executing powerful instructions in a single clock cycle, the ATmega406
achieves throughputs approaching 1 MIPS at 1 MHz.
2.1 Block Diagram
Figure 2-1. Block Diagram
The ATmega406 provides th e following featur es: a Voltag e Regu lator, dedicated Batte ry Protec-
tion Circuitry, integrated cell balancing FETs, high-voltage analog front-end, and an MCU with
two ADCs with On-chip voltage reference for battery fuel gauging.
The voltage regulator operates at a wide range of voltages, 4.0 - 25 volts. This voltage is regu-
lated to a constan t supply voltage of nominally 3.3 volts for the integrated log ic and analog
functions.
The battery protection monitor s the battery voltage and charge/discharge current to detect illega l
conditions and protect the battery from these when requ ired. The illegal conditions are deep
under-voltage during di scharging, short- circuit durin g discharg ing and ove r-current d uring charg-
ing and dischar gin g.
PORTA (8)TWI
SRAMFlash
CPU EEPROM
PV2
NV
OPC
OC
OD
FET
Control
Battery
Protection
Voltage
ADC
Voltage
Reference
Coulumb
Counter ADC
GND
VCC
RESET Power
Supervision
POR &
RESET
Watchdog
Oscillator
Watchdog
Timer
Oscillator
Circuits /
Clock
Generation
PPI
NNI
PVT
SGND
VREF
VREFGND
PI
NI
PA7..0
PA3..0
16 bit T/C1
8 bit T/C0
PORTB (8)
PB7..0
JTAG
Wake-Up
Timer
Voltage
Regulator
Charger
Detect
VFET
VREG
BATT
PV1
DATA BUS
PORTC (1)
PC0SCASCL
Cell
Balancing PV3
PV4
PORTD (2)
PD1..0
XTAL1
XTAL2
42548F–AVR–03/2013
ATmega406
The integrated cell balancing FETs allow cell balancing algorithms to be implemented in
software.
The MCU provides the following features: 40 K b ytes of In-System Programmable Flash with
Read-While-Write capabilities, 512 bytes EEPROM, 2K byte SRAM, 32 general purpose working
registers, 18 general purpose I/O lines, 11 high-voltage I/O lines, a JTAG Interface for On-chip
Debugging support and programming, two flexible Timer/Counters with PWM and compare
modes, one Wake-u p Time r, an SM-B us compliant TWI module, internal and external inte rrup ts,
a 12-bit Sigma Delta ADC for voltage and temperature measurements, a high resolution Sigma
Delta ADC for Coulomb Counting and instantaneous current measurements, a programmable
Watchdog Timer with internal Oscillator, and four software selectable power saving modes.
The AVR core combines a rich instruction set with 32 general purpose working registers. All the
32 registers are directly 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 achiev ing throughputs up to ten times faster than con-
ventional CISC microcontrollers.
The Idle mode stops the CPU while allowing the other chip function to continue functioning. The
Power-down mode allows the voltage regula tor, battery protection , regulator current detection ,
Watchdog Timer, and Wake-up Timer to o perate, while disabling all other chip functions until the
next Interrupt or Hardware Reset. In Po wer-save mode, the Wake-up Timer and Coulomb Coun-
ter ADC continues to run.
The device is manufactured using Atmel’s high voltage high density non-volatile memo ry tech-
nology. The On-chip ISP Flash allows the program memory to be reprogrammed In-System, by
a conventional non-volatile memory programmer or by an On-chip Boot 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 upda ted, providing true Read-Wh ile-Write operation. By combining
an 8-bit RISC CPU with In-System Self-Programm able Flash, fuel gauging ADCs, dedicated bat-
tery protection cir cuitry, Cell Balancing FETs, and a voltage regulator on a monolithic chip, the
Atmel ATmega406 is a powerful microcontroller that provides a highly flexible and cost effective
solution for Li-ion Smart Battery applications.
The ATmega406 AVR is supported with a full suite of program and system development tools
including: C Compilers, Macro Assemblers, Program Debugger/Simulators, and On-chip
Debugger.
5
2548F–AVR–03/2013
ATmega406
2.2 Pin Descriptions
2.2.1 VFET High voltage supply pin. This pin is used as suppl y for the internal vo ltage regulator, descr ibed in
”Voltage Regulator” on page 114. In addition the voltage level on this pi n is monitored by the bat-
tery protection circuit, for deep-under-voltage protection. For details, see ”B atte ry Prot ection ” on
page 125.
2.2.2 VCC Digital supply voltage. Normally connected to VREG.
2.2.3 VREG Output from the internal Voltage Regulator. Used for external decoupling to ensure stable regu-
lator operation. For details, see ”Voltage Regulator” on page 114.
2.2.4 VREF Internal Voltage Reference for external decoupling. For details, see ”Voltage Reference a nd
Temperature Sensor” on page 121.
2.2.5 VREFGND Ground for decoupling of Internal Voltage Reference. For details, see ”Voltage Reference and
Temperature Sensor” on page 121.
2.2.6 GND Ground
2.2.7 SGND Signal ground pin, used as reference for Voltage-ADC conversions. For details, see ”Voltage
ADC – 10-channel General Purpose 12-bit Sigma-Delta ADC” on page 116.
2.2.8 Port A (PA7:PA0)
PA3:PA0 serves as the analog inputs to the Voltage A/D Converter.
Port A also serves as a low-voltage 8-bit bi-d irectional I/O port with internal pull-up resistors
(selected for each bit). As inputs, Port A pins that are externally pulled low will source current if
the pull-up resistors are activated. The Port A pi ns are tri-stated when a reset co ndition becomes
active, even if the clock is not running.
Port A also serves the functions of variou s sp ecial featu res of th e ATmega 40 6 as listed in ”Alter-
nate Functions of Port A” on page 68.
2.2.9 Port B (PB7:PB0)
Port B is a low-voltage 8-bit bi-directional I/O port with internal pull-up resistors (selected for
each bit). As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. Th e Port B pins are tri-stated when a reset co ndition becomes active,
even if the clock is not running.
Port B also serves the functions of variou s sp ecial featu res of th e ATmega 40 6 as listed in ”Alter-
nate Functions of Port B” on page 70.
62548F–AVR–03/2013
ATmega406
2.2.10 Port C (PC0) Port C is a high voltage Open Drain output port.
2.2.11 Port D (PD1:PD0)
Port D is a low-voltage 2-bit bi-directional I/O port with internal pull-up resistors (selected for
each bit). 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.
Port D also serves the functions of various special features of the ATmega406 as listed in ”Alter-
nate Functions of Port D” on page 72.
2.2.12 SCL SMBUS clock, Open Drain bidirectional pin.
2.2.13 SDA SMBUS data, Open Drain bidirectional pin.
2.2.14 OC/OD/OPC High voltage output to drive external Charge/Discharge/Pre-charge FETs. For details, see ”FET
Control” on page 133.
2.2.15 PPI/NNI Unfiltered positive/negative input fro m external current sense resistor, used by the batte ry pro-
tection circuit, for over-current and short-circuit detection. For details, see ”Battery Protection” on
page 125.
2.2.16 PI/NI Filtered positive/negative input from external current sense resistor, used to by the Coulomb
Counter ADC to measure charge/discharge currents flowing in the battery pack. For details, see
”Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC” on page 106.
2.2.17 NV/PV1/PV2/PV3/PV4
NV, PV1, PV2, PV3, and PV4 are the inputs for battery cells 1, 2, 3 and 4, used by the Voltage
ADC to measure each cell voltage. For details, see ”Voltage ADC – 10-channel Ge neral Pur-
pose 12-bit Sigma-Delta ADC” on page 116.
2.2.18 PVT PVT defines the pull-up level for the OD output.
2.2.19 BATT Input for detecting when a charger is connected. This pin also defines the pull-up level for OC
and OPC outputs.
2.2.20 RESET Reset input. A low level on this pin for longer than the minimum pulse length will gen erate a
reset, even if the clock is not running. The minimum pulse length is given in Table 11 on page
38. Shorter pulses are not guaranteed to generate a reset.
7
2548F–AVR–03/2013
ATmega406
2.2.21 XTAL1 Input to the inverting Oscillator amplifier.
2.2.22 XTAL2 Output from the inverting Oscillator amplifier.
3. Resources A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr.
4. About Code Examples
This documentatio n contains simple co de examples that briefly show how to u se various parts of
the device. These code examp les assume that the part specific header file is included b efore
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handlin g in C is com piler d epend ent. Plea se confir m with th e C com piler d ocume n-
tation for more details.
For I/O Registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI”
instructions must be replaced with instructions that allow access to extended I/O. Typically
“LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.
82548F–AVR–03/2013
ATmega406
5. AVR CPU Core
5.1 Introduction 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.
5.2 Architectural Overview
Figure 5-1. Block Diagram of the AVR Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for progr am and data. Instructions in the program memory are
executed w ith a sin gle le ve l pip e lining. While one instruc tion is being executed, the next instruc-
tion is pre-fetched from the program memory. This concept enables instructions to be executed
in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
Watchdog
Timer
I/O Module 2
I/O Module1
I/O Module n
9
2548F–AVR–03/2013
ATmega406
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 typ-
ical ALU operation, two operands are output from the Regi ster File, the op eration is exec uted,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficien t address calculations. One of the these addre ss pointers
can also be used as an address pointer for loo k up tables in Flash prog ram memory. These
added function registers are the 16-bit X-, Y-, and Z-register , described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single r egister o perations can also be executed in the ALU. After an arithmetic opera-
tion, the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and uncon ditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word for-
mat. Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and the
Application Program section. Both sections have dedicated Lock bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot Program section.
During interrupts and subroutine ca lls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
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 r egular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector posi-
tion. The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Regis-
ters, SPI, and other I/O fun ctions. The I/O Memory can be access ed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F. In addition, the ATmega406
has Extended I/O space from 0x60 - 0xFF in SRAM where only the ST/STS/STD and
LD/LDS/LDD instructions can be used.
5.3 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a registe r an d an immed iate ar e executed . Th e ALU opera tio ns are divided
into three main categories – arithmetic, logical, and bit-functions. Some im plementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction Set” section for a detailed description.
10 2548F–AVR–03/2013
ATmega406
5.4 Status Register
The Status Register contai ns information a bout the r esult of th e most r ecently executed ari thme-
tic instruction. This information can 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 ”AVR Instruction Set” description. This will in many cases remove the need for
using the dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored
when returning from an inte rr up t. T his mu st be hand le d by so ftware.
5.4.1 SREG – AVR Status Register
The AVR Status Register – SREG – is defined as:
Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual inter-
rupt enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent 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 th e SEI and CLI instructions, as described in the ”AVR Instruction Set”
description.
Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or desti-
nation 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 r egister in the Register File by th e
BLD instruction.
Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful
in BCD arithmetic. See the ”AVR Instruction Set” for detailed information.
Bit 4 – S: Sign Bit, S = N V
The S-bit is always an exclusive or between the neg ative flag N and the Two’s Complement
Overflow Flag V. See the ”AVR Instruction Set” 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 ”AVR
Instruction Set” for detailed information.
Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative re sult in an arithmeti c or logi c operation. See the ”AVR
Instruction Set” for detailed information.
Bit 76543210
0x3F (0x5F) I T H S V N Z C SREG
Read/Write R/W R/W R/WR/WR/WR/WR/WR/W
Initial Value 0 0 0 0 0 0 0 0
11
2548F–AVR–03/2013
ATmega406
Bit 1 – Z: Zero Flag
The Zero Flag Z ind ica tes a zer o r esult in an arithmetic or logic operation. See the ” AVR Instruc-
tion Set” for detailed information.
Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the ”AVR Instruction
Set” for detailed information.
5.5 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruc tion set. In order t o 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 5-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 5-2. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 5-2, each register is also assigned a d ata memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically imple-
mented as SRAM locations, this memory organizati on 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.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte
12 2548F–AVR–03/2013
ATmega406
5.5.1 The X-register, Y-register, and Z-register
The registers R2 6:R31 have some added functions to their general pur pose usage. Th ese regis-
ters are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 5-3.
Figure 5-3. The X-, Y-, and Z-registers
In the different addr essing modes these ad dr ess register s have functions a s fixed disp lacem ent,
automatic incr ement, and automa tic decrement (see the ”AVR Instruction Set” description for
details).
5.6 Stack Pointer The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Sta ck is impl emented as gr owing from hig her memor y loca-
tions to lower memory locations. This implies that a Stack PUSH command decr ease s th e Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. T he Stack Pointer must be set 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 incre mente d by two when
data is popped from the Stack with return from subr ou tin e RET or re tu rn 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 implementa-
tions of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
15 XH XL 0
X-register 7 0 7 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 0 7 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 7 0 7 0
R31 (0x1F) R30 (0x1E)
13
2548F–AVR–03/2013
ATmega406
5.6.1 SPH and SPL – Stack Po in te r Regis ter
5.7 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clkCPU, directly generated fro m the selected clock source for the
chip. No internal clock division is used.
Figure 5- 4 shows the parallel instruction fetches and instruction executions enabled by the Har-
vard archit ecture and the fast-ac cess Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
Figure 5-4. The Parallel Instruction Fetches and Instruction Executions
Figure 5-5 shows the internal timi ng con cept for the Reg ister File. In a single clock cycl e an ALU
operation using two register operands is executed, and the result is stored back to the destina-
tion register.
Figure 5-5. Single Cycle ALU Operation
Bit 151413121110 9 8
0x3E (0x5E) SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value00000000
00000000
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPU
14 2548F–AVR–03/2013
ATmega406
5.8 Reset 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 are
assigned individual enable bits which must be writte n logic one togeth er with the Global Inter rupt
Enable bit in the Status Register in orde r to enable the interrupt. Depending on the Program
Counter value, interrupts ma y 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 195 for de tails.
The lowest addresses in the progra m memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in ”Interrupts” on page 51. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the highest priority. The Interrupt Vectors can be moved to the start of
the Boot Flas h sectio n by setting the IVSEL bit in the MCU C ontr ol Regist er ( MCUCR ). Refer t o
”Interrupts” on page 51 for more information. The Reset Vector can also be moved to the start of
the Boot Flash section by prog ra mming the BOOTRST Fuse , see ”Boot Loade r Support – Rea d-
While-Write Self-Programming” on page 178.
When an interrupt occurs, the Glob al Interrupt Enable I-bit is cleared and all interrupts are dis-
abled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is au tomatically 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 execute the interrupt handling routine, and hardware clears the correspon ding inter-
rupt flag. Interrupt flags can also be cleared by writing a logic one to th e f l ag bit po sit ion (s) to be
cleared. If an interr upt condition occurs while the cor responding interr upt enable bit is cleared ,
the interrupt flag will be set and remembered until the interrupt is enabled, or the flag is cleared
by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable
bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the Global
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. The se
interrupts do not necessarily have interrupt flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
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 serve d.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
15
2548F–AVR–03/2013
ATmega406
CLI instruction. The following example shows how this can be used to avoid interrupt s during the
timed EEPROM write sequence.
When using the SEI instruction to enable interrupts, the instruction following SEI will be exe-
cuted before any pending interrupts, as shown in this example.
5.8.1 Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles mini-
mum. After four clock cycles the program vector add ress fo r the actua l inte rr upt ha nd ling r outine
is executed. During this four clock cycle period, the Program Counter is pushed onto 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 b y four clock cycles. This increase comes in addition to the
start-up time from the selected sleep mode.
A return from an interrupt handling routine takes four clock cycles. During these four clock
cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is
incremented by two, and the I-bit in SREG is set.
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) */
Assembly Code Example
sei ; set Global Interrupt Enable
sleep; enter sleep, waiting for interrupt
; note: will enter sleep before any pending
; interrupt(s)
C Code Example
_SEI(); /* set Global Interrupt Enable */
_SLEEP(); /* enter sleep, waiting for interrupt */
/* note: will enter sleep before any pending interrupt(s) */
16 2548F–AVR–03/2013
ATmega406
6. AVR Memories
This section describes the differ en t me mori es in the ATme ga 406 . The AVR a rchitecture has two
main memory spaces, the Data Memory and the Program Memory space. In addition, the
ATmega406 features an EEPROM Memory for data storage. All three memory spaces are linear
and regular.
6.1 In-System Reprogrammable Flash Program Memory
The ATmega406 contains 40K bytes On-chip In-System Reprogrammable Flash memory for
program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as
20K x 16. For software security, the Flash Program memory space is divided into two sections,
Boot Program section and Application Program section.
The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATmega406
Program Count er (PC) is 15 bits wide , th us addressing th e 20 K p rogr am m emo ry lo cat i on s. The
operation of Boot Program section and associa ted Boot Lock bits for software protection are
described in detail in ”Boot Loader Support – Rea d-While-Write Self-Programming” on pag e
178. ”Memory Programming” on page 195 contains a detailed description on Flash data serial
downloading.
Constant tables can be allocated within the entire program memory address space (see the LPM
– Load Program Memory instruction description).
Timing diagrams for instruction fetch and execution are presented in ”Instruction Execution Tim-
ing” on page 13.
Figure 6-1. Program Memory Map
0x0000
0x4FFF
Program Memory
Application Flash Section
Boot Flash Section
17
2548F–AVR–03/2013
ATmega406
6.2 SRAM Data Memory
Figure 6-2 shows how the ATmega406 SRAM Memory is organized.
The ATmega406 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/ST D and LD/LDS/LDD instruc-
tions can be used.
The lower 2,304 data memory locations address both the Register File, the I/O memory,
Extended I/O memory, and the internal data SRAM. The first 32 locations address the Register
File, the next 64 location the standard I/O memory, then 160 locations of Extended I/O memory,
and the next 2,048 locations address the internal data SRAM.
The five different addressing modes for the data memory cover: Direct, Indirect with Displace-
ment, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register
File, registers R26 to R31 feature the indirect addressing pointer registers.
The direct addressing reaches the entire data space.
The Indirect with Displacement mo de reaches 63 addre ss locations from the base address given
by the Y- or Z-register.
When using register indirect addressing modes with automatic pre-decrement and post-incre-
ment, the address registers X, Y, and Z ar e decremented or incremented.
The 32 general purpose working registers, 64 I/O Registers, 160 Extended I/O Registers, and
the 2,048 bytes of internal data SRAM in the ATmega406 are all accessible through all these
addressing modes. The Register File is described in ”General Purpose Register File” on page
11.
Figure 6-2. Data Memor y Map
32 Registers
64 I/O Registers
Internal SRAM
(2048 x 8)
0x0000 - 0x001F
0x0020 - 0x005F
0x08FF
0x0060 - 0x00FF
Data Memory
160 Ext I/O Reg.
0x0100
18 2548F–AVR–03/2013
ATmega406
6.2.1 Data Memory Access Times
This section describes the general access timing concepts for internal memory access. The
internal data SRAM access is performed in two clkCPU cycles as described in Fi gu r e 6- 3.
Figure 6-3. On-chip Data SRAM Access Cycles
6.3 EEPROM Data Memo ry
The ATmega406 contains 512 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 endurance of at
least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described
in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and
the EEPROM Control Register.
For a detailed description of Serial and Parallel data downloading to the EEPROM, see page
211 and page 199 respectively.
6.3.1 EEPROM Read/Write Access
The EEPROM Access Registers are accessible in the I/O space.
The write access time for the EEPROM is given in Table 6-1. A self-timing function, however,
lets the user software detect when the next byte can be written. If th e user code contains instruc-
tions that write the EEPROM, some precautions must be taken.
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 EEPROM is written, the CPU is halted for two clock cycles before the next
instruction is executed.
clk
WR
RD
Data
Data
Address Address valid
T1 T2 T3
Compute Address
Read Write
CPU
Memory Access Instruction Next Instruction
19
2548F–AVR–03/2013
ATmega406
6.3.2 EEARH and EEARL – The EEPROM Address Register
Bits 15:9 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bits 8:0 – EEAR8:0: EEPROM Address
The EEPROM Address Registers – EEARH and EEARL specify the EEPROM address in the
512 bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and
511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM
may be accessed.
6.3.3 EEDR – The EEPROM Data Register
Bits 7:0 – EEDR7:0: EEPROM Data
For the EEPROM write oper ation, 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.
6.3.4 EECR – The EEPROM Control Register
Bits 7:6 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bits 5:4 – EEPM1 and EEPM0: EEPROM Programming Mode Bits
The EEPROM Programming mode bit setting defines which programming action that will be trig-
gered when writing EEPE. It is possible to program data in one atomic operation (erase the old
value and program the new value) or to split the Erase and Write operations in two different
operations. The Pr ogrammin g times for th e differen t modes ar e shown in Table 6-1. While EEPE
is set, any write to EEPMn will be ignored. During reset, the EEPMn bits will be reset to 0b00
unless the EEPROM is busy programming.
Bit 151413121110 9 8
0x22 (0x42) EEAR8 EEARH
0x21 (0x41) EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL
76543210
Read/Write RRRRRRRR/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 X
XXXXXXXX
Bit 76543210
0x20 (0x40) MSB LSB EEDR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x1F (0x3F) EEPM1 EEPM0 EERIE EEMPE EEPE EERE EECR
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 X X 0 0 X 0
20 2548F–AVR–03/2013
ATmega406
Bit 3 – EERIE: EEPROM Ready Interrupt Enable
Writing EERIE to one enables the EEPROM Ready Interr upt if the I bit in SREG is set. Writing
EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant inter-
rupt when EEPE is cleared.
Bit 2 – EEMPE: EEPROM Master Programming Enable
The EEMPE bit determines whether setting EEPE to one causes the EEPROM to be written.
When EEMPE is set, setting EEPE within four clock cycles will write data to the EEPROM at the
selected address If EEMPE is zero, setting EEPE will have no effect. When EEMPE has been
written to one by software, hardware clears the bit to zero after four clock cycles. See the
description of the EEPE bit for an EEPROM write procedure.
Bit 1 – EEPE: EEPROM Programming Enable
The EEPROM Write Enable Signal EEPE is the write strobe to the EEPROM. When address
and data are correctly set up, the EEPE bit must be written to one to write the value into the
EEPROM. The EEMPE bit must be written to one before a logical one is written to EEPE, other-
wise no EEPROM write takes place. The following procedure should be followed when writing
the EEPROM (the order of steps 3 and 4 is not essential):
1. Wait until EEPE becomes zero.
2. Wait until SELFPRGEN in SPMCSR 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 EEMPE bit while writing a zero to EEPE in EECR.
6. Within four clock cycles after setting EEMPE, write a logical one to EEPE.
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 relevant if the software contains a Boot Loader allowing the CPU to program the
Flash. If t he F l as h is n e ve r b ein g up da ted by the CPU, step 2 ca n b e om itt ed . Se e ”Boot Loader
Support – Read-While-Write Self-Programming” on page 178 for details about Boot
programming.
Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since the
EEPROM Master Write Enable will time-out. If an interrupt routine accessing 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.
Table 6-1. EEPROM Mode Bits
EEPM1 EEPM0 Programming
Time Operation
0 0 3.4 ms Erase and Write in one operation (Atomic Operation)
0 1 1.8 ms Erase Only
1 0 1.8 ms Write Only
1 1 Reserved for future use
21
2548F–AVR–03/2013
ATmega406
When the write access time has elapsed, the EEPE bit is cleared by hardware. The user soft-
ware can poll this bit and wait for a zero before writing the next byte. When EEPE 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 Signal EERE is the re ad strobe to the EEPROM. When the correct
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 immediately. When the EEPROM is read, the CPU is halted for four cycles before the
next instruction is executed.
The user should poll the EEPE 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 Oscillator is used to time the EEPROM ac cesses. Table 6-2 lists the typic al pro-
gramming time for EEPROM access from the CPU.
The following code examples show one assembly and one C function for writing to the
EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts glob-
ally) so that no interrupts will occur during ex ecution 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.
Table 6-2. EEPROM Programming Time
Symbol Number of Calibrated RC Oscillator Cycles Typ Programming Time
EEPROM write
(from CPU) 26,368 3.3 ms
22 2548F–AVR–03/2013
ATmega406
The next code examples show assembly and C functions for reading the EEPROM. The exam-
ples assume that interrupts are controlled so that no interrupts will occur during execution of
these functions.
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);
}
23
2548F–AVR–03/2013
ATmega406
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;
}
24 2548F–AVR–03/2013
ATmega406
6.4 I/O Memory The I/O space defin i tio n of the AT me g a4 06 is show n in ”Register Summary” on page 236.
All ATmega406 I/Os and peripherals are placed in the I/O space. All I/O locations may be
accessed by the LD/L DS/LDD and ST/STS/STD in structions, transferring dat a between the 32
general purpose working registers and the I/O space. I/O Registers within the address range
0x00 - 0x1F are directly bit-accessible using the SBI and CBI instru ctions. 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 ATmega406 is a complex
microcontroller with more peripheral units than can be supported within the 64 location reserved
in Opcode for the IN an d OUT instructions. For the Extended I/O space from 0x60 - 0xFF in
SRAM, only the ST/ST S/ST D an d LD/LDS/LDD instruct ion s can be us ed.
For compatibility with future devices, reserved bits should be written to zero if accessed.
Reserved I/O memory addresses should never be written.
Some of the status flags are clear ed by writing a logical o ne to them. Note that, unlike most other
AVRs, the CBI and SBI instructions will only oper ate on the specified bit, and can therefore be
used on registers containing such status flags. The CBI and SBI instructions work with registers
0x00 to 0x1F only.
The I/O and peripherals control registers are explained in later sections.
6.4.1 General Purpose I/O Registers
The ATmega406 contains three Genera l Purpose I/O Registers. These r egisters can be used for
storing any information, and they are particularly useful for storing global variables and Status
Flags. General Purpose I/O Registers within the address range 0x00 - 0x1F are directly bit-
accessible using the SBI, CBI, SBIS, and SBIC instructions.
6.4.2 GPIOR2 – Ge n era l Purpo se I/O Re gi st er 2
6.4.3 GPIOR1 – Ge n era l Purpo se I/O Re gi st er 1
6.4.4 GPIOR0 – Ge n era l Purpo se I/O Re gi st er 0
Bit 76543210
0x2B (0x4B) MSB LSB GPIOR2
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value00000000
Bit 76543210
0x2A (0x4A) MSB LSB GPIOR1
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value00000000
Bit 76543210
0x1E (0x3E) MSB LSB GPIOR0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value00000000
25
2548F–AVR–03/2013
ATmega406
7. System Clock and Clock Options
7.1 Clock Systems and their Distribution
Figure 7-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 r educe power co nsumpt ion, th e clo cks to modul es
not being used can be halted by using different sleep modes, as described in ”Power Manage-
ment and Sleep Modes” on page 31. The clock systems are detailed below.
Figure 7-1. Clock Distribution
7.1.1 CPU Clock – clkCPU
The CPU clock is routed to parts of the system concerned with operation of the AVR core.
Examples of such modules are the General Purpose Register File, the Status Register and the
data memory holding the Stack Pointer. Halting the CPU clock inhibits the core from performing
general operations and calculations.
7.1.2 TWI Cloc k - clk TWI
The TWI module is provided with a dedicated clock domain. This is because the TWI module
requires a 4 MHz clock to achieve the specified Data Transfer Speed. It also allows power
reduction by halting the clkTWI clock when T WI communication is not used. Note that address
match detection in the TW I module is carried out asynchronously when clkTWI is halted, enabling
TWI address watch detection in all sleep modes except Power-off.
7.1.3 I/O Clock – clkI/O
The I/O clock is used by the majority of the I/O modules. The I/O clock is also used by the Exter-
nal 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.
7.1.4 Flash Clock – clkFLASH
The Flash clock controls oper ation of the Fl ash interface. The Flash clock is usually active simul-
taneously with the CPU clock.
26 2548F–AVR–03/2013
ATmega406
7.1.5 Voltage ADC Clock – clkVADC
The Voltage ADC is provided with a dedicated clock domain. This allows halting the CPU and
I/O clocks in order to reduce noise generated by digital circuitry. This gives more accurate ADC
conversion results.
7.1.6 Coulomb Counter ADC Clock - clkCCADC
The Coulomb Counter ADC is pro vided with a dedica ted clock domain. This allows operating the
Coulomb Counter ADC in low power modes like Power-save for continuous current
measurements.
7.1.7 Watchdog Timer and Battery Protection Clock
The Watchdog Timer and Battery Protection are provided with a dedicated clock domain. This
allows operation in all modes except Power-off. It also allows very low power operation by utiliz-
ing an Ultra Low Power RC Oscillator dedicated to this purpose.
7.2 Clock SourcesThe device has the following clock sources. The clocks are input to the AVR clock generator,
and routed to the appropriate modules.
7.3 Calibrated Fast RC Oscillator
The calibrated Fast RC Oscillator by default provides a 4.0 MHz cl ock, which is divided down to
1.0 MHz to all modules except the TWI. The frequency is nominal value at 25C. This cl ock will
operate with no external components. During reset, hardware loads the calibration byte into the
FOSCCAL Register and thereby automatically calibrates the Fast RC Oscillator. At 25C, this
calibration gives a frequency of 4 MHz ± 3%. The oscillator can be calibrated to any frequency in
the range 3.7 - 4.0 MHz within ±1% accuracy, by changing the FOSCCAL register. For more
information o n the pre-programme d calibration value, see the s ection ”Calibration Bytes” on
page 198.
The start-up times for the Fa st RC Oscillator are determined by the SUT Fuses as shown in
Table 7-1 on page 26.
Note: 1. The device is shipped with this option selecte d.
Table 7-1. Start-up times for the internal calibrated RC Oscillator clock selection
SUT1:0 Start-up Time from Power-down
and Power-save Additional Delay from Reset
00 6 CK 14CK
01 6 CK 14CK + 4.1 ms
10 6 CK 14CK + 65 ms(1)
11 Reserved
27
2548F–AVR–03/2013
ATmega406
7.4 32 kHz Crystal Oscillator
XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifie r which can be con-
figured for use as an On-chip Oscillator, as shown in Figure 7- 2. This Oscillator is optimized for
use with a 32.768 kHz watch crystal.
C1 and C2 should always be equal. The optimal value of the capacitors depends on the crystal
or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the envi-
ronment. For information on how to choose capacitors and other details on Oscillator operation,
refer to the 32 kHz Crystal Oscillator applic ation note.
Figure 7-2. 32 kHz Crystal Oscillator Connections
7.5 Slow RC Oscillator
The Slow RC Oscillator provides a fixed 131 kHz clock. This clock source can be used as a
backup clock source in case of 32 kHz Crystal Os cillator failure. It can also be used as the only
Run-Time c lock so urce in sys tems wher e the r esulting clock accuracy is acceptable. To provide
good accuracy when used as a Run-Time clock source, the slow RC Oscillator has a calibration
byte stored in the signature address space. See the section ”Calibration Bytes” on page 198. In
order to get the actual timeout periods, the application software must use this calibration byte to
scale the WUT time-outs found in Table 10-1 on page 50.
7.6 Ultra Low Power RC Oscillator
The Ultra Low Power RC Oscillator (ULP Oscillator) provides a clock of 128 kHz. It operates at
very low power consumption, at the expe nse of frequency accuracy.
7.7 CPU, I/O, Flash, and Voltage ADC Clock
The clock source for the CPU, I/O, Flash, and Voltage ADC is the calibrated Fast RC Oscillator.
Note that the Calibrated Fast RC Oscillator will prov ide a 4 MHz clock to the TWI module and a
1 MHz clock to all other modules.
When the CPU wakes up from Power-down or Power-save, the CPU clock source is used to
time the start-up, ensu ring a stable clock before instruction execution s tarts. When the CPU
starts from reset, there is an additional delay allowing the voltage regulator to reach a stable
level before commencing normal operation. The Ultra Low Power RC Oscillator is used for tim-
ing this real-time part of the start-up time. Start-up times are determined by the SUT Fuses as
XTAL2
XTAL1
GND
C2
C1
28 2548F–AVR–03/2013
ATmega406
shown in Table 7-2. The number of Ultra Low Power RC Oscillator cycles used for each time-out
is shown in Table 7-3.
7.8 Coulomb Counter ADC and Wake-up Timer Clock
The Coulomb Counter ADC and Wake-up Timer clock operates asynchronously with the CPU
clock, to allow low p ower operation in slee p modes. The clock source is eith er the 32 kHz Crysta l
Oscillator, or the Slow RC Oscillator (divided by 4). The selected clock is input to the AVR Clock
Control Unit, and is routed to the appropriate modules.
The clock source for the Coulomb Counter ADC and Wake-up Timer is selected by an I/O bit in
the Clock Control and Status Register, see ”Run-Time Clock Source Select” on page 28 for
details.
7.9 Watchdog Timer and Battery Protection Clock
The clock source for the Watchdog T imer and Battery Protection is the Ultra Low Power RC
Oscillator. The Oscillator is automatically enabled in all operational modes where either the
Watchdog Timer, the Battery Protection, or both, are enabled. It is also enabled during reset.
7.10 Run-Time Clock Source Select
The clock source for the Coulomb Counter ADC and Wake-up Timer is run-time selectable as
either the 32 kHz Crystal Oscillator, or the Slow RC oscillator (divided by 4). The clock source is
selected by an I/O bit in the Clock Control and Status Register.
The 32 kHz Crystal Oscillator is the recommended clock source in order to achieve the highest
clock accuracy. The Slow RC Oscillator is provided as a clock source for low cost systems, or as
an alternate clock source in case of crystal clock failure. If the CPU detects that the crystal clock
is not operating correctly, it can switch to the Slow RC Oscillator as a less accurate, but still func-
tional, backup solution.
Table 7-2. Start-up Times for the Calibrated Fast RC Oscillator
SUT1:0 Start-up Time from Power-down
and Power-save Additional Delay from Reset
00 6 CK 14CK
01 6 CK 14CK + 3.9 ms
10 6 CK 14CK + 62.5 ms
11 Reserved
Table 7-3. Number of Ultra Low Power RC Oscillator Cycles
Typ Time-out Number of Cycles
3.9 ms 500
62.5 ms 8000
29
2548F–AVR–03/2013
ATmega406
7.11 Register Description
7.11.1 FOSCCAL – Fast RC Oscillator Calibration Register
Bits 7:0 – FCAL7:0: Fast RC Oscillator Calibration Value
The Fast RC Oscillator Calibration Register is used to trim the Fast RC Oscillator to remove pro-
cess variations from the oscillator frequency. The factory-calibrated value is automatically
written to this register during chip reset, giving an oscillator frequency of 4.0 MHz at 25°C. The
application software can write this register to change the oscillator frequency. The osc illator can
be calibrated to any frequency in the range 3.7 - 4.0 MHz within ±1% accuracy. Calibration out-
side that range is not guaranteed.
Note that this oscillator is used to time EEPROM and Flash write acc esses, and these write
times will be affected accordingly. If the EEPROM or Flash are written, do not calibrate to more
than 4.4 MHz. Otherwise, the EEPROM or Flash write may fail.
The FCAL7 bit determines the range of operation for the oscillator. Setting this bit to 0 gives the
lowest frequency range, setting this bit to 1 gives the highest frequency range. The two fre-
quency ranges are overlapping, in other words a setting of FOSCCAL = 0x7F gives a higher
frequency than FOSCCAL = 0x80.
The FCAL6:0 bits are used to tune the frequency within the selected range. A setting of 0x00
gives the lowest frequ ency in that range, a nd a setting of 0x7F gives the highest frequency in the
range. Incrementing FCAL6:0 by 1 will give a frequency increment of less than 2% in the fre-
quency range 3.7 - 4.0 MHz.
7.11.2 CCSR – Clock Control and Status Register
Bits 7:2 - Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 1 - XOE: 32 kHz Crystal Oscillator Enable
The XOE bit is used to enable the 32 kHz Crystal Oscillator before it is selected as clock source.
This allows the Oscillator clock to stabilize prior to use. The 32 kHz Crystal Oscillator requires
approximately two seconds to stab ilize, this must be timed by the user software. If the software
tries to write a one to ACS and a zero to X OE at the same time, both XOE and ACS will be
cleared by the hardware. Thus, while the 32 kHz Crystal Oscillator is disabled it is not possible to
select it as a clock source .
Bit 76543210
(0x66) FCAL7 FCAL6 FCAL5 FCAL4 FCAL3 FCAL2 FCAL1 FCAL0 FOSCCAL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value Device Specific Calibration Value
Bit 76543210
(0xC0) XOE ACS CCSR
Read/Write R R R R R R R/W R/W
Initial Value00000000
30 2548F–AVR–03/2013
ATmega406
Bit 0 - ACS: Asynchronous Clo ck Select
The ACS bit is used to selected the source of the asynchronous clock for the Coulomb Counter
ADC and Wake-up Timer. The Slow RC Oscillator is selected when this bit is cleared (zero). The
32 kHz Crystal Oscillator is selected when this bit is set (one).
The selected clock source and oscillator enable conditions are illustrated in Table 7-4.
Recommended algorithm for switching from the RC Oscillator to the Crystal Oscillator as the
asynchronous clock for the Coulomb Counter ADC and Wake-up Timer:
1. Enable the Crystal Oscillator by setting the XOE bit (one).
2. Enable the Wake-up Timer, select a two second timeout, and reset the Wake-up Timer
(”Wake-up Timer” on page 49 for details).
3. Wait for the Wake-up Timer time-out.
4. Switch to the Crystal Oscillator by setting the ACS bit (one) while keeping the XOE bit set
(one).
5. Optional: Wait for another Wake-up Timer time-out, to ensure the Crystal Oscillator is
operating correctly. This can be done by enabling another timer inte rrupt with significantly
longer time-o u t, an d ch ec king tha t the Wake-up Timer time- o ut oc cu rs first.
Recommended algorithm for switching from the Crystal Oscillator to the RC Oscillator as the
asynchronous clock for the Coulomb Counter ADC and Wake-up Timer:
1. Switch to the RC Oscillator by clearing the ACS bit (zero) while keeping the XOE bit set
(one).
2. Disable the Crystal Oscillator by clearing the XOE bit (zero) while keeping the ACS bit
cleared (zero).
Table 7-4. Asynchronous Clock Source and Oscillator Enable Conditions
Sleep Mode 32 kHz Crystal
Oscillator Enable Slow RC
Oscillator Enable
Power-off or Power-down 0 0
Other Sleep Modes XOE ACS & (CADEN | WUTEN)
Active Mode XOE 1
31
2548F–AVR–03/2013
ATmega406
8. Power Management and Sleep Modes
Sleep modes enable the application to shut down unused modules in the MCU, thereby saving
power. The AVR provides vario us sleep modes allowing the user to tailor the power consump-
tion to the application’s requirements.
To enter any of the five sleep modes, the SE bit in SMCR must be written to logic one and a
SLEEP instruction must be executed. The SM2:0 bits in the SMCR Register select which sleep
mode (Idle, ADC Noise Reduction, Power-down, Power-save, or P ower-off) will be activated by
the SLEEP instruction. See Table 8-1 for a summar y. If an enabled interrupt occurs while the
MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition
to the start-up time, execute s the interrupt routine, and resum es execution from the instruction
following SLEEP. The contents of the register file and SRAM are unaltered when the device
wakes up from any sleep mode except Power-off. If a reset occurs during slee p mo de , th e M CU
wakes up and executes from the Reset Vector. The MCU will reset when returning from Pow er-
off mode.
Figure 7-1 on page 25 presents the d ifferent clock systems in the ATmega406, and their distri-
bution. The figure is helpful in selecting an appropriate sleep mode.
8.0.1 SMCR – Sleep Mode Control Register
The Sleep Mode Control Register contains control bits for power management.
Bits 7:4 – Res: Reserved Bits
These bits are reserved bits in the ATmega406, and will always read as zero.
Bits 3:1 – SM2:0: Sleep Mode Select Bits 2, 1 and 0
These bits select between the five a vailable sleep modes as shown in Table 8-1.
Note: 1. SMCR is auto-cleared after 4 cycles when this value is set and the SE bit is written to logic
one. To enter this mode, execute SLEEP instruction within 4 cycles after writing SE to logic
one.
Bit 76543210
0x33 (0x53) SM2 SM1 SM0 SE SMCR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 8-1. Sleep Mode Select
SM2 SM1 SM0 Sleep Mode
000Idle
0 0 1 ADC Noise Reduction
010Power-down
011Power-save
100Power-off
(1)
101Reserved
110Reserved
111Reserved
32 2548F–AVR–03/2013
ATmega406
Bit 0 – SE: Sleep Enable
The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP
instruction is executed. To avoid the MCU entering the sle ep mode unless it is the programmer ’s
purpose, it is recommended to write the Sleep Enab le (SE) bit to o ne just before the exec ution of
the SLEEP instruction and to clear it immediately after waking up.
8.1 Idle Mode When the SM2:0 bits are writte n to 000 , the SLEEP instructio n makes the MCU enter Idle mod e,
stopping the CPU but allowing all peripheral functions to continue operating. This sleep mode
basically halts clkCPU and clkFLASH, while allowing the other clocks to run. Idle mode enables the
MCU to wake up from external triggere d interrupts as well as internal ones like the Timer Over-
flow interrupt.
8.2 ADC Noise Reduction Mode
When the SM2:0 bits are written to 001, the SLEEP instruction makes the MCU enter ADC
Noise Reduction mode, stopping the CPU but allowing the Voltage ADC (V-ADC), Wake-up
Timer (WUT), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection
(CBP), Voltage Ba ttery Protect ion (VBP), Wa ke-up on Re gular Curren t (WURC), 32 k Hz crystal
Oscillator (XOSC_32K) or Slow RC Os cillator (RCOSC_SLOW), the ULTRA Low Power RC
Oscillator (RCOSC_ULP), and the Fast RC Oscillator (RCOSC_FAST) to continue operating.
This sleep mode basically halts clkI/O, clkCPU, and clkFLASH, while allowing the other clocks to run.
This improves the noise environment for the Voltage ADC, enabling higher resolution
measurements.
8.3 Power-save Mode
When the SM2:0 bits are written to 011, the SLEEP in struction makes the MCU enter Power-
save mode. In this mode, the internal F ast RC Oscillator (RCOSC_FAST) is stopped, while
Wake-up Timer (WUT), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Pro-
tection (CBP), Voltage Battery Protection (VBP), Wake-up on Regular Current (WURC), 32 kHz
crystal Oscillator (XOSC_32K) or Slow RC Oscillator (RCOSC_SLOW) and the Ultra Low Power
RC Oscillator (RCOSC_ULP) continue operating.
This mode will be the default mode when application software does not require operation of
CPU, Flash or any of the periphery units running at the Fast internal Oscillator (RCOSC_FAST).
If the current through the sense resistor is so small that the Coulomb Counter cannot measure it
accurately, Regular Current dete ction should be enab led to reduce power consu mption. The
WUT keeps accurately track of the time so that battery self discharge can be calculated.
Note that if a level triggered interrupt is used for wake-up from Power-save mode, the changed
level must be held for some time to wake up the MCU. Refer to ”External Interrupts” on page 56
for details.
When waking up from Power-save mode, there is a delay from the wake-up condition occurs
until the wake-up becomes effective. This allows the clock to restart and become stable after
having been stopped. The wake-up period is defined in ”Clock Sources” on page 26.
33
2548F–AVR–03/2013
ATmega406
8.4 Power-down Mode
When the SM2:0 bits are written to 010, the SLEEP in struction makes the MCU enter Power-
down mode. In this mode, the F ast RC Oscillator (RCOSC_FAST), 32 kHz Crystal Oscillator
(XOSC_32K), and Slow RC Oscillator (RCOSC_S LOW) are stopped, while the the Ultra Low
Power RC Oscillator (RCOSC_U LP), External Interrupts, the Battery Protection and the Watch-
dog continue to operate (if enabled).
Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed
level must be held for some time to wake up the MCU. F or more details, see ”External Interrupts”
on page 56.
When waking up from Power-down mode, a delay from the wake-up condition occurs until the
wake-up becomes effective. This allows the clock to restart and become stable after having
been stopped. The wake-up period is defined in ”Clock Sources” on pag e 26.
8.5 Power-off Mode
When the SM2:0 bits are written to 100, the SLEEP instruction makes the CPU ask the voltage
regulator to shut off power to the CPU, leaving only the Regulator and the Charg er Detect Cir-
cuitry to be operational. T o ensure that the MCU enter s Power-off mode only wh en intended, the
SLEEP instruction must be executed within 4 clock cycles after the SM2..0 bits are written.
Note that before entering Power-off sleep mode, interrupts should be disabled by software. Oth-
erwise interrupts may prevent the SLEEP instruction from being executed within the time limit.
Table 8-2. Active modules in different Sleep Modes
Module
Mode
Active Idle ADC
NRM Power-
save Power-
down Power-
off
RCOSC_FAST X X X
RCOSC_ULP XXXXX
XOSC_32K/
RCOSC_SLOW XXXX
CPU X
Flash X
8-bit Timer/16-bit Timer X X
SMBus X X X(1) X(1) X(1)
V-ADC X X X
CC-ADC X X X X
External Interrupts X X X X X
CBP(2) XXXXX
VBP XXXXX
WDT XXXXX
34 2548F–AVR–03/2013
ATmega406
Note: 1. Address Match and Bus Connect/Disconnect Wake-up only.
2. When Discharge-FET is switched off, Short-circuit Protection is automatically disab led to
reduce current consumption.
The sleep mode state diagram is shown in Figure 8-1.
WUT X X X X
VREG XXXXXX
CHARGER_DETECT X
Table 8-3. Wake-up Sources for Sleep Modes
Mode
Wake-up sources
Wake-up on
Regular Current
Battery Protection
Interrupts
External Interrupts
SMBus Address
Match and Bus
Connect/Disconnect
WDT
WUT
SPM/EEPROM
Ready
CC-ADC
V-ADC
Other I/O
Charger Connect
Idle XXX X XXXXXX
ADC NRM XXX X XXXXX
Power-save XXX X XX X
Power-down XX X X
Power-off X
Table 8-2. Active modules in different Sleep Modes (Continued)
Module
Mode
Active Idle ADC
NRM Power-
save Power-
down Power-
off
35
2548F–AVR–03/2013
ATmega406
Figure 8-1. Sleep Mode State Diagram
RESET
Active
Power-off
Regulator-on
Power-downPower-save
Interrupt
Sleep
Interrupt
Sleep
Deep
Under-voltage Deep
Under-voltage
Reset From all States
Reset Time-out
Sleep or
Deep Under-voltage
Charger Connected
Idle
Interrupt
Sleep
Deep
Under-voltage
ADC NRM
Interrupt
Sleep
Deep
Under-voltage
36 2548F–AVR–03/2013
ATmega406
8.6 Power Reduction Register
The Power Reduction Register, PRR, provides a me thod to stop the clock to individual peripher-
als to reduce power consumption. The current state of the peripheral is frozen and the I/O
registers can not be written. Resources used by the peripheral when stopping the clock will
remain occupied, hence the peripheral should in most cases be disabled before stopping the
clock. Waking up a module, which is done by clearing the bit in PRR, puts the module in the
same state as before shutdown.
Module shutdown can be used in Idle mode and Active mode to significantly reduce the overall
power consumption. In all other sleep modes, the clock is already stopped.
8.6.1 PRR0 – Power Reduction Register 0
Bit 7:4 - Res: Re served bits
These bits are reserved in ATmega406 and will always read as zero.
Bit 3 - PRTWI: Power Reduction TWI
Writing a logic one to this bit shuts down the TWI by stopping the clock to the module. When
waking up the TWI again, the TWI should be re initialized to ensure proper operation.
Bit 2 - PRTIM1: Power Reduction Timer/Counter1
Writing a logic one to this bit shuts down the Timer/Counter1 module. When the Timer/Counter1
is enabled, operation will continue like before the shutdown.
Bit 1 - PRTIM0: Power Reduction Timer/Counter0
Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0
is enabled, operation will continue like before the shutdown.
Bit 0 - PRVADC: Power Reduction V-ADC
Writing a logic one to this bit shuts down the V-ADC. The V-ADC must be disabled before shut
down.
Bit 7654 3 2 1 0
(0x64) ––––PRTWIPRTIM1PRTIM0PRVADCPRR0
Read/WriteRRRRR/WR/WR/WR/W
Initial Value0000 0 0 0 0
37
2548F–AVR–03/2013
ATmega406
8.7 Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR
controlled system. In general, sleep modes should be used as much as possible, and the sleep
mode should be selected so that as few as possi ble of the device’s functions are operating. All
functions not needed should be disabled. In particular, the following modules may need special
consideration when trying to achieve the lowest possible power consumption.
8.7.1 Watchdog Timer
If the Watchdog Timer is not needed in the application, the module should be turned off. I f the
Watchdog Timer is enabled, it will be enabled in all sleep modes except Power-off. The Watch-
dog Timer current consumption is significant only in Power-down mode. See ”Watchdog Timer”
on page 43 for details on how to configure the Watchdog Timer.
8.7.2 Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The
most important is then to ensure that no pins drive resistive loads. In sleep modes where both
the I/O clock (clkI/O) and the ADC clock (clkADC) are stopped, the input buffers of the device will
be disabled. This ensures that no power is consumed by the input logic when not needed. In
some cases, the input logic is needed for detecting wake-up conditions, and it will then be
enabled. See ”Digital Input Enable and Sle ep Modes” on page 64 for details on which pins are
enabled. If the in put buffer is enab led and the in put signal is left floatin g or have an analog signal
level close to VREG/2, the input buffer will use excessive power.
For analog input pins, the digital input buffer should be disabled at all times. An analog signal
level close to VREG/2 on an input pin can cause significant curr ent even in active mode. Digital
input buffers can be disabled by writing to the Digital Input Disable Register. Refer to ”DIDR0 –
Digital Input Disable Register 0” on page 120 for details.
8.7.3 On-chip Debug System
If the On-chip debug system is enabled by OCDEN Fuse and the chip enters sleep mode, the
main clock source is enabled, and hence, always consumes power. In the deeper sleep modes,
this will contribute significantly to the total current consumption.
8.7.4 Battery Protection
If one of th e Battery Protec tion features is not needed by the application, this feature should be
disabled, see ”BPCR – Battery Protection Control Register” on page 128. When th e Discharge
FET is switched off, the Short-Circuit Circuitry will automatically be stopped in order to minimize
power consumption. The current consumption in the Battery Protection circuitry is only signifi-
cant in Power-down mode.
8.7.5 Volta ge ADC If enabled, the V-ADC will consume power independent of sleep mode. To save power, the V-
ADC should be disabled when not used, and before entering Power-save or Power-down sleep
modes. See ”Voltage ADC – 10-channel General Purpose 12-bit Sigma-Delta ADC” on page
116 for details on V-ADC operation.
38 2548F–AVR–03/2013
ATmega406
8.7.6 Coloumb Counter
If enabled, the CC-ADC will consume power independent of sleep mode. To save power, the
CC-ADC should be disabled when not used, and before entering Power-do wn slee p mode. Se e
”Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC” on page 106 for details on CC-
ADC operation.
39
2548F–AVR–03/2013
ATmega406
9. System Control and Reset
9.1 Resetting the AVR
During reset, all I/O Registers are set to their initial values, and the program starts execution
from the Reset Vector. The instruction placed at the Reset Vector must be a JMP – Absolute
Jump – instruction to the reset handling routine. If the program never enables an interrupt
source, the Interrupt Vectors are not used, and regular program code can be placed at these
locations. This is also the case if the Reset Vector is in the Application section while the Interrupt
Vectors are in the Boot section or vice ve rsa. The c ircuit diagr am in Figure 9-1 shows the reset
logic.
The I/O ports of the AVR are im mediately reset to their initial state wh en a reset source goes
active. This does not require any clock source to be running.
After all reset sources have gone inactive, a delay counter is invoked, stretching the internal
reset. This allows the voltage regula tor to reach a stable le vel before normal operation starts.
The time-out p eriod of the delay co unter is defi ned by the user through the SUT Fuses. The dif-
ferent selections for the delay period are presented in ”Clock Sources” on page 26.
9.2 Reset SourcesThe ATmega406 ha s several reset sources:
Power-on Reset. If the chip is in Power-off mode, the Charger Detect module generates a
reset pulse when a char ger is connected.See ”Power -on Reset and Charger Connect” on p age
40 for details.
External Reset. The MCU is reset when a low level is present on the RESET pin for longer
than the minimum pulse length. See ”External Reset” on page 41 for details.
Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the
Watchdog is enabled. See ”Watchdog Reset” on page 42 for details.
Brown-out Reset. The MCU is reset when VREG is below the Brown-out Reset Threshold,
VBOT. See ”Brown-out Detection” on page 42 for details.
JTAG AVR Reset. The MCU is Reset as long as there is a logic one in the Reset Register, one
of the scan chains of the JTAG system. See ”JTAG Interface and On-chip Debug System” on
page 171 for details.
40 2548F–AVR–03/2013
ATmega406
Figure 9-1. Reset Logic
9.2.1 Power-on Reset and Charger Connect
To be able to start from power-off, a charger must be detected. In order to detect a charger, the
voltage at the BATT pin must rise above the Charger-on Threshold Voltage level,VCOT. This will
issue a Power- on Reset (POR), and the chip enters RESET mode. Wh en the Delay Counter
times out, the chip will enter Active mode. Table 30-3 on page 230 shows the Power-on Reset
characteristics.
MCU Status
Register (MCUSR)
Reset Circuit
Delay Counters
CK
TIMEOUT
WDRF
EXTRF
PORF
DATA BUS
Clock
Generator
SPIKE
FILTER
Pull-up Resistor
JTRF
BODRF
JTAG Reset
Register
Ultra Low Power
RC Oscillator
SUT[1:0]
Power-on
Reset
Circuit/
Charger
Detect
Watchdog
Timer
RESET
BATT POR
VREG
COUNTER RESET
Brown-out
Detection
VREG
41
2548F–AVR–03/2013
ATmega406
Figure 9-2. Power-on Reset in Operation.
9.2.2 External ResetAn External Reset is generated by a low level on the RESET pin. Reset pulses longer than the
minimum pulse width (see Table 30-3 on page 230 ) will generate a reset, even if the clock is not
running. Shorter pulses are not guaranteed to generate a reset. When the applied signal
reaches the Reset Threshold Voltage – VRST – on its positive edge, the delay counter starts the
MCU after the Time-out period – tTOUT has expired.
Figure 9-3. External Reset During Operation
V
BATT
V
COT
SLEEP_MODE
POR
INTERNAL_RESET
Power-off Reset Active
TIMEOUT
t
TOUT
FET
42 2548F–AVR–03/2013
ATmega406
9.2.3 Watchdog Reset
When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On
the falling edge of this pulse, the delay timer starts counting the Time-out period tTOUT. Refer to
page 43 for details on operation of the Watchdog Timer.
Figure 9-4. Watchdog Reset During Operation
9.2.4 Brown-out Detection
ATmega406 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VREG level
during operation by comparing it to a fixed trigger level VBOT = 2. 7V. Th e t rigge r le ve l ha s a hys -
teresis to ensure spike free Brown-out Detection. The hysteresis on the detection level should
be interpreted as VBOT+ = VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2.
The BOD is automatically enabled in all modes of operation, except in Power-off mode.
When the BOD is enabled, and VREG decrease s to a value below the trigge r level (VBOT- in Fig-
ure 9-5), the Brown-ou t Reset is immediately activated. When VCC increases above the trigger
level (VBOT+ in Figure 9-5), the delay counter starts the MCU after the Time-out period tTOUT has
expired.
Figure 9-5. Brown-out Reset During Operation
CK
FET
VREG
RESET
TIME-OUT
INTERNAL
RESET
VBOT- VBOT+
t
TOUT
43
2548F–AVR–03/2013
ATmega406
9.3 Watchdog Timer
ATmega406 has an Enhanced Watchdog Timer (WDT). The main features are:
Clocked from separate On-chip Oscillator
3 Operating modes
–Interrupt
System Reset
Interrupt and System Reset
Selectable Time-out period from 16ms to 8s
Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode
Figure 9-6. Watchdog Timer
The Watchdog Timer (WDT) is a timer counting cycles of the Ultra Low Power RC Oscillator that
runs at 128 kHz. Th e WDT gives an interrupt or a system reset when the counter reac hes a
given time-out value. In normal operation mode, it is required that the system uses the WDR -
Watchdog Timer Reset - instruction to re start the counter befor e the time-out value is re ached. If
the system doesn't restart the counter, an interrupt or system reset will be issued.
In Interrupt mode, the WDT gives an inter rupt when the timer expir es. This interrup t can b e used
to wake the device from sleep-modes, and also as a general system timer. One example is to
limit the maximum time allowed for certain operations, giving an interrupt when the operation
has run longer than e xpected. In System Reset mode, the WDT gives a reset when the timer
expires. This is typically used to prevent system hang-up in case of runaway code. The third
mode, Interrupt and System Reset mode, combines the other two modes by first giving an inter-
rupt and then switch to System Reset mode. This mode will for instance allow a safe shutdown
by saving critical parameters before a system reset.
The Watchdog always on (WD T ON) fuse, if programmed, w ill force the Watchdog Timer to Sys-
tem Reset mode. With the fuse program med the System Reset mode bit (WDE) and Interrupt
mode bit (WDIE) are locked to 1 and 0 respectively. To further ensure program security, altera-
tions to the Watchdog set-up must follow timed sequences. Th e sequence for cle aring WDE and
changing time-out configuration is as follows:
Ultra Low Power RC
OSCILLATOR
16ms
32ms
64ms
125ms
250ms
0.5s
1.0s
2.0s
4.0s
8.0s
WDP0
WDP1
WDP2
WDP3
WATCHDOG
RESET
WDE
WDIF
WDIE
MCU RESET
INTERRUPT
44 2548F–AVR–03/2013
ATmega406
1. In the same o peration, write a logic one to the Watchdog change enable bit (WDCE) and
WDE. A logic one must be written to WDE regardless of the previous value of the WDE
bit.
2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as
desired, but with the WDCE bit cleared. This must be done in one operation.
The following code example shows one assembly and one C function for turning off the Watch-
dog Timer. The example assumes that interrupts are controlled (e.g. by disabling interrupts
globally) so that no interrupts will occur during the execution of these functions.
Note: 1. See ”About Code Examples” on page 7.
Assembly Code Example(1)
WDT_off:
; Turn off global interrupt
cli
; Reset Watchdog Timer
wdr
; Clear WDRF in MCUSR
in r16, MCUSR
andi r16, (0xff & (0<<WDRF))
out MCUSR, r16
; Write logical one to WDCE and WDE
; Keep old prescaler setting to prevent unintentional time-out
in r16, WDTCSR
ori r16, (1<<WDCE) | (1<<WDE)
out WDTCSR, r16
; Turn off WDT
ldi r16, (0<<WDE)
out WDTCSR, r16
; Turn on global interrupt
sei
ret
C Code Example(1)
void WDT_off(void)
{
__disable_interrupt();
__watchdog_reset();
/* Clear WDRF in MCUSR */
MCUSR &= ~(1<<WDRF);
/* Write logical one to WDCE and WDE */
/* Keep old prescaler setting to prevent unintentional time-out */
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* Turn off WDT */
WDTCSR = 0x00;
__enable_interrupt();
}
45
2548F–AVR–03/2013
ATmega406
Note: If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out
condition, the device will be reset and the Watchdog Timer will stay enabled. If th e code is not
set up to handle the Watchdog, this mi ght lead to an eternal loop of time-out resets. To avoid this
situation, the application software should always clear the Watchdog System Reset Flag
(WDRF) and the WDE control bit in the initialisation routine, even if the Watchdog is not in use.
The following code example shows one assembly and one C function for changing the time-out
value of the Watchdog Timer.
Note: 1. ”About Code Examples” on page 7 .
Note: The Watchdog Timer should be reset before any change of the WDP bits, since a change
in the WDP bits can result in a time-out when switching to a shorter time-out period.
Assembly Code Example(1)
WDT_Prescaler_Change:
; Turn off global interrupt
cli
; Reset Watchdog Timer
wdr
; Start timed sequence
in r16, WDTCSR
ori r16, (1<<WDCE) | (1<<WDE)
out WDTCSR, r16
; -- Got four cycles to set the new values from here -
; Set new prescaler(time-out) value = 64K cycles (~0.5 s)
ldi r16, (1<<WDE) | (1<<WDP2) | (1<<WDP0)
out WDTCSR, r16
; -- Finished setting new values, used 2 cycles -
; Turn on global interrupt
sei
ret
C Code Example(1)
void WDT_Prescaler_Change(void)
{
__disable_interrupt();
__watchdog_reset();
/* Start timed equence */
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* Set new prescaler(time-out) value = 64K cycles (~0.5 s) */
WDTCSR = (1<<WDE) | (1<<WDP2) | (1<<WDP0);
__enable_interrupt();
}
46 2548F–AVR–03/2013
ATmega406
9.4 Register Description
9.4.1 MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU reset.
Bits 7:5 – Res: Reserved Bits
These bits are reserved bits in the ATmega406, and will always read as zero.
Bit 4 – JTRF: JTAG Reset Flag
This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by
the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic
zero to the flag.
Bit 3 – WDRF: Watchdog Reset Flag
This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.
Bit 2 – BODRF: Brown-out Reset Flag
This bit is set if a Brown-out Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.
Bit 1 – EXTRF: External Reset Flag
This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.
Bit 0 – PORF: Power-on Reset Flag
This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag.
To make use of the Reset flags to identify a reset condition, the user should read and then reset
the MCUSR as ear ly as possible in the pr ogram. If the regi ster is cleared before an other reset
occurs, the source of the reset can be found by examinin g the reset flags.
Bit 76543210
0x34 (0x54) JTRF WDRF BODRF EXTRF PORF MCUSR
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 0 0 0 See Bit Description
47
2548F–AVR–03/2013
ATmega406
9.4.2 WDTCSR – Watchdog Timer Control Register
Bit 7 - WDIF: Watchdog Interrupt Flag
This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is config-
ured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt
handling vector. Altern atively, WDIF is clear ed by writing a lo gic one to the flag. Whe n the I-bit in
SREG and WDIE are set, the Watchdog Time-out Interrupt is executed.
Bit 6 - WDIE: Watchdog Interrupt Enable
When this bit is written to one and the I-bit in the Status Re gister is set, the Watc hdog Inte rrupt is
enabled. If WDE is cleared in combination with this setting, the Watchdog Timer is in Interrupt
Mode, and the corr esponding interrupt is executed if time-out in the Watchdog Timer occurs.
If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in
the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will clear WDIE
and WDIF automatically by hardware (the Watchdog goes to System Reset Mode). This is use-
ful for keeping the Watchdog Timer security while usin g the interrupt. To stay in Interrupt and
System Reset Mode, WDIE must b e set after each interrupt. This should however not be done
within the interrupt service routine itself, as this might compromise the safety-function of the
Watchdog System Reset mode. If the interrupt is not executed before the next time-out, a Sys-
tem Reset will be applied.
Bit 5, 2:0 - WDP3:0 : Watchdog Timer Prescaler 3, 2, 1 and 0
The WDP3:0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is
enabled. The different prescaling values and their corresponding Timeout Periods are shown in
Table 9-2.
Bit 4 - WDCE: Watchdog Change Enable
This bit is used in timed sequences for changing WDE and prescaler bits. To clear the WDE bit,
and/or change the prescaler bits, WDCE must be set.
Once written to one, hardware will clear WDCE after four clock cycles.
Bit 76543210
(0x60) WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 WDTCSR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 X 0 0 0
Table 9-1. Watchdog Timer Configuration
WDTON WDE WDIE Mode Action on Time-out
0 0 0 Stopped None
0 0 1 Interrupt Mode Interrupt
0 1 0 System Reset Mode Reset
011
Interrupt and System Reset
Mode Interrupt, then go to System
Reset Mode
1 x x System Reset Mode Reset
48 2548F–AVR–03/2013
ATmega406
Bit 3 - WDE: Watchdog System Reset Enable
WDE is overridden by WDRF in MCUSR. This means that WDE is always set when WDRF is
set. To clear WDE, WDRF must be clear ed first. This feature ensures multiple r esets during con-
ditions causing failure, and a safe start-up after the failure.
Bits 5, 2:0 – WDP3:0: Watchdog Timer Prescaler 3, 2, 1, and 0
The WDP3:0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is
enabled. The different prescaling values and their corresponding Timeout Periods are shown in
Table 9-2..
Table 9-2. Watchdog Timer Prescale Select
WDP3 WDP2 WDP1 WDP0 Number of WDT Oscillator
Cycles Typical Time-out at
VCC = 3.3V
0 0 0 0 2K cycles 16 ms
0 0 0 1 4K cycles 32 ms
0 0 1 0 8K cycles 64 ms
0 0 1 1 16K cycles 0.125 s
0 1 0 0 32K cycles 0.25 s
0 1 0 1 64K cycles 0.5 s
0 1 1 0 128K cycles 1.0 s
0 1 1 1 256K cycles 2.0 s
1 0 0 0 512K cycles 4.0 s
1 0 0 1 1024K cycles 8.0 s
1010
Reserved
1011
1100
1101
1110
1111
49
2548F–AVR–03/2013
ATmega406
10. Wake-up Timer
The following section describes the Wake-up Timer in the ATmega406.
One Wake-up Timer Interrupt
8 Selectable Time-out Periods
Sep a ra te Wake-up Timer Calibration Fla g
Separate Clock Source
10.1 Overview The Wake-up Timer is clocked either from the Slow RC Oscillator or from the external 32 kHz
crystal oscillator. See ”Run-Time Clock Source Select” on page 28 for details. By controlling the
Wake-up Time r pre scaler, t he Wa ke-up in terv al can be adjusted from 31.25 ms to 4 s. Eight dif-
ferent clock cycle periods can be selected to determine the Time-out period.
Figure 10-1. Wake-up Timer
10.2 Register Description
10.2.1 WUTCSR – Wake-up T imer Control and Status Register
Bit 7 – WUTIF: Wake-up Timer Interrupt Flag
The WUTIF bit is set (one) when a n overflow occurs in th e Wake-up Timer . WUTIF is clear ed by
hardware when executing the corresponding interrupt handling vector. Alternatively, WUTIF is
cleared by writing a logic one to the flag. When the SREG I-bit, WUTIE (Wake-up Timer Interrupt
Enable), and WUTIF are set (one), the Wake-up Timer interrupt is executed.
SLOW RC
OSCILLATOR
clkWUT/1K
clkWUT/2K
clkWUT/4K
clkWUT/8K
clkWUT/16K
clkWUT/32K
clkWUT/64K
clkWUT/128K
clkWUT/64
WAKE-UP
WUTR
WUTP0
WUTP1
WUTP2
WUTE
WUTIF WUTCF
32 kHz
OSCILLATOR
1/4
PRESCALER
clkWUT
Bit 76543210
(0x62) WUTIF WUTIE WUTCF WUTR WUTE WUTP2 WUTP1 WUTP0 WUTCSR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
50 2548F–AVR–03/2013
ATmega406
Bit 6 – WUTIE: Wake-up Timer Interrupt Enable
When the WUTIE bit and the I-bit in the Status Register are set (one), the Wake-up Timer inter-
rupt is enabled. The corresponding interru pt is executed if a Wake-up Timer ove rflow occurs,
i.e., when the WUT IF bit is set.
Bit 5 – WUTCF: Wake-up Timer Calibration Flag
The WUTCF bit is set every 1.95 ms (256 Slow RC OScillator clocks or 64 32 kHz Crystal Oscil-
lator clocks). WUTCF is cleared by writing a logic one to the flag. WUTCF can be used to
calibrate the Fast RC Oscillator to the 32 kHz oscillator or the Slow RC Oscillator.
Bit 4 – WUTR: Wake-up Timer Reset
When WUTR bit is written to one, the Wake-up Timer is re set, and starts counting fro m zero.
The WUTR bit is always read as zero.
Bit 3 – WUTE: Wake-up Timer Enable
When the WUTE bit is set (one) the Wake-up Timer is enabled, and if the WUTE is cleared
(zero) the Wake-up Timer function is disabled. It is recommended to reset the Wake-up Timer
when enabling it, by simultaneously setting the WUTR and WUTE bits.
Bits 2:0 – WUTP2, WUTP1, WUTP0: Wake-up Timer Prescaler 2, 1, and 0
The WUTP2, WUTP1 and WUTP0 bits determine the Wake-up Timer prescaling when the
Wake-up Timer is enabled. The different prescaling va lues and their correspo nding time-out
periods are shown in Table 10-1. Th e Wake-up Timer should always be reset when changing
these bits.
Table 10-1. Wake-up Timer Prescale Select
WUTP2 WUTP1 WUTP0 Number of Slow RC
Oscillator Cycles Number of 32kHz Crystal
Oscillator Cycles Typical Time-out
0 0 0 4K(4096) 1K(1024) 31.25 ms
0 0 1 8K(8192) 2K(2048) 62.5 ms
0 1 0 16K(16384) 4K(4096) 125 ms
0 1 1 32K(32768) 8K(8192) 250 ms
1 0 0 64K(65536) 16K(16384) 0.5 s
1 0 1 128K(131072) 32K(32768) 1 s
1 1 0 256K(262144) 64K(65536) 2 s
1 1 1 512K(524288) 128K(131072) 4 s
51
2548F–AVR–03/2013
ATmega406
11. Interrupts This section describes the specifics of the interrupt handling as performed in ATmega406. For a
general explanation of the AVR interrupt handling, refer to ”Reset and Interrupt Handling” on
page 14.
11.1 Interrupt Vectors in ATmega406
Notes: 1. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader address at
reset, see ”Boot Loader Support – Read-While-Write Self-Programming” on page 178 .
2. When the IVSEL bit in MCUCR is set, Interrupt Vectors will be moved to the start of the Boot
Flash Section. The address of each Interrupt Vector will then be the address in this table
added to the start address of the Boot Flash Section.
Table 11-2 shows reset and Interrupt Vectors placement for the various combinations of
BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt
Table 11-1. Reset and Interrupt Vectors
Vector
No. Program
Address(2) Source Interrupt Definition
1 0x0000(1) RESET External Pin, Power-on Reset, Brown-out Reset,
Watchdog Reset, and JTAG AVR Reset
2 0x0002 BPINT Battery Protection Interrupt
3 0x0004 INT0 External Interrupt Request 0
4 0x0006 INT1 External Interrupt Request 1
5 0x0008 INT2 External Interrupt Request 2
6 0x000A INT3 External Interrupt Request 3
7 0x000C PCINT0 Pin Change Interrupt 0
8 0x000E PCINT1 Pin Change Interrupt 1
9 0x0010 WDT Watchdog Time-out Interrupt
10 0x0012 WAKE_UP Wake-up Timer Overflow
11 0x0014 TIMER1 COMP Timer 1 Compare Match
12 0x0016 TIMER1 OVF Timer 1 Overflow
13 0x0018 TIMER0 COMPA Timer 0 Compare Match A
14 0x001A TIMER0 COMPB Timer 0 Compare Match B
15 0x001C TIMER0 OVF Timer 0 Overflow
16 0x001E TWI BUS C/D Two-wire Bus Connect/Disconnect
17 0x0020 TWI Two-wire Serial Interface
18 0x0022 VADC Voltage ADC Conversion Complete
19 0x0024 CCADC CONV CC-ADC Instantaneous Current Conversion
Complete
20 0x0026 CCADC REG CUR CC-ADC Regular Current
21 0x0028 CCADC ACC CC-ADC Accumulate Current Conversion Complete
22 0x002A EE READY EEPROM Ready
23 0x002C SPM READY Stor e Program Memory Ready
52 2548F–AVR–03/2013
ATmega406
Vectors are not used , and regular progra m code can be placed at th ese locations. This is also
the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the
Boot section or vice versa.
Note: 1. The Boot Reset Address is shown in Table 27-7 on page 19 3 . For the BOOTRST Fuse “1”
means unprogrammed while “0” means programmed.
The most typical and general program setup for the Reset and Interrupt Vector Addresses in
ATmega406 is:
Table 11-2. Reset and Interrupt Vectors Placement(1)
BOOTRST IVSEL Reset Address Interrupt Vectors Start Address
1 0 0x0000 0x0002
1 1 0x0000 Boot Reset Address + 0x0002
0 0 Boot Reset Address 0x0002
0 1 Boot Reset Address Boot Reset Address + 0x0002
Address Labels Code Comments
0x0000 jmp RESET ; Reset Handler
0x0002 jmp BPINT ; Battery Protection Interrupt Handler
0x0004 jmp EXT_INT0 ; External Interrupt Request 0 Handler
0x0006 jmp EXT_INT1 ; External Interrupt Request 1 Handler
0x0008 jmp EXT_INT2 ; External Interrupt Request 2 Handler
0x000A jmp EXT_INT3 ; External Interrupt Request 3 Handler
0x000C jmp PCINT0 ; Pin Change Interrupt 0 Handler
0x000E jmp PCINT1 ; Pin Change Interrupt 1 Handler
0x0010 jmp WDT ; Watchdog Time-out Interrupt
0x0012 jmp WAKE_UP ; Wake-up Timer Overflow
0x0014 jmp TIM1_COMP ; Timer1 Compare Handler
0x0016 jmp TIM1_OVF ; Timer1 Overflow Handler
0X0018 jmp TIM0_COMPA ; Timer0 CompareA Handler
0x001A jmp TIM0_COMPB ; Timer0 CompareB Handler
0x001C jmp TIM0_OVF ; Timer0 Overflow Handler
0x001E jmp TWI_BUS_CD ; Two-wire Bus Connect/Disconnect Handler
0x0020 jmp TWI ; Two-wire Serial Interface Handler
0x0022 jmp VADC ; Voltage ADC Conversion Complete Handler
0x0024 jmp CCADC_CONV ; CC-ADC Instantaneous Current Conversion Complete Handler
0x0026 jmp CCADC_REC_CUR ; CC-ADC Regular Current Handler
0x0028 jmp CCADC_ACC ; CC-ADC Accumulate Current Conversion Complete Handler
0x002A jmp EE_RDY ; EEPROM Ready Handler
0x002C jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x002E RESET: ldi r16, high(RAMEND) ; Main program start
0x002F out SPH,r16 ; Set Stack Pointer to top of RAM
0x0030 ldi r16, low(RAMEND)
0x0031 out SPL,r16
0x0032 sei ; Enable interrupts
0x0033 <instr> xxx
0x0034 ... ... ...
;
53
2548F–AVR–03/2013
ATmega406
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Reg-
ister is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector
Addresses is:
Address Labels Code Comments
0x0000 RESET: ldi r16,high(RAMEND); Main program start
0x0001 out SPH,r16 ; Set Stack Pointer to top of RAM
0x0002 ldi r16,low(RAMEND)
0x0003 out SPL,r16
0x0004 sei ; Enable interrupts
0x0005 <instr> xxx
;
.org 0x4C02
0x4C02 jmp BPINT ; Battery Protection Interrupt Handler
0x4C04 jmp EXT_INT0 ; External Interrupt Request 0 Handler
... ... ... ;
0x4C2C jmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST Fuse is pr ogra mmed a nd the Boo t se ctio n si ze set to 2K bytes, the most typi cal and gener al program
setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code Comments
.org 0x0002
0x0002 jmp BPINT ; Battery Protection Interrupt Handler
0x0004 jmp EXT_INT0 ; External Interrupt Request 0 Handler
... ... ... ;
0x002C jmp SPM_RDY ; Store Program Memory Ready Handler
;
.org 0x4C00
0x4C00 RESET: ldi r16,high(RAMEND); Main program start
0x4C01 out SPH,r16 ; Set Stack Pointer to top of RAM
0x4C02 ldi r16,low(RAMEND)
0x4C03 out SPL,r16
0x4C04 sei ; Enable interrupts
0x4C05 <instr> xxx
When the BOOTRST Fuse is programmed, the Boot se ction size set to 2K bytes and the IVSEL bit in the MCUCR Register
is set before any interrupts are enab led, the most typical and general program setup for the Reset and Interrupt Vector
Addresses is:
Address Labels Code Comments
;
.org 0x4C00
0x4C00 jmp RESET ; Reset handler
0x4C02 jmp BPINT ; Battery Protection Interrupt Handler
0x4C04 jmp EXT_INT0 ; External Interrupt Request 0 Handler
... ... ... ;
0x4C2C jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x4C2E RESET: ldi r16,high(RAMEND); Main program start
54 2548F–AVR–03/2013
ATmega406
0x4C2F out SPH,r16 ; Set Stack Pointer to top of RAM
0x4C30 ldi r16,low(RAMEND)
0x4C31 out SPL,r16
0x4C32 sei ; Enable interrupts
0x4C33 <instr> xxx
11.2 Moving Interrupts Between Application and Boot Space
The General Interrupt Control Register controls the placement of the Interrupt Vector table.
Assembly Code Example
Move_interrupts:
; Enable change of Interrupt Vectors
ldi r16, (1<<IVCE)
out MCUCR, r16
; Move interrupts to Boot Flash section
ldi r16, (1<<IVSEL)
out MCUCR, r16
ret
C Code Example
void Move_interrupts(void)
{
/* Enable change of Interrupt Vectors */
MCUCR = (1<<IVCE);
/* Move interrupts to Boot Flash section */
MCUCR = (1<<IVSEL);
}
55
2548F–AVR–03/2013
ATmega406
11.3 Register Description
11.3.1 MCUCR – MCU Control Register
Bit 1 – IVSEL: Interrupt Vector Select
When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash
memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot
Loader section of the Flash. The actual add ress of the start of the Boot Flash Section is deter-
mined by the BOOTSZ Fuses. Refer to the section ”Boot Loader Support – Read-While-Write
Self-Programming” on page 178 for details. To avoid unintentio nal changes of Interrupt Vecto r
tables, a special write procedur e must be followed to change the IVSEL bit:
a. Write the Interru pt Vector Change Enable (IVCE) bit to one.
b. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled
in the cycle IVCE is set, and they remain disabled until after the instruction following the write to
IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status
Register is unaffected by the automatic disabling.
Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is pro-
grammed, interrupts are disabled while executing from the Application section. If Interrupt Vectors
are placed in the Application section and Boot Lo ck bit BLB12 is programed, interrupts are dis-
abled while executing from the Boot Loader section. Refer to the section ”Boot Loader Support –
Read-While-Write Self-Programming” on page 178 for details on Boot Lock bits.
Bit 0 – IVCE: Interrupt Vector Change Enable
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by
hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable
interrupts, as explained in the IVSEL description abo ve. See Code Example below.
Bit 76543210
0x35 (0x55) JTD PUD IVSEL IVCE MCUCR
Read/Write R/W R R R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
56 2548F–AVR–03/2013
ATmega406
12. External Interrupts
12.1 Overview The External Interrupts are triggered by the INT3:0 pins. Observe that, if enabled, the interrupts
will trigger even if the INT3:0 pins are configured as outputs. This feature provides a way of gen-
erating a software interrupt. The External Interrupts can be triggered by a falling or rising edge or
a low level. This is set up as indicated in the specification for the External Interrupt Control Reg-
ister – EICRA. When the external interrupt is enabled and is configured as level triggered, the
interrupt will trigger as long as the pin is held low. Interrupts are detected asynchronously. This
implies that these interrupts can be used for waking the part also from sleep modes other than
Idle mode. The I/O clock is halted in all sleep modes except Idle mode.
Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed
level must be held for some time to wake up the MCU. This makes the MCU less sensitive to
noise. The changed level is sampled twice by the Slow RC Oscillator clock. The period of the
Slow RC Oscillator is 7.8 µs (nominal) at 25C. The MCU will wake up if the input has the
required level during this sampling or if it is held until the en d of the start-up time. The start-up
time is defined by the SUT fuses as described in ”System Clock and Cl ock Option s” on page 2 5 .
If the level is sampled twice by the Slow RC Oscillator clock but disappears before the end of the
start-up time, the MCU will still wake up, but no interrupt will be generated. The required level
must be held long enough for the MCU to complete the wake up to trigger the lev el interrupt.
12.2 Register Description
12.2.1 EICRA – External Interrupt Control Register A
Bits 7:0 – ISC31, ISC30 - ISC01, ISC00: External Interrupt 3 - 0 Sense Control Bits
The External Interrupts 3 - 0 are activated by the external pins INT3:0 if the SREG I-flag and the
correspon ding inte rrup t mas k in the EI MSK is set. The level an d edge s on th e exte rnal p ins tha t
activate the interrupts are defined in Table 12-1 on page 57. Edges on INT3:INT0 are regi stered
asynchronously. Pulses on INT3:0 pins wider than the minimum pulse width given in Table 12-2
on page 57 will generate an interrupt. Shorter pulses are not guaranteed to generate an inter-
rupt. If low level interrupt is selected, the low level must be held until the completion of the
currently executing instruction to generate an interrupt. If enabled, a level triggered interrupt will
generate an interrupt request as long as the pin is held low. When changing the ISCn bit, an
interrupt can occur. Therefore, it is recommended to first disable INTn by clearing its Interrupt
Enable bit in the EIMSK Register. Then, the ISCn bit can be changed. Finally, the INTn interrupt
flag should be cleared by writing a logical one to its Interrupt Flag bit (INTFn) in the EIFR Regis-
ter before the interrupt is re-enabled.
Bit 76543210
(0x69) ISC31 ISC30 ISC21 ISC20 ISC11 ISC10 ISC01 ISC00 EICRA
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
57
2548F–AVR–03/2013
ATmega406
Note: 1. n = 3, 2, 1, or 0.
When changing the ISCn1/ISCn0 bits, the interrupt must be disabled by clearing its Interrupt
Enable bit in the EIMSK Register. Otherwise an interrupt can occur when the bits are changed.
12.2.2 EIMSK – External Interrupt Mask Register
Bits 7:4 – RES: Reserved Bits
These bits are reserved bits ins the ATmega406, and will always read as zero.
Bits 3:0 – INT3 - INT0: External Interru pt Request 3 - 0 Enable
When an INT3 – INT0 bit is written to one and the I-bit in t he Status Register (SREG) is set
(one), the correspo nding external pi n interrupt is enabled. The Interrupt Sense Control bits in the
External Interrupt Control Register – EICRA – defines wh et he r th e ex ter n al inte r ru pt is activated
on rising or falling edge or level sensed. Activity on any of these pins will trigger an interrupt
request even if the pin is enabled as an output. This provides a w ay of generating a software
interrupt.
12.2.3 EIFR – External Interrupt Fla g Register
Bits 7:4 – RES: Reserved Bits
These bits are reserved bits ins the ATmega406, and will always read as zero.
Bits 3:0 – INTF3 - INTF0: External In terrupt Flags 3 - 0
When an edge or logic cha nge on th e INT3:0 pin tri ggers a n interru pt request, INTF3:0 becomes
set (one). If the I-bit in SREG and the corresponding interrupt enable bit, INT3:0 in EIMSK, are
Table 12-1. Interrupt Sense Control
ISCn1 ISCn0 Description(1)
0 0 The low level of INTn generates an interrupt request.
0 1 Any logical change on INTn generates an interrupt request.
1 0 The falling edge of INTn generates an interrupt request.
1 1 The rising edge of INTn generates an interrupt request.
Table 12-2. Asy nc hronous External Interrupt Characteristics
Symbol Parameter Condition Min Typ Max Units
tINT Minimum pulse width for asynchronous
external interrupt 50 ns
Bit 76543210
0x1D (0x3D) INT3 INT2 INT1 INT0 EIMSK
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x1C (0x3C) INTF3 INTF2 INTF1 INTF0 EIFR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
58 2548F–AVR–03/2013
ATmega406
set (one), the MCU will jump to the interrupt vector. The flag is cleared when the interrupt routine
is executed. Alternatively, the flag can be cleared by writing a logical one to it. These flags are
always cleared when INT3:0 are configured as level interrupt. Note that when entering sleep
mode with the INT3:0 interrupts disabled, the input buffers on these pins will be disabled. This
may cause a logic change in internal signals which will set the INTF3:0 flags. See ”Digital Input
Enable and Sleep Modes” on page 64 for more information.
12.2.4 PCICR– Pin Change Interrupt Control Register
Bit 7:2 - Res: Reserved Bits
These bits are reserved bits in the ATmega406, and will always read as zero.
Bit 1 - PCIE1: Pin Change Interrupt Enable 1
When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 1 is enabled. Any change on any enabled PCINT15:8 pin will cause an inter-
rupt. The corres ponding interrupt of Pin Change Inter rupt Request is executed from the PCI1
Interrupt Vector. PCINT15:8 pins are enabled individually by the PCMSK1 Register.
Bit 0 - PCIE0: Pin Change Interrupt Enable 0
When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 0 is enabled. Any change on any enabled PCINT7:0 pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Inter-
rupt Vector. PCINT7:0 pins are enabled individually by the PCMSK0 Register.
12.2.5 PCIFR – Pin Change Interrupt Flag Register
Bit 7:2 - Res: Reserved Bits
These bits are reserved bits in the ATmega406, and will always read as zero.
Bit 1 - PCIF1: Pin Change Interrupt Flag 1
When a logic change on any PCINT15:8 pin triggers an interrupt request, PCIF1 becomes set
(one). If the I-bit in SREG and the PCIE1 bit in PCICR are set (one), the MCU will jump to the
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alter-
natively, the flag can be cleared by writing a logical one to it.
Bit 0 - PCIF0: Pin Change Interrupt Flag 0
When a logic change on any PCINT7:0 pin triggers an interrupt request, PCIF0 becomes set
(one). If the I-bit in SREG and the PCIE0 bit in PCICR are set (one), the MCU will jump to the
Bit 76543210
(0x68) PCIE1 PCIE0 PCICR
Read/Write RRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x1B (0x3B) ––––––PCIF1PCIF0PCIFR
Read/Write RRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
59
2548F–AVR–03/2013
ATmega406
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alter-
natively, the flag can be cleared by writing a logical one to it.
12.2.6 PCMSK1 – Pin Change Mask Register 1
Bit 7:0 – PCINT15:8: Pin Change Enable Mask 15:8
Each PCINT15:8-bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT15:8 is set and the PCIE1 bit in PCICR is set, pin change interrupt is enabled on the
corresponding I/O pin. If PCINT15:8 is cleared, pin change interrupt on the corresponding I/O
pin is disabled.
12.2.7 PCMSK0 – Pin Change Mask Register 0
Bit 7:0 – PCINT7:0: Pin Change Enable Mask 7:0
Each PCINT7:0 bit selects whether pin change interrupt is enabled on the corresponding I/O pin.
If PCINT7:0 is set and the PCIE0 bit in PCICR is set, pin change interrupt is enabled on the cor-
responding I/O pin. If PCINT7:0 is cleared, pin change interrupt on the corresponding I/O pin is
disabled.
Bit 76543210
(0x6C) PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 PCINT8 PCMSK1
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
(0x6B) PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 PCMSK0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
60 2548F–AVR–03/2013
ATmega406
13. Low Voltage I/O-Ports
13.1 Introduction All low voltage AVR ports have true Read-Modify-Write functionality when used as general digi-
tal I/O ports. This means that the direction o f one port pin ca n be changed without unintentionally
changing the direction of any other pin with the SBI and CBI instruc tions. The same a pplies
when changing drive value (if configured as output) or enabling/disabling of pull-u p resistors (if
configured as input). All low voltage p ort pins have individually selectable pull-up resistors with a
supply-voltage invariant resistance. All I/O pins have protection diod es to bo th VREG and Ground
as indicated in Figure 13-1 on page 60. Refer to ”Electrical Characteristics” on page 225 for a
complete list of parameters.
Figure 13-1. Low Voltage I/O Pin Equivalent Schematic
All registers and bit r eferences in this section are written in general form. A lower case “x” repre-
sents the numbering letter for the p ort, and a lower case “ n” represents the bit number. Howeve r,
when using the register or bi t defines in a progr am, the precise form must be used. For example,
PORTB3 for bit no. 3 in Po rt B, her e docume nt ed ge nerally a s PORTxn . The physical I/O Regis-
ters and bit locations are listed in ”Register Description” on page 73.
Three I/O memory address locations are a llocated for each low voltage port, one each for the
Data Register – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The
Port Input Pins I/O location is re ad only, while the Data Register an d th e Data Dir ection Register
are read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in
the corresponding bit in the Data Register. In addition, the Pull-up Disable – PUD bit in MCUCR
disables the pull-up function for all low voltag e pins in all ports when set.
Using the I/O port as Gener al Digital I/O is described in ”Low Voltage Ports as General Digital
I/O” on page 61. Many low voltage port pins are multiplexed with altern ate functions for the
peripheral features on the device. How each alternate function in terferes with the port pin is
described in ”Alternate Port Functions” on page 66. Refer to the individual module sections for a
full description of the alternate functio ns.
Note that enabling the alternate function of some of the port pins does not affect the use of the
other pins in the port as general digital I/O.
Cpin
Logic
Rpu
See Figure
"General Digital I/O" for
Details
Pxn
61
2548F–AVR–03/2013
ATmega406
13.2 Low Voltage Ports as General Digital I/O
The low voltage ports are bi-directional I/O ports with optional internal pull-ups. Figure 13-2
shows a functional description of one I/O-port pin, here generically called Pxn.
Figure 13-2. General Low Voltage Digital I/O(1)
Note: 1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O,
SLEEP, and PUD are common to all ports.
13.2.1 Configuring the Pin
Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in ”Register
Description” on page 73, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits
at the PORTx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one,
Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input
pin.
If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is
activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the p in has to
be configured as an output p in. The p ort pi ns are tri-stated when reset condition becomes active,
even if no clocks are ru nnin g.
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven
high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port
pin is driven low (zero).
clk
RPx
RRx
RDx
WDx
PUD
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
PUD: PULLUP DISABLE
clkI/O: I/O CLOCK
RDx: READ DDRx
D
L
Q
Q
RESET
RESET
Q
QD
Q
Q D
CLR
PORTxn
Q
Q D
CLR
DDxn
PINxn
DATA BU S
SLEEP
SLEEP: SLEEP CONTROL
Pxn
I/O
WPx
0
1
WRx
WPx: WRITE PINx REGISTER
62 2548F–AVR–03/2013
ATmega406
13.2.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn.
Note that the SBI instruction can be used to toggle one single bit in a port.
13.2.3 Switching Between Input and Output
When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn}
= 0b11), an intermediate state with either pull- up enabled {DDxn, PORTxn} = 0b01) or output
low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully accept-
able, as a high-impedant environment will not notice the difference between a strong high driver
and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all
pull-ups in all ports.
Switching between input with pull-up and output low generates the same problem. The user
must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn}
= 0b11) as an intermediate step.
Table 13-1 summarizes the control signals for the pin value.
13.2.4 Reading the Pin Value
Independent of the setting of Data Direction bit DDxn, the port pin can be read through the
PINxn Register bit. As shown in F igure 13- 2, the PINxn Register bit and the pre ceding latch con-
stitute a synchronizer. This is needed to avoid metastability if the physical pin changes value
near the edge of the internal clock, but it also introduce s a delay. F igure 13-3 shows a timing dia-
gram of the synch ronization when reading an externa lly applied pin value. The maximum and
minimum prop a ga tio n dela ys ar e de no te d tpd,max and tpd,min respectively.
Table 13-1. Port Pin Configurations
DDxn PORTxn PUD
(in MCUCR) I/O Pull-up Comment
0 0 X Input No Tri-state (Hi-Z)
0 1 0 Input Yes Pxn will source current if ext. pulled low.
0 1 1 Input No Tri-state (Hi-Z)
1 0 X Output No Output Low (Sink)
1 1 X Output No Output High (Source)
63
2548F–AVR–03/2013
ATmega406
Figure 13-3. Synchronization when Reading an Externally Applied Pin value
Consider the clock period starting shortly after the first falling edge of the system clock. The latch
is closed when the clock is low, and goes transparent when the clock is high, as indicated by the
shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock
goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As in di-
cated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed
between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indi-
cated in Figure 13-4. The out instruction sets the “SYNC LATCH” signal at the positive edge of
the clock. In this case, the delay tpd through the synchronizer is 1 system clock period.
Figure 13-4. Synchronization when Reading a Software Assigned Pin Value
The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define
the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin
values are read back again, but as previously discussed, a nop instruction is included to be able
to read back the value recently assigned to some of the pins.
XXX in r17, PINx
0x00 0xFF
INSTRUCTIONS
SYNC LATCH
PINxn
r17
XXX
SYSTEM CLK
t
pd, max
t
pd, min
out PORTx, r16 nop in r17, PINx
0xFF
0x00 0xFF
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
t
pd
64 2548F–AVR–03/2013
ATmega406
Note: 1. For the assembly program, two temporary registers are used to minimize the time from pull-
ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3
as low and redefining bits 0 and 1 as strong high drivers.
13.2.5 Digital Input Enable and Sleep Modes
As shown in Figure 13-2, the digital inpu t signal can be clamped to ground at the input of the
schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in
Power-down mode and Power-save mode to avoid high power consumption if some input sig-
nals are left floating, or have an analog signal level close to VREG/2.
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt
request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various
other alternate functions as described in ”Alternate Port Functions” on page 66.
If a logic high level (“one”) is present on an asynchronous external interrupt pin configured as
“Interrupt on Rising Edge , Falling Edge, or Any Logic Change on Pin” while the external inter rupt
is not enabled, the corresponding External Interrupt Flag will be set when resuming from the
above mentioned Sleep mode, as the clamping in these sleep mode produces the requested
logic change.
Assembly Code Example(1)
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi r16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0)
ldi r17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0)
out PORTB,r16
out DDRB,r17
; Insert nop for synchronization
nop
; Read port pins
in r16,PINB
...
C Code Example
unsigned char i;
...
/* Define pull-ups and set outputs high */
/* Define directions for port pins */
PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0);
DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0);
/* Insert nop for synchronization*/
_NOP();
/* Read port pins */
i = PINB;
...
65
2548F–AVR–03/2013
ATmega406
13.2.6 Unconnected Pins
If some pins are unused, it is reco mmended to ensur e that these pi ns have a defined le vel. Even
though most of the digital inputs are disabled in the deep sleep modes as described ab ove, float-
ing inputs should be avoided to reduce current consumption in all other modes where the digital
inputs are enabled (Reset, Active mode and Idle mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up.
In this case, the pull-up will be disabled during reset. If low power consumption during reset is
important, it is recommended to use an exte rnal pull-up or pull-down. Connecting unused pins
directly to VCC or GND is not recommended, since this ma y cause ex cessiv e currents if the pin is
accidentally configured as an output.
66 2548F–AVR–03/2013
ATmega406
13.3 Alternate Port Functions
Many low voltag e p or t pin s ha ve alternate functions in addition to being general digital I/Os. Fig-
ure 13-5 shows how the port pin control signals from the simplified Figure 13-2 can be
overridden by alternate functions. The overriding signals may n ot be pre sent in a ll port pin s, but
the figure serves a s a generic description applicable to all port pins in the AVR microcontro ller
family.
Figure 13-5. Alternate Port Functions(1)
Note: 1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O,
SLEEP, and PUD are common to all ports. All other signals are unique for each pin.
clk
RPx
RRx
WRx
RDx
WDx
PUD
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
PUD: PULLUP DISABLE
clk
I/O
: I/O CLOCK
RDx: READ DDRx
D
L
Q
Q
SET
CLR
0
1
0
1
0
1
DIxn
AIOxn
DIEOExn
PVOVxn
PVOExn
DDOVxn
DDOExn
PUOExn
PUOVxn
PUOExn: Pxn PULL-UP OVERRIDE ENABLE
PUOVxn: Pxn PULL-UP OVERRIDE VALUE
DDOExn: Pxn DATA DIRECTION OVERRIDE ENABLE
DDOVxn: Pxn DATA DIRECTION OVERRIDE VALUE
PVOExn: Pxn PORT VALUE OVERRIDE ENABLE
PVOVxn: Pxn PORT VALUE OVERRIDE VALUE
DIxn: DIGITAL INPUT PIN n ON PORTx
AIOxn: ANALOG INPUT/OUTPUT PIN n ON PORTx
RESET
RESET
Q
QD
CLR
Q
Q D
CLR
Q
Q
D
CLR
PINxn
PORTxn
DDxn
DATA BUS
0
1
DIEOVxn
SLEEP
DIEOExn: Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE
DIEOVxn: Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE
SLEEP: SLEEP CONTROL
Pxn
I/O
0
1
PTOExn
WPx
PTOExn: Pxn, PORT TOGGLE OVERRIDE ENABLE
WPx: WRITE PINx
67
2548F–AVR–03/2013
ATmega406
Table 13-2 summarizes the function of the overri ding signals. Th e pin an d port indexes from Fig-
ure 13-5 are not shown in the succeeding tables. The overriding signals are generated internally
in the modules having the alternate function.
The following subsections shortly describe the alternate functions for each port, an d relate the
overriding signals to the alternate function. Refer to the alternate function description for further
details.
Table 13-2. Generic Description of Overriding Signals for Alternate Functions
Signal Name Full Name Description
PUOE Pull-up Override
Enable
If this signal is set, the pull-up enable is controlled by the PUOV
signal. If this signal is cleared, the pull-up is ena bled when
{DDxn, PORTxn, PUD} = 0b010.
PUOV Pull-up Override
Value
If PUOE is set, the pull-up is enabled/disabled when PUOV is
set/cleared, regardless of the setting of the DDxn, PORTxn,
and PUD Register bits.
DDOE Data Dire ct io n
Override Enable
If this signal is set, the Output Driver Enable is controlled by the
DDOV signal. If this signal is cleared, the Output driver is
enabled by the DDxn Register bit.
DDOV Data Dire ct io n
Override Value
If DDOE is set, the Output Driver is enabled/disabled when
DDOV is set/cleared, regardless of the setting of the DDxn
Register bit.
PVOE Port Value
Override Enable
If this signal is set and the Output Driver is enabled, the port
value is controlled by the PVOV signal. If PVOE is cleared, and
the Output Driver is enabled, the port Value is controlled by the
PORTxn Register bit.
PVOV Port Value
Override Value If PVOE is set, the port value is set to PVOV, regardless of the
setting of the PORTxn Register bit.
PTOE Port Toggle
Override Enable If PTOE is set, the PORTxn Register bit is inverted.
DIEOE Digital Input
Enable Override
Enable
If this bit is set, the Digital Input Enable is controlled by the
DIEOV signal. If this signal is cleared, the Digi tal Input Enable
is determine d by MCU state (Normal mode, sleep mod e).
DIEOV Digital Input
Enable Override
Value
If DIEOE is set, the Digital Input is enabled/disabled when
DIEOV is set/cleared, regardless of the MCU state (Normal
mode, sleep mode).
DI Digital Input
This is the Digital Input to alternate functions. In the figure, the
signal is connected to the output of the schmitt trigger but
before the synchronizer. Unless the Digital Input is used as a
clock source, the module with the alternate function will use its
own synchronizer.
AIO Analog
Input/Output
This is the Analog Input/output to/from alternate functions. The
signal is connected directly to the pad, and can be used bi-
directionally.
68 2548F–AVR–03/2013
ATmega406
13.3.1 Alternate Functions of Port A
The Port A has an alternate function as input pins to the Voltage ADC.
The alternate pin configura tion is as follows:
ADC4/INT3:0/PCINT7:4 – Port A, Bit 7:4
Analog to Digital Converter, Channel 4.
INT3 - INT0, External Interrupt Sources 3:0. The PA7:4 pins can serve as external interrupt
sources to the MCU.
PCINT7 - PCINT4, Pin Cha nge Interrupt Sources 7:4. The PA7:4 pins can serve as external
interrupt sources to the MCU.
ADC3:0/PCINT3:0 – Port A, Bit 3:0
Analog to Digital Converter, Channels 3:0.
PCINT3 - PCINT0, Pin Cha nge Interrupt Sources 3:0. The PA3:0 pins can serve as external
interrupt sources to the MCU.
Table 13-3. Port A Pins Alternate Functions
Port Pin Alternate Function
PA7 INT3 (External Interrupt 3)
PCINT7 (Pin Change Interrupt 7)
PA6 INT2 (External Interrupt 2)
PCINT6 (Pin Change Interrupt 6)
PA5 INT1 (External Interrupt 1)
PCINT5 (Pin Change Interrupt 5)
PA4 ADC4 (ADC Input Channel 4)
INT0 (External Interrupt 0)
PCINT4 (Pin Change Interrupt 4)
PA3 ADC3 (ADC Input Channel 3)
PCINT3 (Pin Change Interrupt 3)
PA2 ADC2 (ADC Input Channel 2)
PCINT2 (Pin Change Interrupt 2)
PA1 ADC1 (ADC Input Channel 1)
PCINT1 (Pin Change Interrupt 1)
PA0 ADC0 (ADC Input Channel 0)
PCINT0 (Pin Change Interrupt 0)
69
2548F–AVR–03/2013
ATmega406
Table 13-4 and Table 13-5 relates the alternate functions of Port A to the overriding signals
shown in Figure 13-5 on page 66.
Table 13-4. Overriding Signals for Alternate Functions in PA7:PA4
Signal Name PA7/INT3/
PCINT7 PA6/INT2/
PCINT6 PA5/INT1/
PCINT5 PA4/ADC4
INT0/PCINT4
PUOE0000
PUOV0000
DDOE 0 0 0 0
DDOV 0 0 0 0
PVOE 0 0 0 0
PVOV 0 0 0 0
PTOE––––
DIEOE INT3 ENABLE INT2 ENABLE INT1 ENABLE INT0 ENABLE
DIEOV INT3 ENABLE INT2 ENABLE INT1 ENABLE INT0 ENABLE
DI INT3 INPUT/
PCINT7 INPUT INT2 INPUT/
PCINT6 INPUT INT1 INPUT/
PCINT5 INPUT INT0 INPUT/
PCINT4 INPUT
AIO ADC4 INPUT
Table 13-5. Overriding Signals for Alternate Functions in PA3:PA0
Signal Name PA3/ADC3/
PCINT3 PA2/ADC2/
PCINT2 PA1/ADC1/
PCINT1 PA0/ADC0/
PCINT0
PUOE0000
PUOV0000
DDOE 0 0 0 0
DDOV 0 0 0 0
PVOE 0 0 0 0
PVOV 0 0 0 0
PTOE––––
DIEOE 0 0 0 0
DIEOV 0 0 0 0
DI PCINT3 INPUT PCINT2 INPUT PCINT1 INPUT PCINT0 INPUT
AIO ADC3 INPUT ADC2 INPUT ADC1 INPU T ADC0 INPUT
70 2548F–AVR–03/2013
ATmega406
13.3.2 Alternate Functions of Port B
The Port B pins with alternate functions are shown in Table 13-6.
The alternate pin configuration is as follows:
OC0B/PCINT15 – Port B, Bit 7
OC0B, Output Compare Match B output: The PB7 pin can serve as an external output for th e
Timer/Counter0 Output Compare. The pin has to be configured as an output ( DDB7 set ( one)) to
serve this function. The OC0B pin is also the outp ut pin for the PWM mode timer function.
PCINT15, Pin Change Interrupt Source 15. The PB7 pin can serve as external interrupt source
to the MCU.
OC0A/PCINT14 – Port B, Bit 6
OC0A, Output Compare Match A output: The PB6 pin can serve as an external output for th e
Timer/Counter0 Output Compare. The pin has to be configured as an output ( DDB6 set ( one)) to
serve this function. The OC0A pin is also the outp ut pin for the PWM mode timer function.
PCINT14, Pin Change Interrupt Source 14. The PB6 pin can serve as external interrupt source
to the MCU.
PCINT13:12 – Port B, Bit 5:4
PCINT13 - PCINT12, Pin Change Inter rupt Sou rce 13:12 . The PB5:4 pin S can serve as e xterna l
interrupt sources to the MCU.
TCK/PCINT11 – Port B, Bit 3
TCK, JTAG Test Clock: JTAG operation is synchronous to TCK. When the JTAG Interface is
enabled, this pin can not be used as an I/O pin.
PCINT11, Pin Change Interrupt Source 11. The PB3 pin can serve as external interrupt source
to the MCU.
Table 13-6. Port B Pins Alternate Functions
Port Pin Alternate Functions
PB7 OC0B (Output Compare and PWM Output B for Timer/Counter0)
PCINT15 (Pin Change Interrupt 15)
PB6 OC0A (Output Compare and PWM Output A for Timer/Counter0)
PCINT14 (Pin Change Interrupt 14)
PB5 PCINT13 (Pin Change Interrupt 13)
PB4 PCINT12 (Pin Change Interrupt 12)
PB3 TCK (JTAG Test Clock)
PCINT11 (Pin Change Interrupt 11)
PB2 TMS (JTAG Test Mode Select)
PCINT10 (Pin Change Interrupt 10)
PB1 TDI (JTAG Test Data Input/)
PCINT9 (Pin Change Interrupt 9)
PB0 TDO (JTAG Test Data Output)
PCINT8 (Pin Change Interrupt 8)
71
2548F–AVR–03/2013
ATmega406
TMS/PCINT10 – Port B, Bit 2
TMS, JTAG Test Mode Select: This pin is used for navigating through the TAP-controller state
machine. When the JTAG interface is enabled, this pin can no t be used as an I/O pin.
PCINT10, Pin Change Interrupt Source 10. The PB2 pin can serve as external interrupt source
to the MCU.
TDI/PCINT9 – Port B, Bit 1
TDI, JTAG Test Data Input: Serial input data to be shifted in the Instruction Registe r or Data
Register (scan chains). When the JTAG Inter face is en abled, this pin can not be used as I/O pin.
PCINT9, Pin Change Interrupt Source 9. The PB1 pin can serve as external interrupt source to
the MCU.
TDO/PCINT8 – Port B, Bit 0
TDO, JTAG Test Data Output: Seria l output data from Instruction Register or Data Register.
When the JTAG Interface is ena bled, this pin can not be used as an I/O pin.
PCINT8, Pin Change Interrupt Source 8. The PB0 pin can serve as external interrupt source to
the MCU.
Table 13-7 and Table 13-8 relate the alternate functions of Port B to the overriding signals
shown in Figure 13-5 on page 66.
Table 13-7. Overriding Signals for Alternate Functions in PB7:PB4
Signal Name PB7/OCOB/
PCINT15 PB6/OCOA/
PCINT14 PB5/
PCINT13 PB4/
PCINT12
PUOE0000
PUOV0000
DDOE 0 0 0 0
DDOV 0 0 0 0
PVOE OC0B Enable OC0A Enable 0
PVOV OC0B OC0A 0
PTOE––––
DIEOE0000
DIEOV0000
DI PCINT15 INPUT PCINT14 INPUT PCINT13 INPUT P CINT12 INPUT
AIO––––
72 2548F–AVR–03/2013
ATmega406
.
13.3.3 Alternate Functions of Port D
The Port D pins with alternate functions are shown in Table 13-9.
The alternate pin configuration is as follows:
T0 – Port B, Bit 0
T0, Timer/Counter0 Counter Source.
Table 13-10 on page 73 relates the alternate functions of Port D to the overriding signals shown
in Figure 13-5 on page 66.
Table 13-8. Overriding Signals for Alternate Functions in PB3:PB0
Signal Name PB3/TCK/
PCINT11 PB2/TMS/
PCINT10 PB1/TDI/
PCINT9 PB0/TDO/
PCINT8
PUOE JTAGEN JTAGEN JTAGEN JTAGEN
PUOV1110
DDOE JTAGEN JTAGEN JTAGEN JTAGEN
DDOV000SHIFT_IR + SHIFT_DR
PVOE000JTAGEN
PVOV000TDO
PTOE––––
DIEOE JTAGEN JTAGEN JTAGEN JTAGEN
DIEOV0000
DI TCK/PCINT11
INPUT TMS/PCINT10
INPUT TDI/PCINT9
INPUT PCINT8
INPUT
AIO––––
Table 13-9. Port D Pins Alternate Functions
Port Pin Alternate Function
PD0 T0 (Timer/Counter0 Clock Input)
73
2548F–AVR–03/2013
ATmega406
13.4 Register Description
13.4.1 MCUCR – MCU Control Register
Bit 4 – PUD: Pull-up Disable
When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and
PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01). See ”Con-
figuring the Pin” on page 61 for more details about this feature.
13.4.2 PORTA – Port A Data Register
13.4.3 DDRA – Port A Data Direction Register
13.4.4 PINA – Port A Input Pins Address
Table 13-10. Overriding Signals for Alternate Functions in PD1:PD0
Signal Name PD1 PD0/T0
PUOE 0 0
PUOV 0 0
DDOE 0 0
DDOV 0 0
PVOE 0
PVOV 0
PTOE
DIEOE 0 0
DIEOV 0 0
DI T0 Input
AIO
Bit 7 6 5 4 3 2 1 0
0x35 (0x55) JTD –PUD IVSEL IVCE MCUCR
Read/Write R/W R R R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x02 (0x22) PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 PORTA
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x01 (0x21) DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 DDRA
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x00 (0x20) PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 PINA
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value N/A N/A N/A N/A N/A N/A N/A N/A
74 2548F–AVR–03/2013
ATmega406
13.4.5 PORTB – Port B Data Register
13.4.6 DDRB – Port B Data Direction Register
13.4.7 PINB – Port B Input Pins Address
13.4.8 PORTD – Port D Data Register
13.4.9 DDRD – Port D Data Direction Register
13.4.10 PIND – Port D Input Pins Address
Bit 76543210
0x05 (0x25) PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 PORTB
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x04 (0x24) DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 DDRB
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x03 (0x23) PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 PINB
Read/WriteRRRRRRRR
Initial Value N/A N/A N/A N/A N/A N/A N/A N/A
Bit 76543210
0x0B (0x2B) ––––––PORTD1PORTD0PORTD
Read/WriteRRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x0A (0x2A) ––––––
DDD1 DDD0 DDRD
Read/WriteRRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x09 (0x29) ––––––
PIND1 PIND0 PIND
Read/WriteRRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 N/A N/A
75
2548F–AVR–03/2013
ATmega406
14. High Volt age I/O Ports
All high voltage AVR ports have true Read-Modify-Write functionality when used as general dig-
ital I/O ports. This means that the state of one port pin can be changed without unintentionally
changing the state of any other pin with the SBI and CBI instructions. All high voltage I/O pins
have protection Zener diod es to Ground as indicated in Figure 14-1. See ”Electrical Characteris-
tics” on page 225 for a complete list of parameters.
Figure 14-1. High Voltage I/O Pin Equivalent Schematic
All registers and bit r eferences in this section are written in general form. A lower case “x” repre-
sents the numbering letter for the p ort, and a lower case “ n” represents the bit number. Howeve r,
when using the register or bi t defines in a progr am, the precise form must be used. For example,
PORTC3 for bit number three in Port C, here documented generally a s PORTxn. The physical
I/O Registers and bit locations are listed in ”Register Description for High Voltage Output Ports”
on page 76.
One I/O Memory address location is allocated for each high voltage port, the Data Register –
PORTx. The Data Register is read/write.
Using the I/O port as General Digital Output is described in ”High Voltage Ports as General Dig-
ital Outputs” on page 75.
14.1 High Voltage Ports as General Digital Outputs
The high voltage ports are high voltage tolerant ope n collector output ports. Figure 14 -2 shows a
functional description of one output port pin, here generically called Pxn.
Cpin
Logic
See Figure
"General High Voltage
Digital I/O" for Details
Pxn
76 2548F–AVR–03/2013
ATmega406
Figure 14-2. General High Voltage Digital I/O(1)
Note: 1. WRx and RRx are common to all pins within the same port.
14.2 Configuring the Pin
Each port pin has one register bit: PORTxn. As shown in ”Register Description for High Voltage
Output Ports” on page 76, the PORTxn bits are accessed at the PORTx I/O address. If PORTxn
is written logic one, the port pin is driven low (zero). If PORTxn is written logic zero, the port pin
is tri-stated. The port pins a re tri-stated when a reset conditio n becomes active, even if no clocks
are running.
14.3 Register Description for High Voltage Output Ports
14.3.1 PORTC – Port C Data Register
RRx
WRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RESET
Q
QD
CLR
PORTxn
DATA BUS
Pxn
Bit 76543210
0x08 (0x28) PORTC0 PORTC
Read/WriteRRRRRRRR/W
Initial Value 0 0 0 0 0 0 0 0
77
2548F–AVR–03/2013
ATmega406
15. 8-bit Timer/Counter0 with PWM
Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output
Compare Units, and with PWM support. It allows accurate progr am execution timing (event ma n-
agement) and wave generation. The main features are:
Two Independent Output Comp are Units
Double Buffered Output Comp are Registers
Clear Timer on Compare Match (Auto Reload)
Glitch Free, Phase Correc t Pulse Width Modu lator (PWM)
Variable PWM Period
Frequency Genera tor
Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B)
15.1 Overview A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 15-1. For the actual
placement of I/O pins, refer to ”Pinout ATmega406.” on page 2. CPU accessible I/O Registers,
including I/O bit s and I/O pins, are sh own in bold. The device -specific I/O Reg ister and bit loca-
tions are listed in the ”8-bit Timer/Counter Register Description” on page 88.
The PRTIM0 bit in ”PRR0 – Power Reduction Register 0” on page 36 must be written to zero to
enable Timer/Counter0 module.
Figure 15-1. 8-bit Timer/Counter Block Diagra m
15.1.1 Definitions Many register an d bit references in this section are written in gen eral form. A lower case “n”
replaces the Timer/Counter num ber, in this case 0. A lower case “x” replaces the Output Com-
pare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or
bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing
Timer/Counter0 counter value and so on.
Timer/Counter
DATA BU S
OCRnA
OCRnB
=
=
TCNTn
Waveform
Generation
Waveform
Generation
OCnA
OCnB
=
Fixed
TOP
Value
Control Logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(Int.Req.)
OCnA
(Int.Req.)
OCnB
(Int.Req.)
TCCRnA TCCRnB
clk
Tn
Prescaler
T/C
Oscillator
clk
I/O
TOSC1
TOSC2
78 2548F–AVR–03/2013
ATmega406
The definitions in Table 15-1 are also used exte nsively throughout the document.
15.1.2 Registers Th e Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit
registers. Interrupt request (abbreviated to Int.Req . in the figure) signals are all visible in the
Timer Interrupt Flag Register (T IFR0). All interrupts are individ ually masked with the Timer Inte r-
rupt Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure.
The Timer/Counter can be clocked internally, via th e prescaler, or b y an external clo ck source on
the T0 pin. The Clock Select logic block contro ls which clock source and edge the Tim er/Counter
uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the Clock Select logic is referred to as the timer clock (clkT0).
The double buffered Output Compare Registers (OCR0A and OCR0B) are compared with the
Timer/Counter value at all times. The result of the compare can be used by the Waveform Gen-
erator to generate a PWM or variable frequency output on the Output Compare pins (OC0A and
OC0B). See Section “15.4.3” on page 80. for details. The compare match event will also set the
Compare Flag (OCF0A or OCF0B) which can be used to generate an Output Compare interrupt
request.
15.2 Timer/Counter Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source
is selected by the Clock Select logic which is controlled by the Clock Select (CS02:0) bits
located in the Timer /Counter Control Reg ister (TCCR0B) . For details o n clock sources and p res-
caler, see ”Timer/Counter0 and Timer/Counter1 Prescalers” on page 103.
15.3 Counter Unit The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
15-2 shows a block diagram of the counter and its surroundings.
Figure 15-2. Counter Unit Block Diagram
Signal description (internal signals):
Table 15-1. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes 0x00.
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in th e
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR0A Register. The assignment is depen-
dent on the mode of operation.
DATA BUS
TCNTn Control Logic
count
TOVn
(Int.Req.)
Clock Select
top
Tn
Edge
Detector
( From Prescaler )
clk
Tn
bottom
direction
clear
79
2548F–AVR–03/2013
ATmega406
count Increment or de cre m en t TC NT 0 by 1.
direction Select between increment and decrement.
clear Clear TCNT0 (set all bits to zero).
clkTnTimer/Co un te r clo ck, re fe rr ed to as clk T0 in the following.
top Signalize that TCNT0 has reached maximum value.
bottom Signalize that TCNT0 has reached minimum value (zero).
Depending of the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT0). clkT0 can be generated from an external or inte rnal clock source,
selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the
timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of
whether clkT0 is present or not. A CPU write overrides (has prio rity over) all counter clear or
count operations.
The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in
the Timer/Counter Control Register (TCCR0A) and the WGM02 bit located in the Timer/Counter
Control Register B (TCCR0B). There are close connections between how the counter behaves
(counts) and how waveforms are generated on the Output Compare outputs OC0A and OC0B.
For more details about advanced counting sequences and waveform generation, see ”Modes of
Operation” on page 82.
The Timer/Counter Overflow Flag (TOV0) is set according to the m ode of operation se lected by
the WGM02:0 bits. TOV0 can be used for generating a CPU interrupt.
15.4 Output Compare Unit
The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers
(OCR0A and OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the compara tor signals a
match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock
cycle. If the corresponding inte rrupt is enabled, the Output Compare Flag generates an Output
Compare interrupt. Th e Outp ut Co mpa re Flag is automatically cleared when the interrupt is exe-
cuted. Alternatively, the flag can be cleared by software b y w riting a logical one to its I/O bit
location. The Waveform Generator uses the match signal to generate an output according to
operating mode set by the WGM02:0 bits and Co mpare Output mode (COM0x1:0) bits. The max
and bottom signals are used by the Waveform Generator for handling the special cases of the
extreme values in some modes of operation (”Modes of Operation” on page 82).
Figure 15-3 shows a block diagram of the Output Compare unit.
80 2548F–AVR–03/2013
ATmega406
Figure 15-3. Output Compare Unit, Block Diagram
The OCR0x Registers are double buffered when using any of the Pulse Width Modulation
(PWM) modes. For the normal and Clear Timer on Compare (CTC) mo des of oper ation, the dou-
ble buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare
Registers to either top or bottom of the coun ting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pu lse s, th er eb y ma kin g th e ou tp ut glitch -f re e.
The OCR0x Register access may seem comple x, but this is not case. When the double bu ffering
is enabled, the CPU has access to the OCR0 x Buffer Register, an d if double buffering is di s-
abled the CPU will access the OCR0x directly.
15.4.1 Force Output Compare
In non-PWM waveform generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC0x) bit. Forcing compare match will not set the
OCF0x Flag or reload/clear the timer, but the OC0x pin will be updated as if a real compare
match had occurred (the COM0x1:0 bits settings define whether the OC0x pin is set, cleared or
toggled).
15.4.2 Compare Match Blocking by TCNT0 Write
All CPU write operations to the TCNT0 Register will block any compare match that occur in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR0x to be initial-
ized to the same value as TCNT0 witho ut trigge ring an in terrupt whe n the Timer/Counte r clock is
enabled.
15.4.3 Using the Output Compare Unit
Since writing TCNT0 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT0 when usin g the Output Compare Unit,
independently of whether the Timer/Counter is running or not. If the value written to TCNT0
equals the OCR0x value, the compare match will be missed, resulting in incorrect waveform
generation. Similarly, do not write the TCNT0 value equal to BOTTOM when the count er is
downcounting.
The setup of the OC0x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC0x value is to use the Force Output Com-
OCFnx (Int.Req.)
= (8-bit Comparator )
OCRnx
OCnx
DATA BUS
TCNTn
WGMn1:0
Waveform Generator
top
FOCn
COMnx1:0
bottom
81
2548F–AVR–03/2013
ATmega406
pare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values e ven when
changing between Waveform Generation modes.
Be aware that the COM0x1:0 bits are not double buffered together with the compare value.
Changing the COM0x1:0 bits will take effect immediately.
15.5 Compare Match Output Unit
The Compare Output mode (COM0x1:0) bits ha ve two functions. The Wavefor m Generator uses
the COM0x1:0 bits for defining the Output Compare (OC0x) state at the next compare match.
Also, the COM0x1:0 bits control the OC0x pin output source. Figure 15-4 shows a simplified
schematic of the logic affected by the COM0x1:0 bit setting. The I/O Regis ters, I/O bits, and I/O
pins in the figur e are shown in bold. Only the parts of the general I/O port control registers (DDR
and PORT) that are affected by the COM0x1:0 bits are shown. When referring to the OC0x
state, the reference is for the internal OC0x Register, not the OC0x pin. If a system reset occur,
the OC0x Register is reset to “0”.
Figure 15-4. Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC0x) from the Waveform
Generator if either of the COM0x1:0 bits are set. However, the OC0x pin direction (input or out-
put) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC0x pin (DDR_OC0x) must be set as output before the OC0x value is visi-
ble on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin log ic allows initialization of the OC0x state before the out-
put is enabled. Note that some COM0x1:0 bit settings are reserved for certain modes of
operation. See Section “15.8” on page 88 .
15.5.1 Compare Output Mode and Waveform Generation
The Waveform Generator uses th e COM0x1:0 bits differ ently in Normal, CTC, a nd PWM modes.
For all modes, setting the COM0x1:0 = 0 tells the Waveform Generator that no action on the
OC0x Register is to be perfor med on the ne xt compare match. F or compare output actio ns in the
non-PWM modes refer to Table 15-2 on page 88. For fast PWM m ode, refer to Table 15-3 on
page 88, and for phase correct PWM refer t o Table 15-4 on page 89.
PORT
DDR
DQ
DQ
OCnx
Pin
OCnx
DQ
Waveform
Generator
COMnx1
COMnx0
0
1
DATA BUS
FOCn
clk
I/O
82 2548F–AVR–03/2013
ATmega406
A change of the COM0x1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC0x strobe bits.
15.6 Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is
defined by the comb ination of the Waveform Gen eration mode (WGM02:0) and Compare Output
mode (COM0x1:0) bits. T he Compare Output mode bits do no t affect the counting sequence,
while the Waveform Generation mode bits do. The COM 0x1:0 bits control whether the PWM ou t-
put generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM0x1:0 bits control whether the output should be set, cleared, or toggled at a compare
match (See Section “15.5” on page 81.).
For detailed timing information refer to ”Timer/Counter Timing Diagrams” on page 86.
15.6.1 Normal Mode The simplest mode of operation is the Normal mode (WGM02:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bot-
tom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same
timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. Ho wever, combined with the timer overflow interrupt
that automatically clears the TOV0 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be written
anytime.
The Output Compare unit can be used to ge nerate interrupts at some given time . Usin g the Out-
put Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
15.6.2 Clear Timer on Compare Match (CTC) Mode
In Clear Timer on Compare or CTC mode (WGM02:0 = 2), the OCR0A Register is used to
manipulate the counter resolution . In CTC mode the counter is cleared to zero when the counter
value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter, hence
also its resolution. This m ode allows greater control of the compare match ou tput frequency. It
also simplifies the op e ra tio n of coun tin g exte rn al ev en ts.
The timing diagram for the CTC mode is shown in Figure 15-5. The counter value (TCNT0)
increases until a compare match occurs between TCNT0 and OCR0A, and then counter
(TCNT0) is cleared.
83
2548F–AVR–03/2013
ATmega406
Figure 15-5. CTC Mode, Timing Diagram
An interrupt ca n be gener ated each time the counter value reaches the TOP value by using the
OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing TOP to a value close to BOTTOM when the counter is run-
ning with none or a low pres caler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR0A is lower than the current
value of TCNT0, the counter will miss the compare match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the compare match can
occur.
For generating a waveform output in CTC mode, the OC0A output can be set to togg le its logica l
level on each compare match by setting the Compare Output mode bits to toggle mode
(COM0A1:0 = 1). The OC0A value will not be visible on the port pin unless the data direction for
the pin is set to output. The waveform generated will have a maximum frequency of fOC0 =
fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following
equation:
The N variabl e represents the prescale factor (1, 8, 64, 256, or 1024).
As for the Normal mode of op eration, the TOV0 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
15.6.3 Fast PWM Mode
The fast Pulse Width Modulation or fast PWM mode (WGM02 :0 = 3 or 7) provides a high fre-
quency PWM waveform generation option. The fast PWM differs from the other PWM option by
its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOT-
TOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7. In non-
inverting Compare Output mode, the Output Compare (OC0x) is cleared on the compare match
between TCNT0 and OCR0x, and set at BOTTOM. In inverting Compare Output mode, the out-
put is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the
operating fr equency of the fast PWM mode c an be twice as high as the phase corr ect PWM
mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows phy sically small
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the TOP value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
TCNTn
OCn
(Toggle)
OCnx Interrupt Flag Set
1 4
Period
2 3
(COMnx1:0 = 1)
fOCnx fclk_I/O
2N1OCRnx+
--------------------------------------------------=
84 2548F–AVR–03/2013
ATmega406
PWM mode is shown in Figure 15-6. The TCNT0 value is in the timing diagram shown as a his-
togram for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizo ntal line marks on th e TCNT0 slopes represe nt compare
matches between OCR0x and TCNT0.
Figure 15-6. Fast PWM Mode, Timing Diagram
The Timer/Coun ter Over flo w Flag (TOV0) is set each time the counter reaches TOP. If the inter-
rupt is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare un it allows generation of PWM waveforms on the OC0x pins.
Setting the COM0x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM0x1:0 to three: Setting the COM0A1:0 bits to one allows
the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not ava ilable
for the OC0B pin (see Table 15-6 on page 89). The actual OC0x value will only be visible on the
port pin if the data direction fo r th e port pin is set as ou tput. Th e PWM wa vefor m is gene ra te d by
setting (or clearing) the OC0x Register at the compare match between OCR0x and TCNT0, and
clearing (or setting) the OC0x Register at the timer clock cycle the counter is cleared (changes
from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variabl e represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values fo r the OCR0A Re gister rep resents special case s when gen erating a PW M
waveform output in the fast PWM mode. If the OCR0A is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0A equal to MAX will result
in a constantly high or low output (depending on the polarity of the output set by the COM0A1:0
bits.)
A frequency (with 50 % duty cycle) wavefo rm output in fast PWM mode can be achieved by set-
ting OC0x to toggle its logical level on each compare match (COM0x1:0 = 1). The waveform
generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This
TCNTn
OCRnx Update and
TOVn Interrupt Flag Set
1
Period 2 3
OCn
OCn
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx Interrupt Flag Set
4 5 6 7
fOCnxPWM fclk_I/O
N256
------------------=
85
2548F–AVR–03/2013
ATmega406
feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Out-
put Compare unit is enabled in the fast PWM mode.
15.6.4 Phase Correct PWM Mode
The phase correct PWM mode (WGM02:0 = 1 or 5) provides a high resolution phase correct
PWM waveform generation option. The phase correct PWM mode is based on a dual-slope
operation. The coun ter counts repeatedly from BOTTOM to TOP and then from TOP to BOT-
TOM. TOP is defined as 0xFF when WGM2:0 = 1, and OCR0A when WGM2:0 = 5. In non-
inverting Compare Output mode, the Output Compare (OC0x) is cleared on the compare match
between TCNT0 and OCR0x while upco unting, and set o n the compare match whil e downco unt-
ing. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has
lower maximum operation frequency than single slope operation. However, due to the symmet-
ric feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
In phase correct PWM mode the counter is increm ented until the counter valu e matches TOP.
When the counter reaches TOP, it changes the count direction. The TCNT0 value will be equal
to TOP for one timer clock cycle. The timing diagram fo r th e pha se correct PWM mode is shown
on F igure 15-7 . The TCNT0 value is in the timing diagram shown as a histogram for illustrating
the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The
small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0x
and TCNT0.
Figure 15-7. Phase Correct PWM Mode , Tim in g Dia gr am
The Timer/Counter Overflo w Flag (TOV0) is set each time the counter re aches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted
PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A0 bits to
TOVn Interrupt Flag Set
OCnx Interrupt Flag Set
1 2 3
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx Update
86 2548F–AVR–03/2013
ATmega406
one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is
not available for the OC0B pin (see Table 15-7 on page 90). The actual OC0x value will only be
visible on the port pin if the data direction fo r the port pin is se t as output. The PWM waveform is
generated by clearing (o r setting) the OC0x Register a t the compare ma tch between OCR0x and
TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at compare
match between OCR0x and TCNT0 when the counter decrements. The PWM frequency for the
output when using phase correct PWM can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represent special cases wh en generating a PWM
waveform output in the phase correct PWM mode. If the OC R0A is set equal to BOTTOM, the
output will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 15-7 O Cnx has a transition from high to low even though
there is no Compare Match. The point of this transition is to guarantee sym metry around BOT-
TOM. There are two cases that give a transition without Compare Match.
OCRnx changes its value from MAX, like in Figure 15-7. When the OCR0A value is MAX the
OCn pin value is the same as the result of a down-counting Compare Match. To ensure
symmetry around BOTTOM the OCnx value at MAX must correspond to the result of an up-
counting Compare Match.
The timer starts counting from a value higher than the one in OCRnx, and for that reason
misses the Compare Match and hence the OCnx change that would have happened on the
way up.
15.7 Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT0) is therefore shown as a
clock enable signal in the following figures. The figures include information on when interrupt
flags are set. Figure 15-8 contains timing data for basic Timer/Counter operation. The figure
shows the count sequence close to the MAX value in all modes other than phase correct PWM
mode.
Figure 15-8. Timer/Counter Timing Diagram, no Prescaling
Figure 15-9 shows the same timing data, but with the prescaler enabled.
fOCnxPCPWM fclk_I/O
N510
------------------=
clk
Tn
(clk
I/O
/1)
TOVn
clk
I/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
87
2548F–AVR–03/2013
ATmega406
Figure 15-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
Figure 15-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC
mode and PWM mode, where OCR0A is TOP.
Figure 15-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (fclk_I/O/8)
Figure 15-11 shows the setting of OCF0 A and the clearing of TCNT0 in CTC mode and fast
PWM mode where OCR0A is TOP.
Figure 15-11. Timer/Counter Timing Diagram, Clear Timer on Compare Ma tch mode, with Pres-
caler (fclk_I/O/8)
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clk
I/O
clk
Tn
(clk
I/O
/8)
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clk
I/O
clk
Tn
(clk
I/O
/8)
OCFnx
OCRnx
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clk
I/O
clk
Tn
(clk
I/O
/8)
88 2548F–AVR–03/2013
ATmega406
15.8 8-bit Timer/Counter Register Description
15.8.1 TCCR0A – Timer/Counter Control Register A
Bits 7:6 – COM0A1:0: Compare Match Output A Mode
These bits control the Output Compare pin (OC0A) behavior. If one or both of the COM0A1:0
bits are set, the OC0A output overrides the normal port function ality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0A pin
must be set in order to enable the output driver.
When OC0A is connected to the pin, the function of the COM0A1:0 bits depends on the
WGM02:0 bit setting. Table 15-2 shows the COM0A1:0 bit functionality when the WGM02:0 bits
are set to a normal or CTC mode (non-PWM).
Table 15-3 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See ”Fast PWM Mode” on page 83
for more details.
Bit 7 6 5 4 3 2 1 0
0x24 (0x44) COM0A1 COM0A0 COM0B1 COM0B0 WGM01 WGM00 TCCR0A
Read/Write R/W R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 15-2. Compare Output Mode, non-PWM Mode
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0A disconnected.
0 1 Toggle OC 0A on Compare Match
1 0 Clear OC0A on Compare Match
1 1 Set OC0A on Compare Match
Table 15-3. Compare Output Mode, Fast PWM Mode(1)
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0A disconnected.
01
WGM02 = 0: Normal Port Operation, OC0A Disconnected.
WGM02 = 1: Toggle OC0A on Compare Match.
1 0 Clear OC0A on Compare Match, set OC0A at TOP
1 1 Set OC0A on Compare Match, clear OC0A at TOP
89
2548F–AVR–03/2013
ATmega406
Table 15-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase cor-
rect PWM mode.
Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See ”Phase Correct PWM Mode” on
page 85 for more details.
Bits 5:4 – COM0B1:0: Compare Match Output B Mode
These bits control the Output Compare pin (OC0B) behavior. If one or both of the COM0B1:0
bits are set, the OC0B output overrides the normal port function ality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0B pin
must be set in order to enable the output driver.
When OC0B is connected to the pin, the function of the COM0B1:0 bits depends on the
WGM02:0 bit setting. Table 15-5 shows the COM0B1:0 bit functionality when the WGM02:0 bits
are set to a normal or CTC mode (non-PWM).
Table 15-6 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See ”Fast PWM Mode” on page 83
for more details.
Table 15-4. Compare Output Mode, Phase Correct PWM Mode(1)
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0A disconnected.
01
WGM02 = 0: Normal Port Operation, OC0A Disconnected.
WGM02 = 1: Toggle OC0A on Compare Match.
10
Clear OC0A on Compare Match when up-counting. Set OC0A on
Comp a re Match when down-counti n g.
11
Set OC0A on Compare Match when up-counting. Clear OC0A on
Comp a re Match when down-counti n g.
Table 15-5. Compare Output Mode, non-PWM Mode
COM0B1 COM0B0 Description
0 0 Normal port operation, OC0B disconnected.
0 1 Toggle OC 0B on Compare Match
1 0 Clear OC0B on Compare Match
1 1 Set OC0B on Compare Match
Table 15-6. Compare Output Mode, Fast PWM Mode(1)
COM0B1 COM0B0 Description
0 0 Normal port operation, OC0B disconnected.
01Reserved
1 0 Clear OC0B on Compare Match, set OC0B at TOP
1 1 Set OC0B on Compare Match, clear OC0B at TOP
90 2548F–AVR–03/2013
ATmega406
Table 15-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase cor-
rect PWM mode.
Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See ”Phase Correct PWM Mode” on
page 85 for more details.
Bits 3, 2 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bits 1:0 – WGM01:0: Waveform Generation Mode
Combined with the WGM02 bit found in the TCCR0B Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of wave-
form generation to be used , see Table 15-8. Modes of operation supported by the Timer/Cou nter
unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of
Pulse Width Modulation (PWM) modes (see Modes of Operation” on page 82).
Notes: 1. MAX = 0xFF
2. BOTTOM = 0x00
Table 15-7. Compare Output Mode, Phase Correct PWM Mode(1)
COM0B1 COM0B0 Description
0 0 Normal port operation, OC0B disconnected.
01Reserved
10
Clear OC0B on Compare Match when up-counting. Set OC0B on
Comp a re Match when down-counti n g.
11
Set OC0B on Compare Match when up-counting. Clear OC0B on
Comp a re Match when down-counti n g.
Table 15-8. Waveform Generation Mode Bit Description
Mode WGM02 WGM01 WGM00 Timer/Counter
Mode of Operation TOP Update of
OCRx at TOV Flag
Set on(1)(2)
0 0 0 0 Normal 0xFF Immediate MAX
1 0 0 1 PWM, Phase Correct 0xFF TOP BOTTOM
2 0 1 0 CTC OCRA Immediate MAX
3 0 1 1 Fast PWM 0xFF TOP MAX
4 1 0 0 Reserved
5 1 0 1 PWM, Phase Correct OCRA TOP BOTTOM
6 1 1 0 Reserved
7 1 1 1 Fast PWM OCRA TOP TOP
91
2548F–AVR–03/2013
ATmega406
15.8.2 TCCR0B – Timer/Counter Control Register B
Bit 7 – FOC0A: Force Output Compare A
The FOC0A bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0A bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC0A output is
changed according to its COM0A1:0 bits setting. Note th at the FOC0A bit is implemented as a
strobe. Therefore it is the value present in the COM0A1:0 bits that determines the effect of the
forced compare.
A FOC0A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR0A as TOP.
The FOC0A bit is always read a s zero.
Bit 6 – FOC0B: Force Output Compare B
The FOC0B bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0B bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC0B output is
changed according to its COM0B1:0 bits setting. Note th at the FOC0B bit is implemented as a
strobe. Therefore it is the value present in the COM0B1:0 bits that determines the effect of the
forced compare.
A FOC0B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR0B as TOP.
The FOC0B bit is always read a s zero.
Bits 5:4 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 3 – WGM02: Waveform Generation Mode
See the descript ion in the ”TCCR0A – Timer/Counter Control Register A” on page 88.
Bits 2:0 – CS02:0: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter.
Bit 7 6 5 4 3 2 1 0
0x25 (0x45) FOC0A FOC0B WGM02 CS02 CS01 CS00 TCCR0B
Read/Write W W R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
92 2548F–AVR–03/2013
ATmega406
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
15.8.3 TCNT0 – Timer/Counter Register
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare
Match on th e following time r clock. M odifying the counter (TCNT0) while the counter is running,
introduces a risk of missing a Compare Match between TCNT0 and the OCR0x Registers.
15.8.4 OCR0A – Output Compare Register A
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT0 ). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC0A pin.
15.8.5 OCR0B – Output Compare Register B
The Output Compare Register B contains an 8-bit value that is continuously compared with the
counter value (TCNT0 ). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC0B pin.
Table 15-9. Clock Select Bit Description
CS02 CS01 CS00 Description
0 0 0 No clock source (Timer/Counter stopped)
001clk
I/O/(No prescaling)
010clk
I/O/8 (From prescaler)
011clk
I/O/64 (From prescaler)
100clk
I/O/256 (From prescaler)
101clk
I/O/1024 (From prescaler)
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.
Bit 76543210
0x26 (0x46) TCNT0[7:0] TCNT0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x27 (0x47) OCR0A[7:0] OCR0A
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x28 (0x48) OCR0B[7:0] OCR0B
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
93
2548F–AVR–03/2013
ATmega406
15.8.6 TIMSK0 – Timer/Counter Interrupt Mask Register 0
Bits 7:3 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 2 – OCIE0B: Timer/Counter Output Compare Match B Interrupt Enable
When the OCIE0B bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter Compare Match B interrup t is enab led. The correspondin g interrupt is executed if
a Compare Match in Timer/Counter occurs, i.e., when the OCF0B bit is set in the Timer/Counter
Interrupt Flag Register – TIFR0.
Bit 1 – OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable
When the OCIE0A bit is written to one, and the I-bit in the Status Register is set, the
Timer/Coun te r0 Compare M a tch A in te rr up t is en ab le d. T h e co rr esponding int er ru p t is e xe cu te d
if a Compare Match in Timer/Counter0 occurs, i.e., when the OCF0A bit is set in the
Timer/Counter 0 Interrupt Flag Register – TIFR0.
Bit 0 – TOIE0: Timer/Counter0 Overflow Interrupt Enable
When the TOIE0 bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in the Timer/Counter 0 Inter-
rupt Flag Register – TIFR0.
Bit 7 6 5 4 3 2 1 0
(0x6E) ––––OCIE0BOCIE0ATOIE0TIMSK0
Read/Write RRRRRR/WR/WR/W
Initial Value 0 0 0 0 0 0 0 0
94 2548F–AVR–03/2013
ATmega406
15.8.7 TIFR0 – Timer/Counter 0 Interrupt Flag Register
Bits 7:3 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 2 – OCF0B: Timer/Counter 0 Output Co mpare B Match Flag
The OCF0B bit is set when a Compare Ma tch occurs be tween the Timer/Counte r and the data in
OCR0B – Output Compare Register 0 B. OCF0B is cleared by hardwa re whe n executing the co r-
responding interrupt handling vector. Alternatively, OCF0B is cleare d by writing a logic one to
the flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Match Interrupt Enable),
and OCF0B are set, the Timer/Counter Compare Match Interrupt is executed.
Bit 1 – OCF0A: Timer/Counter 0 Output Compare A Match Flag
The OCF0A bit is set when a Compare Match occurs between the Timer/Counter0 and the data
in OCR0A – Output Compare Register0. OCF0A is cleared by hardware when executing the cor-
responding interrupt handling vector. Alternativel y, OCF0A is cleared by writing a logic on e to
the flag. When the I-bit in SREG, OCIE0A (Timer/Counter0 Compare Match Interrupt Enable),
and OCF0A are set, the Timer/Counter0 Compare Match Interrupt is executed.
Bit 0 – TOV0: Timer/Counter0 Overflow Flag
The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by
writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt
Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed.
The setting of this flag is dependent of the WGM 02:0 bit settin g. Refer to Ta ble 15-8, ”Waveform
Generation Mode Bit Description” on page 90.
Bit 76543210
0x15 (0x35) –––––OCF0BOCF0ATOV0TIFR0
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
95
2548F–AVR–03/2013
ATmega406
16. 16-bit Timer/Counter1
The 16-bit Timer/Counter unit allows accurate program executio n timing (event m anagement) .
The main featur es are:
One Output Compare Unit
Clear Timer on Compare Match (Auto Reload)
Two Independent Interrupt Sources (TOV1 and OCF1A)
16.1 Overview Most register and bit references in this document are written in general form. A lower case “n”
replaces the Timer/Counter number, and a lower case “x” replaces the output compare unit
channel. However, when using the register or bit defines in a program, the precise form must be
used, i.e., TCNT1 for accessing Timer/Counter1 counter value and so on. The physical I/O reg-
ister and bit locations for ATmega406 are listed in the ”16-bit Timer/Counter Register
Description” on page 100.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 16-1. CPU acces sible
I/O registers, including I/O bits and I/O pins, are shown in bold.
The PRTIM1 bit in ”PRR0 – Power Reduction Register 0” on page 36 must be written to zero to
enable TImer/Counter1 module.
Figure 16-1. 16-bit Timer/Counter Block Diagram
16.1.1 Registers The Timer/Counter (TCNT1) and the Output Compare Register (OCR1A) are both 16-bit regis-
ters. Special procedures must be followed when accessing the 16-bit registers. These
procedures are described in the section ”Accessing 16-bit Registers” on page 96.The
Timer/Counter Control Register (TCCR1B) is an 8-bit register an has no CPU access restric-
tions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are visible in the Timer
Interrupt Flag Register (TIFR). Both interrupts are individually masked with the Timer Interrupt
Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure.
The Timer/Counter is clocked internally via the prescaler. The Clock Select logic block controls
which clock source the Timer/Counter uses to increme nt its value. Th e T imer/Counter is inactive
when no clock source is selected. The output from the clock select logic is referred to as the
timer clock (clkT1).
Timer/Counter
D
ATA BUS
OCRnA
=
TCNTn
=0xFFFF
Control Logic
Count
Clear
TOVn
(Int.Req
.)
TCCRnB
clk
Tn
OCFnA
(Int.Req
.)
96 2548F–AVR–03/2013
ATmega406
The Output Compare Register (OCR1A) is compared with the Timer/Counter value at all time.
The compare match event will set the Compare Match Flag (OCF1A) which can be used to gen-
erate an output compare interrupt request.
16.2 Accessing 16-bit Registers
The TCNT1 and OCR1A are 16-bit registers that can be accessed by the AVR CPU via the 8-bit
data bus. The 16-bit register must be byte accessed using two read or write operations. Each
16-bit timer has a single 8-bit register fo r temporary storing of the high byte of the 16-bit access.
The same temporary register is shared between all 16-bit registers within each 16-bit timer.
Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a 16-bit
register is written by the CPU, the high byte stored in the temporary register, and the low byte
written are both copied into the 16-bit register in the same clock cycle. When the low byte of a
16-bit registe r is read by the CPU, the high b yte of the 16-b it register is copied into the temporary
register in the same clock cycle as the low byte is read.
Not all 16-bit accesses uses the temporary register for the high byte. Reading the OCR1A 16-bit
register does not involve using the temporary register.
To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low
byte must be read before the high byte.
The following code examples show how to access the 16-bit tim er registers assuming that no
interrupts updates the temporary register. The same principle can be used directly for accessing
the OCR1A Register. Note that when using “C”, the compiler handles the 16 -bit access.
Note: 1. See ”About Code Examples” on page 7.
The assembly code examp le returns the TCNT1 value in the r17:r16 register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt
occurs between the two instructions accessing the 16-bit register, and the interrupt code
Assembly Code Examples(1)
...
; Set TCNT1 to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNT1H,r17
out TCNT1L,r16
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
...
C Code Examples(1)
unsigned int i;
...
/* Set TCNT1 to 0x01FF */
TCNT1 = 0x1FF;
/* Read TCNT1 into i */
i = TCNT1;
...
97
2548F–AVR–03/2013
ATmega406
updates the tem por ary r egist er by ac cessin g th e sa me or any other of the 16-bit timer registers,
then the result of the access outsid e the interrupt will be corrupted. Therefore , when both the
main code and the interrupt code update the temporary register, the main code must disable the
interrupts du rin g the 16-b it access.
The following code examples show how to do an atomic read of the TCNT1 Register contents.
Reading the OCR 1A Register can be done using th e sa me princip le.
Note: 1. See ”About Code Examples” on page 7.
The assembly code examp le returns the TCNT1 value in the r17:r16 register pair.
Assembly Code Example(1)
TIM16_ReadTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
; Restore global interrupt flag
out SREG,r18
ret
C Code Example(1)
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNT1 into i */
i = TCNT1;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}
98 2548F–AVR–03/2013
ATmega406
The following code examples show how to do an atomic write of the TCNT1 Register contents.
Writing to the OCR1A Register can be done using the same principle.
Note: 1. See ”About Code Examples” on page 7.
The assembly code example requires that the r17:r16 register pair contains the value to be writ-
ten to TCNT1.
16.2.1 Reusing the Temporary High Byte Register
If writing to more than one 16-bit reg ister where the high byte is the same for all r egisters written,
then the high byte only needs to be written once. However, note that the same rule of atomic
operation described previou sly also ap plies in this case.
16.3 Timer/Counter Clock Sources
The Timer/Counter is clocked by an internal clock source. The clock source is selected by the
Clock Select logic which is controlled by the Clock Select (CS1[2:0]) bits located in the
Timer/Counter Control Register B (TCCR1B). For details on clock sources and prescaler, see
”Timer/Counter0 and Timer/Counter1 Prescalers” on page 103.
Assembly Code Example(1)
TIM16_WriteTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT1 to r17:r16
out TCNT1H,r17
out TCNT1L,r16
; Restore global interrupt flag
out SREG,r18
ret
C Code Example(1)
void TIM16_WriteTCNT1( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNT1 to i */
TCNT1 = i;
/* Restore global interrupt flag */
SREG = sreg;
}
99
2548F–AVR–03/2013
ATmega406
16.4 Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit.
Figure 16-2 shows a block diagram of the counter and its surroundings.
Figure 16-2. Counter Unit Block Diagram
Signal description (internal signals):
Count Increment TCNT1 by 1.
Clear Clear TCNT1 (set all bits to zero).
clkT1Timer/Counter clock.
The 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNT1H) con-
taining the upper e ight bits of the coun ter, and Counter Low (TCNT1L) containing the lower eight
bits. The TCNT1H Register can only be indire ctly acce ssed by the CPU. Whe n the CPU does an
access to the TCNT1H I/O location, the CPU accesses the high byte temporary re gister (TEMP).
The temporary register is updated with the TCNT1H value when the TCNT1L is read, and
TCNT1H is updated with the temporary register value when TCNT1L is written. This allows the
CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus.
It is important to notice that there are special cases of writing to the TCNT1 Register when the
counter is counting that will give unpredictable results. The special cases are described in the
sections where they are of importance.
Depending on the mode of operation used, the counter is cleared or incremented at each Timer
Clock (clkT1). The clkT1 is generated from an internal clock source, selected by the Clock Select
bits (CS1[2:0]). When no clock source is selected (CS1[2:0] = 0) the timer is stopped. However,
the TCNT1 value can be accessed by the CPU, independent o f whether clk T1 is pr esent or not. A
CPU write overrides (has priority over) all counter clear or count operations.
16.5 Output Compare Unit
The 16-bit comparator continuously compares TCNT1 with the Output Compare Register
(OCR1A). If TCNT equals OCR1A the comparator signals a match. A match will set the Output
Compare Flag (OCF1A) at th e next tim er cloc k cycle. If e nabled (O CIE1A = 1 ), the outp ut com-
pare flag generates an output compare interrupt. The OCF1A flag is automatically cleared when
the interrupt is executed. Alternatively the OCF1A flag can be cleared by software by writing a
logical one to its I/O bit location.
TEMP (8-bit)
DATA BUS (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit) Control Logic
Count
Clear
TOVn
(Int.Req
.)
clkTn
100 2548F–AVR–03/2013
ATmega406
Figure 16-3 shows a block diagram of the output compare unit. The small “n” in the register and
bit names indicates the device number (n = 1 for Timer/Co unter1), and the “x” indicates output
compare unit (A). The elements of the block diagram that are not directly a part of the output
compare unit are gray sh aded.
Figure 16-3. Output Compare Unit, Block Diagram
16.5.1 Compare Match Blocking by TCNT1 Write
All CPU writes to the TCNT1 Register will block any compare match that occurs in the next timer
clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the
same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled.
16.5.2 Using the Output Compare Unit
Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT1 when using any of the output compare
channels, independent of whether the Timer/Counter is running or not. If the value written to
TCNT1 equals the OCR1x value, the compare match will be missed.
16.6 16-bit Timer/Counter Register Description
16.6.1 TCCR1B – Timer/Counter1 Control Register B
Bit 7:4 – Res: Reserved Bits
These bits is a reserved bit in the ATmega406 and always reads as zero.
Bit 3 – CTC1: Clear Timer/Counter1 on Compare Match
When the CTC1 control bit is set (one), Timer/Counter1 is reset to 0x00 in the CPU clock cycle
after a compar e mat ch.
OCFnx (Int.Req.)
=
(16-bit Comparator )
TEMP (8-bit)
DATA BUS
(8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
OCRnx (16-bit Register)
OCRnxH (8-bit) OCRnxL (8-bit)
Bit 76543210
(0x81) CTC1 CS12 CS11 CS10 TCCR1B
Read/Write R/W R/W R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
101
2548F–AVR–03/2013
ATmega406
Bit 2:0 – CS1[2:0]: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter.
16.6.2 TCNT1H and TCNT1L – Timer/Counter1
The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct
access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To
ensure that both the high and low bytes are read and written simultaneously when the CPU
accesses these registers, the access is performed using an 8-bit temporary high byte register
(TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit
Registers” on page 96.
Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a com-
pare match between TCNT1 and one of the OCR1x Registers.
Writing to the TCNT1 register blocks (removes) the compare match on the following timer clock
for all compare units.
16.6.3 OCR1AH and OCR1AL – Output Compare Register 1 A
The Output Compare Register con tains a 16-bit value that is continuously compared with the
counter value (TCNT1).
The Output Compare Register is 16 -bit in size. To ensure that both the high and low bytes are
written simultaneously when the CPU writes to these registers, the access is per formed using an
8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-
bit registers. See “Accessing 16-bit Registers” on page 96.
Table 16-1. CS1[2:0] - Clock Select Bit Description
CS12 CS11 CS10 Description
0 0 0 No clock source (Timer/counter stopped).
001clk
I/O/1 (No prescaling)
010clk
I/O/8 (From prescaler)
011clk
I/O/32 (From prescaler)
100clk
I/O/64 (From prescaler)
101clk
I/O/128 (From prescaler)
110clk
I/O/256 (From prescaler)
111clk
I/O/1024 (From prescaler)
Bit 76543210
(0x85) TCNT1[15:8] TCNT1H
(0x84) TCNT1[7:0] TCNT1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
(0x89) OCR1A[15:8] OCR1AH
(0x88) OCR1A[7:0] OCR1AL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
102 2548F–AVR–03/2013
ATmega406
16.6.4 TIMSK1 – Timer/Counter Interrupt Mask Register 1
Bit 7:2 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and always reads as zero.
Bit 1 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Cou nter1 Output Compare A Match interrupt is enabled. The corresp onding
Interrupt Vector (see “Reset and Interrupt Handling” on page 14) is executed when the OCF1A
flag, located in TIFR1, is set.
Bit 0 – TOIE1: Timer/Counter1, Overflow Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 overflow interrupt is enabled. The corresponding Interrupt Vector
(see “Reset and Interrupt Handling” on page 14) is executed when the TOV1 flag, located in
TIFR1, is set.
16.6.5 TIFR1 – Timer/Counter Interrupt Flag Register
Bit 7:2 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and always reads as zero.
Bit 1 – OCF1A: Timer/Counter1, Output Compare A Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output
Compare Register A (OCR1A).
OCF1A is automatically cleared when the Output compare Match A In terrupt Ve ctor is exe cuted.
Alternatively, OCF1A can be cleared by writing a logic one to its bit location.
Bit 0 – TOV1 : Timer/Counter1, Overflow Flag
TOV1 Flag is set when the Timer overflows.
TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed.
Alternatively, TOV1 can be cleared by writing a logic one to its bit location.
Bit 7 6 5 4 3 2 1 0
(0x6F) ––––OCIE1ATOIE1TIMSK1
Read/WriteRRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
0x16 (0x36) ––––––OCF1ATOV1TIFR1
Read/Write RRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
103
2548F–AVR–03/2013
ATmega406
17. Timer/Counter0 and Timer/Counter1 Prescalers
Timer/Counter1 and Timer/Counter0 share the same prescaler module, but the Timer/Counters
can have different prescaler settings. The description below applies to both Timer/Counter1 and
Timer/Counter0.
17.1 Internal Clock Source
The Timer/Counter can be clocked d ire ctly by the system clock (by se tting the CSn2 :0 = 1). This
provides the fastest operation, with a maximum Timer/Counter clock frequency equal to system
clock frequency (fCLK_I/O). Alternatively , one of the taps from th e prescaler can be used a s a
clock source by setting the CSn2:0. See Tab le 15 -9 o n pag e 92 for Timer/Co unter0 settin gs and
Table 16-1 on page 1 01 for Timer/Counter1 settings. The prescaled clock h as a frequency of
either fCLK_I/O/8, fCLK_I/O/32, fCLK_I/O/64, fCLK_I/O/128, fCLK_I/O/256, or fCLK_I/O/1024.
17.2 Prescaler Reset
The prescaler is free running, i.e., operates independently of the Clock Select logic of the
Timer/Counter, and it is shared b y Timer/Counter1 and Time r/Counter0. Since the prescaler is
not affected by the Timer/Counter’s clock select, the state of the prescaler will have implications
for situations where a prescaled clock is used. One example of prescaling artifacts occurs when
the timer is enabled and clocked by the p rescale r ( 6 > CSn2:0 > 1) . The numb er of system clock
cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system
clock cycles, where N equals the prescaler divisor.
It is possible to use the prescaler reset for synchron izing the Timer/Counter to program execu-
tion. However, care must be taken if the other Timer/Counter that shares the same prescaler
also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is
connected to.
17.3 External Clock Source
An external clock source applied to the T0 pin can be used as Timer/Counter0 clock (clkT0). The
T0 pin is sampled once every system clock cycle by the pin synchronization logic. The synchro-
nized (sampled) signal is th en passed throug h the edge d etector. Figur e 17-1 shows a functional
equivalent block diagram of the T0 synchronization and edge detector logic. The registers are
clocked at the positive edge of the internal system clock (clkI/O). The latch is transparent in the
high period of the internal system clock.
The edge detector gen erates one cl k T0 pulse for each positive (CSn2:0 = 7) or neg ative (CSn2 :0
= 6) edge it detects.
Figure 17-1. T1/T0 Pin Sampling
Tn_sync
(To Clock
Select Logic)
Edge DetectorSynchronization
DQDQ
LE
DQ
Tn
clk
I/O
104 2548F–AVR–03/2013
ATmega406
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the T0 pi n to the counter is updated.
Enabling and disabling of the clock input must be done when T0 has been stable for at least one
system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the sys-
tem clock frequency (fExtClk < fclk_I/O/2) give n a 50/50% duty cycle. Since th e edge detector use s
sampling, the maximum frequency of an external clock it can detect is half the sampling fre-
quency (Nyquist sampling theorem). However, du e to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximu m frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be pre sca le d.
Figure 17-2. Prescaler for Timer/Counter0 and Timer/Counter1(1)
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 17-1.
PSRSYNC
Clear
clk
T1
clk
T0
T0
clk
I/O
Synchronization
CK/32
CK/8
CK/64
CK/256
CK/128
CK/1024
105
2548F–AVR–03/2013
ATmega406
17.4 Register Description
17.4.1 GTCCR – General Timer/Counter Control Register
Bit 7 – TSM: Timer/Counter Synchronization Mode
Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the
value that is written to the PSRSYNC bit is kept, hence keeping the corresponding prescaler
reset signals asserted. This ensures that the corresponding Timer/Counters are halted and can
be configured to the same value without the risk of one of them advancing during configuration.
When the TSM bit is written to zero, the PSRSYNC bit is cleared by hardware, and the
Timer/Counters start counting simultaneously.
Bit 0 – PSRSYNC: Prescaler Reset
When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is nor-
mally cleared im mediately by har dware, except if the TSM bit is set. Note that Timer/Counter1
and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both
timers.
Bit 7654321 0
0x23 (0x43) TSM ––––– PSRSYNC GTCCR
Read/WriteR/WRRRRRRR/W
Initial Value 0 0 0 0 0 0 0 0
106 2548F–AVR–03/2013
ATmega406
18. Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC
18.1 Features Sampled System Coulomb Counter
Low Power Sigma-Delta ADC Optimized for Coulomb Counting
Instantaneous Current Output with 3.9 ms Conversion Time
Accumulate Current Output with Programmable Conversion Time: 125/250/500/1000 ms
Input voltage Range Larger than ± 0.15V, Allowing Measu rement of more than ± 30A @ 5 m
13-bit Resolution (in cluding sign) correspondin g to 53.7 µV (10.7 mA @ 5 m) for Instantaneous
Current Output
18-bit Resolution (in clud in g sign) corresponding to 1.68 µV (0.335 µA @ 5 m) for Accumulate
Current Output
Input Offset Less than 10 µV for the ADC
Interrupt on Instantaneous Current Conversion Comple te
Interrupt on Accumu la te Current Conv e r si on Comple te
Interrupt on Regular Current with Programmable Compare Level and Programmable Sampling
Interval: 250/500/1000/2000 ms
ATmega406 features a d edicated Sigma-Delta ADC (CC-ADC) optimized for Coulomb Counting
to sample the charge or discharge current flowing through the external sense resistor RSENSE.
Two different output values are provided, Instantaneous Current and Accumu late Current. The
Instantaneous Current Output has a short conversion time at the cost of lower resolution. The
Accumulate Current Output provides a highly accurate current measurement for Coulomb
Counting.
The sampling Coulomb Counter provide s a highly accurate and flexible solution. Accuracy can
easily be traded against conversion time. It also provides Regular Current detection. This allows
ultra-low power operation in Power-save mode when small charge or discharge currents are
flowing.
Figure 18-1. Coulomb Counter Block Diagram
Sigma Delta
modulator
Current
Comparator
Control &
Status
Register
IRQ
8-BIT DATABUS
R
SENSE
PI
NI
Regular
Current IRQ
Level
Decimation
INSTANTANEOUS
CURRENT
Decimation
IRQ
IRQ
ACCUMULATE
CURRENT
107
2548F–AVR–03/2013
ATmega406
18.2 Operation When enabled, the CC-ADC continuou sly measur es the voltage over th e ex tern al sense re sistor
RSENSE.
The Instantaneous Current conversion time is fixed to 3.9 ms (typical value) allowing the output
value to closely follow the input. After each Instantaneous Current conversion an inter rupt is
generate if the interrupt is enabled. Data from conversion will be updated in the Instantaneous
Current registers - CADICL and CADICH simultaneously as the interrupt is given. To avoid los-
ing conversion data, both the low an d high byte must be read within a 3,9 ms timing window after
the correspondin g interrup t is give n. When the low byte register is rea d, updating of the Insta nta-
neous Current registers and interrupts will be stopped until the high byte is read. Figure 18-2
shows an Instantaneous Current conversion diagram, where DATA4 will be lost because DATA3
reading is not completed withi n the limited period.
Figure 18-2. Instantaneous Current Conversion
The Accumulate Current output is a high-re solution, high accuracy output with progra mmable
conversion time selected by the CADAS bits in CADCSRA. The converted value is an accurate
measurement of the average current flow dur ing one conversion period. The CC- ADC generates
an interrupt each time a new Accumulate Current conversion has finished if the interru pt is
enabled. Data from conversion will be updated in the Accumulation Current registers - CADAC0,
CADAC1, CADAC2 and CADAC3 simultaneously as the interrupt is given. To avoid losing con-
version data, all bytes must be read within the selected conversion period. When the lower byte
registers are read, updating of the Accumulation Current registers and interrupts will be stopped
until the highest byte is read. Figure 18-3 on page 108 shows an Accumulat ion Current conver-
sion example, where DATA4 will be lost because DATA3 reading is not completed within the
limited period.
Enable
Instantaneous Interrupt
Instantaneous Data
Read low byte
Read high byte
DATA1 DATA 2 DATA 3 D ATA 5Setting of Digital Filters
~12 ms settling 3.9 ms 3.9 ms 7.8 ms
108 2548F–AVR–03/2013
ATmega406
Figure 18-3. Accumulation Current Conversion
While the CC-ADC is conv erting, the CPU can enter sleep mode and wait for an interrupt from
the Accumulate Current conversion. After addin g the new Accumulate Current value for Cou-
lomb Counting, the CPU can go back to sleep again. This reduces the CPU workload, and
allows more time spent in low power modes, reducing po wer consumption. The CC-ADC ca n
generate an interrupt if the result of an Instantaneous Current conversion is greater than a pro-
grammable threshold. This allows the detection of a Regular Current condition. This function is
available in Active mode and all sleep modes except Power-down and Power-off mode. This
allows an ultra-low power operation in Power-save, where the CC-ADC can be configured to
enter a Regular Current detection mode with a programmable current sampling interval. By set-
ting the CADSE bit in CADCSRA, the Coulomb Counter will repeatedly do one Instantaneous
Current conversion, before it is being turned off for a timing interval specified by the CADSI bits
in CADCSRA. This allows operating the Regular Current detection while keeping the Coulomb
Counter off most of the time.
The Coulomb Counter is ha lted in Powe r- do wn mode. In this mode, time measurements and the
battery self-discharge characteristics should be used to estimate the charge flow. When waking
up from Power-down mode, the CC-ADC will automatically resume continuous operation.
The CC-ADC is enabled by se tting the CC-ADC Enable bit, CADEN, in CADCSRA. Note that the
bandgap voltage reference must be enabled separately, see ”BGCCR – Bandgap Calibration C
Register” on page 123.
The CC-ADC will not consume power when CADEN is cleared. It is therefore recommended to
switch off the CC-ADC whenever the Coulomb Counter or Regular Current Detection functions
are not used. The CC-ADC is autom atically disabled in Power-down and Power-off mode.
After the CC-ADC is enabled, either by setting the CADEN bit or leaving Power-down with
CADEN already set, the first four conversions do not contain useful data and should be ignored.
This also applies after clear ing the CADSE bit.
In-system offset voltage for the CC -ADC is typic ally in the range 0 - 100 µV. To compensate for
this offset error, a CC-ADC offset value should be stored in EEPROM and subtracted from each
Accumulate Current conversions before the resulting value is added for Coloumb Counting. The
CC-ADC offset value can be found by performing a CC-ADC conversion at typical temperature
with zero current flowing through RSENSE.
When the battery is not used or the current level stays very low for a long time, it is recom-
mended to estimate the charge flow instead of using the CC-ADC for Coloumb Counting. The
Enable
Accumulation Interrupt
Accumulation Data
Read byte 1
Read byte 2
Read byte 3
Read byte 4
DATA1 DATA 2 DATA 3 D ATA 5Setting of Digital Filters
125, 250, 500,
or 1000 ms
250, 500, 1000,
or 2000 ms
125, 250, 500,
or 1000 ms
109
2548F–AVR–03/2013
ATmega406
charge flow estimation should be based on the self-discharg e rate of the b attery and th e standby
current of the ba tt er y syst em .
18.2.1 CADCSRA – CC-ADC Control and Status Register A
Bit 7 – CADEN: CC-ADC Enable
When the CADEN bit is cleared (zero), the CC-ADC is disab led, and any ongoing conversions
will be terminated. When the CADEN bit is set (one), the CC-ADC will continuously measure the
voltage drop over the external sense resistor RSENSE. In Power-off, the CC-ADC is always dis-
abled. Note that the bandgap voltage refe rence must be enabled separately, see ”BGCCR –
Bandgap Calibration C Register” on page 123.
Bit 6 – Res: Reserved
This bit is reserved bit in the ATmega406 and will always read as zero.
Bit 5 - CADUB: CC-ADC Update Busy
The CC-ADC operates in a different clock domain than the CPU. Whenever a new value is writ-
ten to CADCSRA, CADRCC or CADRDC, this value must be synchronized to the CC-ADC clock
domain. Subsequent writes to these registers will be blocked during this synchronization. Syn-
chronization of one of the registers, will block updating o f all the others. The CADUB bit will be
read as one while any of these registers is being synchronized , and will be read as zero when
neither register is being synchronized.
Bits 4:3 – CADAS1:0: CC-ADC Accumulate Current Select
The CADAS bits select the conversion tim e for the Accu mulate Current output a s shown in Table
18-1.
Bit 765 4 3 210
(0xE4) CADEN CADUB CADAS1 CADAS0 CADSI1 CADSI0 CADSE CADCSRA
Read/Write R/W R R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 18-1. CC-ADC Accumulate Current Conversion Time
CADAS1:0 CC-ADC Accumulate Current Conversion Time
00 125 ms
01 250 ms
10 500 ms
11 1 s
110 2548F–AVR–03/2013
ATmega406
Bits 2:1 – CADSI1:0: CC-ADC Current Sampling Interval
The CADSI bits determine the current sampling interval for the Regular Current detection as
shown in Table 18-2. The current sampling interval is only used if the CADSE bit is set.
Notes: 1. The actual value of depends on the actual frequency of the ”Slow RC Oscillator” on page 27.
See ”Electrical Characteristics” on page 225.
2. Sampling time ~ 12 ms.
Bit 0 – CADSE: CC-ADC Current Sampling Enable
When the CADSE bit is written to one, the ongoing CC-ADC conversion is aborte d, an d th e CC -
ADC enters Regular Current detection mode.
18.2.2 CADCSRB – CC-ADC Control and Status Register B
Bits 7, 3 – Res: Reserved
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 6 – CADACIE: CC-ADC Accumulate Current Interrupt Enable
When the CADACIE bit is set (one), and the I-b it in the Status Register is set (one), the CC-ADC
Accumulate Current Interrupt is enabled.
Bit 5 – CADRCIE: CC-ADC Regular Current Interrupt Enable
When the CADRCIE bit is set (one), and the I-bit in the Status Register is set ( one), the CC-ADC
Regular Current Interrupt is enabled.
Bit 4 – CADICIE: CC-ADC Instantaneous Current Interrupt Enable
When the CADICIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC
Instantaneous Current Interrupt is enabled.
Bit 2 – CADACIF: CC-ADC Accumulate Current Interrupt Flag
The CADACIF bit is set (one) after the Accumulate Current conversion has completed. The CC-
ADC Accumulate Current Interrupt is executed if the CADACIE bit and the I-bit in SREG are set
(one). CADACIF is cleared by hardware when executing the corresponding Interrupt Handling
Vector. Alternatively, CADACIF is cleared by writing a logic one to the flag.
Bit 1 – CADRCIF: CC-ADC Regular Current Interrupt Flag
Table 18-2. CC-ADC Regular Current Sampling Interval
CADSI1:0 CC-ADC Regular Current Sampling Interval(1)(2)
00 250 ms (+ sampling time)
01 500 ms (+ sampling time)
10 1 s (+ sampling time)
11 2 s (+ sampling time)
Bit 7 6 5 4 3 2 1 0
(0xE5) CADACIE CADRCIE CADICIE CADACIF CADRCIF CADICIF CADCSRB
Read/Write R R/W R/W R/W R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
111
2548F–AVR–03/2013
ATmega406
The CADRCIF bit is set (one) when the absolute value of the result of the la st CC-ADC co nver-
sion is greater than, or equal to, the compare values set by the CC-ADC Regular
Charge/Discharge Current Level Registers. A positive value is compared to the Regular Charge
Current Level, and a negative value is compared to the Regular Discharge Current Level. The
CC-ADC Regular Current Interrupt is executed if the CADRCIE bit and the I-bit in SREG are set
(one). CADRCIF is cleared by hardware when ex ecuting the corresponding Interrupt Handling
vector. Alternatively, CADRCIF is cleared by writing a logic one to the flag.
Bit 0 – CADICIF: CC-ADC Instantaneous Current Interrupt Flag
The CADICIF bit is set (one) when a CC-ADC Instantaneous Current conversion is completed.
The CC-ADC Instantaneous Current Interrupt is executed if the CADICIE bit and the I-bit in
SREG are set (one). CADICIF is cleared by hardware when executing the corresponding Inter-
rupt Handling vector. Alternativ ely, CADICIF is cleared by writing a logic one to the flag.
18.2.3 CADICH and CADICL – CC-ADC Instantaneous Current
When a CC-ADC Instantaneous Current conversion is complete, the result is found in these two
registers. CADIC15:0 represents the converted result in 2's complement format, sign extende d
to 16 bits.
When CADICL is read, the CC-ADC Instantaneous Current register is not updated until CADCH
is read. Reading the registers in the sequence CADICL, CADICH will ensure that consistent val-
ues are read .
18.2.4 CADAC3, CADAC2, CADAC1 and CADAC0 – CC-ADC Accumulate Current
The CADAC3, CADAC2, CADAC1 and CADAC0 Registers contain the Accumulate Current
measurements in 2’s complement format, sign extended to 32 bits.
Bit 151413121110 9 8
(0xE9) CADIC[15:8] CADICH
(0xE8) CADIC[7:0] CADICL
Bit 76543210
Read/Write RRRRRRRR
RRRRRRRR
Initial Value00000000
00000000
Bit 3130292827262524
23 22 21 20 19 18 17 16
15 14 13 12 11 10 9 8
76543210
(0xE3) CADAC[31:24] CADAC3
(0xE2) CADAC[23:16] CADAC2
(0xE1) CADAC[15:8] CADAC1
(0xE0) CADAC[7:0] CADAC0
Read/Write RRRRRRRR
RRRRRRRR
RRRRRRRR
Initial Value00000000
00000000
00000000
112 2548F–AVR–03/2013
ATmega406
When CADAC0 is read, the CC-ADC Ac cumulate Current register is not updated until CADAC3
is read. Reading th e registers in the sequence CADAC0, CADAC1, CADAC2, CADAC3 will
ensure that co ns iste nt value s ar e re ad .
18.2.5 CADRCC – CC-ADC Regular Charge Current
The CC-ADC Regular Charge Current Register determines the threshold level for the Regular
Charge Current detection. When the result of a CC-ADC Instantaneous Current conversion is
positive with a value greater than, or equal to, the Regular Charge Current level, the CC-ADC
Regular Current Interrupt Flag is set.
The value in this register is specified in 2's complement format, and it defines the eight least sig-
nificant bits of the Regular Charge Cu rrent le vel. The mo st signif ica nt bits of the Regu lar Charge
Current level are always zero. The programmable range for the Regular Charge Current level is
given in Table 18-3.
The CC-ADC Regula r Charge Current Re gister does not aff ect the setting of th e CC-ADC Con-
version Complete Interrupt Flag.
18.2.6 CADRDC – CC-ADC Regular Discharge Current
The CC-ADC Regular Discharge Curren t Register determine s the thresho ld level for the Regu lar
Discharge Current detection. When the result of a CC-ADC Instantaneous Current conversion is
negative with an absolute value greater than, o r equal to, the Regular Discharge Current level,
the CC-ADC Regular Current Interrupt Flag is set.
The value in this register is specified in 2's complement format, and it defines the eight least sig-
nificant bits of the Regular Discharge Current level. The most significant bits of the Regular
Bit 76543210
(0xE6) CADRCC[7:0] CADRCC
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value00000000
Table 18-3. Programmable Range for the Regular Charge Current Level
Minimum Maximum Step Size
Voltage (µV) 0 13700 53.7
Current (mA) RSENSE = 5 m0 2740 10.7
RSENSE = 7 m0 1957 7.7
Bit 76543210
(0xE7) CADRDC[7:0] CADRDC
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value00000000
113
2548F–AVR–03/2013
ATmega406
Charge Current level are always one. The programmable range for the Regular Discharge Cur-
rent level is given in Table 18-4.
The CC-ADC Regular Discharge Current Register does not affect the setting of the CC-ADC
Conversion Complete Interrupt Flag.
Table 18-4. Programmable Range for the Regular Discharge Current Level
Minimum Maximum Step Size
Voltage (µV) 0 13700 53.7
Current (mA) RSENSE = 5 m0 2740 10.7
RSENSE = 7 m0 1957 7.7
114 2548F–AVR–03/2013
ATmega406
19. Voltage Regulator
19.1 Features Linear Regulation.
Operating Voltage Range 4.0 - 25V.
Fixed Output Voltage at 3.3V.
ATmega406 is supplied by the VFET terminal. Operating voltage range at the VFET terminal is
4.0 - 25V. The In ternal Voltage Regula tor regulates this voltage down to 3.3V, which is a suitable
supply voltage for the internal logic, I/O lines, and analog circuitry.
An external decoupling capacitor of 1 µF or larger is required for stable operation of the Voltage
Regulator. A larger capacitor will allow larger load currents and increase start-up time.
The block diagram of the Voltage Regulator is shown in Figure 19-1.
Figure 19-1. Voltage Regulator Block Diagram
19.2 Operation The Regulator will operate in all sleep modes, including Power-off. In this mode the regulator will
automatically red uce the ATmega406's power consu mption by turning off supply fo r all periph-
eral modules, allowing only the Charger Detect module and the Voltage Regulator itself to
operate.
The Regulator will automatically ensure that it has stable work conditions before allowing itself to
start regulating the VFET terminal. If the voltage at the VFET pin is below the Regulator-on
Threshold voltage, VROT, the LDO will be switched off.
Powering-up the regulator is either done from the battery side when the smart battery controller
is assembled with the battery pack and there is no charger present, or from the charger side
when a deep discharge has occurred (0V charging).
When powering- up with a charger pre sent, the voltage between the VFET and the PVT pin must
be above a Charge-Threshold voltage, VCHT.
LDO
Regulator
Regulator
Control
Creg > 1 u
F
VFET
Power
Distributor
PVT
LDO_ONPV1
Rsense
RP
RN
VREG
Voltage Regulator
Analog
Supply
Digital
Supply
POWER_OFF
115
2548F–AVR–03/2013
ATmega406
When powering-up without a charger present, the voltage on Cell1, VPV1, must be above the
Cell1-Threshold voltage, VPV1T.
After powering-up the regulator the chip will enter Power-off sleep mode (lowest power con-
sumption). Until a charger is detected, the chip will stay in this mode. For details on Charger
Detect, see ”Power-on Reset and Charger Connect” on page 40.
Table 30-2 on page 230 shows the characteristics for powering-up the LDO.
116 2548F–AVR–03/2013
ATmega406
20. Voltage ADC – 10-channel General Purpose 12-bit Sigma-Delta ADC
20.1 Features 12-bit Resolution
±1 LSB Accuracy
519µs Conversion Time
Four Differential Input Channels for Cell Voltage Measurements
Six Single Ended Input Channels
0 to 0.9 x VREF Input Voltage Range
0.2x Pre-sc a ling of Cell Voltag es and VREG
Interrupt on V-ADC Conversion Complete
The ATmega40 6 features a 12-bit Sigm a-Delta ADC. Automatic offset cancellation techniqu e
reduces the input offset voltage to less than 0.5 mV.
The Voltage ADC (V-ADC) is connected to ten different sou rces through t he Input Multiple xer.
There are four differential channels for Cell Voltage measurements. These channels are scaled
0.2x to comply with the Full Scale range of the V-ADC. In addition there are six single ended
channels referenced to SGND. One channel is for measuring the internal temperature sensor
VPTAT and five channels for measuring the ADC input pins at Port A. ADC3:0 are not scaled,
meaning that full-scale reading corresponds to 1.1 V. ADC4 is scaled by 0.2x, meaning that full-
scale reading corres ponds to 5.5 V. The ADC4 input ca n be used to meas ure the volta ge at th e
PA4 pin when this pin is used to supply an external thermistor, see Figure 29-1 on page 223.
To obtain a total absolute accuracy better than ± 0.25% for the cell voltage measurements, cali-
bration regist ers for the indiv idual cell v oltage gain in the analog front-en d is pro vided. A fac tory
calibration value is stored in the sig nature row, see Se ction 27.7 .10 ” Reading the Signature Row
from Software” on page 189. The V-ADC conversion of a cell voltage must be scaled with the
corresponding calibratio n value by software to correct for gain error in the analog front-end.
The PRVADC bit in ”PRR0 – Power Reduction Register 0” on page 36 must b e writte n to zero to
enable V-ADC module.
117
2548F–AVR–03/2013
ATmega406
Figure 20-1. Voltage ADC Block Schematic
20.2 Operation To enable V-ADC conversions, the V-ADC Enable bit, VADEN, in V-ADC Control and Status
Register – VADCSR must be set. If this bit is cleared, the V-ADC will be switched off, and any
ongoing conversions will be terminated. The V-ADC is automatically halted in Power-save,
Power-down and Power-off mode. Note that the bandgap voltage reference must be enabled
and disabled separately, see “BGCCR – Bandgap Calibration C Register” on page 123.
Figure 20-2. Voltage ADC Conversion Diagram
To perform a V- ADC conversion, th e analog input channe l must first be selected by writing to the
VADMUX bits in VADMUX. When a logical one is written to the V-ADC Start Conversion bit
VADSC, a conversion of the selected channel will start. The VADSC bit stays high as long as the
conversion is in progress and will be cleared by hardware when the conversion is completed. If a
different data channel is selected while a conversion is in progress, the ADC will finish the cur-
rent conversion before performing the channel change. When a conversion is finished the V-
V-ADC CONVERSION COMPLETE IRQ
8-BIT DATA BUS
V-ADC MULTIPLEXER
SEL. REG (VADMUX) V-ADC CONTROL AND
STATUS REG (VADCSR)
V-ADC DATA REGISTER
(VADCL/ADCH)
VADCCIE
VADCCIF
12-BIT
SIGMA-DELTA ADC
INPUT
MUX
V-ADC CONTROL
ADC3
ADC2
ADC1
ADC0
V
TEMP
ADC4
PV4
PV3
PV2
PV1
NV
Note:
The shaded signals are scaled by 0.2,
other signals are scaled by 1.0
VREF SGND
Start Conversion
Interrupt
Conversion Result
INVALID DATA
INVALID DATA
OLD DATA VALID DATA
519 us
118 2548F–AVR–03/2013
ATmega406
ADC Conversion Complete Interrupt Fla g – VADCCIF is set. One 12-bit conversion takes 519 µs
to complete from the star t bit is set to the in terrupt flag is set. To ensure that correct data is read,
both high and low byte data registers should be read before starting a new conversion.
20.3 Register Description
20.3.1 VADMUX – V-ADC Multiplexer Selection Register
Bit 7:4 – RES: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 3:0 – VADMUX3:0: V-ADC Channel Selection Bits
The VADMUX bits determine the V-ADC channel selection. See Table 20-1 on page 118.
20.3.2 VADCSR – V-ADC Control and Status Register
Bit 7:4 – RES: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 3 – VADEN: V-ADC Enable
Writing this bit to one enables V-ADC conversion. By writing it to zero, the V-ADC is turned off.
Turning the V-ADC off while a conversion is in progress will terminate this conversion. Note that
the bandgap voltage reference must be enabled separately, see “BGCCR – Bandgap Calibra-
tion C Register” on page 123.
Bit 7654 3 2 1 0
(0x7C) VADMUX3 VADMUX2 VADMUX1 VADMUX0 VADMUX
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 20-1. VADMUX channel selection
VADMUX3:0 Channel Selected Scale
0001 CELL 1 0.2
0010 CELL 2 0.2
0011 CELL 3 0.2
0100 CELL 4 0.2
0101 ADC4 0.2
0110 VTEMP 1.0
0111 ADC0 1.0
1000 ADC1 1.0
1001 ADC2 1.0
1010 ADC3 1.0
Bit 76543210
(0x7A) –– VADEN VADSC VADCCIF VADCCIE VADCSR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
119
2548F–AVR–03/2013
ATmega406
Bit 2 – VADSC: Voltage ADC Start Conversion
Write this bit to one to start a new conversion of the selected channel.
VADSC will read as one as long as the conversion is not finished. When the conversion is com-
plete, it returns to zero. Writing zero to this bit has no effect. VADSC will automatically be
cleared when the VADEN bit is written to zero.
Bit 1 – VADCCIF: V-ADC Conversion Complete Interrupt Flag
This bit is set when a V-ADC conversion completes and the data registers are updated. The V-
ADC Conversion Complete Interrupt is executed if the VADCCIE bit and the I-bit in SREG are
set. VADCCIF is cleared by hardware when executing the corresponding interrupt handling vec-
tor. Alternatively, VADCCIF is cleared by writing a logical one to the flag. Beware that if doing a
Read-Modify-Write on VADCSR, a pending interrupt can be disabled.
Bit 0 – VADCCIE: V-ADC Conversion Complete Interrupt Enable
When this bit is written to one and the I-bit in SREG is set, the V-ADC Conversion Complete
Interrupt is activated.
20.3.3 VADCL and VADCH – The V-ADC Data Register
When a V-ADC conversio n is comp lete, the resu lt is found in these two registers. To ensure that
correct data is read, the data registers must be read before starting a new conversion.
VADC11:0: V- AD C Conversion Result
These bits represent the result from the conversion.
To obtain the best absolute accuracy for the cell voltage measurements, gain and offset com-
pensation is required. Factory calibration values are stored in the device signature row, refer to
section ”Reading the Signature Row from Software” on page 189 for details. The cell voltage in
mV is given by:
When performing a Vtemp conversion, the result must be adjusted by the factory calibration
value stored in th e signature r ow, refer to section Reading the Signature Row from Softwa re” on
page 189 for details. The absolute temperature in Kelvin is given by:
Bit 15 14 13 12 11 10 9 8
(0x79) VADC[11:8] VADCH
(0x78) VADC[7:0] VADCL
7 6543 210
Read/WriteR RRRR RRR
R RRRR RRR
Initial Value 0 0 0 0 0 0 0 0
0 0000 000
Cellnvoltage mV
celln result cellngain calibra tion word
TBD
--------------------------------------------------------------------------------------------------- cellnoffset calibration word=
T(K) Vtempresult VPTAT calibration word
TBD
------------------------------------------------------------------------------------------------=
120 2548F–AVR–03/2013
ATmega406
20.3.4 DIDR0 – Digital Input Disable Register 0
Bits 7:4 – Res: Reserved Bits
These bits are reser ved for future use. To ensure compatib ility with future devices, these bits
must be written to zero when DIDR0 is written.
Bit 3:0 – VADC3D:VADC0D: V-AD C3:0 Digital Input Disable
When this bit is written logic one, the digital input buffer on the corresponding V-ADC pin is dis-
abled. The corresponding PIN Register bit will always read as zero when this bit is set. When an
analog signal is applied to the VADC3:0 pin and the digital input from this pin is not needed, this
bit should be written logic one to reduce power consumption in the digital input buffer.
Bit 7 6 5 4 3 2 1 0
(0x7E) VADC3D VADC2D VADC1D VADC0D DIDR0
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
121
2548F–AVR–03/2013
ATmega406
21. Volt age Reference and Temperature Sensor
21.1 Features Accurate Voltage Referen ce of 1.100V
± 0.1% Accuracy After Calibration (2 mV Calibration Steps)
Temperature Drift Less than 80 ppm/°C after Calibration
Alternate Low Power Voltage Reference for Voltage Regulator
Internal Temperature Sensor
Possibility for Runtime Compensation of Temperature Drift in Both Voltage Reference and On-
chip Oscill ators
External Decoupling for Optimum Noise Performance
Low Power Cons umption
A low power band-gap reference provides ATmega406 with an accurate On-chip voltage refer-
ence VREF of 1.100V. This reference voltage is used as reference for the On-chip Voltage
Regulator, the V-ADC and the CC-ADC. The reference to the ADCs uses a buffer with external
decoupling capacitor to enable excellent noise performance with minimum power consumption.
The referenc e voltage VREF_P/VREF_N to the CC-ADC is scaled to match the full scale require-
ment at the current sense input pins. This configuration also enables concurrent operation of
both V-ADC and CC-ADC.
To guaranty ultra low t emper ature drift afte r factory calibration, ATmega406 features a two-step
calibration algorithm. The first step is performed at 85C and the second at room temperature.
By default, Atmel fact ory calibration is performed at 85C, and the result is stored in Flash. The
customer can easily implement the second calibration step in their test flow. Th is requires an
accurate input voltage and a stable room temperature. Temperature drift after this calibration is
guarantied by design and characterization to be less than 80 ppm/C from 0C to 60C and 100
ppm/C from 0C to 85C. The BG Calibration C Register can also be altered runtime to imple-
ment temp eratur e compen sation in softwar e. Very h igh accu racy fo r any tem peratu re inside the
temperature range can thus be achieved at the cost of extra calibration steps.
A lower power, less accurate voltage reference source exists. This voltage reference source is
chosen as reference for the voltage reg ulator whenever the band-gap voltage refer ence is dis-
abled. This voltage reference source is not available for the V-ADC and CC-ADC.
ATmega406 ha s an On-chip temperatu re sensor for monitor ing the die temperatu re. A voltage
Proportional-To-Absolute-Temperature, VPTAT, is gene rated in the voltage reference circuit and
connected to the multiplexer at the V-ADC input. This temperature sensor can be used for run-
time compensation of temperature drift in both the voltage reference and the On-chip Oscillator.
To get the absolute temperature in degrees Kelvin, the measured VPTAT voltage must be scaled
with the VPTAT factory calibration val ue stored in the sign ature row. See ”Reading the Signa ture
Row from Software” on page 189 for details.
122 2548F–AVR–03/2013
ATmega406
Figure 21-1. Reference Circuitry
21.2 Writing to Bandgap Calibration Registers
When the calibration registers are changed it will affect both the Voltage Regulator output and
BOD-level. The BOD will react quickly to new detection levels, while the regulator will adjust the
voltage more slowly, depending on the size of the external decoupling capacitor. To avoid that a
BOD-reset is issued when calibration is done, it is recommended to ch ange the values of the
BGCC and BGCR bits stepwise, with a step size of 1, and with a hold-off time between each
step.
The hold-off time depends on the size of the voltage regulators external decoupling capacitor.
For details, see Table 21-1.
BG Reference
VREF
VREF_P
VREF_N
VREF_GND
CREF
VPTAT
1.1V
0.22V
Table 21-1. Hold-off Times depending on CREG.
Regulator Cap Hold-off Time BGCCR Hold-off Time BGCRR
1 F1.2 s3.0 s
2 F2.4 s6.0 s
3 F3.6 s9.0 s
4 F4.8 s 12.0 s
5 F6.0 s 15.0 s
6 F7.2 s 18.0 s
7 F8.4 s 21.0 s
8 F9.6 s 24.0 s
9 F 10.8 s 27.0 s
10 F 12.0 s 30.0 s
123
2548F–AVR–03/2013
ATmega406
21.3 Register Description for Voltage Reference and Temperature Sensor
21.3.1 BGCCR – Bandgap Calibration C Register
•Bit 7 - BGEN
This bit is not available from revision E and on of the ATmega406. A complete description is
found in the revision A of this document.
Bit 6 – Res: Reserved Bit
This bit is reserved for future use.
Bit 5:0 – BGCC5:0: BG Calibration of PTAT Current
These bits are used for trimming of the nominal value of the bandgap reference voltage. These
bits are binary coded. Minimum VREF: 000000, maximum VREF: 111111. Step size approxi-
mately 2 mV.
21.3.2 BGCRR – Bandgap Calibration R Register
Bit 7:0 – BGCR7:0: BG Calibration of Resistor ladder
These bits are used for temperature gradient adjustment of the bandgap reference. Figure 21-2
illustrates VREF as a function of temperature. VREF has a positive temperature co efficient at
low temperatures and negative temperature coefficient at high temperatures. Depending on the
process variations, the top of the VREF curve may be located at higher or lower temperatures.
To minimize the temperature drift in the temperature range of interest, BGCRR is used to adjust
the top of the curve towards the centre of the te mperature range of interest. The BGCRR bits are
temperature coded resulting in 9 possible settings: 000 00000, 00000001, 00000011, 00000111,
… , 11111111. The value 00000000 shifts the top of the VREF curve to the highest possible
temperature, and the value 11111111 shifts the top of the VREF curve to the lowest possible
temperature.
Bit 76543210
(0xD0) BGEN BGCC5 BGCC4 BGCC3 BGCC2 BGCC1 BGCC0 BGCCR
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
(0xD1) BGCR7 BGCR6 BGCR5 BGCR4 BGCR3 BGCR2 BGCR1 BGCR0 BGCRR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
124 2548F–AVR–03/2013
ATmega406
Figure 21-2. Illustration of VREF as a function of temperature.
0
0.5
1
1.5
-40 -20 0 20 40 60 80 10
0
Temperature [
o
C]
VREF [V]
Temperature range of interest
BGCRR is used to move the top of the VREF
curve to the center of the tempearture range of
interest.
125
2548F–AVR–03/2013
ATmega406
22. Battery Protection
22.1 Features Deep Under - voltage Protection
Charge Over-current Protection
Discharge Over-current Protection
Short-circuit Protection
Programmable and Lockable Detection Levels and Reaction Times
Autonomous Operatio n Independent of CPU
If the volta ge at the VFET pin falls be low the pr og ra mmable De ep Under- voltage d etection level,
C-FET, PC-FET, and D-FET are disabled an d the ch ip is set in Po wer- off mod e to red uce power
consumption to a minimum.
The Current Battery Protection circuitry (CBP) monitors the charge and discharge current and
disables C-FET, PC-FET, and D-FET if an over-current or short-circuit condition is detected.
There are three different programmable detection leve ls: Discharge Over-current Detectio n
Level, Charge Over-current Detection Level and Short-circuit Detection Level. The external filter
at the PI/NI input pins will cause too large delay for short-circuit detection. Therefore the sepa-
rate PPI/NNI inputs are used for Current Battery Protection. There are two different
programmable delays for activating Current Battery Protection: Short-circuit Reaction Time and
Over-current Reaction Time. After Current Battery Protection has been activated, the application
software must re-enable the FETs. The Battery Prot ection hard ware provide s a hold-o ff time of 1
second before software can re-enable the discharge FET. This provide s safety in case the ap pli-
cation software should unintentionally re-enable the discharge FET too early.
The activation of a protection also issues an interrupt to the CPU. The battery protection inter-
rupts can be individually enabled and disabled by the CPU.
The effect of the various battery protection types is given in Table 22-1.
In order to reduce power consumption , b oth Short-circuit and Discharge Over-current Protection
are automatically deactivated when the D-FET is disabled. The Charge Over-current Protection
is disabled when both the C-F ET and the PC-FET are disabled. Note howe ver that Charge Ove r-
current Protection is never automatically disabled when any of the C-FET or PC-FETs are con-
trolled by PWM.
Table 22-1. Effect of Battery Protection Types
Battery Protection Type Interrupt Requests C-FET D-FET PC-FET Cell Balanci ng FETs MCU
Deep Under-voltage
Detected CPU Reset on exit Disabled Disabled Disabled Disabled Power-off
Discharge Over-current
Protection Entry and exit Disabled Disabled Disabled Operational Operational
Charge Over-current
Protection Entry and exit Disabled Disabled Disabled Operational Operational
Short-circuit Protection Entry and exit Disabled Disabled Disabled Operational Operational
126 2548F–AVR–03/2013
ATmega406
22.2 Deep Under-volt age Protection
The Deep Under-voltage Protection ensures that the battery cells will not be discharged deeper
than the programmable Deep Under-voltage detection level. If the voltage at the VFET pin is
below this level for a time lon ger th an th e progr ammable d elay tim e, C-FET, PC-FET and D-F ET
are automatically switched off and the chip enters Power-off mode. The Deep Under-voltage
Early Warning interrupt flag (DUVIF) will be set 250 ms before the chip enters Power-off. This
will give the CPU a chance to take necessary actions before the power is switched off.
The device will remain in the Power-off mode until a charger is connected. When a charger is
detected, a normal power-up sequence is started and the chip initializes to default state.
The Deep Under-voltage delay time and Deep Under-voltage detection level are set in the Bat-
tery Protection Deep Under-voltage Register (BPDUV). The Parameter Registers can be locked
after the initial configuration, prohibiting any further updates until the next Hardware Reset.
Refer to ”Register Description for Battery Protection” on page 128 for register descriptions.
22.3 Discharge Over-current Protection
The Current Battery Protection (CBP) monitors the cell current by sampling the shunt resistor
voltage at the PPI/NNI input pins. A differential operational amplifier amplifies the voltage with a
suitable gain. The output from th e operation al amplifier is compar ed to an accurate, pr ogramma-
ble On-chip voltage reference by an Analog Comparator. If the shunt resistor voltage is above
the Discharge Over-current Detection level for a time longer than Over-current Protection Reac-
tion Time, the chip activates Discharge Over-current Protection. A sampled system clocked by
the internal ULP Oscillator is used for Over-current and Short-circuit P rotection. This ensures a
reliable clock source , off -s et ca nc ella tio n and low power consumptio n.
When the Discharge Over-current Protection is activate d, the external D-FET, PC-FET, and C-
FET are disabled and a Curr ent Protection Timer is started. This timer ensur es that the FETs are
disabled for at least one second. The application software must then set the DFE and CFE bits
in the FET Control and Stat us Register to re -enab le normal oper ation. If the D-FET is re-e nabled
while the loading of the battery still is too large, the Discharg e Over-current Protection will be
activated again.
22.4 Charge Over-current Protection
If the voltage at the PPI/NNI pins is above the Charge Over-current Detection level for a time
longer than Over-current Protection Reaction Time, the chip activates Charge Over-current
Protection.
When the Charge Over-cur re nt Protection is activated, th e exter nal D-F ET, PC-F ET, a nd C-F ET
are disabled and a Cur rent Prote ction Timer is st arte d. This timer ensur es that the FETs are dis-
abled for at least one second. The application software must then set the DFE and CFE bits in
the FET Control and Status Register to re-enable normal operation. If the C-FET is re-enab led
and the charger continues to supply too high currents, the Charge Over-current Protection will
be activated ag ain .
127
2548F–AVR–03/2013
ATmega406
22.5 Short-circuit Protection
A second level of high current detection is provided to enable a faster response tim e to very
large discharge currents. If a discharge current larger than the Short-circuit Detection Level is
present for a period longer than Short-circuit Reaction Time, the Short-circuit Protection is
activated.
When the Short-circuit Protection is activated, the external D-FET, PC-FET, and C-FET are dis-
abled and a Current Protection Timer is started. This timer ensures that the D-FET, PC-FET,
and C-FET are disabled for at least one second. T he application software must the n set the DFE
and CFE bits in the FET Control and Status Regist er to re-enable normal operatio n. If the D-FET
is re-enab led b e for e th e cause of th e sh or t- circ ui t condition is removed, the Short-circuit Protec-
tion will be activated again.
The Over-curren t and Short-circ uit Protection parame ters are progr ammable to ada pt to different
types of batteries. The parameters are set by writing to I/O Registers. The Parameter Registers
can be locked after the initial con figuration, prohibitin g any further updates unt il the next Hard-
ware Reset.
Refer to ”Register Description for Battery Protection” on page 128 for register descriptions.
22.6 Battery Protection CPU Interface
The Battery Protection CPU Interface is illustrated in Figure 22-1.
Figure 22-1. Battery Protection CPU Interface
Each protection has an Interrupt Flag. Each Flag can be read and cleared b y the CPU, and each
flag has an individual interrupt enable. All enabled flags are combined into a single battery pro-
tection interrupt request to the CPU. This interrupt can wake up the CPU from any operation
mode, except Power-off. The interrupt flags are cleared by writing a logic ‘1’ to their bit locations
from the CPU.
Note that there are neither flags no r status bits indica ting that the chip has entere d the Power Off
mode. This is because the CPU is pow ered down in this mode. The CPU will, however be abl e
4
/
4
/
8
/
Interrupt
Request
Interrupt
Acknowledge
FET
Control
Current
Battery
Protection
Battery Protection
Control Register
Battery Protection
Timing Register
Battery Protection
Level Register
Battery Protection
Parameter Lock
Register
Voltage
Battery
Protection
PPI
NNI
VFET
LOCK? LOCK? LOCK?
8-BIT DATA BUS
Deep Under-voltage
Power-off
Battery
Protection
Interrupt
Register
Current
Protection
128 2548F–AVR–03/2013
ATmega406
to detect that it came fr om a Power- off situa tion by mo nitoring CPU reset flag s when it resumes
operation.
22.7 Register Description for Battery Protection
The Battery Protection module operates in a different clock domain than the CPU. Whenever a
new value is written to BPCR, BPDUV, BPOCD, BPSCD, or CPBTR, the value must be synchro-
nized to the Battery Protection clock domain. Subsequent writes to this register should not be
made during this synchronization. Therefore, after writing to one of these registers, the same
register should not be re-written within the next 8 CPU clock periods. Note that each register is
synchronized independently of the others.
22.7.1 BPPLR – Battery Protection Parameter Lock Register
Bit 7:2 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 1 – BPPLE: Battery Protection Parameter Lock Enable
Bit 0 – BPPL: Battery Protection Parameter Lock
The Battery Protection parameters set in the Batter y Protection Paramete r Registers and the
disable function set in the Battery Protection Disable Register can be locked from any further
software updates. Once locked, these registers cannot be accessed until the next hardware
reset. This provides a safe method for protecting these registers from unintentional modification
by software runaway. It is recommended that software sets these registers shortly after reset,
and then protects these registers from any further updates.
To lock these registers, the following algorithm must be followed:
1. In the same operation, write a logic one to BPPLE and BPPL.
2. Within the next four clock cycles, in the same operation. write a logic zero to BPPLE and
a logic one to BPPL.
The Battery Protection Parameter Registers are BPCR, CBPTR, BPOCP, BPSCD and BPDUV.
22.7.2 BPCR – Battery Protection Control Register
Bit 7:4 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 3 – DUVD: Deep Under-voltage Protection Disable
Bit 76543210
(0xF8) ––––––BPPLEBPPLBPPLR
Read/Write RRRRRRR/WR/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
(0xF7) DUVD SCD DCD CCD BPCR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
129
2548F–AVR–03/2013
ATmega406
When the DUVD bit is set, the Deep Under-voltage Protection is disabled. The Deep Under-volt-
age Detection will be disabled, and any Deep Under-voltage condition will be ignored
Bit 2 – SCD: Short Circuit Protection Disabled
When the SCD bit is set, the Short-circuit Protection is disabled. The Short-circuit D etection will
be disabled, and any Short-circuit condition will be ignored.
Bit 1 – DCD: Discharge Over-current Protection Disable
When the DCD bit is set, the Discharge Over-current Protection is disabled. The Disch arge
Over-current Detection will be disabled, and any Discharge Over-current condition will be
ignored.
Bit 0 – CCD: Charge Over-current Protection Disable
When the CCD bit is set, the Charge Over-current Protection is disabled. The Charge Over-cur-
rent Detection will be disabled, and any Charge Over-current condition will be ignored.
22.7.3 CBPTR – Current Battery Prot ection Timing Register
Bit 7:4 – SCPT3:0: Short-circuit Protection Timing
These bits control the delay of the Short-circuit Protection. See Table 22-2.
Bit 3:0 – OCPT3:0: Over-current Protection Timing
These bits control the delay of the Charge and Discharge Current Protection. See Table 22-3.
Note that the same setting applies to both types of over-current protection.
Bit 76543210
(0xF6) SCPT[3:0] OCPT[3:0] CBPTR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 22-2. SCPT[3:0] with Corresponding Short-circuit Delay Time
Short-circuit Protection Reaction Time
SCPT[3:0] Typ SCPT[3:0] Typ SCPT[3:0] Typ SCPT[3:0] Typ
0000 61 µs 0100 305 µs 1000 610 µs 1100 1098 µs
0001 122 µs 0101 366 µs 1001 732 µs 1101 1220 µs
0010 183 µs 0110 427 µs 1010 854 µs 1110 1342 µs
0011 244 µs 0111 488 µs 1011 976 µs 1111 1464 µs
Table 22-3. OCPT[3:0] with Corres po nd in g Ove r -cu rr ent Delay T i me
Over-current Protection Reaction Time
OCPT[3:0] Typ OCPT[3:0] Typ OCPT[3:0] Typ OCPT[3:0] Typ
0000 1 ms 0100 8 ms 1000 16 ms 1100 24 ms
0001 2 ms 0101 10 ms 1001 18 ms 1101 26 ms
0010 4 ms 0110 12 ms 1010 20 ms 1110 28 ms
0011 6 ms 0111 14 ms 1011 22 ms 1111 30 ms
130 2548F–AVR–03/2013
ATmega406
22.7.4 BPOCD – Battery Protection Over-current Detection Level Register
Bits 7:4 – DCDL3:0: Discharge Over-current Detection L evel
These bits set the RSENSE voltage level for detection of Discharge Over-current, as defined in
Table 22-4.
Bits 3:0 – CCDL3:0: Charge Over-current Detection Level
These bits set the RSENSE voltage level for detection of Charge Over-curr ent, as d efined in Table
22-5.
22.7.5 BPSCD – Battery Protection Short-circuit Detection Level Register
Bit 7:4 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bits 3:0 – SCDL3:0: Short-circuit Detection Level
These bits set the RSENSE voltage level for detection of Short-circuit in the discharge direction,
as defined in Table 22-6 on page 131.
Bit 76543210
(0xF5) DCDL[3:0] CCDL[3:0] BPOCD
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 22-4. DCDL[3:0] with Corresponding RSENSE Voltage for Discharge Over-curre nt Detec-
tion Level
Discharge Over-current Protection Detection Level
DCDL[3:0] Typ DCDL[3:0] Typ DCDL[3:0] Typ DCDL[3:0] Typ
0000 0.050V 0100 0.070V 1000 0.110V 1100 0.160V
0001 0.055V 0101 0.080V 1001 0.120V 1101 0.180V
0010 0.060V 0110 0.090V 1010 0.130V 1110 0.200V
0011 0.065V 0111 0.100V 1011 0.140V 1111 0.220V
Table 22-5. CCDL[3:0] with Corresponding RSENSE Voltage for Charge Over-cu rrent Detection
Level
Charge Over-current Protection Detection Level
CCDL[3:0] Typ CCDL[3:0] Typ CCDL[3:0] Typ CCDL[3:0] Typ
0000 0.050V 0100 0.070V 1000 0.110V 1100 0.160V
0001 0.055V 0101 0.080V 1001 0.120V 1101 0.180V
0010 0.060V 0110 0.090V 1010 0.130V 1110 0.200V
0011 0.065V 0111 0.100V 1011 0.140V 1111 0.220V
Bit 76543210
(0xF4) SCDL[3:0] BPSCD
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
131
2548F–AVR–03/2013
ATmega406
22.7.6 BPDUV – Battery Protection Deep Under Voltage Register
Bit 7:6 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bits 5:4 – DUVT1:0: Deep Under-voltage Timing
These bits set the Deep Under-voltage Protection delay.
Bits 3:0 – DUDL3:0: Deep Under-voltage Detection Level
These bits set the Deep Under-voltage detection level.
Table 22-6. SCDL[3:0] with Corresponding RSENSE Voltage for Short-circuit Detection Level
Short-circuit Protectio n Detection Level
SCDL[3:0] Typ SCDL[3:0] Typ SCDL[3:0] Typ SCDL[3:0] Typ
0000 0.100V 0100 0.140V 1000 0.220V 1100 0.320V
0001 0.110V 0101 0.160V 1001 0.240V 1101 0.360V
0010 0.120V 0110 0.180V 1010 0.260V 1110 0.400V
0011 0.130V 0111 0.200V 1011 0.280V 1111 0.440V
Bit 76543210
(0xF3) DUVT[1:0] DUDL[3:0] BPDUV
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 22-7. DUVT[1:0] with Corresponding Deep Under-voltage Delay
DUVT1:0 Deep Under-voltage Delay
00 750 ms
01 1000 ms
10 1250 ms
11 1500 ms
Table 22-8. DUDL[3:0] with Corresponding Deep Under-voltage Detection Level
DUDL[3:0] Typ DUDL[3:0] Typ
0000 4.71V 1000 7.23V
0001 5.03V 1001 7.54V
0010 5.34V 1010 7.86V
0011 5.66V 1011 8.17V
0100 5.97V 1100 8.49V
0101 6.29V 1101 8.80V
0110 6.60V 1110 9.11V
0111 6.91V 1111 9.43V
132 2548F–AVR–03/2013
ATmega406
22.7.7 BPIR – Battery Protection Interrupt Register
Bit 7 – DUVIF: Deep Under-voltage Early Warning Interrupt Flag
If the voltage at VFET pin is below the Deep Under-voltage de tection level and only 250 ms is
left of the Deep Under-voltage delay, DUVIF becomes set. The flag must be cleared by writing a
logical one to it.
Bit 6 – COCIF: Charge Ove r -current Protection Activated Interrupt Flag
When the Charge Over-current Protection is activated, COCIF becomes set. The flag must be
cleared by writing a logical one to it.
Bit 5 – DOCIF: Discharge Over-current Protection Activated Interrupt Flag
When the Discharge Over-current Pro tection is activated, DOCIF becomes set. The flag m ust be
cleared by writing a logical one to it.
Bit 4 – SCIF: Short-circuit Protection Activated Interrupt Flag
When the Short-circuit Protection is activated, SCIF becomes set. The flag must be cleared by
writing a logical one to it.
Bit 3 – DUVIE: Deep Under-voltage Early Warning Interrupt Enable
The DUVIE bit enables interrupt ca used by the Deep Under-voltage Ear ly Warning Interrupt Flag
Bit 2 – COCIE: Charge Over-current Protection Activated Interrupt Enable
The COCIE bit enables interrupt caused by the Charge Over-current Protection Activated Inter-
rupt Flag.
Bit 1 – DOCIE: Discharge Over- current Protection Activated Interrupt Enable
The DOCIE bit enables interrupt caused by the Dis charge Over-current Protection Activated
Interrupt Flag.
Bit 0 – SCIE: Short-circuit Protection Activated Interrupt Enable
The SCIE bit enables interrupt caused by the Short-circuit Protection Activated Interrupt Flag.
If one of the Batter y Protect ion Inte rrupt Fla gs is set, a nd the co rrespo nding I nterrupt Enable b it
and the I-bit in the Status Register (SREG) are set, the MCU will jump to the Battery Protection
interrupt vector. The application software must read the Battery Protection Interrupt Register to
determine the cause of the interrupt. The interrupt fla gs will not be cleared when the interrupt
routine is executed, they must be cleared by writing a log ical one to them.
Bit 76543210
(0xF2) DUVIF COCIF DOCIF SCIF DUVIE COCIE DOCIE SCIE BPIR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
133
2548F–AVR–03/2013
ATmega406
23. FET Control In addition to the FET disable control signals from the battery protection circuitry, the CPU may
disable the Charge FET (C-FET), the Discharge FET (D-F ET), or both, by writing to the FET
Control Register. Note that the CPU is never allowed to enable a FET that is disabled by the bat-
tery protection circuitry. The FET control is shown in Figure 23-1 on page 133.
The PWM output from the 8-bit Timer/Counter0, OC0B, can be configured to drive the C-FET,
Precharge FET (PC-FET) or both directly. This can be useful for controlling the charging of the
battery cells. The PWM is configured by the COM0B1:0 and WGM02:0 bits in the
TCCR0A/TCCR0B registers. Note that the OC0B pins does not need to be configured as an out-
put. This means that the PWM output can be used to drive the C-FET and/or the PC-FET
without occupying the OC0B-pin.
If C-FET is disabled and D-FET enabled, discharge current will run through the body-drain diode
of the C-FET and vice versa. To avoid the potential heat problem from this situation, software
must ensure that D-FET is not disabled when a charge current is flowing, and that C-FET is not
disabled when a discharge current is flowing.
If the battery has been deeply discharged, large surge currents may result when a charger is
connected. In this case, it is recommended to first pre charge the battery throug h a current limi t-
ing resistor. For this purpose, ATmega406 provides a Precharge FET (PC-FET) control output.
This output is default enabled.
If ATmega406 has entered the Power-off mode, all FET control outputs will be disabled. When a
charger is connected, the CPU will wake up. When waking up from Power-off mode, the C-FET
and D-FET control outputs will remain disabled while PC-FET is default enabled. When the CPU
detects that the cell voltage s have risen enough to allow nor mal charging, it should enable th e
C-FET and D-FE T co ntr o l outp u ts an d dis ab le th e PC-F ET con tr ol ou tp ut .
If the Current Battery Protection has been activated, the Current Protection Timer will ensure a
hold-off time of 1 second before software can re-enable the external FETs.
Figure 23-1. FET Control Block Diagram
FET
Control
and
Status
Register
FET
Driver
FET
Driver
DFE
CFE
CURRENT_PROTECTION
Power-off Mode
8-BIT D ATA BU S
OC
OD
Current Protection
Timer
1
0
PWMOC
OC0B
FET
Driver
PFD
OPC
1
0
PWMOPC
134 2548F–AVR–03/2013
ATmega406
23.1 FET Driver
Figure 23-2. Connection of external FETs
The connection of external FETs to OD, OC, and OPC is shown in Figure 23-2.
When switching on an FET, the output pulls the gate quickly low to avoid heating of the FET.
When the FET is switched completely on, the output chang es oper ation mod e in orde r to r educe
current consumption. The gate-source voltage for the FET when switched on, |VGS_ON|, is limited
to 13V ± 15%.
When disabling an external FET, the FET Driver output quickly pushes the gate voltage to the
source pin potential, making the gate-source voltage of the FET close to zero. This disables the
FET, and the FET Driver output switches operation mode to high impedance in order to reduce
current consumption. The external resistor will keep the gate-source voltage at zero until the
FET is enabled again and its gate is pulled low as explained above.
23.2 Register Description for FET Control
The FET Controller operates in a different clock do main than the CPU. Whenever a ne w value is
written to the FCSR, the value m ust be synchronized to the FET Controlle r clock domain. Subse-
quent writes to this register should not be made during this synchronization. Therefore, after
writing to this register, a guard time of 3 ULP Oscillator cycles + 3 CPU clock cycles is required.
It is recommended that software only reads the FCSR when handling a Battery Protection Inter-
rupt (BPINT).
23.2.1 FCSR – FE T Co nt rol an d Status Register
Bits 7:6 – Res: Reserved Bits
These bits are reserved bits in the ATmega406, and will always read as zero.
Bit 5 – PWMOC: Pulse Width Modulation of OC output
RcfRdf
OC OPCODPVT BATT
Rpf
Rpc
+
RN
Bit 76 5 4 3210
(0xF0) PWMOC PWMOPC CPS DFE CFE PFD FCSR
Read/Write R R R/W R/W R R/W R/W R/W
Initial Value00 0 0 0000
135
2548F–AVR–03/2013
ATmega406
When the PWMOC is cleared (zero), the CFE bit and the battery protection circuitry controls the
OC output. When this bit is set (one), the OC output will be the logical A ND of the PWM output
from the 8-bit Timer/Counter0 and the inverse of CURRENT_PROTEC TION from the Battery
Protection circuitry.
Bit 4 – PWMOPC: Pulse Width Modulation of OPC output
When the PWMOPC is cleared (zero), the PFD bit and the battery protection circuitry controls
the OPC output. When this bit is set (one), the OPC output will be the logical AND of the PWM
output from the 8-bit Timer/Counter0 and the inverse of CURRENT_PROTECTION from the
Battery Protection circuitry.
Bit 3 – CPS: Current Protection Status
The CPS bit shows the status of the Current Protection. This bit is set (one) when the Current
Protection Timer is activated, and is cleared (zero) when the hold-off time has elapsed.
Bit 2 – DFE: Discharge FET Enable
When the DFE bit is cleared (zero), the Discharge FET will be disabled regardless of the state of
the Battery Protection circuitry. When this bit is set (on e), the Discharge FET state is dete rmined
by the Battery Protection circuitry. This bit will be cleared when CURRENT_PROTECTION is set
(one).
Bit 1 – CFE: Charge FET Enable
When the CFE bit is clea red (zero), the Charge FET will be disabled regard less of the state of
the Battery Protection circuitry. When this bit is set (one), th e Charge FET sta te is determined by
the Battery Protection circuitry. This bit will be cleared when CURRENT_PROTECTION is set
(one).
Bit 0 – PFD: Precharge FET Disable
The PFD bit provides complete control of the Precharge FET. When the PFD bit is cleared
(zero), the Precharge FET will be enabled. When the PFD bit is cleared, the Precharge FET will
be enabled. When the PFD bit is set (one), the Precharge FET will be disabled. This bit will be
cleared when the CURRENT_PROTECTION is set (one)
136 2548F–AVR–03/2013
ATmega406
24. Cell Balancing
ATmega406 incorporates cell balan cing FETs. The chip provides one cell balancing FET for
each battery cell in series. The FETs are directly controlled by the application software, allowing
the cell balancing algorithms to be implemented in software. The FETs are connected in parallel
with the individual battery cells. The cell balancing is illustrated in Figure 24-1. The figure shows
a four-cell configuration. The cell balancing FETs are disabled in the Power-off mode.
Typical current through the Cell Balancing FETs (TCB) is 2 mA. The Cell Balancing FETs are
controlled by the CBCR. Neighbouring FETs ca nnot be simultaneously enabled. If trying to
enable two neighbouring FETs, both will be disabled.
Figure 24-1. Cell Balancing
Cell Balancing
Control Register
TCB
RP
RP
RP
RP
TCB
TCB
TCB
Level
Shift
Level
Shift
Level
Shift
Level
Shift
PV1
NV
PV2
PV3
PV4
8-BIT DATA BUS
RP
137
2548F–AVR–03/2013
ATmega406
24.1 Register Description
24.1.1 CBCR – Cell Balancing Control Register
Bit 7:4 – Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 3 – CBE4: Cell Balancing Enable 4
When this bit is set, the integrated Cell Balancing FET between terminals PV4 and PV3 will be
enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing
FETs are always disabled in Power-off mode. CBE4 cannot be set if CBE3 is set.
Bit 2 – CBE3: Cell Balancing Enable 3
When this bit is set, the integrated Cell Balancing FET between terminals PV3 and PV2 will be
enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing
FETs are always disabled in Power-off mode. CBE3 cannot be set if CBE2 or CBE4 is set.
Bit 1 – CBE2: Cell Balancing Enable 2
When this bit is set, the integrated Cell Balancing FET between terminals PV2 and PV1 will be
enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing
FETs are always disabled in Power-off mode. CBE2 cannot be set if CBE1 or CBE3 is set.
Bit 0 – CBE1: Cell Balancing Enable 1
When this bit is set (one), the integrated Cell Balancing FET between terminals PV1 and NV will
be enabled. When the bit is cleared (zero), the Cell Balancing FET will be disabled. The Cell Bal-
ancing FETs are always disabled in Power-off mode. CBE1 cannot be set if CBE2 is set.
Bit 76543210
(0xF1) CBE4 CBE3 CBE2 CBE1 CBCR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
138 2548F–AVR–03/2013
ATmega406
25. 2-wire Serial Interface
25.1 Features Simple yet Powerful and Flexible Communication Interf ace, Only Two Bus Lines Needed
Both Master and Slave Operation Supported
Device can Operate as Transmitter or Receiver
7-bit Address Space allows up to 128 Diffe rent Slave Addresses
Multi-master Arbitration Support
Operates on 4 MHz Clock, achiev ing up to 100 kHz Data Transfer Speed
Slew-rate Limited Output Drivers
Noise Suppre ssion Circuitry Rejects Spikes on Bus Lines
Fully Programmable Slave Address with General Call Support
Address Recognition Ca uses Wake-up when AVR is in Sleep Mode
25.2 Two-wire Serial Interface Bus Definition
The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The
TWI protoc ol allows t he syste ms desig ner to interconnect up to 128 different devices using only
two bi-directional bus lines, one for clock (SCL) and one for data (SDA). The only external hard-
ware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All
devices connec ted to the bus have individual add resses, and mechanisms for reso lving bus
contention are inherent in the TWI protocol.
The PRTWI bit in ”PRR0 – Power Reduction Register 0” on page 36 must be written to zero to
enable TWI module.
Figure 25-1. TWI Bus Interconnection
Device 1 Device 2 Device 3 Device n
SDA
SCL
........
R1 R2
V
BUS
139
2548F–AVR–03/2013
ATmega406
25.2.1 TWI Terminology
The following definitions are frequently encountered in this section.
25.2.2 Electrical Interconnection
As depicted in Figure 25 -1, both bus lines are connected to the positive supply voltage through
pull-up resistor s. The bus drivers of all TWI-compliant devices are open-drain or open-collector.
This implements a wired-AND function which is essential to the operation of the interface. A low
level on a TWI bus line is generated when one or more TWI devices output a zero. A high level
is output when all TWI devices tri-state their outputs, allowing the pull-up resistors to pull the line
high. Note that all AVR devices connected to the TWI bus must be powered in orde r to allow any
bus operation.
The number of devices that can be connected to the bus is only limited by the bus capacitance
limit of 400 pF and the 7-bit slave address space. A detailed specification of the electrical char-
acteristics of the TWI is given in ”2-wire Serial Interface Characteristics” on page 229.
25.3 Data Transfer and Frame Format
25.3.1 Transferring Bits
Each data b it tran sfer red o n the T WI bus is acco mpa nied by a p ulse on th e cloc k line. The lev el
of the data line must be stable when the clock line is high. The only exception to this rule is for
generating start and stop conditions.
Figure 25-2. Data Validity
Table 25-1. TWI Terminology
Term Description
Master The device that initiates and terminates a transmission. The Master also generates the
SCL clock.
Slave The device addressed by a Master.
Transmitter The device placing data on the bus.
Receiver The device reading data from the bus.
SDA
SCL
Data Stable Data Stable
Data Change
140 2548F–AVR–03/2013
ATmega406
25.3.2 START and STOP Conditions
The Master initiates and terminates a data transmission. The transmission is initiated when the
Master issues a START condition on the bus, and it is terminated when the Master issues a
STOP condition. Between a START and a STOP condition, the bus is considered busy, and no
other Master should try to seize control of the bus. A special case occurs when a new START
condition is issued between a START and STOP condition. This is referred to as a REPEATED
START condition, and is used when the Master wishes to initiate a new transfer without relin-
quishing control of the bus. After a REPEATED START, the bus is considered busy until the next
STOP. This is identical to the START behavior, and therefore START is used to describe both
START and REPEATED START for the remainder of this datasheet, unless otherwise noted. As
depicted below, START an d STOP conditions are signalled by cha nging the level of the SDA
line when the SCL line is high.
Figure 25-3. START, REPEATED START, and STOP Conditions
25.3.3 Address Packet Format
All address packets transmitted on the TWI bus are nine bits long, consisting of seven address
bits, one READ/WRITE contro l bit and an acknowledge bit. If the READ/WRITE bit is set, a read
operation is to be perfo rmed, otherwise a write operation should be p erformed. When a slave
recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL
(ACK) cycle. If the addressed Slave is busy, or for some other reason can not service the Mas-
ter’s request, the SDA line should be left high in the ACK clock cycle. The Master can then
transmit a STOP condition, or a REPEATED START condition to initiate a new transmission. An
address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or
SLA+W, respectively.
The MSB of the address byte is transmitted first. Slave addresses can freely be allocated by the
designer, but the address 0000 000 is reserved for a general call.
When a general call is issued, all slaves should respond by pulling the SDA line low in the ACK
cycle. A general call is used when a Master wishes to transmit the same message to several
slaves in the system. When the general call address followed by a write bit is transmitted on the
bus, all slaves set up to ackn ow ledge the general call will pull the SDA line low in the ack cycle.
The following data packets will then be received by all the slaves that acknowledged the general
call. Note that transmitting the general call address followed by a Read bit is meaningless, as
this would cause contention if several slaves started transmitting different data.
All addresses of the format 1111 xxx should be reserved for future purposes.
SDA
SCL
START STOPREPEATED START
STOP START
141
2548F–AVR–03/2013
ATmega406
Figure 25-4. Address Packet Format
25.3.4 Data Packet Format
All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and
an acknowledge bit. During a data transfer, the Master generates the clock and the START and
STOP conditions, while the Receiver is responsible for acknowledging the reception. An
Acknowledge (ACK) is signalled by the Receiver pulling the SDA line low during the ninth SCL
cycle. If the Rece iver leaves the SDA line high, a NACK is signalled. When th e Receiver has
received the last byte, or for some reason cannot receive any more bytes, it should inform the
Transmitter by sending a NACK after the final byte. The MSB of the data byte is transmitted first.
Figure 25-5. Data Packet Format
25.3.5 Combining Address and Data Packets Into a Transmission
A transmission basically consists of a START condition, a SLA+R/W, one or more data packets
and a STOP condition. An emp ty message, consisting of a START followed by a STOP condi-
tion, is illegal. Note that the wired-ANDing of the SCL line can be used to implement
handshaking between the Master and the Slave. The Slave can extend the SCL low period by
pulling the SCL line low. This is useful if the clock speed set up by the Master is too fast for the
Slave, or the Slave needs extra time for processing between the data transmissions. The Slave
extending the SCL low period will not affect the SCL high period, which is determined by the
Master. As a consequence, the Slave can reduce the TWI data transfer speed by prolonging the
SCL duty cycle.
Figure 25-6 shows a typical data transmission. Note that several data bytes can be transmitted
between the SLA+R/W and the STOP con dition, depending on the software proto col imple-
mented by the application software.
SDA
SCL
START
12 789
Addr MSB Addr LSB R/W ACK
12 789
Data MSB Data LSB ACK
Aggregate
SDA
SDA from
Transmitter
SDA from
Receiver
SCL from
Master
SLA+R/W Data Byte
STOP, REPEATED
START, or Next
Data Byte
142 2548F–AVR–03/2013
ATmega406
Figure 25-6. Typical Data Transmission
25.4 Multi-master Bus Systems, Arbitration and Synchronization
The TWI protocol allows bus systems with several masters. Special concerns have been taken
in order to ensure that transmissions will proceed as normal, even if two or more masters initiate
a transmission at the same time. Two problems arise in multi-master systems:
An algorithm must be implemented allo wing only one of the masters to complete the
transmission. All other masters should cease transmission when they discover that they have
lost the selection process. This selection process is called arbitration. When a contending
master discovers that it has lost the ar bitration process, it should immediately switch to Slave
mode to check whether it is being addressed by the winning master. The fact that multiple
masters have started transmission at the same time should not be detectable to the slaves
(i.e., the data being transferred on the bus must not be corrupted).
Different masters may use different SCL frequencies. A scheme must be devised to
synchronize the serial clocks from all masters, in order to let the transmission proceed in a
lockstep fashion. This will facilitate the arbitration process.
The wired-ANDing of the bus lines is us ed to solve both these problems. The serial clocks from
all masters will be wired-ANDed, yielding a co mbined clock with a high period equal to the one
from the master with the shortest high period. The low period of the combined clock is equal to
the low period of the master with the longest low period. Note that all masters listen to the SCL
line, effectively starting to count their SCL high and low Time-out periods when the combined
SCL line goes high or low, respectively.
12 789
Data Byte
Data MSB Data LSB ACK
SDA
SCL
START
12 789
Addr MSB Addr LSB R/W ACK
SLA+R/W STOP
143
2548F–AVR–03/2013
ATmega406
Figure 25-7. SCL Synchroniza tio n be tw ee n Mu ltip le Master s
Arbitration is carried out by all masters continuously monitoring the SDA line after outputting
data. If the value read from the SDA line does not match the value the master had output, it has
lost the arbitration. Note that a master can only lo se arbitration when it outpu ts a high SDA value
while another master outputs a low value. The losing master should immediately go to Slave
mode, checking if it is being addressed by the winning master. The SDA line should be left high,
but losing masters are allowed to generate a clock signal until the end of the current data or
address packet. Arbitration will continue until only one mas ter remains, and this may take many
bits. If several masters are trying to address the same slave, arbitration will continue into the
data packet.
Figure 25-8. Arbitration between Two Master s
Note that arbitration is not allowed between:
A REPEATED START condition and a data bit.
A STOP condition and a data bit.
A REPEATED START and a STOP condition.
TA
low
TA
high
SCL from
Master A
SCL from
Master B
SCL bus
Line
TB
low
TB
high
Masters Start
Countin
g
Low Period
Masters Start
Countin
g
Hi
g
h Period
SDA from
Master A
SDA from
Master B
SDA Line
Synchronized
SCL Line
START Master A Loses
Arbitration, SDAA
SDA
144 2548F–AVR–03/2013
ATmega406
It is the user software’s responsibility to ensur e that these illegal arbitration conditions never
occur. This implies that in multi-master systems, all data transfers must use the same composi-
tion of SLA+R/W and data pa ckets. In other words: All transmissions must contain the same
number of data packets, otherwise the result of the arbitration is undefined.
25.5 Overview of the TWI Module
The TWI module is comprised of several submodu les, as shown in Figure 25-9 . The shaded re g-
isters are accessible through the AVR data bus.
Figure 25-9. Overview of the TWI Module
25.5.1 SCL and SDA Pins
These pins interface the AVR TWI with the rest of the MCU system. The output drivers contain a
slew-rate limiter in order to conform to the TWI specification. The input stages contain a spike
suppression unit removing spikes shorter than 50 ns.
TWI Unit
Address Register
(TWAR)
Address Match Unit
Address Comparator
Control Unit
Status Register
(TWSR)
State Machine and
Status Control
SCL
Slew-rate
Control
Spike
Filter
SDA
Slew-rate
Control
Spike
Filter
Bit Rate Generator
Bit Rate Register
(TWBR)
Prescaler
Bus Interface Unit
START / STOP
Control
Arbitration Detection Ack
Spike Suppression
Address/Data Shift
Register (TWDR)
Control Register
(TWCR)
145
2548F–AVR–03/2013
ATmega406
25.5.2 Bit Rate Generator Unit
This unit controls the period of SCL when operating in a Master mode. Th e SCL period is con-
trolled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status
Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but th e
CPU clock frequency in the slave must be at lea st 16 times higher tha n the SCL frequ ency. Note
that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock
period. The SCL frequency is generated according to the following equation:
TWBR = Value of the TWI Bit Rate Register.
TWPS = Value of the prescaler bits in the TWI Status Register.
Notes: 1. TWBR should be 10 or higher if the TWI operates in Master mode. If TWBR is lower than 10,
the master may produce an incorrect output on SDA and SCL for the reminder of the byte. The
problem occurs when operating the TWI in Master mode, sending Start + SLA + R/W to a
slave (a slave does not need to be connected to the bus for the condition to happen).
2. The TWI clock is 4 MHz, see “Calibrated Fast RC Oscillator” on page 26.
25.5.3 Bus Interface Unit
This unit contains the Data and Address Shift Register (TWDR), a START/STOP Controller and
Arbitration detection ha rdwa re . The TWDR conta ins the address or data bytes to be tra nsmitted,
or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also
contains a register containing the (N)AC K bit to be transmitted or received. This (N)ACK Re gis-
ter is not directly accessible by the application softwar e. H owever, when r eceiving, it can be set
or cleared by manipulating the TWI Control Register (TWCR). When in Transmitter mode, the
value of the received (N)ACK bit can be determined by the value in the TWSR.
The START/STOP Controller is responsible for generation and detection of START, REPEATED
START, and STOP conditions. The START/STOP controller is able to detect START and STOP
conditions even when the AVR MCU is in one of the sleep mode s, enab ling the MCU to wa ke up
if addressed by a Mast er .
If the TWI has initiat ed a transmission as M aster, the Arbitration Detection hardware continu-
ously monitors the tra nsmission trying to determ i ne if arbitration is in process. If the TWI has lost
an arbitration, the Control Unit is informed. Correct action can then be taken and appropriate
status codes generated.
25.5.4 Address Match Unit
The Address Ma tch unit checks if received address bytes match the 7-bit address in the TWI
Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the
TWAR is written to one, all incoming address bits will also be compared against the General Call
address. Upon an address match, the Control unit is informed, allowing correct action to be
taken. The TWI may or may not acknowledge its address, depending on settings in the TWCR.
The Address Match unit is able to compare addresses even when the AVR MCU is in sleep
mode, enabling the MCU to wake-up if addressed by a Master.
SCL frequency TWI Clock frequency
16 2(TWBR) 4TWPS
+
-----------------------------------------------------------=
146 2548F–AVR–03/2013
ATmega406
25.5.5 Control Unit The Control unit monitors the TWI bus and gen erates responses cor responding to settings in the
TWI Control Register (TWCR). When an event requirin g the attention of the application occurs
on the TWI bus, the TWI Interrupt Fla g (TWINT) is asserted. In the next clock cycle, the TWI Sta-
tus Register (TWSR) is updated with a status code identifying the event. The TWSR only
contains releva nt status information when the TWI interr upt flag is asserted. At al l other times,
the TWSR contains a special status code indicating that no relevant status information is avail-
able. As long as the TWINT flag is set, the SCL line is held low. This allows the application
software to complete its tasks before allowing the TWI transmission to continue.
The TWINT flag is set in the following situations:
After the TWI has transmitted a START/REPEATED START condition.
After the TWI has transmitted SLA+R/W.
After the TWI has transmitted an address byte.
After the TWI has lost arbit ra tio n.
After the TWI has been addressed by own slave address or general call.
After the TWI has received a data byte.
After a STOP or REPEATED START has been received while still addressed as a Slave.
When a bus error has occurred due to an illegal START or STOP condition.
147
2548F–AVR–03/2013
ATmega406
25.6 TWI Register Description
25.6.1 TWBR – TWI Bit Rate Register
Bits 7:0 – TWI Bit Rate Register
TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency
divider which generates the SCL clock frequency in the Master modes. See ”Bit Rate Generator
Unit” on page 145 for calculating bit rates.
25.6.2 TWCR – TWI Control Register
The TWCR is used to con trol the operat ion of the TWI . It is used t o enab le the TWI, to initiate a
Master access by applying a START condition to the bus, to generate a Receiver acknowledge,
to generate a stop condition, and to control halting of the bus while the data to be written to the
bus are written to the TWDR. It also indicates a write collision if data is attempted written to
TWDR while the register is inaccessible.
Bit 7 – TWINT: TWI Interrupt Flag
This bit is set by hardware when the TWI has finished its current job and expects application
software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the
TWI Interrupt Vector. While the TWINT flag is set, the SCL low period is stretched. The TWINT
flag must be cleared by software b y writing a logic one to it. Note that this flag is not auto mati-
cally cleared by hardware when executing the interrupt routine. Also note that clearing this flag
starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Sta-
tus Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this
flag.
Bit 6 – TWEA: TWI Enable Acknowledge Bit
The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to
one, the ACK pulse is generated on the TWI bus if the following conditions are met:
1. The device’ s own slave address has been received.
2. A general call has been received, while the TWGCE bit in the TWAR is set.
3. A data by te has been received in Master Receive r or Slave Receiver mode.
By writing the TWEA bit to zero, the device can be virtually discon nected from the Two-wire
Serial Bus temporarily. Address recogn ition can then be resumed by writing the TWEA bit to one
again.
Bit 5 – TWSTA: TWI START Condition Bit
The application writes the TWSTA bit to one when it desires to become a Master on the Two-
wire Serial Bus. The TWI hardware checks if the bus is available, and generates a START con-
Bit 76543210
(0xB8) TWBR7 TWBR6 TWBR5 TWBR4 TWBR3 TWBR2 TWBR1 TWBR0 TWBR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 76543210
(0xBC) TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE TWCR
Read/Write R/W R/W R/W R/W R R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
148 2548F–AVR–03/2013
ATmega406
dition on the bus if i t is free. However, if the bus is not free, the TWI waits until a STOP condition
is detected, and then generates a new ST ART condition to claim the Bus Master status. TWSTA
is cleared by the TWI hardware when the START condition has been transmitted.
Bit 4 – TWSTO: TWI STOP Condition Bit
Writing the TWSTO bit to one in M aster mode will generate a STOP condition on the Two-wire
Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared auto-
matically. In Slave mode, setting the TWSTO bit can be used to recover from an error condition.
This will not generate a STOP condition, but the TWI returns to a well-defined unaddressed
Slave mode and releases the SCL and SDA lines to a high impedance state.
Bit 3 – TWWC: TWI Write Collision Flag
The TWWC bit is set when attempting to write to the TWI Data Register – TWDR when T WINT is
low. This flag is cleared by writing the TWDR Register when TWINT is high.
Bit 2 – TWEN: TWI Enable Bit
The TWEN bit enables TWI operation and activa tes the TWI interface. When TWEN is written to
one, the TWI takes control over the I/O pins connected to the SCL and SDA pins, enabling the
slew-rate limiters and spike filters. If this bit is written to zero, the TWI is switch ed off an d a ll TWI
transmissions are terminated , regardless of any ongoing operation.
Bit 1 – Res: Reserved Bit
This bit is a reserved bit and will always read as zero.
Bit 0 – TWIE: TWI Interrupt Enable
When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be acti-
vated for as long as the TWINT flag is high.
25.6.3 TWSR – TWI Status Register
Bits 7:3 – TWS: TWI Status
These five bits reflect the status of the TWI logic and the Two-wire Serial Bus. The different sta-
tus codes are described in Table 25-3 on page 156 through Table 25-6 on page 165. Note that
the value read from TWSR co ntains both the 5-bi t status value and th e 2-bit prescaler value. The
application designer should mask the prescaler bits to zero when checking the status bits. This
makes status checkin g independent of prescaler s etting. This approach is used in this da ta-
sheet, unless otherwise noted.
Bit 2 – Res: Reserved Bit
This bit is reserved and will always read as zero.
Bits 1:0 – TWPS: TWI Prescaler Bits
These bits can be read and written, and control the bit rate prescaler.
Bit 76543210
(0xB9) TWS7 TWS6 TWS5 TWS4 TWS3 TWPS1 TWPS0 TWSR
Read/Write RRRRRRR/WR/W
Initial Value 1 1 1 1 1 0 0 0
149
2548F–AVR–03/2013
ATmega406
To calculate bit rates, se e ”Bit Ra te Gener ator Unit” o n page 145 . The value of TWPS1 :0 is used
in the equation.
25.6.4 TWDR – TWI Data Register
In Transmit mode, TWDR contains the next byte to be transmitted. In Receive mode, the TWDR
contains the last byte received. It is writable while the TWI is not in the process of sh ifting a byte.
This occurs when the TWI Interrupt Flag (TWINT) is set by h ardware. Note that the data register
cannot be initialized by the user befo re the fi rst inte rr upt occur s. The data in TWDR remain s sta-
ble as long as TWINT is s et. While data is s hifted out, data on the bus is simultaneously shifted
in. TWDR always contains the last byte present on the bus, except after a wake-up fr om a sleep
mode by the TWI interr upt. In this ca se , the conten ts of TWDR is unde fin ed. In the ca se of a lost
bus arbitration, no data is lost in the transition from Master to Slave. Handling of the ACK bit is
controlled automatically by the TWI logic, the CPU cannot access the ACK bit directly.
Bits 7:0 – TWD: TWI Data Register
These ei ght bits c onstitute the next d ata byte t o be transmitted, or the latest data byte received
on the Two-wire Serial Bus.
25.6.5 TWAR – TWI (Slave) Address Register
The TWAR should be loaded with the 7-bit slave address (in the seven most significant bits of
TWAR) to which the TWI will respond when programmed as a slave transmitter or Receiver, and
not needed in the Master modes. In multi-master systems, TW AR must be set in masters whic h
can be addressed as slaves by other masters.
The LSB of TWAR is used to enable recognition of the general call address (0x00). There is an
associated address comparator that looks for the slave address (or general call address if
enabled) in the received serial address. If a match is found, an interrupt request is generated.
Bits 7:1 – TWA: TWI (Slave) Address Register
These seven bits constitute the slave address of the TWI unit.
Table 25-2. TWI Bit Rate Prescaler
TWPS1 TWPS0 Prescaler Value
00 1
01 4
10 16
11 64
Bit 76543210
(0xBB) TWD7 TWD6 TWD5 TWD4 TWD3 TWD2 TWD1 TWD0 TWDR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
Bit 76543210
(0xBA) TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE TWAR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 0
150 2548F–AVR–03/2013
ATmega406
Bit 0 – TWGCE: TWI General Call Recognition Enable Bit
If set, this bit enables the recognition of a General Call given over the Two-wire Serial Bus.
25.6.6 TWAMR – TWI (Slave) Address Mask Register
Bits 7:1 – TWAM: TWI Address Mask
The TWAMR can be loaded with a 7-bit Slave Address mask. Each of the bits in TWAMR can
mask (disable) th e correspondin g address bits in the TWI Address Register (TWAR). If the mask
bit is set to one then the address match logic ignores the compare between the incoming
address bit and the corresponding bit in TWAR. Figure 25-10 shown the address match logic in
detail.
Figure 25-10. TWI Address Match Logic, Block Diagram
Bit 0 – Res: Reserved Bit
This bit is an unused bit in the ATmega406, and will always read as zero.
25.7 Using the TWIThe AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all bus events, like
reception of a b yte or transmission of a START condition. Because the TWI is interrupt-base d,
the application softwar e is free to carr y on oth e r op erations d uri ng a TWI byte tra nsfer. Note that
the TWI Interrupt Enable (TWIE) bit in TWCR together with the Global Interrupt Enable bit in
SREG allow the application to decide whether or not assertion of the TWINT flag should gener-
ate an interrupt request. If the TWIE bit is cleared, the application must poll the TWINT flag in
order to detect actions on the TWI bus.
When the TWINT flag is asserted, the TWI has finished an operation and awaits application
response. In this case, the TWI Status Register (TWSR) contains a value indicating the current
state of the TWI bus. The application software can then decide how the TWI should behave in
the next TWI bus cycle by manipulating the TWCR and TWDR registers.
Figure 25-11 is a simple example of how the application can inte rface to the TWI hardware. In
this example, a Mast er wish es to tr ansm it a sing le data byte to a Slave. T his des criptio n is quite
abstract, a more detailed explanation follows later in this section. A simple code example imple-
menting the desired behavior is also presented.
Bit 76543210
(0xBD) TWAM[6:0] –TWAMR
Read/Write R/W R/W R/W R/W R/W R/W R/W R
Initial Value 0 0 0 0 0 0 0 0
Addre
ss
Match
Address Bit Comparator 0
Address Bit Comparator 6..1
TWAR0
TWAMR0
Address
Bit 0
151
2548F–AVR–03/2013
ATmega406
Figure 25-11. Interfacing the Application to the TWI in a Typical Transmission
1. The first step in a TWI transmission is to transmit a START condition. This is done by
writing a specific value into TWCR, instructing the TWI hardware to transmit a START
condition. Which value to write is described later on. However, it is important that the
TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will
not start any operation as long as the TWINT bit in TWCR is set. Immediately after the
application has cleared TWINT, the TWI will initiate transmission of the START condition.
2. When the START condition has been transmitted, the TWINT flag in TWCR is set, and
TWSR is updated with a status code indicating that the START condition has success-
fully been sent.
3. The application software should now examine the value of TWSR, to make sure that the
START condition was successfully transmitted. If TWSR indicates otherwise, the applica-
tion software might take some special action, like calling an error routine. Assuming that
the status code is as expected, the application must load SLA+W into TWDR. Remember
that TWDR is used both for address and data. After TWDR has been loaded with the
desired SLA+W , a specific value must be written to TWCR, instructing the TWI hardware
to transmit the SLA+W present in TWDR. Which value to write is described later on.
However, it is important that the TWINT bit is set in the value written. Writing a one to
TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in
TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate
transmission of the address packet.
4. When the address packet has been transmitted, the TWINT flag in TWCR is set, and
TWSR is updated with a status code indicating that the address packet has successfully
been sent. The status code will also reflect whether a slave acknowledged the packet or
not.
5. The application software should now examine the value of TWSR, to make sure that the
address packet was successfully transmitted, and that the value of the ACK bit was as
expected. If TWSR indicates otherwise, the application so ftware might t ake some special
action, like calling an error routine. Assuming that the status code is as expected, the
application must load a data packet into TWDR. Subsequently, a specific value must be
written to TWCR, instructing the TWI hardware to transmit the data packet present in
TWDR. Which value to write is described later on. However, it is important that the
TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will
START SLA+W A Data A STOP
1. Application
writes to TWCR to
initiate
transmission of
START
2. TWINT set.
Status code indicates
START condition sent
4. TWINT set.
Status code indicates
SLA+W sent, ACK
received
6. TWINT set.
Status code indicates
data sent, ACK received
3. Check TWSR to see if START was
sent.
Application loads SLA+W into TWDR,
and loads appropriate control signals
into TWCR, making sure that TWINT is
written to one
5. Check TWSR to see if SLA+W was
sent and ACK received.
Application loads data into TWDR, and
loads appropriate control signals into
TWCR, making sure that TWINT is
written to one
7. Check TWSR to see if data was sent
and ACK received.
Application loads appropriate control
signals to send STOP into TWCR,
making sure that TWINT is written to one
TWI bus
Indicates
TWINT set
Application
Action
TWI
Hardware
Action
152 2548F–AVR–03/2013
ATmega406
not start any operation as long as the TWINT bit in TWCR is set. Immediately after the
application has cleared TWINT, the TWI will initiate transmission of the data packet.
6. When the dat a packet has been transmitted , the TWINT flag in TWCR is set, an d TWSR
is updated with a status code indicating that the dat a packet has successfully been sent.
The status code will also reflect w hether a slave acknowledged the packet or not.
7. The application software should now examine the value of TWSR, to make sure that the
data packet was successfully transmitted, and that the value of the ACK bit was as
expected. If TWSR indicates otherwise, the application so ftware might t ake some special
action, like calling an error routine. Assuming that the status code is as expected, the
application must write a specific value to TWCR, instructing the TWI hardware to transmit
a STOP condition. Which value to write is described later on. However , it is important that
the TWINT bit is set in the value written. Wr iting a one to TWINT clears the flag. The TWI
will not start any operation as long as the TWINT bit in TWCR is set. Immediately after
the application has cleared TWINT, the TWI will initiate transmission of the STOP condi-
tion. Note that TWINT is NOT set after a STOP conditio n has been sent.
Even though this e xample is simple, it shows the principles involved in all TWI transmissions.
These can be summarized as follows:
When the TWI has finished an operation and expects application response, the TWINT flag is
set. The SCL line is pulled low until TWINT is cleared.
When the TWINT flag is set, the user must update all TWI registers with the valu e relevant for
the next TWI bus cycle. As an example, TWDR must be loaded with the value to be transmitted
in the next bus cycle.
After all TWI Register updates and other pending application software tasks have been
completed, TWCR is written. When writing TWCR, the TWINT bit should be set. Writing a one
to TWINT clears the flag. The TWI will then commence executing whatever operation was
specified by the TWCR setting.
In the following an assembly and C implementation of the example is given. Note that the code
below assumes that several definitions have been made for example by using include-files.
Assembly code exa m ple (1) C example(1) Comments
1
ldi r16,
(1<<TWINT)|(1<<TWSTA)|
(1<<TWEN)
out TWCR, r16
TWCR = (1<<TWINT)|(1<<TWSTA)|
(1<<TWEN) Send START condition
2
wait1:
in r16,TWCR
sbrs r16,TWINT
rjmp wait1
while (!(TWCR & (1<<TWINT)))
;Wait for TWINT flag set. This
indicates that the START
condition has be en transmitted
3
in r16,TWSR
andi r16, 0xF8
cpi r16, START
brne ERROR
if ((TWSR & 0xF8) != START)
ERROR(); Check value of TWI Status
Register. Mask prescaler bits. If
status different from ST ART go to
ERROR
153
2548F–AVR–03/2013
ATmega406
Note: 1. See ”About Code Examples” on page 7.
25.8 Transmission Modes
The TWI can operate in one of four major modes. These are named Master Transmitter (MT),
Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these
modes can be us ed in th e s am e ap p licat ion . As an example, the TWI can use MT mode to write
data into a TWI EEPROM, MR mode to read the data back from the EEPROM. If other masters
are present in the system, some of these might transmit data to the TWI, and then SR mode
would be used. It is the application software that decides which modes are legal.
The following sections describe each of these modes. Possible status codes are described
along with figures detailing data transmission in each of the modes. These figures contain the
following abbreviations:
4
ldi r16, SLA_W
out TWDR, r16
ldi r16, (1<<TWINT) |
(1<<TWEN)
out TWCR, r16
TWDR = SLA_W;
TWCR = (1<<TWINT) |
(1<<TWEN);
Load SLA_W into TWDR
Register. Clear TWINT bit in
TWCR to start transmission of
address
wait2:
in r16,TWCR
sbrs r16,TWINT
rjmp wait2
while (!(TWCR & (1<<TWINT)))
;Wait for TWINT flag set. This
indicates that the SLA+W has
been transmitted, and
ACK/NACK has been received.
5
in r16,TWSR
andi r16, 0xF8
cpi r16, MT_SLA_ACK
brne ERROR
if ((TWSR & 0xF8) !=
MT_SLA_ACK)
ERROR();
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
MT_SLA_ACK go to ERROR
ldi r16, DATA
out TWDR, r16
ldi r16, (1<<TWINT) |
(1<<TWEN)
out TWCR, r16
TWDR = DATA;
TWCR = (1<<TWINT) |
(1<<TWEN); Load DATA into TWDR Register.
Clear TWINT bit in TWCR to start
transmission of data
6
wait3:
in r16,TWCR
sbrs r16,TWINT
rjmp wait3
while (!(TWCR & (1<<TWINT)))
;Wait for TWINT flag set. This
indicates that the DA T A has been
transmitted, and ACK/NACK has
been received.
7
in r16,TWSR
andi r16, 0xF8
cpi r16, MT_DATA_ACK
brne ERROR
if ((TWSR & 0xF8) !=
MT_DATA_ACK)
ERROR();
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
MT_DATA_ACK go to ERROR
ldi r16,
(1<<TWINT)|(1<<TWEN)|
(1<<TWSTO)
out TWCR, r16
TWCR = (1<<TWINT)|(1<<TWEN)|
(1<<TWSTO); Transmit STOP condition
Assembly code exa m ple (1) C example(1) Comments
154 2548F–AVR–03/2013
ATmega406
S: START condition
Rs: REPEATED START condition
R: Read bit (high level at SDA)
W: Write bit (low level at SDA)
A: Acknowledge bit (low level at SDA)
A: Not acknowledge bit (high level at SDA)
Data: 8-bit data byte
P: STOP condition
SLA: Slave Address
In Figu re 25-1 3 to Figure 25-19, circles are used to indicate that the TWINT flag is set. The num-
bers in the circles show the status code held in TWSR, with the prescaler bits masked to zero. At
these points, actions must be taken by the application to continue or complete the TWI transfer.
The TWI transfer is suspended until the TWINT flag is cleared by software.
When the TWINT flag is set, the status code in TWSR is used to determine the appropriate soft-
ware action. For each statu s code, the required software action an d details of the following serial
transfer are given in Table 25-3 to Table 25-6. Note that the prescaler bits are m asked to zero in
these tables.
25.8.1 Master Transmitter Mode
In the Master Tr an sm itte r mo de , a n umb er of da ta bytes are transmitted to a slave receiver (see
Figure 25-12). In order to en ter a Maste r mode, a START condition m ust be transmitte d. The for-
mat of the f ollowing ad dress p acket de termines whethe r Maste r Tran smitter or Maste r Receiver
mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted,
MR mode is entered. All the status codes mentioned in this section assume that the prescaler
bits are zero or are masked to zero.
Figure 25-12. Data Transfer in Master Transmitter Mode
Device 1
MASTER
TRANSMITTER
Device 2
SLAVE
RECEIVER
Device 3 Device n
SDA
SCL
........ R1 R2
V
BUS
155
2548F–AVR–03/2013
ATmega406
A START condition is sent by writing the following value to TWCR:
TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to
transmit a START condition an d TWINT must be written to o ne to clear the TWINT flag. The TWI
will then test the Two-wire Serial Bus and generate a START condition as soon as the bus
becomes free. After a START condition has been transmitted, the TWINT flag is set by hard-
ware, and the status code in TWSR will be 0x08 (see Table 25-3). In order to ente r MT mode,
SLA+W must be transmitted. This is don e by writing SLA+W to TWDR. Th ereafter the TWINT bit
should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing
the following value to TWCR:
When SLA+W have been transmitted and an acknowledgment bit has been received, TWINT is
set again and a number of status codes in TWSR are possible. Pos sible stat us codes in Master
mode are 0x18, 0x20, or 0x38. The approp riate action to be taken for each of th ese status codes
is detailed in Table 25-3.
When SLA+W has be en successfully tran smitted, a data packet should be transmitted. This is
done by writing the data byte to TWDR. TWDR must only be written when TWINT is high. If not,
the access will be discarded, and the Write Collision bit (TWWC) will be set in the TWCR Regis-
ter. After updating TWDR, the TWINT bit should be cleared (by writing it to one) to continue the
transfer. This is accomplished by writing the following value to TWCR:
This scheme is repeated until the last byte has been sent and the transfer is ended by generat-
ing a STOP condition or a repeated START condition. A STOP condition is generated by writing
the following value to TWCR:
A REPEATED START condition is generated by writing the following value to TWCR:
After a repeated START condition (state 0x10) the Two-wire Serial Interface can access the
same slave again, or a new slave without transmitting a STOP condition. Repeated START
enables the master to switch between slaves, Master Tr ansmitter mode and M aster Receiver
mode without losing control of the bus.
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X10X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X00X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X00X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X01X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X10X10 X
156 2548F–AVR–03/2013
ATmega406
Table 25-3. Status Codes for Master Transmitter Mo de
Status Code
(TWSR)
Prescaler Bits
are 0
Status of the Two-wire Serial
Bus and Two-wire Serial Inter-
face Hardware
Application Software Response
Next Action Taken by TWI Hardware
To/from TWDR
To TWCR
STA STO TWINT TWEA
0x08 A START condition has been
transmitted Load SLA+W X 0 1 X SLA+W will be transmitted;
ACK or NOT ACK will be received
0x10 A repeated START condition
has been transmitted Load SLA+W or
Load SLA+R
X
X
0
0
1
1
X
X
SLA+W will be transmitted;
ACK or NOT ACK will be received
SLA+R will be transmitted;
Logic will switch to Master R eceiver mode
0x18 SLA+W has been transmitted;
ACK has been received Load data byte or
No TWDR action or
No TWDR action or
No TWDR action
0
1
0
1
0
0
1
1
1
1
1
1
X
X
X
X
Data byte will be transmitted and A CK or NOT ACK will
be received
Repeated START will be transmitted
STOP condition will be transmitted and
TWSTO flag will be reset
STOP condition followed by a START conditio n will be
transmitted and TWSTO flag will be reset
0x20 SLA+W has been transmitted;
NOT ACK has been received Load data byte or
No TWDR action or
No TWDR action or
No TWDR action
0
1
0
1
0
0
1
1
1
1
1
1
X
X
X
X
Data byte will be transmitted and A CK or NOT ACK will
be received
Repeated START will be transmitted
STOP condition will be transmitted and
TWSTO flag will be reset
STOP condition followed by a START conditio n will be
transmitted and TWSTO flag will be reset
0x28 Data byte has been transmit-
ted;
ACK has been received
Load data byte or
No TWDR action or
No TWDR action or
No TWDR action
0
1
0
1
0
0
1
1
1
1
1
1
X
X
X
X
Data byte will be transmitted and A CK or NOT ACK will
be received
Repeated START will be transmitted
STOP condition will be transmitted and
TWSTO flag will be reset
STOP condition followed by a START conditio n will be
transmitted and TWSTO flag will be reset
0x30 Data byte has been transmit-
ted;
NOT ACK has been received
Load data byte or
No TWDR action or
No TWDR action or
No TWDR action
0
1
0
1
0
0
1
1
1
1
1
1
X
X
X
X
Data byte will be transmitted and A CK or NOT ACK will
be received
Repeated START will be transmitted
STOP condition will be transmitted and
TWSTO flag will be reset
STOP condition followed by a START conditio n will be
transmitted and TWSTO flag will be reset
0x38 Arbitration lost in SLA+W or
data bytes No TWDR action or
No TWDR action
0
1
0
0
1
1
X
X
Two-wire Serial Bus will be released and not ad-
dressed slave mode entered
A START condition will be transmitted when the bus
becomes free
157
2548F–AVR–03/2013
ATmega406
Figure 25-13. Formats and States in the Master Transmitter Mode
25.8.2 Master Receiv er Mode
In the Master Receiver mode, a number of data bytes are received from a slave transmitter (see
Figure 25-14). In order to en ter a Maste r mode, a START condition m ust be transmitte d. The for-
mat of the f ollowing ad dress p acket de termines whethe r Maste r Tran smitter or Maste r Receiver
mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted,
MR mode is entered. All the status codes mentioned in this section assume that the prescaler
bits are zero or are masked to zero.
S SLA W A DATA A P
$08 $18 $28
R SLA W
$10
AP
$20
P
$30
A or A
$38
A
Other master
continues
A or A
$38
Other master
continues
R
A
$68
Other master
continues
$78 $B0
To corresponding
states in slave mode
MT
MR
Successfull
transmission
to a slave
receiver
Next transfer
started with a
repeated start
condition
Not acknowledge
received after the
slave address
Not acknowledge
received after a data
byte
Arbitration lost in slave
address or data byte
Arbitration lost and
addressed as slave
DATA A
n
From master to slave
From slave to master
Any number of data bytes
and their associated acknowledge bits
This number (contained in TWSR) corresponds
to a defined state of the Two-wire Serial Bus. The
p
rescaler bits are zero or masked to zero
S
158 2548F–AVR–03/2013
ATmega406
Figure 25-14. Data Transfer in Master Receiver Mode
A START condition is sent by writing the following value to TWCR:
TWEN must be writte n to one to enable the Two-wire Serial Interface, TWSTA must be written to
one to transmit a START condition and TWINT must be set to clear the TWINT flag. The TWI will
then test the Two-wire Se rial Bus and gener ate a START cond ition as soon as the bus becomes
free. After a START condition has been transmitted, the TWINT flag is set by hardware, and the
status code in TWSR will be 0x08 (see Table 25-3). In order to enter MR mode, SLA+R must be
transmitted. This is done by writing SLA+R to TWDR. Thereafter the TWINT bit should be
cleared (by writing it to one) to continue th e transfer. This is accomplished by writing the follow-
ing value to TWCR:
When SLA+R have been transmitted and an acknowledgment bit has been received, TWINT is
set again and a number of status codes in TWSR are possible. Possible status c odes in M aster
mode are 0x38, 0x40, or 0x48. The approp riate action to be taken for each of th ese status codes
is detailed in Table 25-13. Received data ca n be read from the TWDR Register when the TWINT
flag is set high by hardware. This scheme is repeated until the last byte has been received. After
the last byte has been received, the MR should inform the ST by sending a NACK after the last
received data byte. The tran sfe r is ende d by gen era ting a STOP condition or a re pea ted START
condition. A STOP condition is generated by writing the following value to TWCR:
A REPEATED START condition is generated by writing the following value to TWCR:
After a repeated START condition (state 0x10) the Two-wire Serial Interface can access the
same slave again, or a new slave without transmitting a STOP condition. Repeated START
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X10X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X00X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X01X10 X
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 1 X10X10 X
Device 1
MASTER
RECEIVER
Device 2
SLAVE
TRANSMITTER
Device 3 Device n
SDA
SCL
........
R1 R2
VBUS
159
2548F–AVR–03/2013
ATmega406
enables the master to switch between slaves, Master Tr ansmitter mode and M aster Receiver
mode without losing control over the bus.
Table 25-4. Status Codes for Master Receiver Mode
Status Code
(TWSR)
Prescaler Bits
are 0
Status of the Two-wire Serial
Bus and Two-wire Serial Inter-
face Hardware
Application Software Response
Next Action Taken by TWI Hardware
To/from TWDR
To TWCR
STA STO TWINT TWEA
0x08 A START condition has been
transmitted Load SLA+R X 0 1 X SLA+R will be transmitted
ACK or NOT ACK will be received
0x10 A repeated START condition
has been transmitted Load SLA+R or
Load SLA+W
X
X
0
0
1
1
X
X
SLA+R will be transmitted
ACK or NOT ACK will be received
SLA+W will be transmitted
Logic will switch to Master Transmitter mode
0x38 Arbitration lost in SLA+R or
NOT ACK bit No TWDR action or
No TWDR action
0
1
0
0
1
1
X
X
Two-wire Serial Bus will be released and not ad-
dressed Slave mode will be entered
A START condition will be transmitted when the bus
becomes free
0x40 SLA+R has been transmitted;
ACK has been received No TWDR action or
No TWDR action
0
0
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x48 SLA+R has been transmitted;
NOT ACK has been received No TWDR action or
No TWDR action or
No TWDR action
1
0
1
0
1
1
1
1
1
X
X
X
Repeated START will be transmitted
STOP condition will be transmitted and TWSTO f l ag
will be reset
STOP condition followed by a START conditio n will be
transmitted and TWSTO flag will be reset
0x50 Data byte has been received;
ACK has been returned Read data byte or
Read data byte
0
0
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x58 Data byte has been received;
NOT ACK has been returned Read data byte or
Read data byte or
Read data byte
1
0
1
0
1
1
1
1
1
X
X
X
Repeated START will be transmitted
STOP condition will be transmitted and TWSTO f l ag
will be reset
STOP condition followed by a START conditio n will be
transmitted and TWSTO flag will be reset
160 2548F–AVR–03/2013
ATmega406
Figure 25-15. Formats and States in the Master Receiver Mode
25.8.3 Slave Receiver Mode
In the Slave Receiver mode, a number of data by tes are received from a ma ster tran smitter (see
Figure 25-16). All the status codes mentioned in this section assume that the prescaler bits are
zero or are masked to zero.
Figure 25-16. Data Transfer in Slave Receiver Mode
To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows:
S SLA R A DATA A
$08 $40 $50
SLA R
$10
AP
$48
A or A
$38
Other master
continues
$38
Other master
continues
W
A
$68
Other master
continues
$78 $B0
To corresponding
states in slave mode
MR
MT
Successfull
reception
from a slave
receiver
Next transfer
started with a
repeated start
condition
Not acknowledge
received after the
slave address
Arbitration lost in slave
address or data byte
Arbitration lost and
addressed as slave
DATA A
n
From master to slave
From slave to master
Any number of data bytes
and their associated acknowledge bits
This number (contained in TWSR) corresponds
to a defined state of the Two-wire Serial Bus. The
p
rescaler bits are zero or masked to zero
PDATA A
$58
A
R
S
Device 3 Device n
SDA
SCL
........ R1 R2
V
BUS
Device 2
MASTER
TRANSMITTER
Device 1
SLAVE
RECEIVER
161
2548F–AVR–03/2013
ATmega406
The upper seven bits are the address to which the Two-wire Serial Interface will respond when
addressed by a master. If the LSB is set, the TW I will respon d to the g eneral call addr ess (0x00),
otherwise it will ignore the general call address.
TWEN must be written to on e to enable the TWI. The TWEA b it mu st be wr itte n to one to en able
the acknowledgment of the device’s own slave add re ss or th e gen eral call ad dre ss. TWSTA and
TWSTO must be written to zero.
When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own
slave address (or the gen eral call address if enabled) follo wed by the data direction bit. If the
direction bit is “0” (write), the TWI will operate in SR mode, otherwise ST mode is entered. A fter
its own slave address and the write bit have been received, the TWINT flag is set and a valid
status code can be read from TWSR. The status code is used to determine the appropriate soft-
ware action. The appropriate action to be taken for each status code is detailed in Table 25-5.
The Slave Receiver mode may also b e entere d if ar bitration is lost while the TWI is in the Master
mode (see states 0x68 and 0x7 8).
If the TWEA bit is reset during a transfer, the TWI will return a “Not Acknowledge” (“1”) to SDA
after the next received data byte. This can be used to indicate that the slave is not able to
receive any more bytes. While T WEA is zero, the TWI does not acknowledg e its own slave
address. However, the Two-wire Serial Bus is still monitored and address recognition may
resume at any time by se tting TWEA. Th is implies th at the TWEA bit may be us ed to tempo rarily
isolate the TW I fro m th e Tw o- wire Ser ial B us.
In all sleep mo des other than Idle mode, t he clock system to the TWI is turned off. If the TWEA
bit is set, the interface can still acknowledge its own slave address or the general call address by
using the Two-wire Serial Bus clock as a clock source. The part will then wake-up from sleep
and the TWI will hold the SCL clock low during the wake up and until the TWINT flag is cleared
(by writing it to one). Further data reception will be carried out as normal, with the A VR clocks
running as normal. Observe that if the AVR is set up with a long star t-up time, th e SC L line ma y
be held low for a long time, blocking other data transmissions.
Note that the Two-wire Serial Interface Data Register – TWDR does not reflect the last byte
present on the bus when waking up from these Sleep modes.
TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
Value Device’s Own Slave Address
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 0100010 X
162 2548F–AVR–03/2013
ATmega406
Table 25-5. Status Codes for Slave Receiver Mode
Status Code
(TWSR)
Prescaler Bits
Are 0
Status of the Two-wire Serial Bu s
and Two-wire Serial Interface
Hardware
Application Software Respon se
Next Action Taken by TWI Hardware
To/from TWDR
To TWCR
STA STO TWINT TWEA
0x60 Own SLA+W has been received;
ACK has been returned No TWDR action or
No TWDR action
X
X
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x68 Arbitration lost in SLA+R/W as
master; own SLA+W has been
received; ACK has been returned
No TWDR action or
No TWDR action
X
X
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x70 General call address has been
received; ACK has been returned No TWDR action or
No TWDR action
X
X
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x78 Arbitration lost in SLA+R/W as
master; General call address has
been received; ACK has been
returned
No TWDR action or
No TWDR action
X
X
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x80 Previously addressed with own
SLA+W; data has been received;
ACK has been returned
Read data byte or
Read data byte
X
X
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x88 Previously addressed with own
SLA+W; data has been received;
NOT ACK has been returned
Read data byte or
Read data byte or
Read data byte or
Read data byte
0
0
1
1
0
0
0
0
1
1
1
1
0
1
0
1
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA;
a START condition will be transmitted when the bus
becomes free
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”;
a START condition will be transmitted when the bus
becomes free
0x90 Previously addressed with
general call; data has been re-
ceived; ACK has been returned
Read data byte or
Read data byte
X
X
0
0
1
1
0
1
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
0x98 Previously addressed with
general call; data has been
received; NOT ACK has been
returned
Read data byte or
Read data byte or
Read data byte or
Read data byte
0
0
1
1
0
0
0
0
1
1
1
1
0
1
0
1
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA;
a START condition will be transmitted when the bus
becomes free
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”;
a START condition will be transmitted when the bus
becomes free
0xA0 A STOP condition or repeated
START condition has been
received while still addressed as
slave
Read data byte or
Read data byte or
Read data byte or
Read data byte
0
0
1
1
0
0
0
0
1
1
1
1
0
1
0
1
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA;
a START condition will be transmitted when the bus
becomes free
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”;
a START condition will be transmitted when the bus
becomes free
163
2548F–AVR–03/2013
ATmega406
Figure 25-17. Formats and States in the Slave Receiver Mode
S SLA W A DATA A
$60 $80
$88
A
$68
Reception of the own
slave address and one or
more data bytes. All are
acknowledged
Last data byte received
is not acknowledged
Arbitration lost as master
and addressed as slave
Reception of the general call
address and one or more data
bytes
Last data byte received is
not acknowledged
n
From master to slave
From slave to master
Any number of data bytes
and their associated acknowledge bits
This number (contained in TWSR) corresponds
to a defined state of the Two-wire Serial Bus. The
prescaler bits are zero or masked to zero
P or SDATA A
$80 $A0
P or SA
A DATA A
$70 $90
$98
A
$78
P or SDATA A
$90 $A0
P or SA
General Call
Arbitration lost as master and
addressed as slave by general call
DATA A
164 2548F–AVR–03/2013
ATmega406
25.8.4 Slave Transmitter Mode
In the Slave Transmitter mode , a nu mber o f data bytes are transmitted to a master re ceiver (see
Figure 25-18). All the status codes mentioned in this section assume that the prescaler bits are
zero or are masked to zero.
Figure 25-18. Data Transfer in Slave Transmitter Mode
To initiate the Slave Transmitter mode , TWAR and TWCR must be initialized as follows:
The upper seven bits are the address to which the Two-wire Serial Interface will respond when
addressed by a master. If the LSB is set, the TW I will respon d to the g eneral call addr ess (0x00),
otherwise it will ignore the general call address.
TWEN must be written to on e to enable the TWI. The TWEA b it mu st be wr itte n to one to en able
the acknowledgment of the device’s own slave add re ss or th e gen eral call ad dre ss. TWSTA and
TWSTO must be written to zero.
When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own
slave address (or the gen eral call address if enabled) follo wed by the data direction bit. If the
direction bit is “1” (read), the TWI will operate in ST mode, otherwise SR mode is entered. A fter
its own slave address and the write bit have been received, the TWINT flag is set and a valid
status code can be read from TWSR. The status code is used to determine the appropriate soft-
ware action. The appropriate action to be taken for each status code is detailed in Table 25-6.
The Slave Transmitte r mode may also be entered if arbitration is lost while the TWI is in the
Master mode (see state 0xB0).
If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte of the trans-
fer. State 0xC0 or state 0xC8 will be entered, depending on whether the master receiver
transmits a NACK or ACK after the final b yte. The TWI is switched to the not addressed Slave
mode, and will ignore the master if it continues the transfer. Thus the ma ster receiver receives
all “1” as serial data. State 0xC8 is entered if the master demands additional data bytes (by
transmitting ACK), even though the slave has transmitted the last byte (TWEA zero and expect-
ing NACK from the master).
TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
Value Device’s Own Slave Address
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
Value 0100010 X
Device 3 Device n
SDA
SCL
........
R1 R2
VBUS
Device 2
MASTER
RECEIVER
Device 1
SLAVE
TRANSMITTER
165
2548F–AVR–03/2013
ATmega406
While TWEA is zero, the TWI does not respo nd to its own slave ad dress. However, the Two-wire
Serial Bus is still monitored and address recognition may resume at any time by setting TWEA.
This implies that the TWEA bit may be used to temporarily isolate the TWI from the Two -wire
Serial Bus.
In all sleep mo des other than Idle mode, t he clock system to the TWI is turned off. If the TWEA
bit is set, the interface can still acknowledge its own slave address or the general call address by
using the Two-wire Serial Bus clock as a clock source. T he part will then wake up from sleep
and the TWI will hold the SCL clock will low during the wake up and until the TWINT flag is
cleared (by writing it to one). Further data transmission will be carried out as normal, with the
AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the
SCL line may be held low for a long time, blocking other da ta transmissions.
Note that the Two-wire Serial Interface Data Register – TWDR – does not reflect the last byte
present on the bus when waking up from these sleep modes.
Table 25-6. Status Codes for Slave Transmitter Mode
Status Code
(TWSR)
Prescaler
Bits are 0
Status of the Two-wi re Serial Bus
and Two-wire Serial Interface
Hardware
Application Software Response
Next Action Taken by TWI Hardware
To/from TWDR To TWCR
STA STO TWINT TWEA
0xA8 Own SLA+R has been received;
ACK has been returned Load data byte or
Load data byte
X
X
0
0
1
1
0
1
Last data byte will be transmitted and NOT ACK should
be receive d
Data byte will be transmitted and ACK should be re-
ceived
0xB0 Arbitration lost in SLA+R/W as
master; own SLA+R has been
received; ACK has been ret urned
Load data byte or
Load data byte
X
X
0
0
1
1
0
1
Last data byte will be transmitted and NOT ACK should
be receive d
Data byte will be transmitted and ACK should be re-
ceived
0xB8 Data byte in TWDR has been
transmitted; ACK has been
received
Load data byte or
Load data byte
X
X
0
0
1
1
0
1
Last data byte will be transmitted and NOT ACK should
be receive d
Data byte will be transmitted and ACK should be re-
ceived
0xC0 Data byte in TWDR has been
transmitted; NOT ACK has been
received
No TWDR action or
No TWDR action or
No TWDR action or
No TWDR action
0
0
1
1
0
0
0
0
1
1
1
1
0
1
0
1
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA;
a START condition will be transmitted when the bus
becomes free
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”;
a START condition will be transmitted when the bus
becomes free
0xC8 Last dat a byte in TWDR has been
transmitted (TWEA = “0”); ACK
has been received
No TWDR action or
No TWDR action or
No TWDR action or
No TWDR action
0
0
1
1
0
0
0
0
1
1
1
1
0
1
0
1
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”
Switched to the not addressed Slave mode;
no recognition of own SLA or GCA;
a START condition will be transmitted when the bus
becomes free
Switched to the not addressed Slave mode;
own SLA will be recognized;
GCA will be recognized if TWGCE = “1”;
a START condition will be transmitted when the bus
becomes free
166 2548F–AVR–03/2013
ATmega406
Figure 25-19. Formats and States in the Slave Transmitter Mode
25.8.5 Miscellaneous States
There are two status codes th at do not correspond to a defined TWI state, see Table 25-7.
Status 0xF8 indicate s that no relevant information is ava ilable because the TWINT flag is not
set. This occurs between other states, and when the TWI is not involved in a serial transfer.
Status 0x00 indicates that a b us er ror has o ccurred during a Two-wire Serial Bus transfer. A bus
error occurs when a START or STOP condition occurs at an illegal position in the format frame.
Examples of such illegal positions are during the serial transfer of an address byte, a data byte,
or an acknowledge bit. When a bus error occurs, TWINT is set. To recover from a bus error, the
TWSTO flag must set and TWINT must be cleared by writing a logic one to it. Th is causes the
TWI to enter th e not ad dressed Slave mode and to cle ar the TWSTO flag ( no other bits in TWCR
are affected). The SDA and SCL lines are released, and no STOP condition is transmitted.
S SLA R A DATA A
$A8 $B8
A
$B0
Reception of the own
slave address and one or
more data bytes
Last data byte transmitted.
Switched to not addressed
slave (TWEA = '0')
Arbitration lost as master
and addressed as slave
n
From master to slave
From slave to master
Any number of data bytes
and their associated acknowledge bits
This number (contained in TWSR) corresponds
to a defined state of the Two-wire Serial Bus. The
prescaler bits are zero or masked to zero
P or SDATA
$C0
DATA A
A
$C8
P or SAll 1's
A
167
2548F–AVR–03/2013
ATmega406
25.8.6 Combining Several TWI Modes
In some cases, several TWI modes must be combined in order to complete the desired action.
Consider for example reading data from a serial EEPROM. Typically, such a transfer involves
the following steps:
1. The transfer must be initiated.
2. The EEPROM must be instructed what location should be read.
3. The reading must be performed.
4. The transfer must be finished.
Note that data is transmitted both fro m Master to Slave and vice versa. The Master must instr uct
the slave what location it wants to read, requiring the use of the MT mode. Subsequ ently, data
must be read fr om the slave, imp lyin g the use of the MR mode. Thus, the transfer direction must
be changed. The Master must keep control of the bus during all these steps, and the steps
should be carried out as an atomic operation. If this principle is violated in a multi-master sys-
tem, another master can alter the data pointer in the EEPROM between steps 2 and 3, and the
master will read the wrong data location. Such a change in transfer direction is accomplished by
transmitting a REPEATED START between the transmission of the address byte and reception
of the data. After a REPEATED START, the mast er keeps ownership of the bus. The following
figure shows the flow in this transfer.
Figure 25-20. Combining Several TWI Modes to Access a Serial EEPROM
25.9 Multi-master Systems and Arbitration
If multiple master s are connected to the same bu s, transmissions may be initiated simulta ne-
ously by one or more of them. The TWI standard ensures that such situations are handled in
such a way that one of the masters will be allowed to proceed with the transfer, and that no data
will be lost in the process. An example of an arbitration situation is depicted below, where two
masters are trying to transmit data to a slave receiver.
Table 25-7. Miscellaneous States
Status Code
(TWSR)
Prescaler Bits
are 0
Status of the Two-wire Serial
Bus and Two-wire Serial Inter-
face hardware
Application Software Response
Next Action Taken by TWI Hardware
To/from TWDR
To TWCR
STA STO TWINT TWEA
0xF8 No relevant state information
available; TWINT = “0” No TWDR action No TWCR action Wait or proce ed current transfer
0x00 Bus error due to an illegal
START or STOP condition No TWDR action 0 1 1 X Only the internal hardware is affected, no STOP cond i-
tion is sent on the bus. In all cases, the bus is released
and TWSTO is cleared.
Master Transmitter Master Receiver
S = START Rs = REPEATED START P = STOP
Transmitted from master to slave Transmitted from slave to master
S SLA+W A ADDRESS A Rs SLA+R A DATA A P
168 2548F–AVR–03/2013
ATmega406
Figure 25-21. An Arbitration Example
Several different scenarios may arise during arbitration, as described below:
Two or more masters are performing identical communication with the same slave. In this
case, neither the slave nor any of the masters will know about the bus contention.
Two or more masters are accessing the same slave with different data or direction bit. In this
case, arbitration will occur , either in the READ/WRITE bit or in the dat a bits. The masters trying
to output a one on SDA while another master outputs a zero will lose the arbitration. Losing
masters will switch to not addressed Slave mode or wait until the bus is free and transmit a
new START condition, depending on application software action.
Two or more masters are accessing different slaves. In this case, arbitration will occur in the
SLA bits. Masters trying to output a one on SDA while another master outputs a zero will lose
the arbitration. Masters losing arbitration in SLA will switch to Slave mode to check if they are
being addressed by the winning master. If addressed, they will switch to SR or ST mode,
depending on the value of the READ/WRITE bit. If they are not being addressed, they will
switch to not addressed Slave mode or wait until the bus is free and transmit a new START
condition, depending on application software action.
This is summarized in Figure 25-22. Possible status values are given in circles.
Figure 25-22. Possible Status Codes Caused by Arbitration
Device 1
MASTER
TRANSMITTER
Device 2
MASTER
TRANSMITTER
Device 3
SLAVE
RECEIVER
Device n
SDA
SCL
........
R1 R2
VBUS
Own
Address / General Call
received
Arbitration lost in SLA
TWI bus will be released and not addressed slave mode will be entered
A START condition will be transmitted when the bus becomes free
No
Arbitration lost in Data
Direction
Ye s
Write
Data byte will be received and NOT ACK will be returned
Data byte will be received and ACK will be returned
Last data byte will be transmitted and NOT ACK should be received
Data byte will be transmitted and ACK should be received
Read
B0
68/78
38
SLASTART Data STOP
169
2548F–AVR–03/2013
ATmega406
25.10 Bus Connect/Disconnect for Two-wire Serial Interface
The Bus Connect/Disconnect module is an addition to the TWI Interface. Based on a configura-
tion bit, an interrupt can be generated either when the TWI bus is connected or disconnected.
Figure 25-23 illustrates the Bus Connect/Disconnect logic, where SDA and SCL are the TWI
data and clock lines, respectively.
When the TWI bus is connected, both the SDA and the SCL lines will become high simultane-
ously. If the TWBCIP bit is cleared, the interrupt will be executed if enabled. Once the bus is
connected, the TWBCIP bit should be set. This enables detection of when the bus is discon-
nected, and prevents repetitive interrupts every time both the SDA and SCL lines ar e high (e.g.
bus IDLE state).
When the TWI bus is disconnected, both the SDA and the SCL lines will become low simultane-
ously. If the TWBCIP bit is set, the interrupt will be executed if enabled and if both lines remain
low for a configurable time period. By add ing th is time constraint , unwanted inter rupts caused by
both lines going low during normal bus communication is prevented.
Figure 25-23. Overview of Bus Connect/Disconnect.
25.10.1 TWBCSR – TWI Bus Control and Status Register
Bit 7 - TWBCIF: TWI Bus Connect/Disconnect Interrupt Flag
Based on the TWBCIP bit, the TWBCIF bit is set when the TWI bus is connected or discon-
nected. TWBCIF is cleared by hardware when executing the corresponding interrupt handling
vector. Alternatively, TWBCIF is cleared by w riting a logic one to the flag. When the SREG I-bit,
TWBCIE (TWI Bus Connect/Disconnect Interrupt Enable), and TWBCIF are set, the TWI Bus
DELAY ELEMENT
START OUTPUT
DELAY
TWBCSR
S
DA
S
CL
SET TWBCIF
IR
Q
TWBDT
TWBCIP
8-BIT DATA BUS
Bit 7 6 5 4 3 2 1 0
(0xBE) TWBCIF TWBCIE TWBDT1 TWBDT0 TWBCIP TWBCSR
Read/Write R/W R/W R R R R/W R/W R/W
Initial Value X00000 0 0
170 2548F–AVR–03/2013
ATmega406
Connect/Disconnect Interrupt is executed. If both SDA and SCL are high during reset, TWBCIF
will be set after reset. Otherwise TWBCIF will be cleared after reset.
Bit 6 - TWBCIE: TWI Bus Connect/Disconn ect Interrupt Enable
When the TWBCIE bit and the I-bit in the Status Register are set, the TWI Bus Connect/Discon-
nect Interrupt is enabled. The corresponding interrupt is executed if a TWI Bus
Connect/Disconnect occurs, i.e., when the TWBCIE bit is set.
Bit 5:3 - Res: Reserved Bits
These bits are reserved bits in the ATmega406 and will always read as zero.
Bit 2:1 - TWBDT1, TWBDT0: TWI Bus Disconnect Time-out Period
The TWBDT bits decides how long both the TWI data (SDA) and clock (SCL) signals must be
low before generating the TWI Bus Disconnect Interrupt. The different configuration values and
their corresponding time-out periods are shown in Table 25-8.
Bit 0 - TWBCIP: TWI Bus Connect/Disconnect Interrupt Polarity
The TWBCIP bit decide if the TWI Bus Connect/Disconnect Interrupt Flag (TWBCIF) should be
set on a Bus Connect or a Bus Disconnect. If TWBCIP is cleared, the TWBCIF flag is set on a
Bus Connect. If TWBCIP is set, the TWBCIF flag is set on a Bus Disconnect.
Table 25-8. TW Bus Disconnect Time-out Period
TWBDT1 TWBDT0 TWI Bus Disconnect Time-out Period
0 0 250 ms
0 1 500 ms
1 0 1000 ms
1 1 2000 ms
171
2548F–AVR–03/2013
ATmega406
26. JTAG Interface and On-chip Debug System
26.1 Features JTAG (IEEE std. 1149.1 Compliant) Interf ace
Debugger Access to:
All Internal Peripheral Units
Internal and Extern al RAM
The Internal Register File
–Program Counter
EEPROM and Flash Memories
Extensive On-chip Debug Support for Break Conditions, Including
AVR Break Instruction
Break on Change of Program Memory Flow
Single Step Break
Program Memory Break Points on Single Address or Address Range
Data Memory Break Points on Single Address or Address Range
Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface
On-chip Debugging Supported by AVR Studio®
26.2 Overview The AVR IEEE std. 1149.1 compliant JTAG interface can be used for
Programming the non-volatile memories, Fuses and Lock bits
On-chip debu g gin g
A brief description is given in the following sections. Detailed description s for Programming via
the JTAG interface can be found in the section ”Programming via the JTAG Interface” on page
211. The On-chip Debug support is considered being privat e JTAG in structions , and distrib uted
within ATMEL and to selected third party vendors only.
Figure 26-1 shows a block diagram of the JTAG interface and the On-chip Deb ug system. The
TAP Controller is a state machine controlled by the TCK and TMS signals. The TAP Controller
selects either the JTAG Instruction Register or one of several Data Registers as the scan chain
(Shift Register) betwe en the T DI – inp ut and TDO – o utpu t. The In structio n Regi ster h olds JTAG
instructions controlling the behavior of a Data Register.
The JTAG Programming Interface (actually consisting of several physical and virtual Data Reg-
isters) is used for serial programming via the JTAG interface . The Internal Scan Chain and
Break Point Scan Chain are used for On-chip debugging only.
26.3 Test Access Port – TAP
The JTAG interface is accessed through fou r of the AVR’s pins. In JTAG terminology, these pins
constitute the Test Access Port – TAP. These pins are:
TMS: Test mode select. This pin is used for navigating through the TAP-controller state
machine.
TCK: Test Clock. JTAG operation is synchronous to TCK.
TDI: Test Data In. Serial input data to be shifted in to the Instruction Register or Data Register
(Scan Chains).
TDO: Test Data Out. Serial output data from Instruction Register or Data Register.
172 2548F–AVR–03/2013
ATmega406
The IEEE std. 1149.1 also specifies an optional TAP signal; TRST – Test ReSeT – which is not
provided.
When the JTAGEN Fu se is unprogrammed, the se four TAP pins are normal po rt pins, and the
TAP controller is in reset. When programmed, the input TAP signals are internally pulled high
and the JTAG is enabled for programming. The device is shipped with this fuse programmed.
For the On-chip Debug system, in addition to the JTAG interface pins, the RESET pin is moni-
tored by the debugger to be able to detect external reset sources. The debugger can also pull
the RESET pin low to reset the whole system, assuming only open collectors on the reset line
are used in the application.
Figure 26-1. Block Diagram
TAP
CONTROLLER
TDI
TDO
TCK
TMS
FLASH
MEMORY
AVR CPU
DIGITAL
PERIPHERAL
UNITS
JTAG / AVR CORE
COMMUNICATION
INTERFACE
BREAKPOINT
UNIT FLOW CONTROL
UNIT
OCD STATUS
AND CONTROL
INTERNAL
SCAN
CHAIN
M
U
X
INSTRUCTION
REGISTER
ID
REGISTER
BYPASS
REGISTER
JTAG PROGRAMMING
INTERFACE
PC
Instruction
Address
Data
BREAKPOINT
SCAN CHAIN
ADDRESS
DECODER
173
2548F–AVR–03/2013
ATmega406
Figure 26-2. TAP Controller State Diagram
26.4 TAP Contro ller
The TAP controller is a 16-state finite state machin e tha t contro ls the op er ation of the JTAG pr o-
gramming circuitry, or On-chip Debug system. The state transitions depicted in Figure 26-2
depend on the signal present on TMS (shown adjacent to each state transition) at the time of the
rising edge at TCK. The initial state after a Power-on Reset is Test-Logic-Reset.
As a definition in this document, the LSB is shifted in and out first for all Shift Registers.
Assuming Run-Test/Idle is the present state, a typical scenario for using the JTAG interface is:
At the TMS input , ap ply the se qu en ce 1, 1, 0, 0 at the rising edges of TCK to enter the Shift
Instruction Register – Shift-IR sta te. While in this state, shift the four bits of the JTAG
instructions into the JTAG Instructio n Register from the TDI input at the rising edge of TCK.
The TMS input must be held low during input of the 3 LSBs in order to remain in the Shift-IR
state. The MSB of the instruction is shifted in when this state is left by setting TMS high. While
the instruction is shifted in from the TDI p in, the captured IR-state 0x01 is shifted out on the
TDO pin. The JTAG Instruction selects a particular Data Register as path between TDI and
TDO and controls the circuitry surrounding the selected Data Register.
Test-Logic-Reset
Run-Test/Idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR Scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR Scan
Capture-DR
0
1
011 1
00
00
11
10
1
1
0
1
0
0
10
1
1
0
1
0
0
00
11
174 2548F–AVR–03/2013
ATmega406
Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched
onto the p arallel o utput from the Shif t Reg ister path in the Update-IR state. The Exit-IR, Pause-
IR, and Exit2-IR states are only used for navigating the state machine.
At the TMS input, ap ply the seq uen ce 1 , 0, 0 a t the rising e dges of TCK to e nter the Sh ift Data
Register – Shift- DR state. While in this st ate, upload the selected data register (se lected by the
present JTAG instruction in the JTAG Instruction Register) from the TDI input at the rising edge
of TCK. In order to remain in the Shif t-DR sta te, the TMS input must be held low during in put of
all bits except the MSB. The MSB of the data is shifted in when this state is left by setting TMS
high. While the data regi ster is shifted in from the TDI pin, the parallel inputs to the data
register captured in the Capture-DR st ate is shifted out on the TDO pin.
Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. If the selected data register
has a latched parallel-output, the latching takes place in the Update-DR state. The Exit-DR,
Pause-DR, and Exit2-DR states are only used for navigating the state machine.
As shown in the state diagram, the Run-Test/Idle state need not be entered between selecting
JTAG instruction and using data registers, and some JTAG instructions may select certain func-
tions to be performed in the Run-Test/Idle, making it unsuitable as an Idle state.
Note: Independent of the initial state of the TAP Controller, the Test-Logic-Reset state can always be
entered by holding TMS high for five TCK clock periods.
For detailed information on the JTAG specification, refer to the literature listed in ”JTAG Inter-
face and On-chip Debug System” on page 171.
26.5 Using the On-chip Debug System
As shown in Figure 26-1, the hardware support for On-chip Debugging consists mainly of
A scan chain on the interface between the internal AVR CPU and the internal peripheral units.
Break Point unit.
Communication interface between the CPU and JTAG system.
All read or modify/write operations needed for implementing the Debugger are done by applying
AVR instructions via the internal AVR CPU Scan Chain. The CPU sends the result to an I/O
memory mapped location which is part of the communication interface be tween the CPU and the
JTAG system.
The Break Point Unit implements Break on Change of Program Flow, Single Step Break, two
Program Memory Break Points, and two combined Break Points. Together, the four Break
Points can be configured as either:
4 single Program Memory Break Points.
3 Single Program Memory Break Point + 1 single Data Memory Break Point.
2 single Program Memory Break Points + 2 single Data Memory Break Points.
2 single Program Memory Break Points + 1 Program Memory Break Point with mask (“range
Break Point”).
2 single Program Memory Break Point s + 1 Data Memory Brea k Point with mask (“range Break
Point”).
A debugger, like the AVR Studio, may however use one or more of these resources for its inter-
nal purpose, leaving less flexibility to the end-user.
A list of the On-chi p Debug specific JTAG instructions is given in ”On-chip Debug Specific JTAG
Instructions” on page 175.
175
2548F–AVR–03/2013
ATmega406
The JTAGEN Fuse must be programmed to enable the JTAG Test Access Port. In addition, the
OCDEN Fuse must be programmed and no Lock bits must be set for the On-chip debug system
to work. As a security feature, the On-chip debug system is disabled when either of the L B1 or
LB2 Lock bits are set. Otherwise, the O n-chip debug system would have p rovided a back-door
into a secured device.
The AVR Studio enables the user to fully control execution of programs on an AVR device with
On-chip Debug capability, AVR In-Circuit Emulator, or the built-in AVR Instruction Set Simulator.
AVR Studio® supports source level execution of Assembly programs assembled with Atmel Cor-
poration’s AVR Assembler and C programs compiled with third party vendors’ compilers.
AVR Studio runs under Microsoft® Windows® 95/98/2000 and Microsoft Windows NT®.
For a full description of the AVR Studio, please refer to the AVR Studio User Guide. Only high-
lights are presented in this document.
All necessary executio n commands are available in AVR Studio , both on source level and on
disassembly level. T he user can execute the pr ogram, single step through th e code either by
tracing into or stepping over functions, step out of functions, place the cursor on a statement and
execute until the statement is reached, stop the execution, and reset the execution target. In
addition, the user can have an unlimited number of code Break Points (using the BREAK
instruction) and up to two data memory Break Points, alternatively combined as a mask (range)
Break Point.
26.6 On-chip Debug Specific JTAG Instructions
The On-chip debu g support is consid ered be ing private JTAG instr uctions, and distribute d within
ATMEL and to selected third party vendors only. Instruction opcodes are listed for reference.
26.6.1 PRIVATE0; 0x8Private JTAG instruction for accessing On-chip debug system.
26.6.2 PRIVATE1; 0x9Private JTAG instruction for accessing On-chip debug system.
26.6.3 PRIVATE2; 0xAPrivate JTAG instruction for accessing On-chip debug system.
26.6.4 PRIVATE3; 0xBPrivate JTAG instruction for accessing On-chip debug system.
176 2548F–AVR–03/2013
ATmega406
26.7 On-chip Debug Related Register
26.7.1 OCDR – On-chip Debug Register
The OCDR Register provides a communication channel from the running program in the micro-
controller to the debugger. The CPU can transfer a byte to the debugger by writing to this
location. At the same time, an internal flag; I/O Debug Register Dirty – IDRD – is set to indicate
to the debug ger that the register has been writte n. When the CPU re ads th e OCDR Register the
7 LSB will be from the OCDR Register, while the MSB is the IDRD bit. The debugger clears the
IDRD bit when it has read the information.
In some AVR devices, this register is shared with a standard I/O location. In this case, the OCDR
Register can only be accessed if the OCDEN Fuse is pro grammed, and the debugger enables
access to the OCDR Register. In all other cases, the standard I/O location is accessed.
Refer to the debugger documentation for further information on how to use this register.
26.7.2 MCUCR – MCU Control Register
The MCU Control Register contains control bits for general MCU functions.
Bit 7 - JTD: JTAG Interface Disable
When this bit is zero, the JTAG interface is enabled if the JTAGEN Fuse is programmed. If this
bit is one, the JTAG interface is disabled. In order to avoid unintentional disabling or enabling of
the JTAG interface, a timed sequence must be followed when changing this bit: The application
software must write this bit to the desired value twice within four cycles to change its value.
Note that this bit must not be altered when using the On-chip Debug system.
Bit 7 6543210
0x31 (0x51) On-Chip Debug Register OCDR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6543210
0x35 (0x55) JTD PUD IVSEL IVCE MCUCR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
177
2548F–AVR–03/2013
ATmega406
26.8 Using the JTAG Programming Capabilities
Programming of AVR parts via JTAG is performe d via the 4-pin JTAG port, TCK, TMS, TDI, and
TDO. These are the only pins that need to be controlled/observed to perform JTAG program-
ming (in addition to power pins). It is not required to apply 12V externally. Th e JTAGEN Fuse
must be programmed and the JTD bit in the MCUCR Register must be cleared to enable the
JTAG Test Access Port.
The JTAG programming capability supports:
Flash programming and verifying.
EEPROM programming and verifying.
Fuse programming and verifying.
Lock bit programming and verifying.
The Lock bit security is exactly as in parallel programming mode. If the Lock bits LB1 or LB2 are
programmed, the OCDEN Fuse cannot be programmed unless first doing a chip erase. This is a
security feature that ensures no back-door exists for reading out the content of a secured
device.
The details on programming through the JTAG interface and programming specific JTAG
instructions are given in the section ”Programming via the JTAG Interface” on page 211.
178 2548F–AVR–03/2013
ATmega406
27. Boot Loader Support – Read-While-Write Self-Programming
The Boot Loader Support provides a real Read-While-Write Self-Programming mechanism for
downloading and up loading progr am code by the MCU itsel f. This feature allows flexible applica-
tion software updates controlled by the MCU using a Flash-resident Boot Loader program. The
Boot Loader program can use any available data interface and associated protocol to read code
and write (program) that code into the Flash memory, or read the code from the program mem-
ory. The program code within the Boot Loader section has the capability to write into the entire
Flash, including the Boot Loader memory. The Boot Loader can thus even modify itself, and it
can also erase itself from the code if the feature is not needed anymore. The size of the Boot
Loader memory is configurable with fuses and the Boot Loader has two separate sets of Boot
Lock bits which can be set independently. This gives the user a uniq ue flexibility to select differ-
ent levels of protection.
27.1 Boot Loader Features
Read-While-Write Self-Programming
Flexible Boot Memory Size
High Security (Separate Boot Lock Bits for a Flexible Protection)
Separate Fuse to Select Reset Vector
Optimized Page(1) Size
Code Efficient Algorithm
Efficient Read-Modify-Write Support
Note: 1. A page is a section in the Flash consisting of several bytes (see ”Page Size” on page 198)
used during programming. The page organization does not affect normal operation.
27.2 Application and Boot Loader Flash Sections
The Flash memory is organized in two main sections, the Application section and the Boot
Loader section (see Figure 27-2). The size of the different sections is configured by the
BOOTSZ Fuses as shown in Table 27- 7 on page 193 and Figure 27-2. These two sections can
have different level of protection since they have different sets of Lock bits.
27.2.1 Application Section
The Application section is the section of the Flash that is used for storing the application code.
The protection level for the Application section can be selected by the application Boot Lock bits
(Boot Lock bits 0), see Table 27-2 on page 182. The Application section can never store any
Boot Loader code sin ce the SPM instruction is disab led when executed from the Application
section.
27.2.2 BLS – Boot Loader Section
While the Application section is used for storing the application code, the The Boot Loader soft-
ware must be located in the BLS since the SPM instruction can initiate a programming when
executing from the BLS only. The SPM instruction can access the entire Flash, including the
BLS itself. The protection level for the Boot Loader section can be selected by the Boot Loader
Lock bits (Boot Lock bits 1), see Table 27-3 on page 182.
179
2548F–AVR–03/2013
ATmega406
27.3 Read-While-Write and No Read-While-Write Flash Sections
Whether the CPU supports Read-While-Write or if the CPU is halted during a Boot Loader soft-
ware update is depende nt on which address that is being progr ammed. In addition to the two
sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also
divided into two fixed sections, the Read-While-Write (RWW) section and the No Read-While-
Write (NRWW) section. The limit between the RWW- and NRWW sections is given in Table 27-
8 on page 193 and Figure 27-2 on page 181. The main difference between the two sections is:
When erasing or writing a page located inside the RWW section, the NR WW section can be
read during the operation.
When erasing or writing a page located inside the NRWW section , the CPU is halted durin g the
entire operation.
Note that the user software ca n never read any code that is located inside the RWW section dur-
ing a Boot Loader software operation. The syntax “Read-Wh ile-Write section” re fers to which
section that is being programmed (erased or written), not which section that actually is being
read during a Boot Loader software update.
27.3.1 RWW – Read-While-Write Section
If a Boot Loader software update is programming a page inside the RWW section, it is possible
to read code from the Flash, but only code that is located in the NRWW section. During an on-
going programming, the software must ensure that the RWW section never is being read. If the
user software is trying to read code that is located inside the RWW section (i.e., by a
call/jmp/lpm or an interrupt) during programming, the software might end up in an unknown
state. To avoid this, the interrupts should either be disabled or moved to the Boot Loader sec-
tion. The Boot Loader section is always located in the NRWW section. The RWW Section Busy
bit (RWWSB) in the Store Program Memory Control and Status Register (SPMCSR) will be read
as logical one as long as the RWW section is blocked for reading. After a programming is com-
pleted, the RWWSB must be cleared by software before reading code located in the RWW
section. See Section “27.5.1” on page 183. for details on how to clear RWWSB.
27.3.2 NRWW – No Read-While-Write Section
The code located in the NRWW section can be read when the Boot Loader software is updating
a page in the RWW section. When the Boot Loader code updates the NRWW section, the CPU
is halted during the entire Page Erase or Page Write operation.
Table 27-1. Read-While-Write Features
Which Section does the Z-pointer
Address During the Prog ramming? Which Section Can be Read
During Programming? CPU
Halted? Read-While-Write
Supported?
RWW Section NRWW Section No Yes
NRWW Section None Yes No
180 2548F–AVR–03/2013
ATmega406
Figure 27-1. Read-While-Write vs. No Read-While-Write
Read-While-Write
(RWW) Section
No Read-While-Write
(NRWW) Section
Z-pointer
Addresses RWW
Section
Z-pointer
Addresses NRWW
Section
CPU is Halted
During the Operation
Code Located in
NRWW Section
Can be Read During
the Operation
181
2548F–AVR–03/2013
ATmega406
Figure 27-2. Memory Sections
Note: 1. The parameters in the figure above are given in Table 27-7 on page 193.
27.4 Boot Loader Lock Bits
If no Boot Loader capability is needed, the entire Flash is available for application code. The
Boot Loader has two separ ate sets of Boot Lock bits which ca n be set inde pende ntly. This gives
the user a unique flexibility to select different levels of protection.
The user can select:
To protect the entire Flash from a software update by the MCU.
To protect only the Boot Loader Flash section from a software update by the MCU.
To protect only the Application Flash section from a software update by the MCU.
Allow software update in the entire Flash.
See Table 27-2 and Table 27-3 for further details. The Boot Lock bits can be set in software and
in Serial or Parallel Programming mode, but they can be cleared by a Chip Erase command
only. The general Write Lock (Lock Bit mode 2) does not co ntrol the programming of the Flash
memory by S PM instructio n. Similarly, the general Read/Write Lock (Lock Bit mode 1) does not
control reading nor writing by LPM/SPM, if it is attempted.
0x0000
Flashend
Program Memory
BOOTSZ = '11'
Application Flash Section
Boot Loader Flash Section Flashend
Program Memory
BOOTSZ = '10'
0x0000
Program Memory
BOOTSZ = '01'
Program Memory
BOOTSZ = '00'
Application Flash Section
Boot Loader Flash Section
0x0000
Flashend
Application Flash Section
Flashend
End RWW
Start NRWW
Application Flash Section
Boot Loader Flash Section
Boot Loader Flash Section
End RWW
Start NRWW
End RWW
Start NRWW
0x0000
End RWW, End Application
Start NRWW, Start Boot Loader
Application Flash SectionApplication Flash Section
Application Flash Section
Read-While-Write SectionNo Read-While-Write Section Read-While-Write SectionNo Read-While-Write Section
Read-While-Write SectionNo Read-While-Write SectionRead-While-Write SectionNo Read-While-Write Section
End Application
Start Boot Loader
End Application
Start Boot Loader
End Application
Start Boot Loader
182 2548F–AVR–03/2013
ATmega406
Note: 1. “1” means unprogrammed, “0” means programmed
Note: 1. “1” means unprogrammed, “0” means programmed
Table 27-2. Boot Lock Bit0 Protection Modes (Application Section)(1)
BLB0 Mode BLB02 BLB01 Protection
111
No restrictions for SPM or LPM accessing the Application
section.
2 1 0 SPM is not allowed to write to the Application section.
300
SPM is not allowed to write to the Application section, and LPM
executing from the Boot Loader section is not allowed to read
from the Application section. If Interrupt Vectors are placed in
the Boot Loader section, interrupts are disabled while executing
from the Application section.
401
LPM executing from the Boot Loa der section is not allowed to
read from the Application section. If Interrupt V ectors are placed
in the Boot Loader section, inte rrupts are disabled while
executing from the Application section.
Table 27-3. Boot Lock Bit1 Protection Modes (Boot Loader Section) (1)
BLB1 Mode BLB12 BLB11 Protection
111
No restrictions for SPM or LPM accessing the Boot Loader
section.
2 1 0 SPM is not allowed to write to the Boot Loader section.
300
SPM is not allowed to write to the Boot Loader section, and LPM
executing from the Application section is not allowed to read
from the Boot Loader section. If Interrupt Vectors are placed in
the Application section, interrupts are disabled while executing
from the Boot Loader section.
401
LPM executing from the Application section is not allowed to
read from the Boot Loader section. If Interrupt Vectors are
placed in the Application section, interrupts are disabled wh ile
executing from the Boot Loader section.
183
2548F–AVR–03/2013
ATmega406
27.5 Entering the Boot Loader Program
Entering the Boot Loader takes place by a jump or call from the application program. This may
be initiated by a t rigger such as a comm and received via the TW I interface. Alterna tively, the
Boot Reset Fuse can be programmed so that the Reset Vector is p ointin g to the Bo ot Fl ash sta rt
address after a reset. In this case, the Boot Loader is started after a reset. After the application
code is loaded, the prog ram can sta rt executing the ap plication code. Note th at the fuse s cannot
be changed by the MCU itself. This me ans that once the Boot Reset Fuse is programmed, the
Reset Vector will always point to the Boot Loader Reset and the fuse can only be changed
through the serial or parallel pr ogramming interface.
Note: 1. “1” means unprogrammed, “0” means programmed
27.5.1 SPMCSR – Store Program Memory Control and Status Register
The Store Program Me mory Control an d Status Regi ster contains the control bits n eeded to con-
trol the Boot Load e r oper at ion s.
Bit 7 – SPMIE: SPM Interrupt Enable
When the SPMIE bit is written to one, and the I-bit in the Status Register is set (one), the SPM
ready interrupt will be enabled. The SPM ready Interrupt will be executed as long as the SPMEN
bit in the SPMCSR Register is cleared.
Bit 6 – RWWSB: Read-While-Write Sect ion Busy
When a Self-Programming (Page Eras e or Page Write) operation to the RWW section is initi-
ated, the RWWSB will be set (one) by hardware. When the RWWSB bit is set, the RWW section
cannot be accessed. The RWWSB bit will be cleared if the RWWSRE bit is written to one after a
Self-Programming operation is completed. Alternatively the RWWSB bit will automatically be
cleared if a page load oper ation is initiated.
Bit 5 - SIGRD: Signature Row Read
If this bit is written to one at the same time as SPMEN, the next LPM instruction within three
clock cycles will read a byte from the signature row into the destination register. see “Reading
the Signature Row from Software” on page 189 for details.
An SPM instruction within four cycles after SIGRD and SPMEN are set will have no effect. This
operation is reserved for future use and should not be used.
Table 27-4. Boot Reset Fuse(1)
BOOTRST Reset Address
1 Reset Vector = Application Reset (address 0x0000 )
0 Reset Vector = Boot Loader Reset (see Table 27-7 on page 193)
Bit 7 6 5 4 3 2 1 0
0x37 (0x57) SPMIE RWWSB SIGRD RWWSRE BLBSET PGWRT PGERS SPMEN SPMCSR
Read/Write R/W R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
184 2548F–AVR–03/2013
ATmega406
Bit 4 – RWWSRE: Read-While-Write Section Read Enable
When programming (Page Erase or Page Write) to the RWW section, the RWW se ction is
blocked for reading (the RWWSB will be set by hardware). To re-enable the RWW section, the
user software must wait until the programming is completed (SPMEN will be cleared). Then, if
the RWWSRE bit is written to one at the same time as SPMEN, the next SPM instruction within
four clock cycles re-enables the RWW section. The RWW section cannot be re-enabled while
the Flash is busy with a Page Erase or a Page Write (SPMEN is set). If the RWWSRE bit is writ-
ten while the Flash is being loaded, the Flash load operation will abort and the data loaded will
be lost.
Bit 3 – BLBSET: Boot Lock Bit Set
If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock
cycles sets Boot Lock bits, according to the data in R0. The data in R1 and the ad dr ess in the Z-
pointer are ignored. The BLBSET bit will automatically be cleared upon completion of the Lock
bit set, or if no SPM instruction is executed within four clock cycles.
An LPM instruction within three cycles after BLBSET and SPMEN are set in the SPMCSR Reg-
ister, will read either the Lock bits or the Fuse bits (depending on Z0 in the Z-pointer) into the
destination register. See ”Reading the Fuse and Lock Bits from Software” on page 188 for
details.
Bit 2 – PGWRT: Page Write
If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock
cycles executes Page Write, with the data stored in the temporary buffer. The page address is
taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit
will auto-clear upon completion of a Page Write, or if no SPM instruction is executed within four
clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is
addressed.
Bit 1 – PGERS: Page Erase
If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock
cycles executes Page Erase. The page address is taken from the high part of the Z-pointer. The
data in R1 and R0 are ignored. The PGERS bit will auto-clear upon completion of a Page Erase,
or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire
Page Write operation if the NRWW section is addressed.
Bit 0 – SPMEN: Store Program Memory Enable
This bit enables the SPM instruction for the next four clock cycles. If written to one together with
either RWWSRE, BLBSE T, PGWRT’ or PGERS, the following SPM instruction will have a spe-
cial meaning, see description above. If only SPMEN is written, the following SPM instruction will
store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of
the Z-pointer is ignored. The SPMEN bit will auto-clear upon completion of an SPM instruction,
or if no SPM instruction is executed within fo ur cloc k cycles. During Page Erase and Page Write,
the SPMEN bit remains high until the operation is completed.
Writing any other combination than “100001”, “010001”, “001001”, “000101”, “000011” or
“000001” in the lower five bits will have no effect.
185
2548F–AVR–03/2013
ATmega406
27.6 Addressing the Flash During Self-Programming
The Z-pointer is used to address the SPM commands.
Since the Flash is organized in pages (see ”Fuse Bits” on page 19 6), the Program Counter can
be treated as having two differ ent sections. One section, cons isting of the least significant bits, is
addressing the words within a page, while the most significant bits are addressing the pages.
This is shown in Figure 27-3. Note that the Page Erase and Page Write operations are
addressed independently. Therefore it is of major importance that the Boot Loader software
addresses the same page in both the Page Erase a nd Page Write operation. Once a program-
ming operation is initiated, the address is latched and the Z-pointer can be used for other
operations.
The only SPM operation that does no t use the Z-pointer is Setting the Boot Loader Lock bits.
The content of the Z-pointer is ignored and will have no effect on the operation. The LPM
instruction does also use the Z-pointer to store the address. Since this instruction addresses the
Flash byte-b y-b yt e, also the LSB (bit Z0) of the Z-po in te r is used .
Figure 27-3. Addressing the Flash During SPM(1)
Note: 1. The different variables used in Figure 27-3 are listed in Table 27-9 on page 193.
Bit 151413121110 9 8
ZH (R31) Z15 Z14 Z13 Z12 Z11 Z10 Z9 Z8
ZL (R30) Z7Z6Z5 Z4Z3Z2Z1Z0
76543210
PROGRAM MEMORY
0115
Z - REGISTER
BIT
0
ZPAGEMSB
WORD ADDRESS
WITHIN A PAGE
PAGE ADDRESS
WITHIN THE FLASH
ZPCMSB
INSTRUCTION WORD
PAGE PCWORD[PAGEMSB:0]:
00
01
02
PAGEEND
PAGE
PCWORDPCPAGE
PCMSB PAGEMSB
PROGRAM
COUNTER
186 2548F–AVR–03/2013
ATmega406
27.7 Self-Programming the Flash
The program memory is updated in a page by page fashion. Before programming a page with
the data stored in the tempo rary page buffer, the page must be era sed. The temporary pag e buf-
fer is filled one word at a time using SPM and the buffer can be filled either before the Pag e
Erase command or between a Page Erase and a Page Write operation:
Alternative 1, fill the buffer before a Page Erase
Fill temporary page buffer
Perform a Page Erase
Perform a Page Write
Alternative 2, fill the buffer after Page Erase
Perform a Page Erase
Fill temporary page buffer
Perform a Page Write
If only a part of the page needs to be changed, the rest of the page must be stored (for example
in the temporary page buffer) before the erase, and then be rewritten. When using alternative 1,
the Boot Loader provides an effe ctive Read- Mod ify- Write fe atur e which allows the user software
to first read the page, do the necessary changes, and then write back the modified data. If alter-
native 2 is used, it is not p ossible to read the old data while loading since the page is already
erased. The temporary page buffer can be accessed in a random sequence. It is essential that
the page address used in both the Page Erase and Page Write operation is addressing the
same page. See Simple Assembly Code Example for a Boot Loader” on page 191 for an
assembly code example.
27.7.1 Performing Page Erase by SPM
To execute Page Erase, set up the address in the Z-pointer, write “X0000011” to SPMCSR and
execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored.
The page address must be written to PCPAGE in the Z-register. Othe r bits in the Z-pointer will
be ignored during this operation.
Page Erase to the RWW section: The NRWW section can be read during the Page Erase.
Page Erase to the NRWW section: The CPU is halted dur ing the operation.
27.7.2 Filling the Temporary Buffer (Page Loading)
To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write
“00000001” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. Th e
content of PCWORD in the Z-register is used to address the data in the temporary buffer. The
temporary buffer will auto-erase after a Page Write operation or by writing the RWWSRE bit in
SPMCSR. It is also erased after a system reset. Note that it is not possible to write more than
one time to each address without erasing the temporary buffer.
187
2548F–AVR–03/2013
ATmega406
27.7.3 Performing a Page Write
To execute Page Write, set up the address in the Z-pointer, write “X0000101” to SPMCSR and
execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored.
The page address must be written to PCPAGE. Other bits in the Z-pointer will be ignored during
this operation.
Page Write to the RWW section: The NRWW section can be read during the Page Write.
Page Write to the NRWW section: The CPU is halted during the operation.
27.7.4 Using the SPM Interrupt
If the SPM interrupt is enabled, the SPM interrupt will generate a constant interrupt when the
SPMEN bit in SPMCSR is cleared. This means that the interrupt can be used instead of polling
the SPMCSR Register in software. When using the SPM interrupt, the Interrupt Vectors should
be moved to the BLS section to avoid that an interrupt is accessing the RWW section when it is
blocked for reading. How to move the interrupts is described in ”Interrupts” on page 51.
27.7.5 Consideration While Updating BLS
Special care must be taken if the user allows the Boot Loader section to be updated by leaving
Boot Lock bit11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the
entire Boot Loader, and further software updates might be impossible. If it is not necessary to
change the Boot Loader software itself, it is r ecommended to progra m the Boot Lock bit11 to
protect the Boot Loader software from any internal software changes.
27.7.6 Prevent Reading the RWW Section During Self-Programming
During Self-Programming (either Page Erase or Page Write), the RWW section is always
blocked for reading. The user software itself must prevent that this section is addressed during
the self programming operation. The RWWSB in the SPMCSR will be set as long as the RWW
section is busy. During Self-Pro gramming the Inte rrup t Vector table should b e move d to the BLS
as described in ”Interrupts” on page 51, or the interrupts must be disabled. Before addressing
the RWW section after the programming is completed, the user software must clear the
RWWSB by writing the RWWSRE. See ”Simple Assembly Code Example for a Boot Loader” on
page 191 for an example.
27.7.7 Setting the Boot Loader Loc k Bits by SPM
To set the Boot Loader Lock bits, write the desired data to R0, write “X0001 001” to SPMCSR
and execute SPM within four clock cycles after writing SPMCSR. The only accessible Lock bits
are the Boot Lock bits that may prevent the Application and Boot Loader section from any soft-
ware update by the MCU.
See Table 27-2 and Table 27-3 for how the different settings of the Boot Loader bits affect the
Flash acces s .
If bits 5:2 in R0 are cleared (zero), the corresponding Boot Lock bit will be programmed if an
SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCSR.
The Z-pointer is don’t care during this operation, but for future compatibility it is recommended to
load the Z-pointer with 0x0001 (same as used fo r reading the lO ck bits). For future compatibility it
Bit 76543210
R0 1 1 BLB12 BLB11 BLB02 BLB01 1 1
188 2548F–AVR–03/2013
ATmega406
is also recommended to set bits 7, 6, 1, and 0 in R0 to “1” when writing the Lock bits. When pro-
gramming the Lock bits the entire Flash can be read during the operation.
27.7.8 EEPROM Write Prevents Writing to SPMCSR
Note that an EEPROM write operation will block all software programming to Flash. Reading the
Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It
is recommended that the u ser checks the status bit (EEWE) in the EECR Register and verifies
that the bit is cleared before writing to the SPMCSR Register.
27.7.9 Reading the Fuse and Lock Bits from Software
It is pos sible to read both the Fuse and Lock bits from software. To read the Lock bits, load th e
Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCSR. When an LPM instruc-
tion is executed within three CPU cycles after the BLBSET and SPMEN bits are set in SPMCSR,
the value of the Lock bits will be loaded in the destination register. The BLBSET and SPMEN
bits will auto-clear upon completion of reading the Lock bits or if no LPM instruction is executed
within three CPU cycles or no SPM instruction is executed within four CPU cycles. When BLB-
SET and SPMEN are cleared, LPM will work as described in the ”AVR Instruction Set”
description.
The algorithm for reading the Fuse Low byte is similar to the one described above for reading
the Lock bits. To read the Fu se Low byte, load the Z-pointer with 0 x0000 and set the BLBSET
and SPMEN bits in SPMCSR. When an LPM instruction is executed within three cycles after the
BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low byte (FLB) will be
loaded in the destination register as shown below. Refer to Table 28-4 on page 197 for a
detailed description and mapping of the Fuse Low byte.
Similarly, when reading th e Fuse High byte, loa d 0x000 3 in the Z-p ointer. When an LPM instruc-
tion is executed within three cycles after the BLBSET and SPMEN bits are set in the SP MCSR,
the value of the Fuse High byte (FHB) will be loaded in the destination register as shown below.
Refer to Table 28-3 on page 196 for detailed description and mapping of the Fuse High byte.
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are
unprogrammed, will be read as one.
Bit 76543210
Rd BLB12 BLB11 BLB02 BLB01 LB2 LB1
Bit 76543210
Rd FLB7 FLB6 FLB5 FLB4 FLB3 FLB2 FLB1 FLB0
Bit 76543210
Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0
189
2548F–AVR–03/2013
ATmega406
27.7.10 Reading the Signature Row from Software
To read the Signature Row from software, load the Z-pointer with the signature byte address
given in Table 27-5 and set the SIGRD and SPMEN bits in SPMCSR. When an LPM instruction
is executed within three CPU cycles after the SIGRD and SPMEN bits are set in SPMCSR, the
signature byte value will be loaded in the destination register. The SIGRD and SPMEN bits will
auto-clear upon completion of reading the Signature Row Lo ck bits or if no LPM instruction is
executed within three CPU cycles. When SIGRD and SPMEN are cleared, LPM will work as
described in the ”AVR Instruction Set” description.
Table 27-5. Signature Row Addressing
Signature Byte Z-Pointer Address
Device ID 0, Manufacture ID 0x00
Device ID 1, Flash Size 0x02
Device ID 2, Device 0x04
FOSCCAL(1) 0x01
Reserved 0x03
Slow RC FRQ(2) 0x05
Slow RC L 0x06
Slow RC H(3) 0x07
Slow RC Temp Prediction L 0x0C
Slow RC Temp Prediction H(7) 0x0D
ULP RC FRQ(5) 0x08
ULP RC L 0x0A
ULP RC H(6) 0x0B
Bandgap PTAT Current Calibration Byte(4) 0x09
V-ADC RAW Cell 1 L 0x0E
V-ADC RAW Cell 1 H(8) 0x0F
V-ADC Cell1 Gain Calibration Word L 0x10
V-ADC Cell1 Gain Calibration Word H(9) 0x11
V-ADC Cell2 Gain Calibration Word L 0x12
V-ADC Cell2 Gain Calibration Word H(9) 0x13
V-ADC Cell3 Gain Calibration Word L 0x14
V-ADC Cell3 Gain Calibration Word H(9) 0x15
V-ADC Cell4 Gain Calibration Word L 0x16
V-ADC Cell4 Gain Calibration Word H(9) 0x17
V-ADC ADC0 Gain Calibration Word L 0x18
V-ADC ADC0 Gain Calibration Word H(10) 0x19
V-ADC Cell1 Offset(12) 0x1C
190 2548F–AVR–03/2013
ATmega406
Notes: 1. Default FOSCCAL value after reset.
2. Slow RC oscillator Frequency in kHz
3. Slow RC Oscillator fastest timeout in µs.
4. Calibration valu e found for BGCCR which gives 1.1V at VREF when BGCRR = 0x0F.
5. ULP RC Oscillator Frequency in kHz.
6. ULP RC Oscillator fastest timeout in µs.
7. Slow RC Oscillator Frequency Temperature drift prediction value (word). Measured over sev-
eral lots. Not implemented.
8. Calibration Word used for the second step of VREF calibra tion. This step is performed by the
customer at 25C. Value stored is VADCH/L when Cell1 had 4096 mV at 85C.
9. Calibration Word used to compensate for gain error in V-ADC Cell input 1 - 4. Cell x in mV =
VADCH/L*this word/16384 .
10.Calibration Word used to compensate for gain error in V-ADC ADC0. ADC0 in 0.1mV =
VADCH/L*this word/16384 .
11. Calibration Word used to calculate the absolute temperatu re in Kelvin from VTEMP conver-
sion. Temp in K = VADCH/L *this word/16384.
12.Calibration Byte used to compensate for offset in V- ADC Cells. Not implemented.
All other addresses are reserved for future use.
V-ADC Cell2 Offse(12)t 0x1D
V-ADC Cell3 Offse(12)t 0x1E
V-ADC Cell4 Offset(12) 0x1F
VPTAT CAL L 0x1A
VPTAT CAL H(11) 0x1B
Table 27-5. Signature Row Addressing
Signature Byte Z-Pointer Address
191
2548F–AVR–03/2013
ATmega406
27.7.11 Programming Time for Flash when Using SPM
The Fast RC Oscillator is used to time Flash accesses. Table 27-6 shows the typical program-
ming time for Flash accesses from the CPU.
27.7.12 Simple Assembly Code Example for a Boot Loader
;-the routine writes one page of data from RAM to Flash
; the first data location in RAM is pointed to by the Y pointer
; the first data location in Flash is pointed to by the Z-pointer
;-error handling is not included
;-the routine must be placed inside the Boot space
; (at least the Do_spm sub routine). Only code inside NRWW section
; can be read during Self-Programming (Page Erase and Page Write).
;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24),
; loophi (r25), spmcrval (r20)
; storing and restoring of registers is not included in the routine
; register usage can be optimized at the expense of code size
;-It is assumed that either the interrupt table is moved to the
; Boot loader section or that the interrupts are disabled.
.equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words
.org SMALLBOOTSTART
Write_page:
; Page Erase
ldi spmcrval, (1<<PGERS) | (1<<SPMEN)
call Do_spm
; re-enable the RWW section
ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN)
call Do_spm
; transfer data from RAM to Flash page buffer
ldi looplo, low(PAGESIZEB) ;init loop variable
ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256
Wrloop:
ld r0, Y+
ld r1, Y+
ldi spmcrval, (1<<SPMEN)
call Do_spm
adiw ZH:ZL, 2
sbiw loophi:looplo, 2 ;use subi for PAGESIZEB<=256
brne Wrloop
; execute Page Write
subi ZL, low(PAGESIZEB) ;restore pointer
sbci ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256
ldi spmcrval, (1<<PGWRT) | (1<<SPMEN)
call Do_spm
; re-enable the RWW section
Table 27-6. SPM Programming Time
Symbol Min Programming Time Max Programming Time
Flash write (Page Erase, Page Write, and
write Lock bits by SPM) 3.7 ms 4.5 ms
192 2548F–AVR–03/2013
ATmega406
ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN)
call Do_spm
; read back and check, optional
ldi looplo, low(PAGESIZEB) ;init loop variable
ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256
subi YL, low(PAGESIZEB) ;restore pointer
sbci YH, high(PAGESIZEB)
Rdloop:
lpm r0, Z+
ld r1, Y+
cpse r0, r1
jmp Error
sbiw loophi:looplo, 1 ;use subi for PAGESIZEB<=256
brne Rdloop
; return to RWW section
; verify that RWW section is safe to read
Return:
in temp1, SPMCSR
sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet
ret
; re-enable the RWW section
ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN)
call Do_spm
rjmp Return
Do_spm:
; check for previous SPM complete
Wait_spm:
in temp1, SPMCSR
sbrc temp1, SPMEN
rjmp Wait_spm
; input: spmcrval determines SPM action
; disable interrupts if enabled, store status
in temp2, SREG
cli
; check that no EEPROM write access is present
Wait_ee:
sbic EECR, EEWE
rjmp Wait_ee
; SPM timed sequence
out SPMCSR, spmcrval
spm
; restore SREG (to enable interrupts if originally enabled)
out SREG, temp2
ret
193
2548F–AVR–03/2013
ATmega406
27.7.13 ATmega406 Boot Loader Parameters
In T able 27-7 through Table 27-9, the parameters used in the description of the Self-Program-
ming are given
Note: 1. The different BOOTSZ Fuse configurations are shown in Figure 27-2
Note: 1. For details about these two section, see ”NRWW – No Read-While-Write Section” on page
179 and ”RWW – Read-W hile-Write Section” on page 179.
Table 27-7. Boot Size Configuration(1)
BOOTSZ1
BOOTSZ0
Boot Size
Pages
Application
Flash Section
Boot Loader
Flash Section
End Applicatio n
Section
Boot Reset
Address
(Start Boot
Loader Section)
11
256
words 40x0000 -
0x4EFF 0x4F00 -
0x4FFF 0x4EFF 0x4F00
10
512
words 80x0000 -
0x4DFF 0x4E00 -
0x4FFF 0x4DFF 0x4E00
01
1024
words 16 0x0000 -
0x4BFF 0x4C00 -
0x4FFF 0x4BFF 0x4C00
00
2048
words 32 0x0000 -
0x47FF 0x4800 -
0x4FFF 0x47FF 0x4800
Table 27-8. Read-While-Write Limit(1)
Section Pages Address
Read-While-Write section (RWW) 288 0x0000 - 0x47FF
No Read-While-Write section (NRWW) 32 0 x 4800 - 0x4FFF
Table 27-9. Explanation of different variables used in Figure 27-3 and the mapping to the Z-
pointer(1)
Variable Corresponding
Z-value Description
PCMSB 14 Most significant bit in the Program Counter. (The
Program Coun te r is 13 bi ts PC[12:0])
PAGEMSB 5 Most significant bit which is used to address the
words within one page (64 words in a page requires
six bits PC [5:0]).
ZPCMSB Z15 Bit in Z-register that is mapped to PCMSB. Because
Z0 is not used, the ZPCMSB equals PCMSB + 1.
ZPAGEMSB Z6 Bit in Z-register that is mapped to PCMSB. Because
Z0 is not used, the ZP AGEMSB equals PAGEMSB +
1.
PCPAGE PC[14:6] Z13:Z7 Program Counter page address: Page select, for
Page Erase and Page Write
PCWORD PC[5:0] Z6:Z1 Program Counter word address: Word select, for
filling temporary buffer (must be zero during Page
Write operation)
194 2548F–AVR–03/2013
ATmega406
Note: 1. Z0: should be zero for all SPM commands, byte select for the LPM instruction.
See ”Addressing the Flash During Self-Programming” on page 185 for details about the use of
Z-pointer during Self-Programming.
195
2548F–AVR–03/2013
ATmega406
28. Memory Programming
28.1 Program And Data Memory Lock Bits
The ATmega406 provides six Lock bits which can be left unprogrammed (“1”) or can be pro-
grammed (“0”) to obtain the additional features listed in Table 28-2. The Lock bits can only be
erased to “1” with the Chip Erase command.
Note: 1. “1” means unprogrammed, “0” means programmed
Table 28-1. Lock Bit Byte(1)
Lock Bit Byte Bit No Description Default Value
7 1 (unprogrammed)
6 1 (unprogrammed)
BLB12 5 Boot Lock bit 1 (unprogrammed)
BLB11 4 Boot Lock bit 1 (unprogrammed)
BLB02 3 Boot Lock bit 1 (unprogrammed)
BLB01 2 Boot Lock bit 1 (unprogrammed)
LB2 1 Lock bit 1 (unprogrammed)
LB1 0 Lock bit 1 (unprogrammed)
Table 28-2. Lock Bit Protection Modes(1)(2)
Memory Lock Bits Protection Type
LB
Mode LB2 LB1
1 1 1 No memory lock features enabled.
210
Further programming of the Flash and EEPROM is disabled in
Parallel and Serial Programming mode. The Fuse bits are locked in
both Serial and Parallel Programming mode.(1)
300
Further programming and verification of the Fla s h and EEPROM is
disabled in Parallel and Serial Programming mode. The Boot Lock
bits and Fuse bits are locked in both Serial and Parallel
Programming mode.(1)
BLB0
Mode BLB02 BLB01
1 1 1 No restrictions for SPM or LPM accessing the Application secti on.
2 1 0 SPM is not allowed to write to the Application section.
300
SPM is not allowed to write to the Application section, and LPM
executing from the Boot Loader section is not allowed to read from
the Application section. If Interru pt Vectors are placed in the Boot
Loader section, interrupts are disabled while executing from the
Application section.
401
LPM executing from the Boot Loader section is not allowed to read
from the Application section. If Interrupt Vectors are placed in the
Boot Loader section, interrupts are disabled while executing from
the Application section.
196 2548F–AVR–03/2013
ATmega406
Notes: 1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2.
2. “1” means unprogrammed, “0” means programmed
28.2 Fuse Bits The ATmega406 has two Fuse bytes. Table 28-3 - Table 28-4 describe briefly the functionality of
all the fuses and how they are mapped into the Fuse bytes. Note that the fuses are read as logi-
cal zero, “0”, if they are pr og r am m ed .
28.2.1 High Byte
Notes: 1. Never ship a product with the OCDEN Fuse programmed regardless of the setting of Lock bits
and JTAGEN Fuse. A programmed OCDEN Fuse enab les some parts of the clock system to
be running in all sleep modes. This may increase the power consumption.
BLB1
Mode BLB12 BLB11
1 1 1 No restrictions for SPM or LPM accessing the Boot Loader section.
2 1 0 SPM is not allowed to write to the Boot Loader section.
300
SPM is not allowed to write to the Boot Loader section, and LPM
executing from the Application section is not allowed to read from
the Boot Loader section. If Interrupt Vectors are placed in the
Application section, interrupts are disabled while executing from the
Boot Loader section.
401
LPM executing from the Application section is not allowed to read
from the Boot Loader section. If Interrupt Vectors are placed in the
Application section, interrupts are disabled while executing from the
Boot Loader section.
Table 28-2. Lock Bit Protection Modes(1)(2) (Continued)
Memory Lock Bits Protection Type
Table 28-3. Fus e High Byte
Fuse High Byte Bit No Description Default Value
–7 1
–6 1
–5 1
–4 1
–3 1
–2 1
OCDEN(1) 1 Enable OCD 1 (unprogrammed, OCD
disabled)
JTAGEN 0 Enable JTAG 0 (programmed, JTAG enabled)
197
2548F–AVR–03/2013
ATmega406
28.2.2 Low Byte
Notes: 1. The default value of SUT1:0 results in maximum start-up time for the default clock source. See
Table 7-2 on page 28 for details.
2. The default value of BOOTSZ1:0 results in maximum Boot Size. See Table 27-7 on page 193
for details.
3. See ”WDTCSR – Watchdog Timer Control Register” on page 47 for details.
4. When unpgrogrammed, Internal RC Oscillator is used. Programming this fuse is for test pur-
pose only, and should not be used in application.
The status of the Fuse bits is not affected by Chip Erase. Note that the Fuse bits are locked if
Lock bit1 (LB1) is programmed. Program the Fuse bits before programming the Lock bits.
28.2.3 Latching of Fuses
The fuse values are latched when the device enters programming mode and changes of the
fuse values will have no effect until the part leaves Programming mode. This does not apply to
the EESAVE Fuse which will take effect once it is programmed. The fuses are also latched on
Power-up in Normal mode.
Table 28-4. Fuse Low Byte
Fuse Low Byte Bit No Description Defaul t Value
WDTON(3) 7 Watchdog Timer always on 1 (unprogrammed)
EESAVE 6 EEPROM memory is preserved
through the Chip Erase 1 (unprogrammed, EEPROM
not preserved)
BOOTSZ1 5 Select Boot Size ( see Ta ble 27 -7 on
page 193 for details) 0 (programmed)(2)
BOOTSZ0 4 Select Boot Size ( see Ta ble 27 -7 on
page 193 for details) 0 (programmed)(2)
BOOTRST 3 Select Reset Vector 1 (unprogrammed)
SUT1 2 Select start-up time 1 (unprogrammed)(1)
SUT0 1 Select start-up time 0 (programmed)(1)
CKSEL 0 Clock Selection 1 (unprogrammed)(4)
198 2548F–AVR–03/2013
ATmega406
28.3 Signature Bytes
All Atmel microcontrollers have a three- byte signature code which identifies the device. This
code can be read in both serial and parallel mode, also when the device is locked. The three
bytes reside in a separate address sp ace.
For the ATmega406 the signature bytes are:
1. 0x000: 0x1E (indicates manufactured by Atmel).
2. 0x001: 0x95 (indicates 40KB Flash memory).
3. 0x002: 0x07(indicates ATmega406 device when 0x001 is 0x95).
28.4 Calibration Bytes
The ATmega406 has calibration bytes for the Fast RC Oscillator, Slow RC Oscillator, internal
voltage reference, internal temperature reference and each differential cell voltage input. These
bytes reside in the high bytes in the signature addres s spac e. Dur ing Re set, th e calibra tion byte
for the Fast RC Oscillator is automatically written into the corresponding calibration register. The
other calibration bytes should be handled by the application software. See ”Reading the Signa-
ture Row from Software” on page 189 for details.
28.5 Page Size
Table 28-5. No. of Words in a Page and No. of Pages in the Flash
Flash Size Page Size PCWORD No. of Pages PCPAGE PCMSB
20K words (40K bytes) 64 words PC[5:0] 320 PC[14:6] 14
Table 28-6. No. of Words in a Page and No. of Pages in the EEPROM
EEPROM Size Page Size PCWORD No. of Pages PCPAGE EEAMSB
512 bytes 4 bytes EEA[1:0] 128 EEA[8:2] 8
199
2548F–AVR–03/2013
ATmega406
28.6 Parallel Programming
This section describes parameters, pin map ping, and commands used to parallel program and
verify Flash Progr am memory, EEPRO M Data memory, Memory Lock bits, and Fuse bits in the
ATmega406. Pulses are assumed to be at least 250 ns unless otherwise noted.
28.6.1 Considerations for Efficient Programming
The loaded command and address are retained in the device during programming. For efficient
programming, the following should be considered.
The command needs only be loaded once when writing or reading multiple memory locations.
Skip writing the data value 0xFF, that is the contents of the entire EEPROM (unless the
EESAVE Fuse is programmed) and Flash after a Chip Erase.
Address high byte needs only be loaded before programming or reading a new 256 word win-
dow in Flash or 256 byte EEPROM. This consideration also applie s to Signature bytes reading.
28.6.2 Signal Names In this section, some pins of the ATmega406 are referenced by signal names describ ing their
functionality during parallel programming, see Figure 28-1 on page 199 and Table 28-7 on page
200. Pins not described in the following table are referenced by pin names.
The XA1/XA0 pins determine the action executed when the XTAL1 pin is given a positive pulse.
The bit coding is shown in Table 28-9 on page 200.
When pulsing WR or OE, the com mand loaded determines the action executed. The different
Commands are sh own in Table 28-10 on page 201. Table 28-11 on page 210 shows th e Parallel
programming characteristics.
Figure 28-1. Parallel Programming
V
FET
+4 - 25V
GND
XTAL1 DATA
RESET
V
PP
BS1
XA0
XA1
OE
RDY/BSY
PAGEL
WR
BS2
V
REG
V
CC
(3.3V)
PV1
BATT
PVT
See "Enter Programming Mode"
200 2548F–AVR–03/2013
ATmega406
Table 28-7. Pin Name Mapping
Signal Name in
Programming Mode Pin
Name I/O Function
BS2 PA0 I Byte Select 2 (“0” selects low byte, “1” selects 2’nd high
byte).
RDY/BSY PA1 O 0: Device is busy programming, 1: Device is ready for new
command.
OE PA2 I Output Enable (Active low).
WR PA3 I Write Pulse (Active low).
BS1 PA4 I Byte Select 1 (“0” selects low byte, “1” selects high byte).
XA0 PA5 I XTAL Action Bit 0
XA1 PA6 I XTAL Action Bit 1
PAGEL PA7 I Program Memory and EEPROM data Page Load.
DATA PB7:0 I/O Bi-directional Data bus (Output when OE is low).
Table 28-8. Pin Values Used to Enter Programming Mode
Pin Symbol Value
PAGEL Prog_enable[3] 0
XA1 Prog_enable[2] 0
XA0 Prog_enable[1] 0
BS1 Prog_enable[0] 0
Table 28-9. XA1 and XA0 Coding
XA1 XA0 Action when XTAL1 is Pulsed
00
Load Flash or EEPROM Address (High or low address byte determined by
BS1).
0 1 Load Data (High or Low data byte for Flash determined by BS1).
1 0 Load Command
1 1 No Action, Idle
201
2548F–AVR–03/2013
ATmega406
28.6.3 Enter Programming Mode
The following algorithm puts the device in parallel programming mode:
1. Make sure the chip is started as explained in Section 9.2.1 ”Power-on Reset and Char ger
Connect” on page 40.
2. Set RESET to “0” and toggle XTAL1 at least six times.
3. Set the Prog_enable pin s listed in Table 28-8 on page 20 0 to “0000” and wait at least 100
ns.
4. Apply 11.5 - 12.5V to RESET. Any activity on Prog_enable pins within 100 ns after +12V
has been applied to RESET, will cause the device to fail entering programming mode.
5. Wait at least 50 µs before sending a new command.
28.6.4 Chip Erase The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are
not reset until the program memory has been completely erased. The Fuse bits are not
changed. A Chip Erase must be performed before the Flash and/or EEPROM are
reprogrammed.
Note: 1. The EEPRPOM memory is preserved during Chip Erase if the EESAVE Fuse is programmed.
Load Command “Chip Erase”
1. Set XA1, XA0 to “10”. This enables command loading.
2. Set BS1 to “0”.
3. Set DATA to “1000 0000”. This is the command for Chip Erase.
4. Give XTAL1 a positive pulse. This loads the command.
5. Give WR a negative pulse. This starts the Chip Erase. RDY/BSY goes low.
6. Wait until RDY/BSY goes high before loading a new command.
Table 28-10. Command Byte Bit Coding
Command Byte Command Executed
1000 0000 Chip Erase
0100 0000 Write Fuse bits
0010 0000 Write Lock bits
0001 0000 Write Flash
0001 0001 Write EEPROM
0000 1000 Read Signature Bytes and Calibration byte
0000 0100 Read Fuse and Lock bits
0000 0010 Read Flash
0000 0011 Read EEPROM
202 2548F–AVR–03/2013
ATmega406
28.6.5 Programming the Flash
The Flash is organized in pages, see Table 28-5 on page 198. When programming the Flash,
the program data is latched into a page buffer. This allows one page of program data to be pro-
grammed simultaneously. The following procedure describes how to program the entire Flash
memory:
A. Load Command “Write Flash”
1. Set XA1, XA0 to “10”. This enables command loading.
2. Set BS1 to “0”.
3. Set DATA to “0001 0000”. This is the command for Write Flash.
4. Give XTAL1 a positive pulse. This loads the command.
B. Load Address Low byte
1. Set XA1, XA0 to “00”. This enables address loading.
2. Set BS1 to “0”. This selects low address.
3. Set DATA = Address low byte (0x00 - 0xFF).
4. Give XTAL1 a positive pulse. This loads the address low byte.
C. Load Data Low Byte
1. Set XA1, XA0 to “01”. This enables data loading.
2. Set DATA = Data low byte (0x00 - 0xFF).
3. Give XTAL1 a positive pulse. This loads the data byte.
D. Load Data High Byte
1. Set BS1 to “1”. This selects high data byte.
2. Set XA1, XA0 to “01”. This enables data loading.
3. Set DATA = Data hi gh byte (0x00 - 0xFF).
4. Give XTAL1 a positive pulse. This loads the data byte.
E. Latch Data
1. Set BS1 to “1”. This selects high data byte.
2. Give PAGEL a positive pulse. This latches the data bytes. (See Figure 28-3 for signal
waveforms)
F. Repeat B through E until the entire buffer is filled or until all da ta within the pa ge is loaded .
While the lower bits in the add ress a re mapped to words within th e page, th e highe r bits addr ess
the pages within the FLASH. This is illustrated in Figure 28-2 on page 203. Note that if less than
eight bits are required to address words in the page (pagesize < 256), the most significant bit(s)
in the address low byte are used to address the page when performing a Page Write.
G. Load Address High byte
1. Set XA1, XA0 to “00”. This enables address loading.
2. Set BS1 to “1”. This selects high address.
3. Set DATA = Address high byte (0x00 - 0xFF).
4. Give XTAL1 a positive pulse. This loads the address high byte.
203
2548F–AVR–03/2013
ATmega406
H. Program Page
1. Give WR a negative pulse. This st art s programming of the entire page of d ata. RDY/BSY
goes low.
2. Wait until RDY/BSY goes high (See Figure 28-3 for signal waveforms).
I. Repeat B through H until the entire Flash is programmed or until all data has been
programmed.
J. End Page Programming
1. 1. Set XA1, XA0 to “10”. This enables command loading.
2. Set DATA to “0000 0000”. This is the command for No Operation.
3. Give XTAL1 a positive pulse . This loa ds the command, and the intern al wr ite sig nal s ar e
reset.
Figure 28-2. Addressing the Flash Which is Organized in Pages(1)
Note: 1. PCPAGE and PCWORD are listed in Table 28-5 on page 198.
PROGRAM MEMORY
WORD ADDRESS
WITHIN A PAGE
PAGE ADDRESS
WITHIN THE FLASH
INSTRUCTION WORD
PAGE PCWORD[PAGEMSB:0]:
00
01
02
PAGEEND
PAGE
PCWORDPCPAGE
PCMSB PAGEMSB
PROGRAM
COUNTER
204 2548F–AVR–03/2013
ATmega406
Figure 28-3. Programming the Flash Waveforms(1)
Note: 1. “XX” is don’t care. The letters refer to the programming description above.
28.6.6 Programming the EEPROM
The EEPROM is organized in pages, see Table 28-6 on page 198. When programming the
EEPROM, the program data is latched into a page buffer. This allows one page of data to be
programmed simultaneously. The programming algorithm for the EEPROM data memory is as
follows (refer to ”Programming the F lash” on page 202 for details o n Command, Address and
Data loading):
1. A: Load Command “0001 0001”.
2. G: Load Address High Byte (0x00 - 0xFF).
3. B: Load Address Low Byte (0x00 - 0xFF).
4. C: Load Data (0x00 - 0xFF).
5. E: Latch data (give PAGEL a positive pulse).
K: Repeat 3 through 5 until the entire buffer is filled.
L: Program EEPROM page
1. Set BS to “0”.
2. Give WR a negative pulse. This starts programming of the EEPROM page. RDY/BSY
goes low.
3. W ait until to RDY/BSY goes high befor e programming the n ext page (See Figure 28-4 for
signal waveforms).
RDY/BSY
WR
OE
RESET +12V
PAGEL
BS2
0x10 ADDR. LOW ADDR. HIGH
DATA DATA LOW DATA HIGH ADDR. LOW DATA LOW DATA HIGH
XA1
XA0
BS1
XTAL1
XX XX XX
ABCDEBCDEGH
F
205
2548F–AVR–03/2013
ATmega406
Figure 28-4. Programming the EEPROM Waveforms
28.6.7 Reading the Flash
The algorithm for reading the Flash m emory is as follows (refer to ”Programming the Flash” on
page 202 for details on Command and Address loading):
1. A: Load Command “0000 0010”.
2. G: Load Address High Byte (0x00 - 0xFF).
3. B: Load Address Low Byte (0x00 - 0xFF).
4. Set OE to “0”, and BS1 to “0”. The Flash word low byte can now be read at DATA.
5. Set BS to “1”. The Flash word high byte can now be read at DATA.
6. Set OE to “1”.
28.6.8 Reading the EEPROM
The algorithm for reading the EEPROM memory is as follows (refer to ”Programming the Flash”
on page 202 for details on Command and Address loading):
1. A: Load Command “0000 0011”.
2. G: Load Address High Byte (0x00 - 0xFF).
3. B: Load Address Low Byte (0x00 - 0xFF).
4. Set OE to “0”, and BS1 to “0”. The EEPROM Data byte can now be read at DATA.
5. Set OE to “1”.
RDY/BSY
WR
OE
RESET +12V
PAGEL
BS2
0x11 ADDR. HIGH
DATA ADDR. LOW DATA ADDR. LOW DATA XX
XA1
XA0
BS1
XTAL1
XX
AGBCEBC EL
K
206 2548F–AVR–03/2013
ATmega406
28.6.9 Programming the Fuse Low Bits
The algorith m for program ming the Fu se Lo w bits is as follows (refer to ”Progra mming the Flash”
on page 202 for details on Command and Data loading):
1. A: Load Command “0100 0000”.
2. C: Load Data Low Byte. Bit n = “0” programs and bit n = “1” erases the Fuse bit.
3. Give WR a negative pulse and wait for RDY/BS Y to go high.
28.6.10 Programming the Fuse High Bits
The algorithm for programming the Fuse High bits is as follows (refer to ”Programming the
Flash” on page 202 for details on Command and Data loading):
1. A: Load Command “0100 0000”.
2. C: Load Data Low Byte. Bit n = “0” programs and bit n = “1” erases the Fuse bit.
3. Set BS1 to “1” and BS2 to “0”. This selects high data byte.
4. Give WR a negative pulse and wait for RDY/BS Y to go high.
5. Set BS1 to “0”. This selects low data byte.
Figure 28-5. Programming the FUSES Waveforms
28.6.11 Programming the Lock Bits
The algorithm for programming the Lock bits is as follows (refer to ”Programming the Flash” on
page 202 for details on Command and Data loading):
1. A: Load Command “0010 0000”.
2. C: Load Data Low Byte. Bit n = “0” programs the Lock bit. If LB mode 3 is programmed
(LB1 and LB2 is programmed), it is not possible to program the Boot Lock bits by any
External Programming mode.
3. Give WR a negative pulse and wait for RDY/BS Y to go high.
The Lock bits can only be cleared by executing Chip Erase.
RDY/BSY
WR
OE
RESET +12V
PAGEL
0x40
DATA DATA XX
XA1
XA0
BS1
XTAL1
AC
0x40 DATA XX
AC
Write Fuse Low byte Write Fuse high byte
BS2
207
2548F–AVR–03/2013
ATmega406
28.6.12 Reading the Fuse and Lock Bits
The algorithm for readin g the Fuse and Lock bits is as follows (refer to ”Programming the Flash”
on page 202 for details on Command loading):
1. A: Load Command “0000 0100”.
2. Set OE to “0”, BS2 to “0” and BS1 to “0”. The status of the Fuse Low bits can now be
read at DATA (“0” means programmed).
3. Set OE to “0”, BS2 to “1” and BS1 to “1”. The status of the Fuse High bits can now be
read at DATA (“0” means programmed).
4. Set OE to “0”, BS2 to “0” and BS1 to “1”. The status of the Lock bits can now be rea d at
DATA (“0” means programmed).
5. Set OE to “1”.
Figure 28-6. Mapping Between BS1, BS2 and the Fuse and Lock Bits During Read
28.6.13 Reading the Signature Bytes
The algorithm for reading the Signature bytes is as follows (refer to ”Programm i ng t he F lash” on
page 202 for details on Command and Address loading):
1. A: Load Command “0000 1000”.
2. B: Load Address Low Byte (0x00 - 0x02).
3. Set OE to “0”, and BS to “0”. The selected Signature byte can now be read at DATA.
4. Set OE to “1”.
28.6.14 Reading the Calibration Byte
The algorithm for reading the Calibration byte is as follows (refer to ”Progr am ming the F las h” o n
page 202 for details on Command and Address loading):
1. A: Load Command “0000 1000”.
2. B: Load Address Low Byte, 0x00.
3. Set OE to “0”, and BS1 to “1”. The Calibration byte can now be read at DATA.
4. Set OE to “1”.
Lock Bits 0
1
BS2
Fuse High Byte
0
1
BS1
DATA
Fuse Low Byte 0
1
BS2
0
208 2548F–AVR–03/2013
ATmega406
28.6.15 Parallel Programming Characteristics
Figure 28-7. Parallel Programming Timing, Including some General Timing Requirements
Figure 28-8. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
Note: 1. The timing requirements shown in Figure 28-7 (i.e., tDVXH, tXHXL, and tXLDX) also apply to load-
ing operation.
Data & Contol
(DATA, XA0/1, BS1, BS2)
XTAL1
t
XHXL
t
WLWH
t
DVXH
t
XLDX
t
PLWL
t
WLRH
WR
RDY/BSY
PAGEL
t
PHPL
t
PLBX
t
BVPH
t
XLWL
t
WLBX
t
BVWL
WLRL
XTAL1
PAGEL
t
PLXH
XLXH
tt
XLPH
ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
DATA
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE) LOAD DATA
(LOW BYTE) LOAD DATA
(HIGH BYTE)
LOAD DATA
LOAD ADDRESS
(LOW BYTE)
209
2548F–AVR–03/2013
ATmega406
Figure 28-9. Parallel Programming Timing, Reading Sequence (within the Same Page) with
Timing Requirements(1)
Note: 1. The timing requirements shown in Figure 28-7 (i.e., tDVXH, tXHXL, and tXLDX) also apply to read-
ing operation.
XTAL1
OE
ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
DATA
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE) READ DATA
(LOW BYTE) READ DATA
(HIGH BYTE) LOAD ADDRESS
(LOW BYTE)
t
BVDV
t
OLDV
t
XLOL
t
OHDZ
210 2548F–AVR–03/2013
ATmega406
Notes: 1. tWLRH is valid for the Write Flash, Write EEPROM, Write Fuse bits and Write Lock bits
commands.
2. tWLRH_CE is valid for the Chip Erase command.
Table 28-11. Parallel Programming Characteristics
Symbol Parameter Min Typ Max Units
VPP Programming Enable Voltage (RESET input) 11.5 12.5 V
IPP Programming Enable Current 250 A
tDVXH Data and Control Valid before XTAL1 High 67 ns
tXLXH XTAL1 Low to XTAL1 High 200 ns
tXHXL XTAL1 Pulse Width High 150 ns
tXLDX Data and Control Hold after XTAL1 Low 67 ns
tXLWL XTAL1 Low to WR Low 0 ns
tXLPH XTAL1 Low to PAGEL high 0 ns
tPLXH PAGEL low to XTAL1 high 150 ns
tBVPH BS1 Valid before PAGEL High 67 ns
tPHPL PAGEL Pulse Width High 150 ns
tPLBX BS1 Hold after PAGEL Low 67 ns
tWLBX BS2/1 Hold after WR Low 67 ns
tPLWL PAGEL Low to WR Low 67 ns
tBVWL BS1 Valid to WR Low 67 ns
tWLWH WR Pulse Width Low 150 ns
tWLRL WR Low to RDY/BSY Low 0 1 s
tWLRH WR Low to RDY/BSY High(1) 3.7 4.5 ms
tWLRH_CE WR Low to RDY/BSY High for Chip Erase(2) 7.5 9 ms
tXLOL XTAL1 Low to OE Low 0 ns
tBVDV BS1 Valid to DATA valid 0 250 ns
tOLDV OE Low to DATA Valid 250 ns
tOHDZ OE High to DATA Tri-stated 250 ns
211
2548F–AVR–03/2013
ATmega406
28.7 Programming via the JTAG Interface
Programming through the JTAG interface requires control of the four JTAG specific pins: TCK,
TMS, TDI, and TDO. Control of the reset and clock pins is not required.
To be able to use the JTAG interface, the JTAGEN Fuse must be programmed. The device is
default shipped with the fuse progr ammed. In addi tion, the JTD bit in MCUCSR must be cleared.
Alternatively, if the JTD bit is set, the external reset can be fo rced low. Then, the JTD bit will be
cleared after two chip clocks, and the JTAG pins are available for programming. This provides a
means of using the JTAG pins as normal port pins in Running mode while still allowing In-Sys-
tem Programming via the JTAG interface. Note that this technique can not be used when using
the JTAG pins for Boundary-scan or On-chi p Debug. In these cases the JTAG pi ns must be ded-
icated for this purpose.
As a definition in this datasheet, the LSB is shifted in and out first of all Shift Registers.
28.7.1 Programming Specific JTAG Instructions
The instruction register is 4-bit wide, supporting up to 16 instructions. The JTAG instructions
useful for programming are listed below.
The OPCODE for each instruction is shown behind the instruction name in hex format. The text
describes which data register is selected as path between TDI and TDO for each instruction.
The Run-Test/Idle state of the TAP controller is used to generate internal clocks. It can also be
used as an idle state between JTAG sequences. The state machine sequence for changing the
instruction word is shown in Figure 28-10.
212 2548F–AVR–03/2013
ATmega406
Figure 28-10. State Machine Sequence for Changing the Instruction Word
28.7.2 AVR_RESET (0xC)
The AVR specific public JTAG instruction for setting the AVR device in the Reset mode or taking
the device out from the Reset mode. The TAP controller is not re set b y this instruction. The one
bit Reset Register is selected as data register. Note that the reset will be active as long as there
is a logic “one” in the Reset Chain. The output from this chain is not latched.
The active states are:
Shift-DR: The Reset Register is shifted by the TCK input.
28.7.3 PROG_ENABLE (0x4)
The AVR specific public JTAG instruction for enabling programming via the JTAG port. The 16-
bit Programming Enable Register is selected as data register. The active states are the
following:
Shift-DR: The programming enable signature is shifted into the data register.
Update-DR: The programming enable signature is compared to the correct value, and
Programming mode is entered if the signature is valid.
Test-Logic-Reset
Run-Test/Idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR Scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR Scan
Capture-DR
0
1
011 1
00
00
11
10
1
1
0
1
0
0
10
1
1
0
1
0
0
00
11
213
2548F–AVR–03/2013
ATmega406
28.7.4 PROG_COMMANDS (0x5)
The AVR specific public JTAG instruction for entering programming commands via the JTAG
port. The 15-bit Programming Command Register is selected as data register. The active states
are the following:
Capture-DR: The result of the previous command is loaded into the data register.
Shift-DR: The da ta register is shifted by the TCK input, shifting out the result of the previous
command and shifting in the new command.
Update-DR: The programming command is applied to the Flash inputs
Run-Test/Idle: One clock cycle is generated, executing the applied command (not always
required, see Table 28-12 below).
28.7.5 PROG_PAGELOAD (0x6)
The AVR specific public JTAG instruction to directly load the Flash data page via the JTAG port.
An 8-bit Flash Data Byte Register is selected as the data register. This is physically the 8 LSBs
of the Programming Command Register. The active states are the following:
Shift-DR: The Flash Data Byte Register is shifted by the TCK input.
Update-DR: The content of the Flash Dat a Byte Register is copied into a temporary register. A
write sequence is initiated that within 11 TCK cycles loads the con tent of the temporary register
into the Flash page buffer. The AVR automatically alternates between writing the low and the
high byte for each new Update-DR state, starting with the low byte for the first Update-DR
encountered after entering the PROG_PAGELOAD command. The Program Counter is pre-
incremented before writing the low byte, exce pt for the first written byte. This ensures that the
first data is written to the address set up by PROG_COMMANDS, and loading the last l ocation
in the page buffer does not make the program counter increment into the next page.
28.7.6 PROG_PAGEREAD (0x7)
The AVR specific public JTAG instruction to directly capture the Flash content via the JTAG port.
An 8-bit Flash Data Byte Register is selected as the data register. This is physically the 8 LSBs
of the Programming Command Register. The active states are the following:
Capture-DR: The content of the selected Flash byte is captured into the Flash Data Byte
Register . The AVR automatically alternates between reading the low an d the high byte for each
new Capture-DR state, starting with the low byte for the first Capture-DR enco untered after
entering the PROG_PAGEREAD command. The Program Counter is post-incremented after
reading each high byte, in cluding the first r ead byte. This ensu res that the first dat a is ca ptured
from the first address set up by PROG_COMMANDS, a nd reading the last location in th e page
makes the program counter increment into the next page.
Shift-DR: The Flash Data Byte Register is shifted by the TCK input.
28.7.7 Data RegistersThe data registers are selected by the JTAG instruction registers described in se ction ”Program-
ming Specific JT AG Instructions” on page 211. The data registers relevant for programming
operations are:
Reset Register
Programming Enable Register
Programming Command Register
Flash Data Byte Register
214 2548F–AVR–03/2013
ATmega406
28.7.8 Reset RegisterThe Reset Register is a Test Data Register used to reset the part during programming. It is
required to reset the part before entering Programming mode.
A high value in the Reset Register corresponds to pulling the external reset low. The part is reset
as long as there is a high value present in the Reset Register. Depending on the Fuse settings
for the clock options, the part will remain reset for a Reset Time-out period (refer to ”Clock
Sources” on page 26) after releasing the Reset Register. The o utput from this data register is n ot
latched, so the reset will take place immediately, as shown in Figure 9-1 on page 40.
28.7.9 Programming Enable Register
The Programming Enable Register is a 16-bit register. The contents of this register is compared
to the programming enable signature, binary code 0b1010_0011_0111_0000. When the con-
tents of the register is equal to the programming enable signature, programming via the JTAG
port is enabled. The register is reset to 0 on Power-on Reset, and should always be reset when
leaving Programming mode.
Figure 28-11. Programming Enable Register
28.7.10 Programming Command Register
The Programming Command Register is a 15-bit register. This register is used to serially shift in
programming comman ds, and to serially shift out the re sult of the p revious command, i f any. The
JTAG Programming Instruction Set is shown in Table 28-12. The state sequence when shifting
in the programming commands is illustrated in Figure 28-13.
TDI
TDO
D
A
T
A
=DQ
ClockDR & PROG_ENABLE
Programming Enable
0xA370
215
2548F–AVR–03/2013
ATmega406
Figure 28-12. Programming Command Register
TDI
TDO
S
T
R
O
B
E
S
A
D
D
R
E
S
S
/
D
A
T
A
Flash
EEPROM
Fuses
Lock Bits
Table 28-12. JTAG Programming Instruction
Set
a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don’t care
Instruction TDI Sequence TDO Sequence Notes
1a. Chip Erase
0100011_10000000
0110001_10000000
0110011_10000000
0110011_10000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
1b. Poll for Chip Erase Complete 0110011_10000000 xxxxxox_xxxxxxxx (2)
2a. Enter Flash Write 0100011_00010000 xxxxxxx_xxxxxxxx
2b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
2c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
2d. Load Data Low Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx
2e. Load Data High Byte 0010111_iiiiiiii xxxxxxx_xxxxxxxx
2f. Latch Data 0110111_00000000
1110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx (1)
2g. Write Flash Page
0110111_00000000
0110101_00000000
0110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
2h. Poll for Page Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
3a. Enter Flash Read 0100011_00000010 xxxxxxx_xxxxxxxx
3b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
3c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
216 2548F–AVR–03/2013
ATmega406
3d. Read Data Low and High Byte 0110010_00000000
0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
xxxxxxx_oooooooo Low byte
High byte
4a. Enter EEPROM Write 0100011_00010001 xxxxxx x_xx xxxxxx
4b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
4c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
4d. Load Data Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx
4e. Latch Data 0110111_00000000
1110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx (1)
4f. Write EEPROM Page
0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
4g. Poll for Page Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
5a. Enter EEPROM Read 0100011_00000011 xxxxxxx_xxxxxxxx
5b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
5c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
5d. Read Data Byte 0110011_bbbbbbbb
0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
6a. Enter Fuse Write 0100011_0100 0000 xxxxxxx_xxxxxxxx
6b. Load Data High Byte(6) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6c. Write Fuse High Byte
0110111_00000000
0110101_00000000
0110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6d. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
6e. Load Data Low Byte(7) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6f. Write Fuse Low Byte
0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6g. Poll for Fuse Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
7a. Enter Lock Bit Write 0100011_00100000 xxxxxx x_xxxxxxxx
7b. Load Data Byte(8) 0010011_11iiiiii xxxxxxx_xxxxxxxx (4)
Table 28-12. JTAG Programming Instruction (Continued)
Set (Continued) a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = dat a in, x
Instruction TDI Sequence TDO Sequence Notes
217
2548F–AVR–03/2013
ATmega406
Notes: 1. This command sequence is not required if the seven MSB are correctly set by the previous command sequence (which is
normally the case).
2. Repeat until o = “1”.
3. Set bits to “0” to program the corresponding Fuse, “1” to unprogram the Fuse.
4. Set bits to “0” to program the corresponding Lock bit, “1” to leave the Lock bit unchanged.
5. “0” = programmed, “1” = unprogramme d.
6. The bit mapping for Fuses High byte is listed in Table 28-3 on page 196
7. The bit mapping for Fuses Low byte is listed in Tabl e 28-4 on page 197
8. The bit mapping for Lock bits byte is listed in Table 28-1 on page 195
9. Address bits exceeding PCMSB and EEAMSB (Table 28-5 and Table 28-6) are don’t care
10.All TDI and TDO sequences are represented by binary digits (0b...).
7c. Write Lock Bits
0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
7d. Poll for Lock Bit Write complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
8a. Enter Fuse/Lock Bit Read 0100011_0000 0100 xxxxxxx_xxxxxxxx
8b. Read Fuse High Byte(6) 0111110_00000000
0111111_00000000 xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8c. Read Fuse Low Byte(7) 0110010_00000000
0110011_00000000 xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8d. Read Lock Bits(8) 0110110_00000000
0110111_00000000 xxxxxxx_xxxxxxxx
xxxxxxx_xxoooooo (5)
8e. Read Fuses and Lock Bits
0111010_00000000
0110010_00000000
0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
xxxxxxx_oooooooo
xxxxxxx_oooooooo
(5)
Fuse High byte
Fuse Low byte
Lock bits
9a. Enter Signature Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx
9b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
9c. Read Signature Byte 0110010_00000000
0110011_00000000 xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
10a. Enter Calibration Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx
10b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
10c. Read Calibration Byte 0110110_00000000
0110111_00000000 xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
11a. Load No Operation Command 0100011_00000000
0110011_00000000 xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
Table 28-12. JTAG Programming Instruction (Continued)
Set (Continued) a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = dat a in, x
Instruction TDI Sequence TDO Sequence Notes
218 2548F–AVR–03/2013
ATmega406
Figure 28-13. State Machine Sequence for Changing/Reading the Data Word
28.7.11 Flash Data Byte Register
The Flash Data Byte Register provides an efficient way to load the entire Flash page buffer
before executing Page Write, or to read out/verify the content of the Flash. A state machine sets
up the control signals to the Flash and senses the strobe signals from the Flash, thus only the
data words need to be shifted in/out.
The Flash Data Byte Re gister actually cons ists of the 8-bit scan chain and a 8- bit temporar y reg-
ister. During page load , the Update-DR state copies the conte nt of the scan chain over to th e
temporary register and initiates a write sequence that within 11 TCK cy cles loads t he cont ent of
the temporary register into the Flash page buffer. The AVR automatically alternates between
writing the low and the high byte for each new Up date-DR state, starting with the low byte for the
first Update-DR encountered after entering the PROG_PAGELOAD command. The Program
Counter is pre-increm ented before writing the low byte, except for the first writ ten byte. This
ensures that the first data is written to the address set up by PROG_COMMANDS, and loading
the last location in the page buffer does not make the Program Counter increment into the next
page.
During Page Read, the content of the selected Flash byte is captured into the Flash Data Byte
Register during the Capture-DR state. The AVR automatically alternates between reading the
low and the high byte for each new Capture- DR stat e, starting with the low byte for the first Cap-
Test-Logic-Reset
Run-Test/Idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR Scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR Scan
Capture-DR
0
1
011 1
00
00
11
10
1
1
0
1
0
0
10
1
1
0
1
0
0
00
11
219
2548F–AVR–03/2013
ATmega406
ture-DR encountered after en te ring the PROG_PAGEREAD command. The Program Counter is
post-incremented after reading each high byte, including the first read byte. This ensures that
the first data is captured from the first address set up by PROG_COMMANDS, and reading the
last location in the page makes the program counter increment into the next page.
Figure 28-14. Flash Data Byte Register
The state machine controlling the Flash Data Byte Register is clocked by TCK. During normal
operation in which eight bits are shifted for eac h Flash by te , the clock cycles ne ede d to naviga te
through the TAP controller automatically feeds the state machine for the Flash Data Byte Regis-
ter with sufficient number of clock pulses to complete its operation transparently for the user.
However, if too few bits are shifted between each Update-DR state during page load, the TAP
controller should stay in the Run-Test/Idle state for some TCK cycles to ensure th at the re ar e at
least 11 TCK cycles between each Update-DR state.
28.7.12 Programming Algorithm
All references below of type “1a”, “1b”, and so on, refer to Table 28-12.
28.7.13 Entering Programming Mode
1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset Register.
2. Enter instruction PROG_ENABLE and shift 0b1010_0011_0111_0000 in the Program-
ming Enable Register.
28.7.14 Leaving Programming Mode
1. Enter JTAG instruction PROG_COMMANDS.
2. Disable all programming instructions by using no operation instruction 11a.
3. Enter instruction PROG_ENABLE and shift 0b0000_0000_0000_0000 in the pro gram-
ming Enable Register.
4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register.
TDI
TDO
D
A
T
A
Flash
EEPROM
Fuses
Lock Bits
STROBES
ADDRESS
State
Machine
220 2548F–AVR–03/2013
ATmega406
28.7.15 Performing Chip Erase
1. Enter JTAG instruction PROG_COMMANDS.
2. Start Chip Erase using programming instruction 1a.
3. Poll for Chip Erase complete using programming instruction 1b, or wa it for tWLRH_CE (refer
to Table 28-11 on page 210).
28.7.16 Programming the Flash
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash write using programming instruction 2a.
3. Load address High byte using programming instruction 2b.
4. Load address Low byte using programming instruction 2c.
5. Load data using programming instructions 2d, 2e and 2f.
6. Repeat steps 4 and 5 for all instru ction words in the page.
7. Write the page using programming instruction 2g.
8. Poll for Flash write complete using pro gramming instruction 2h, or wait for tWLRH (refer to
Table 28-11 on page 210).
9. Repeat steps 3 to 7 until all data have been programmed.
A more efficient data transfer can be achieved using the PROG_PAGELOAD instruction:
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash write using programming instruction 2a.
3. Load the page address using programming instructions 2b and 2c. PCWORD (refer to
Table 28-5 on page 198) is used to address within one page and must be written as 0.
4. Enter JTAG instruction PROG_PAGELOAD.
5. Load the entire page by shifting in all instruction words in the p age byte-by-byte, starting
with the LSB of the first instruction in the page and ending with the MSB of the last
instruction in the page. Use Update-DR to copy the contents of the Flash Data Byte Reg-
ister into the Flash page location and to auto-increment the Program Counter before
each new word.
6. Enter JTAG instruction PROG_COMMANDS.
7. Write the page using programming instruction 2g.
8. Poll for Flash write complete using pro gramming instruction 2h, or wait for tWLRH (refer to
Table 28-11 on page 210).
9. Repeat steps 3 to 8 until all data have been programmed.
28.7.17 Reading the Flash
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash read using programming instruction 3a.
3. Load address using programming instructions 3b and 3c.
4. Read data using programming instruction 3d.
5. Repeat steps 3 and 4 until all dat a have been read.
A more efficient data transfer can be achieved using the PROG_PAGEREAD instruction:
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash read using programming instruction 3a.
3. Load the page address using programming instructions 3b and 3c. PCWORD (refer to
Table 28-5 on page 198) is used to address within one page and must be written as 0.
221
2548F–AVR–03/2013
ATmega406
4. Enter JTAG instruction PROG_PAGEREAD.
5. Read the entire p age (or Flash) by shif ting out all instruction words in the page (or Flash),
starting with the LSB of the first instru ctio n in the page (Flash) an d end ing with th e MSB
of the last instruction in the page (Flash). The Capture-DR st ate both captures the data
from the Flash, and also auto-increments the program counter after each word is read.
Note that Capture-DR comes be fore the shift-DR state. Hence, the first byte which is
shifted out contains valid data.
6. Enter JTAG instruction PROG_COMMANDS.
7. Repeat steps 3 to 6 until all data have been read.
28.7.18 Programming the EEPROM
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable EEPROM write using programming instruction 4a.
3. Load address High byte using programming instruction 4b.
4. Load address Low byte using programming instruction 4c.
5. Load dat a using programming instructions 4d and 4e.
6. Repeat steps 4 and 5 for all dat a bytes in the page.
7. Write the data using programming instruction 4f.
8. Poll for EEPROM write complete using programming instruction 4g, or wait for tWLRH
(refer to Table 28-11 on page 210).
9. Repeat steps 3 to 8 until all data have been programmed.
Note that the PROG_PAGELOAD instruction can not be used when programming the EEPROM.
28.7.19 Reading the EEPROM
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable EEPROM read using programming instruction 5a.
3. Load address using programming instructions 5b and 5c.
4. Read data using programming instruction 5d.
5. Repeat steps 3 and 4 until all dat a have been read.
Note that the PROG_PAGEREAD instruction can not be used when reading the EEPROM.
28.7.20 Programming the Fuses
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Fuse write using programming instruction 6a.
3. Load data high byte using programming instructions 6b. A bit value of “0” will program
the corresponding fuse, a “1” will unprogram the fuse.
4. Write Fuse High byte using programming instruction 6c.
5. Poll for Fuse write complete using programming instruction 6d, or wait for tWLRH (ref er to
Table 28-11 on page 210).
6. Load data low byte using programming instructions 6e. A “0” will program the fuse, a “1”
will unprogram the fuse.
7. Write Fuse low byte using programming instruction 6f.
8. Poll for Fuse write complete using programming instruction 6g, or wait for tWLRH (ref er to
Table 28-11 on page 210).
222 2548F–AVR–03/2013
ATmega406
28.7.21 Programming the Lock Bits
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Lock bit write using programming instruction 7a.
3. Load data using programming instructions 7b. A bit value of “0” will program the corre-
sponding lock bit, a “1” will leave the lock bit unchanged.
4. Write Lock bits using programming instruction 7c.
5. Poll for Lock bit write complete using programming instruction 7d, or wait for tWLRH (refer
to Table 28-11 on page 210).
28.7.22 Reading the Fuses and Lock Bits
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Fuse/Lock bit read using programming instruction 8a.
3. To read all Fuses and Lock bits, use programming instruction 8e.
To only read Fuse High byte, use programming instructio n 8b.
To only read Fuse Low byte, use programming instruction 8c.
To only read Lock bits, use programming instruction 8d.
28.7.23 Reading the Signature Bytes
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Signature byte read using programming instruction 9a.
3. Load address 0x00 using programming instruction 9b.
4. Read first signature byte using programming instruction 9c.
5. Repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third
signature bytes, respectively.
28.7.24 Reading the Calibration Byte
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Calibration byte read using programming instruction 10a.
3. Load address 0x00 using programming instruction 10b.
4. Read the calibration byte using programming instruction 10c.
223
2548F–AVR–03/2013
ATmega406
29. Operating Circuit
Figure 29-1. Operating Circuit Diagram
RP
RN
RP
RP
RP
RP
Rsense
Rpi
Rni
Ci
Rpc
Rpf
RcfRdf
Rled
Rled
Rled
Rled
Rled
ATmega406
+
NV
PPI
PI
NI
PA4
PA3
PA2
XTAL2
RESET
XTAL1
VREG
SCK
PB4
PB3
PB0
PB1
PB2
SDA
GND
-
CREG 1 CREG 2
V CC
100
100
SMB Clo
ck
SMB Da
ta
RP1 RP2
SGNDVREF VREFGND
RT4
RT3
RT2
PA1
Rnni NNI
Ci
Ci
Rppi
CP
CP
CP
CP
PV1
PV2
PV3
PV4
PVT
OD OC BATT
VFETOPC
RT1
PA0/ADC0
R1
CXTAL2
CXTAL 2
CRESET
CREF
224 2548F–AVR–03/2013
ATmega406
Table 29-1. Recommended values for external devices
Note: 1. The sense resistor should be adjusted to the current flow for the application.
2. The pre-charger resistor should be adjusted to the pre-charger curret flow for the application.
Symbol Use Parameter Min Typ Max unit
R1 Pull-up resistor for thermistors R 10 k
RT1
RT2
RT3
RT4
NTC Thermistor
R@25C10k
B-constant 3000 4000 K
RSSource Impedance when
using PA0...4 as V-ADC inpu ts R037k
Worst Gain-error due to RS012%
Rnni
Rppi
Current protection LP-filter
resistor R1k
Rni
Rpi
Current sense LP-filter
resistors R 10 100 500
CiCurrent sense LP-filter
capasitor C0.010.10.4µF
(Rpi-Rni)*CiCurrent sense LP-filter time
constant 10 20 µs
Rsense(1) Current sense resistor R 5 m
RP Cell input LP-filter resistor R 10 500 1000
CP Cell input LP-filter capacitor C 0.01 0.1 0.5 µF
RP*CP Cell input LP-filter time
constant 6.5 25 100 µs
RN Pull-up resistor R 0 10 TBD
Rdf
Rcf
Rpf
Pull-up resistors R 1 M
Rpc(2) Pre-charge resistor R 1 k
CREF VREF decoupling C 1 1 22 µF
CREG1
CREG2 VREG charge-storage C 0.1 µF
1
RP1
RP2 TWI Pull-up resistors C 2.2 M
CRESET C 0.1 µF
225
2548F–AVR–03/2013
ATmega406
30. Electrical Characteristics
30.1 Absolute Maximum Ratings*
30.2 DC Characteristics
Operating Temperature.......................... ... .........-30C to +85C*NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent dam-
age to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature..................................... -65°C to +150°C
Voltage on PA0 - PA7, PB0 - PB7, PD0 - PD1,
VCC, PI, PPI, NI, NNI, XTAL1, and XTAL2
with respect to Ground .............................-0.5V to VREG +0.5V
Voltage on SCL, SDA, NV, PV1 and RESET
with respect to Ground ..................................... -0.5V to + 6.0V
Voltage on PVT and VFET
with respect to Ground ...................................... -0.5V to + 35V
Voltage on PC0, OPC, OC and BATT
with respect to Ground ...........................-0.5V to VFET + 0.5V
Voltage on OD, PV2 - PV4
with respect to Ground .............................-0.5V to PVT + 0.5V
Maximum Operating Voltage ............................................. 25V
DC Characteristics, TA = -30C to 85C, VCC = 3.3V
Parameter Condition Min Typ Max Unit
Supply Current Power Supply Current
Active 1.2 mA
Idle 270 A
ADC Noise Reduction 220 A
Power-save 35 A
Power-down 20 A
Power-off 1.5 A
Voltage
Regulator(1)
Regulated Output Voltage(2) IOUT = 5 mA 3.25 3.3 3.35 V
Temperature Stability(2)
IOUT = 5 mA
TA = 0 - 60 C± 5 ± 15 mV
IOUT = 5 mA
TA = -30 – 85 C± 20 ± 70 mV
Load Regulation 0.1 mA < IOUT < 5 mA ± 20 ± 60 mV
Line Regulation 4V < VFET < 25V, IOUT = 1 mA ± 2 ± 10 mV
VREF
Referenc e vol tage 1.1 V
Ref. Voltage Accuracy After calibration, at ca libration
temperature ±0.1 ± 0.2 %
Temperature Drift(3) TA = -30 – 60 C 80 ppm/C
226 2548F–AVR–03/2013
ATmega406
V-ADC
Referenc e Volta ge 1.100 V
Conversion Time 519 s
Effective Resolution 12 Bits
1 LSB Un-scaled Inputs 269 V
1 LSB Scaled Inputs (x 0.2) 1.34 mV
INL ± 1 ± 3 LSB
Input Voltage Range
ADC0, ADC1, ADC2, ADC3,
VTEMP 01V
ADC4 0 5 V
CELL1 2 5 V
CELL2, PV1 2V 0 5 V
CELL3, PV1 2V 0 5 V
CELL4, PV1 2V 0 5 V
Offset 1.6 mV
Gain Error Cell Inputs(5) ± 1 ± 0.5 %
CC-ADC
Reference Voltage ± 220 mV
Conversion Time and
Resolution 53.7 V Resolution 3.9 ms
1.68 V Resolution 125 1000 ms
INL 1000 ms conversion time ± 4 LSB
CC-ADC Offset(6) Uncompensated ± 50 ± 200 V
CC-ADC Offset Drift (4) TA = 0 - 60 1± 15V
CC-ADC Gain Error ± 1
Temperature
Sensor
VPTAT, V olt age Proportional to
Absolute Temperature 0.6 mV/K
Absolute Accuracy(3) ± 4 K
FET Driver
|VGS_ON|1115V
OC/OD Rise time (10 - 90%)
(Switching OFF) CL = 10 nF 10 50 µs
OC/OD Fall time
(VGS = 0 - VGS = -5V)
(Switching ON) CL = 10 nF 100 µs
OPC Rise time (10 - 90%)
(Switching OFF) CL = 1 nF 100 500 µs
OPC Fall time
(VGS = 0 - VGS = -5V)
(Switching ON) CL = 1 nF 100 500 µs
DC Characteristics, TA = -30C to 85C, VCC = 3.3V (Continued)
Parameter Condition Min Typ Max Unit
227
2548F–AVR–03/2013
ATmega406
Notes: 1. Voltage Regulator performance is based on 1 µF smooth capacitor.
2. After VREF calibration at second temperature. By default the first calibration is performed at 85 C in Atmel factory test. The
second calibration step can easily be implemented in a standard test flow at room temperature.
3. This value is not tested in production.
4. After system offset compensation in software.
5. After software gain error compensation.
6. This value should be measured at system level and stored in EEPROM for software offset compensation.
Slow RC
Oscillator Frequency TA = - 30 – 85C 165 kHz
Temperature Drift 5 %
Ultra Low Power
RC Oscillator Frequency TA = - 30 – 85C 124 kHz
Temperature Drift 8 %
DC Characteristics, TA = -30C to 85C, VCC = 3.3V (Continued)
Parameter Condition Min Typ Max Unit
228 2548F–AVR–03/2013
ATmega406
30.3 General I/O Lines characteristics
30.3.1 Low voltage ports
Notes: 1. Applicable for all except PC0.
2. “Max” means the highest value where the pin is guaranteed to be read as low.
3. “Min” means the lowest value where the pin is guaranteed to be read as high.
4. Although each I/O port can sink more than the test conditions (5 mA at VCC = 3.3V) under steady state conditions (non-tran-
sient, the following must be observed:
- The sum of all IOL should not exceed 20 mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
5. Although each I/O port can source more than the test conditions (2 mA at VCC = 3.3V) under steady state conditions (non-
transient, the following must be observed:
- The sum of all IOH should not exceed 2 mA.
30.3.2 High voltage ports
Notes: 1. Parameter characterized and not tested.
2. Cb = capacitance of one bus line in pF
Figure 30-1. TA = -30C to 85C, VCC = 3.3V (unless otherwise noted) (1)
Symbol Parameter Condition Min. Typ. Max. Units
VIL Input Low Voltage VCC = 3.3V -0.5 0.3VCC(2) V
VIH Input High Voltage VCC = 3.3V 0.6VCC(3) VCC + 0.5 V
VOL Output Low Voltage(4) IOL = 5mA, VCC = 3.3V 0.5 V
VOH Output High Voltage(5) IOH = 2 mA, VCC = 3.3V 2.3 V
IIL Input Leakage
Current I/O Pin VCC = 3.3V, pin low
(absolute value) A
IIH Input Leakage
Current I/O Pin VCC = 3.3V, pin high
(absolute value) A
Figure 30-2. TA = -30C to 85C, VCC = 3.3V (unless otherwise noted)
Symbol Parameter Condition Min. Typ. Max. Units
VOL(1) Output Low Voltage VCC = 3.3V 0.5 V
tr(1) Rise Time VCC = 3.3V 300 ns
tof(1) Output Fall Time from
VIHmin to VILmax Cb < 400 pF(2) 200 ns
229
2548F–AVR–03/2013
ATmega406
30.4 2-wire Serial Interface Characteristics
Table 30-1 descri bes the requireme nts for devices conn ected to the Two-wire Ser ial Bus. The AT mega40 6 Two-wire Se rial
Interface meets or exceeds these requirements under the noted conditions.
Timing symbols refer to Figure 30-3.
Notes: 1. In ATmega406, this parameter is characterized and not tested.
2. Cb = capacitance of one bus line in pF.
3. fCK = CPU clock frequency
4. This requirement applies to all ATmeg a406 Two-wire Serial Interface operation. Other devices connected to the Two-wire
Serial Bus need only obey the general fSCL requirement.
Table 30-1. Two-wire Serial Bus Requirements
Symbol Parameter Condition Min Max Units
VIL Input Low-voltage -0.5 0.8 V
VIH Input High-voltage 2.1 5.5 V
VOL(1) Output Low-voltage 350 µA sink current 0 0.4 V
tr(1) Rise Time for both SDA and SCL 300 ns
tof(1) Output Fall T ime from VIHmin to VILmax Cb < 400 pF(2) 250 ns
tSP(1) Spikes Suppressed by Input Filter 0 50 ns
IiInput Current each I/O Pin 0.1VBUS < Vi < 0.9V BUS -5 5 µA
Ci(1) Capacitance for each I/O Pin 10 pF
fSCL SCL Clock Frequency fCK(3) > max(16fSCL, 450 kHz)(4) 0 100 kHz
Rp Value of Pull-up resistor fSCL 100 kHz
tHD;STA Hold Time (repeated) START Condition fSCL 100 kHz 4.0 µs
tLOW Low Period of the SCL Clock fSCL 100 kHz 4.7 µs
tHIGH High period of the SCL clock fSCL 100 kHz 4.0 µs
tSU;STA Set-up time for a repeated START condition fSCL 100 kHz 4.7 µs
tHD;DAT Data hold ti me fSCL 100 kHz 0.3 3.45 µs
tSU;DAT Data setup time fSCL 100 kHz 250 ns
tSU;STO Setup time for STOP condition fSCL 100 kHz 4.0 µs
tBUF Bus free time between a STOP and START
condition fSCL 100 kHz 4.7 µs
VBUS 0,4V
350µA
-------------------------------
VBUS 0,4V
100µA
-------------------------------
230 2548F–AVR–03/2013
ATmega406
Figure 30-3. Two-wire Serial Bus Timing
30.5 Reset Characteristics
Notes: 1. Power-on Reset is issued when a charger is connected and the regulator has stable work conditions.
2. Values based on characterization.
Note: Internal Voltage Regulator must be on.
Note: Internal Voltage Regulator must be on.
t
SU;STA
t
LOW
t
HIGH
t
LOW
t
of
t
HD;STA
t
HD;DAT
t
SU;DAT
t
SU;STO
t
BUF
SCL
SDA
t
r
Table 30-2. Characteristics for Powering-up the LDO(1)
Symbol(2) Parameter Min Typ Max Units
Charger Present
VROT Regulator Power-on Threshold 3.0 4.0 V
VCHT Charge Voltage Threshold 1.0 V
No Charger Present
VROT Regulator Power-on Threshold 3.0 4.0 V
VPVIT Voltage Threshold on Battery Cell 1 2.0 V
Table 30-3. Power-on Reset Characteristics
Symbol Parameter Condition Min Typ Max Units
VCOT Charger-on Thresholt Voltage Regulator must operate 6 7 8 V
Table 30-4. External Reset Characteristics
Symbol Parameter Condition Min Typ Max Units
VRST RESET Pin Threshold Voltage VREG = 3.3V 0.66 2.8 V
tRST Minimum pulse width on RESET Pin 900 ns
231
2548F–AVR–03/2013
ATmega406
30.6 Supply Current of I/O Modules
Table 30-5 on page 231 is showing the additional current cons umption compared to ICC Active
and ICC Idle for every I/O module controlled by the Power Reduction Register, see ”PRR0 –
Power Reduction Register 0” on pa ge 36 for details. The ta bles and formulas below can be used
to calculate the additional current consumption for the different I/O modules in Active and Idle
mode.
30.6.0.1 Example 1
Calculate the expected current consumption in idle mode with TIMER1, V-ADC and Battery Pro-
tection enabled at VCC = 3.3V and F = 1MHz. From Table 30-5 , fourth column, we see that we
need to add 1.7% for the TIMER1, 1.9% for the V-ADC, and 25.2% for the TWI module. Reading
from ”DC Characteristics” on page 225, we find that the idle current consumption is typically 1.2
mA at VCC = 3.3V and F = 1MHz. The total current consumption in idle mode with USART0,
TIMER1, and SPI enabled, gives:
Table 30-5. Additional Current Consumption for the different I/O modules
PRR0 bit
Additional Current
Consumptio n at
VCC = 3.3V, F = 1 MHZ
[µA]
Additional Current
Consumption compared
to Active mode [%]
Additional Current
Consumption compared
to Idle mode [%]
PRTWI 68.0 5.6 25.2
PRTIM1 4.5 0.4 1.7
PRTIM0 6.0 0.5 2.2
PRVADC 5.0 4.2 1.9
ICCtotal 1.2mA 1 0.017 0.019 0.252+++1.55mA
232 2548F–AVR–03/2013
ATmega406
31. Typical Characteristics – Preliminary
The following charts are tested on a few microcontrollers only. These figures are not tested dur-
ing manufacturing, and are added for illustration purpose.
31.1 Pin Pull-up
Figure 31-1. I/O Pin Pull-Up Resistor Current vs. Input Voltage (VCC = 3.3V)
Figure 31-2. Reset Pull-Up Resistor Current vs. Input Voltage (VCC = 3.3V)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
V
CC
= 3.3V
85 ˚C
25 ˚C
-30 ˚C
0
10
20
30
40
50
60
70
80
90
0 0,5 1 1,5 2 2,5 3 3,5
V
I
(V)
I
OP
(uA)
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE
V
CC
= 3.3V
85 ˚C
25 ˚C
-30 ˚C
0
10
20
30
40
50
60
70
80
0 0,5 1 1,5 2 2,5 3 3,5
V
RESET
(V)
I
RESET
(uA)
233
2548F–AVR–03/2013
ATmega406
31.2 Pin Driver Strength
Figure 31-3. I/O Pin Putput Voltage vs. Sink Current (VCC = 3.3V)
Figure 31-4. I/O Pin output Voltage vs. Source Current (VCC = 3.3V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT
V
CC
= 3.3V
85 ˚C
25 ˚C
-30 ˚C
0.4
0.5
0.6
0.7
0.8
0.9
1
1.1
1.2
1.3
0 5 10 15 20 25
I
OL
(mA)
V
OL
(V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT
V
CC
= 3.3V
85 ˚C
25 ˚C
-30 ˚C
1.5
1.7
1.9
2.1
2.3
2.5
2.7
2.9
0 5 10 15 20 25
I
OH
(mA)
V
OH
(V)
234 2548F–AVR–03/2013
ATmega406
31.3 Internal Oscillator Speed
Figure 31-5. Watchdog Oscillator Frequency vs. Temperature (VCC = 3.3V)
Figure 31-6. Calibrated 1 MHz RC Oscillator Frequency vs. Temperature (V CC = 3.3V)
WATCHDOG OSCILLATOR FREQUENCY vs. TEMPERATURE
V
CC
= 3.3 V
117
118
119
120
121
122
123
124
125
126
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature
FRC
(k
Hz)
CALIBRATED 1 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
V
CC
= 3.3 V
0.975
0.98
0.985
0.99
0.995
1
1.005
1.01
1.015
1.02
1.025
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature
F
RC
(MHz)
235
2548F–AVR–03/2013
ATmega406
Figure 31-7. Calibrated 1 MHz RC Oscillator Frequency vs. OSC CAL Value (VCC = 3.3V)
Figure 31-8. Slow RC Oscillator Frequency vs. Temperature (VCC = 3.3V)
CALIBRATED 1 MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE
85 ˚C
25 ˚C
-30 ˚C
0
0.5
1
1.5
2
2.5
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
F
RC
(MHz)
SLOW RC OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
153
153.5
154
154.5
155
155.5
156
156.5
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature
F
RC
(kHz)
236 2548F–AVR–03/2013
ATmega406
32. Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
(0xFF) Reserved
(0xFE) Reserved
(0xFD) Reserved
(0xFC) Reserved
(0xFB) Reserved
(0xFA) Reserved
(0xF9) Reserved
(0xF8) BPPLR BPPLE BPPL 128
(0xF7) BPCR DUVD SCD DCD CCD 128
(0xF6) CBPTR SCPT[3:0] OCPT[3:0] 129
(0xF5) BPOCD DCDL[3:0] CCDL[3:0] 130
(0xF4) BPSCD SCDL[3:0] 130
(0xF3) BPDUV DUVT1 DUVT0 DUDL[3:0] 131
(0xF2) BPIR DUVIF COCIF DOCIF SCIF DUVIE COCIE DOCIE SCIE 132
(0xF1) CBCR CBE4 CBE3 CBE2 CBE1 137
(0xF0) FCSR PWMOC PWMOPC CPS DFE CFE PFD 134
(0xEF) Reserved
(0xEE) Reserved
(0xED) Reserved
(0xEC) Reserved
(0xEB) Reserved
(0xEA) Reserved
(0xE9) CADICH CADIC[15:8] 111
(0xE8) CADICL CADIC[7:0] 111
(0xE7) CADRDC CADRDC[7:0] 112
(0xE6) CADRCC CADRCC[7:0] 112
(0xE5) CADCSRB CADACIE CADRCIE CADICIE CADACIF CADRCIF CADICIF 110
(0xE4) CADCSRA CADEN CADUB CADAS1 CADAS0 CADSI1 CADSI0 CADSE 109
(0xE3) CADAC3 CADAC[31:24] 111
(0xE2) CADAC2 CADAC[23:16] 111
(0xE1) CADAC1 CADAC[15:8] 111
(0xE0) CADAC0 CADAC[7:0] 111
(0xDF) Reserved
(0xDE) Reserved
(0xDD) Reserved
(0xDC) Reserved
(0xDB) Reserved
(0xDA) Reserved
(0xD9) Reserved
(0xD8) Reserved
(0xD7) Reserved
(0xD6) Reserved
(0xD5) Reserved
(0xD4) Reserved
(0xD3) Reserved
(0xD2) Reserved
(0xD1) BGCRR BGCR7 BGCR6 BGCR5 BGCR4 BGCR3 BGCR2 BGCR1 BGCR0 123
(0xD0) BGCCR BGEN BGCC5 BGCC4 BGCC3 BGCC2 BGCC1 BGCC0 123
(0xCF) Reserved
(0xCE) Reserved
(0xCD) Reserved
(0xCC) Reserved
(0xCB) Reserved
(0xCA) Reserved
(0xC9) Reserved
(0xC8) Reserved
(0xC7) Reserved
(0xC6) Reserved
(0xC5) Reserved
(0xC4) Reserved
(0xC3) Reserved
(0xC2) Reserved
(0xC1) Reserved
(0xC0) CCSR –XOEACS 29
237
2548F–AVR–03/2013
ATmega406
(0xBF) Reserved
(0xBE) TWBCSR TWBCIF TWBCIE TWBDT1 TWBDT0 TWBCIP 169
(0xBD) TWAMR TWAM[6:0] –150
(0xBC) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN –TWIE 147
(0xBB) TWDR 2–wire Serial Interface Data Register 149
(0xBA) TWAR TWA[6:0] TWGCE 149
(0xB9) TWSR TWS[7:3] TWPS1 TWPS0 148
(0xB8) TWBR 2–wire Serial Interface Bit Rate Register 147
(0xB7) Reserved
(0xB6) Reserved
(0xB5) Reserved
(0xB4) Reserved
(0xB3) Reserved
(0xB2) Reserved
(0xB1) Reserved
(0xB0) Reserved
(0xAF) Reserved
(0xAE) Reserved
(0xAD) Reserved
(0xAC) Reserved
(0xAB) Reserved
(0xAA) Reserved
(0xA9) Reserved
(0xA8) Reserved
(0xA7) Reserved
(0xA6) Reserved
(0xA5) Reserved
(0xA4) Reserved
(0xA3) Reserved
(0xA2) Reserved
(0xA1) Reserved
(0xA0) Reserved
(0x9F) Reserved
(0x9E) Reserved
(0x9D) Reserved
(0x9C) Reserved
(0x9B) Reserved
(0x9A) Reserved
(0x99) Reserved
(0x98) Reserved
(0x97) Reserved
(0x96) Reserved
(0x95) Reserved
(0x94) Reserved
(0x93) Reserved
(0x92) Reserved
(0x91) Reserved
(0x90) Reserved
(0x8F) Reserved
(0x8E) Reserved
(0x8D) Reserved
(0x8C) Reserved
(0x8B) Reserved
(0x8A) Reserved
(0x89) OCR1AH Timer/Counter1 – Output Compare Register A High Byte 101
(0x88) OCR1AL Timer/Counter1 – Output Compare Register A Low Byte 101
(0x87) Reserved
(0x86) Reserved
(0x85) TCNT1H Timer/Counter1 – Counter Register High Byte 101
(0x84) TCNT1L Timer/Counter1 – Counter Register Low Byte 101
(0x83) Reserved
(0x82) Reserved
(0x81) TCCR1B CTC1 CS12 CS11 CS10 100
(0x80) Reserved
(0x7F) Reserved
(0x7E) DIDR0 VADC3D VADC2D VADC1D VADC0D 120
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
238 2548F–AVR–03/2013
ATmega406
(0x7D) Reserved
(0x7C) VADMUX VADMUX3 VADMUX2 VADMUX1 VADMUX0 118
(0x7B) Reserved
(0x7A) VADCSR VADEN VADSC VADCCIF VADCCIE 118
(0x79) VADCH VADC Data Register High byte 119
(0x78) VADCL VADC Data Register Low byte 119
(0x77) Reserved
(0x76) Reserved
(0x75) Reserved
(0x74) Reserved
(0x73) Reserved
(0x72) Reserved
(0x71) Reserved
(0x70) Reserved
(0x6F) TIMSK1 –OCIE1ATOIE1 102
(0x6E) TIMSK0 OCIE0B OCIE0A TOIE0 93
(0x6D) Reserved
(0x6C) PCMSK1 PCINT[15:8] 59
(0x6B) PCMSK0 PCINT[7:0] 59
(0x6A) Reserved
(0x69) EICRA ISC31 ISC30 ISC21 ISC20 ISC11 ISC10 ISC01 ISC00 56
(0x68) PCICR –PCIE1PCIE0 58
(0x67) Reserved
(0x66) FOSCCAL Fast Oscillator Calibration Re gister 29
(0x65) Reserved
(0x64) PRR0 PRTWI PRTIM1 PRTIM0 PRVADC 36
(0x63) Reserved
(0x62) WUTCSR WUTIF WUTIE WUTCF WUTR WUTE WUTP2 WUTP1 WUTP0 49
(0x61) Reserved
(0x60) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 47
0x3F (0x5F) SREG I T H S V N Z C 10
0x3E (0x5E) SPH SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 12
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 12
0x3C (0x5C) Reserved
0x3B (0x5B) Reserved
0x3A (0x5A) Reserved
0x39 (0x59) Reserved
0x38 (0x58) Reserved
0x37 (0x57) SPMCSR SPMIE RWWSB SIGRD RWWSRE BLBSET PGWRT PGERS SPMEN 183
0x36 (0x56) Reserved
0x35 (0x55) MCUCR JTD –PUD IVSEL IVCE 55/73/176
0x34 (0x54) MCUSR JTRF WDRF BODRF EXTRF PORF 46
0x33 (0x53) SMCR SM2 SM1 SM0 SE 31
0x32 (0x52) Reserved
0x31 (0x51) OCDR On-Chip Debug Register 176
0x30 (0x50) Reserved
0x2F (0x4F) Reserved
0x2E (0x4E) Reserved
0x2D (0x4D) Reserved
0x2C (0x4C) Reserved
0x2B (0x4B) GPIOR2 General Purpose I/O Register 2 24
0x2A (0x4A) GPIOR1 General Purpose I/O Register 1 24
0x29 (0x49) Reserved
0x28 (0x48) OCR0B Timer/Counter0 Output Compare Register B 92
0x27 (0x47) OCR0A Timer/Counter0 Output Compare Register A 92
0x26 (0x46) TCNT0 Timer/Count er0 (8 Bit) 92
0x25 (0x45) TCCR0B FOC0A FOC0B WGM02 CS02 CS01 CS00 91
0x24 (0x44) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 –WGM01WGM00 88
0x23 (0x43) GTCCR TSM PSRSYNC 105
0x22 (0x42) EEARH High Byte 19
0x21 (0x41) EEARL EEPROM Address Register Low Byte 19
0x20 (0x40) EEDR EEPROM Data Register 19
0x1F (0x3F) EECR EEPM1 EEPM0 EERIE EEMPE EEPE EERE 19
0x1E (0x3E) GPIOR0 General Purpose I/O Register 0 24
0x1D (0x3D) EIMSK INT3 INT2 INT1 INT0 57
0x1C (0x3C) EIFR INTF3 INTF2 INTF1 INTF0 57
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
239
2548F–AVR–03/2013
ATmega406
Notes: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O registers within the address range $00 - $1F are di rectly bit-accessible using the SBI and CBI instructions. In these reg-
isters, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on
all bits in the I/O register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions
work with registers 0x00 to 0x1F only.
4. When using the I/O specific commands IN and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O reg-
isters as data space using LD and ST instructions, $20 must be added to these addresses. The ATmega406 is a complex
microcontroller with more peripheral units than can be supported within th e 64 location reserved in Opcode for the IN and
OUT instructions. For the Extended I/O space from $60 - $FF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions
can be used.
0x1B (0x3B) PCIFR –PCIF1PCIF0
0x1A (0x3A) Reserved
0x19 (0x39) Reserved
0x18 (0x38) Reserved
0x17 (0x37) Reserved
0x16 (0x36) TIFR1 –OCF1ATOV1 102
0x15 (0x35) TIFR0 –OCF0BOCF0ATOV0 94
0x14 (0x34) Reserved
0x13 (0x33) Reserved
0x12 (0x32) Reserved
0x11 (0x31) Reserved
0x10 (0x30) Reserved
0x0F (0x2F) Reserved
0x0E (0x2E) Reserved
0x0D (0x2D) Reserved
0x0C (0x2C) Reserved
0x0B (0x2B) PORTD PORTD1 PORTD0 74
0x0A (0x2A) DDRD DDD1 DDD0 74
0x09 (0x29) PIND PIND1 PIND0 74
0x08 (0x28) PORTC –PORTC0 76
0x07 (0x27) Reserved
0x06 (0x26) Reserved
0x05 (0x25) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 74
0x04 (0x24) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 74
0x03 (0x23) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 74
0x02 (0x22) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTB3 PORTA2 PORTA1 PORTA0 73
0x01 (0x21) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 73
0x00 (0x20) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 73
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
240 2548F–AVR–03/2013
ATmega406
33. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd Rd Rr Z,N,V 1
ANDI Rd, K Log ical AND Register and Constant Rd Rd K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd Rd Rr Z,N,V 1
COM Rd One’s Complement Rd 0xFF Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd 0x00 Rd Z,C,N,V, H 1
SBR Rd,K Set Bit(s) in Register Rd Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd Rd (0xFF - K) Z,N,V 1
INC Rd Increment Rd Rd + 1 Z,N,V 1
DEC Rd Decrement Rd Rd 1 Z,N,V 1
TST Rd Test for Zero or Minus R d Rd Rd Z,N,V 1
CLR Rd Clear Register Rd Rd Rd Z,N,V 1
SER Rd Set Register Rd 0xFF None 1
MUL Rd, Rr Multiply Unsigned R1:R0 Rd x Rr Z,C 2
MULS Rd, Rr Multiply Signed R1:R0 Rd x Rr Z,C 2
MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 Rd x Rr Z,C 2
FMUL Rd, Rr Fractional Multip ly Unsigned R1:R0 (Rd x Rr) << 1 Z,C 2
FMULS Rd, Rr Fra ctional Multiply Signed R1:R0 (Rd x Rr) << 1 Z,C 2
FMULSU Rd, Rr Fracti onal Multiply Signed with Unsigned R1:R0 (Rd x Rr) << 1 Z,C 2
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC PC + k + 1 Non e 2
IJMP Indirect Jump to (Z) PC Z None 2
JMP k Direct Jump PC kNone3
RCALL k Relative Subroutine Cal l PC PC + k + 1 None 3
ICALL Indirect Call to (Z) PC ZNone3
CALL k Direct Subrou tine Call PC kNone4
RET Subroutine Return PC STACK None 4
RETI Interrupt Return PC STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd Rr C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1 /2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PCPC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PCPC+k + 1 N one 1/2
BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1 /2
BRLT k Branch if Less Than Zero, Signed if (N V= 1) then PC PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1/2
BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1/2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1/2
241
2548F–AVR–03/2013
ATmega406
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) 1None2
CBI P,b Clear Bit in I/O Register I/O(P,b) 0None2
LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)C,Rd(n+1) Rd(n),CRd(7) Z,C,N,V 1
ROR Rd Rotate Right Through Carry Rd(7)C,Rd(n) Rd(n+1),CRd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) None 1
BSET s Flag Set SREG(s) 1 SREG(s) 1
BCLR s Flag Clear SREG(s) 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) TNone1
SEC Set Carry C 1C1
CLC Clear Carry C 0 C 1
SEN Set Negative Flag N 1N1
CLN Clear Negative Flag N 0 N 1
SEZ Set Zero Flag Z 1Z1
CLZ Clear Zero Flag Z 0 Z 1
SEI Global Interrupt Enable I 1I1
CLI Global Interrupt Disable I 0 I 1
SES Set Signed Test Flag S 1S1
CLS Clear Signed Test Flag S 0 S 1
SEV Set Twos Complement Overflow. V 1V1
CLV Clear Twos Complement Overflow V 0 V 1
SET Set T in SREG T 1T1
CLT Clear T in SREG T 0 T 1
SEH Set Half Carry Flag in SREG H 1H1
CLH Clear Half Carry Flag in SREG H 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd KNone1
LD Rd, X Load Indirect Rd (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None 2
LD Rd, Y Load Indirect Rd (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd (Y), Y Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y Y - 1, Rd (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd (Y + q) None 2
LD Rd, Z Load Indirect Rd (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd (Z), Z Z+ 1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z Z - 1, Rd (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd (k) None 2
ST X, Rr Store Indirect (X) Rr None 2
ST X+, Rr Store Indirect and Post-In c. (X) Rr, X X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X X - 1, (X) Rr None 2
ST Y, Rr St ore Indirect (Y) Rr None 2
ST Y+, Rr Store Indirect and Post-In c. (Y) Rr, Y Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y Y - 1, (Y) Rr None 2
STD Y+q,Rr Store Indirect wit h Displacement (Y + q) Rr None 2
ST Z, Rr Store Indire ct (Z) Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) Rr, Z Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z Z - 1, (Z) Rr None 2
STD Z+q,Rr Store Indirect with Di splacement (Z + q) Rr None 2
STS k, Rr Store Direct to SRAM (k) Rr None 2
LPM Load Program Memory R0 (Z) None 3
LPM R d, Z Load Program Memory Rd (Z) None 3
LPM R d, Z+ Loa d P r ogram Memory and Post-Inc Rd (Z), Z Z+1 None 3
SPM Store Program Memory (Z) R1:R0 None -
IN Rd, P In Port Rd PNone1
33. Instruction Set Summary (Continued)
Mnemonics Operands Description Operation Flags #Clocks
242 2548F–AVR–03/2013
ATmega406
OUT P, Rr Out Port P Rr None 1
PUSH Rr Push Register on Stack STACK Rr None 2
POP Rd Pop Register from Stack Rd STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) N one 1
WDR Watchdog Reset (see specific descr. for WDR/timer) None 1
BREAK Break For On-chip Debug Only None N/A
33. Instruction Set Summary (Continued)
Mnemonics Operands Description Operation Flags #Clocks
243
2548F–AVR–03/2013
ATmega406
34. Ordering Information
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS direc-
tive). Also Halide free and fully Green.
Speed (MHz) Power Supply Ordering Code Package(1) Oper ation Range
1 4.0 - 25V ATmega406-1AAU(2) 48AA Industrial
(-30C to 85C)
Package Type
48AA 48-lead, 7 x 7 x 1.44 mm body, 0.5 mm lead pitch, Low Profile Plastic Quad Flat Package (LQFP)
244 2548F–AVR–03/2013
ATmega406
35. Packaging Information
35.1 48AA
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
48AA, 48-lead, 7 x 7 mm Body Size, 1.4 mm Body Thickness,
0.5 mm Lead Pitch, Low Profile Plastic Quad Flat Package (LQFP) D
48AA
2010-10-19
PIN 1 IDENTIFIER
0°~7°
PIN 1
L
C
A1 A2 A
D1
D
eE1 E
B
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
Notes:
1. This package conforms to JEDEC reference MS-026, Variation BBC.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable
protrusion is 0.25 mm per side. Dimensions D1 and E1 are maximum
plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.08 mm maximum.
A 1.60
A1 0.05 0.15
A2 1.35 1.40 1.45
D 8.75 9.00 9.25
D1 6.90 7.00 7.10 Note 2
E 8.75 9.00 9.25
E1 6.90 7.00 7.10 Note 2
B 0.17 0.27
C 0.09 0.20
L 0.45 0.75
e 0.50 TYP
245
2548F–AVR–03/2013
ATmega406
36. Errata
36.1 Rev. F Voltage-ADC Common Mode Offset
Volt a g e Reference Sp ik e
1. Voltage-ADC Common Mode Offset
The cell conversion will have an Offset-error depending on the Common Mode (CM) level.
This means that the error of a cell is depending on the voltage of the lower cells. The CM
Offset is calibrated away in Atmel production when the cells are balanced. When the cells
get un-balanced the CM depending offset will reappear:
a. Cell 1 defines its own CM level, and will never be affected by the CM dependent
offset.
b. The CM level for Cell 2 will change if Cell 1 voltage deviates from Cell 2 voltage.
c. The CM level for Cell 3 will change if Cell 1 and/or Cell 2 voltage deviates from the
voltage at Cell 3. The wo rst-case error is when Cell 1 and 2 are balanced while Cell 3
voltage deviates from the voltage at Cell 1 and 2.
d. The CM level for Cell 4 will change if Cell 1, Cell 2 and/or Cell 3 deviate from the volt-
age at Cell 4. The worst-case error is when Cell 1, Cell 2 and Cell 3 are balanced
while Cell 4 voltage deviates from the voltage at Cell 1, 2 and 3.
Figure 36-1 on page 246, shows the error of Cell2, Cell3 and Cell4 with 5% and 10% unbal-
anced cells.
246 2548F–AVR–03/2013
ATmega406
Figure 36-1. CM Offset with unbalanced cells.
Problem Fix/Workaround
Avoid getting unbalanced cells by using the internal cell balancing FETs.
2. Voltage Reference spike
The Voltage Reference, VREF, will spike each time the internal temperature sensor is
enabled. The temperature sensor is enabled when the VTEM P is selected in the VADMUX
register and the V-ADC is enabled by the VADEN bit.
The spike will be approximately 50mV and lasts for about 5ms, and it will affect any ongoing
current accumulation in the CC-ADC, as well as V-ADC conversions in the period of the
spike. Figure 36-2 on page 247 illustrates the Volt age Referenc e spik e.
247
2548F–AVR–03/2013
ATmega406
Figure 36-2. Voltage Reference Spike
Problem workaround:
To get correct temperature measurement, the VADSC bit should not be written until the
spike has settled (external decoupling capacitor of 1F).
VREF
time
Voltage
t ~< 5ms
V~50mV
1.1 V
VADEN
VADMUX3:0 XXX VTEMP
248 2548F–AVR–03/2013
ATmega406
36.2 Rev. E Voltage ADC not functional bel ow 0°C
Voltage-ADC Common Mode Offset
Volt a g e Reference Sp ik e
1. Voltage-ADC Failing at Low Tempe r atures
Voltage ADC not functional below 0°C. The voltage ADC has a very large error below 0°C,
and can not be used
Problem Fix/Workaround
Do not use this revision below 0 celsius.
2. Voltage-ADC Common Mode Offset
The cell conversion will have an Offset-error depending on the Common Mode (CM) level.
This means that the error of a cell is depending on the voltage of the lower cells. The CM
Offset is calibrated away in Atmel production when the cells are balanced. When the cells
get un-balanced the CM depending offset will reappear:
a. Cell 1 defines its own CM level, and will never be affected by the CM dependent
offset.
b. The CM level for Cell 2 will change if Cell 1 voltage deviates from Cell 2 voltage.
c. The CM level for Cell 3 will change if Cell 1 and/or Cell 2 voltage deviates from the
voltage at Cell 3. The wo rst-case error is when Cell 1 and 2 are balanced while Cell 3
voltage deviates from the voltage at Cell 1 and 2.
d. The CM level for Cell 4 will change if Cell 1, Cell 2 and/or Cell 3 deviate from the volt-
age at Cell 4. The worst-case error is when Cell 1, Cell 2 and Cell 3 are balanced
while Cell 4 voltage deviates from the voltage at Cell 1, 2 and 3.
Figure 36-1 on page 246, shows the error of Cell2, Cell3 and Cell4 with 5% and 10% unbal-
anced cells.
249
2548F–AVR–03/2013
ATmega406
Figure 36-3. CM Offset with unbalanced cells.
Problem Fix/Workaround
Avoid getting unbalanced cells by using the internal cell balancing FETs.
3. Voltage Reference Spike
The Voltage Reference, VREF, will spike ea ch time a temperature measurement is sta rted
with the Voltage-ADC.
Problem Fix/Workaround
An accurate temperature measurement could be obtained by doing 10 temperature conver-
sions immediately after each other. The first 9 results would be inaccurate, but the 10th
conversion will be correct.
Figure 36-4 on page 250 illustrates the spike on the Voltage Reference when doing 10 tem-
perature conversions in a row (external decoupling capacitor of 1F).
250 2548F–AVR–03/2013
ATmega406
Figure 36-4. Voltage Reference Spike
If the CC-ADC is doing current accumulation while the V-ADC is doing temperature m ea-
surement, both the Instantaneous and the Accumulated conversion results will be affected.
The spike on VREF will be vis ible on 1 Accumulated Current (CADAC3…0) and 2 Instanta-
neous Current (CADIC1…0) conversion results.
36.3 Rev. D Voltage ADC not functional below 0°C
Voltage-ADC Common Mode Offset
Volt a g e Reference Sp ik e
Voltage Regulator S tart-up sequence
VREF influenced by MCU state
EEPROM read from application code does not work in Lock Bit Mode 3
1. Voltage-ADC Failing at Low Tempe r atures
Voltage ADC not functional below 0°C. The voltage ADC has a very large error below 0°C,
and can not be used
Problem Fix/Workaround
1. Voltage-ADC Common Mode Offset
The cell conversion will have an Offset-error depending on the Common Mode (CM) level.
This means that the error of a cell is depending on the voltage of the lower cells. The CM
Offset is calibrated away in Atmel production when the cells are balanced. When the cells
get un-balanced the CM depending offset will reappear:
VREF
time
Voltage
t ~< 5ms
V~50mV
1.1 V
VADSC (10 VTEMP conversion in a row)
VADMUX3:0 XXX VTEMP
251
2548F–AVR–03/2013
ATmega406
a. Cell 1 defines its own CM level, and will never be affected by the CM dependent
offset.
b. The CM level for Cell 2 will change if Cell 1 voltage deviates from Cell 2 voltage.
c. The CM level for Cell 3 will change if Cell 1 and/or Cell 2 voltage deviates from the
voltage at Cell 3. The wo rst-case error is when Cell 1 and 2 are balanced while Cell 3
voltage deviates from the voltage at Cell 1 and 2.
d. The CM level for Cell 4 will change if Cell 1, Cell 2 and/or Cell 3 deviate from the volt-
age at Cell 4. The worst-case error is when Cell 1, Cell 2 and Cell 3 are balanced
while Cell 4 voltage deviates from the voltage at Cell 1, 2 and 3.
Figure 36-1 on page 246, shows the error of Cell2, Cell3 and Cell4 with 5% and 10% unbal-
anced cells.
Figure 36-5. CM Offset with unbalanced cells.
Problem Fix/Workaround
Avoid getting unbalanced cells by using the internal cell balancing FETs.
252 2548F–AVR–03/2013
ATmega406
3. Voltage Reference Spike
The Voltage Reference, VREF, will spike ea ch time a temperature measurement is sta rted
with the Voltage-ADC.
Problem Fix/Workaround
An accurate temperature measurement could be obtained by doing 10 temperature conver-
sions immediately after each other. The first 9 results would be inaccurate, but the 10th
conversion will be correct.
Figure 36 -6 illustrates the spike on the Voltage Reference when doing 10 temperature con-
versions in a row (external deco upling capacitor of 1F).
Figure 36-6. Voltage Reference Spike
If the CC-ADC is doing current accumulation while the V-ADC is doing temperature m ea-
surement, both the Instantaneous and the Accumulated conversion results will be affected.
The spike on VREF will be vis ible on 1 Accumulated Current (CADAC3…0) and 2 Instanta-
neous Current (CADIC1…0) conversion results.
VREF
time
Voltage
t ~< 5ms
V~50mV
1.1 V
VADSC (10 VTEMP conversion in a row)
VADMUX3:0 XXX VTEMP
253
2548F–AVR–03/2013
ATmega406
4. Voltage Regulator Start-up sequence
When powering up ATmega406 some precautions are necessary to ensure proper start-up
of the Voltage Regulator .
Problem Fix/Workaround
The three steps below are needed to ensure proper start-up of the voltage re gulator.
a. Do NOT connect a capacitor larger than 100 nF on the VFET pin. This is to ensure
fast rise time on the VFET pin when a supply voltage is connected.
b. During assembly, always connect Cell1 first, then Cell2 and so on until the top cell is
connected to PVT. If the cell voltages are about 2 volts or larger, the Voltage Regula-
tor will normally start up properly in Power-off mode (VREG appr. 2.8 volts).
c. After all cells have been as sembled as described in step 2, a cha rger source must be
connected at the BATT+ terminal to initialize the chip, see Section 8.3 ”Power-on
Reset and Charger Connect” on page 38 in the datasheet.
If the Voltage Regulator started up in Power-off during assembly of the cells, the chip will ini-
tialize when the charger source makes the voltage at the BATT pin exceed 7 - 8 Volts.
If the Voltage Regulator did not start up properly, the charger source has one additional
requirement to ensur e prop er start up a nd in itialization. In this case the ch arg er so urce must
ensure that the voltage at the VFET pin increases quickly at least 3 Volts above the voltage
at the PVT pin, and that the voltage at the BATT pin exceeds 7 - 8 Volts. This will start up
and initialize the chip directly.
5. VREF influenced by MCU state
The reference voltage at the VREF pin depends on the following conditions of the device:
a. Charger Over-current and/or Discharge Over-current Protection active but Short-cir-
cuit inactive. This will increase VREF voltage with typical 1 mV comp ared to a
condition were all Current Protections are disabled.
b. Short-circuit Protection active. Short-circuit measurements are activated when SCD
in BPCR is zero (default) and DFE in FET Control and S t atus Register (FCSR) is set.
This will increase VREF voltage with typical 8 mV compared to a conditio n with short-
circuit measurements inactive.
c. V-ADC conversion of the internal VTEMP voltage. This will increase VREF voltage
with typical 15 mV compared to a condition with short-circuit measurements inactive.
Problem Fix/Work around
To ensure the highest accuracy, set the Bandgap Calibration Register (BGCC) to get 1.100
V at VREF after the chip is configured with the actual Battery Protection settings and the Dis-
charge FET is enabled.
6. EEPROM read from application code does not work in Lock Bit Mode 3
When the Memory Lock Bits LB2 and LB1 are programmed to mod e 3, EEPROM read does
not work from the application code.
Problem Fix/Work around
Do not set Lock Bit Protection Mode 3 when the application code needs to read from
EEPROM.
254 2548F–AVR–03/2013
ATmega406
37. Datasheet Revision History
37.1 Rev 2548F - 03/13
37.2 Rev 2548E - 07/06
1. Updated heading titles of “PPI/NNI” and ”PI/NI” on page 6.
2. Updated Note 10 in Table 27-5 on page 189
3. Updated Section 30 .2 on pag e 22 5.
1. Updated ”Pin Configurations” on page 2.
2. Updated ”ADC Noise Reduction Mode” on page 32.
3. Updated ”Power-save Mode” on page 32.
4. Updated ”Power-down Mode” on page 33.
5 Updated ”Power-off Mode” on page 33.
6. Updated ”Power Reduction Register” on page 36.
7. Added ”Voltage ADC” on page 37 and ”Coloumb Counter” on page 38.
8. Updated ”Reset Sources” on page 39.
9. Updated ”Power-on Reset and Charger Connect” on page 40.
10. Updated ”External Reset” on page 41.
11. VCC replaced by VREG in ”Brown-out Detecti on” on page 42.
12. Updated ”Alternate Port Functions” on page 66.
13. Updated ”Internal Clock Source” on page 103.
14. Updated ”External Clock Source” on page 103.
15. Updated Features in ”Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC”
on page 106.
16. Updated Operation in Section 18. ”Coulomb Counter - Dedicated Fuel Gauging
Sigma-delta ADC” on page 106.
17. Updated Features in ”Voltage Regulator” on page 114.
18. Updated Operation in ”Voltage Regulator” on page 114.
19. Updated Bit description in ”VADCL and VADCH – The V-ADC Data Register” on page
119.
20. Updated ”Writing to Bandgap Calibration Registers” on page 122.
21. Updated Text in ”Register Description for FET Control” on page 134.
22. Added ”MCUCR – MCU Control Register” on page 176.
23 Updated ”Operating Circuit” on page 223
24. Updated ”Electrical Characteristics” on page 225.
25. Added ”Typical Characteristics – Preliminary” on page 232.
26 Updated ”Register Summary” on page 236.
27. Updated ”Errata” on page 245.
28. Updated Table 9-2 on page 48, Table 27-5 on page 189.
29. Updated Figure 8-1 on page 35, Figure 9-5 on page 42, Figure 17-2 on page 104,
Figure 18-2 on page 107, Figure 18-3 on page 108, Figure 19-1 on page 114, Figure
29-1 on page 223.
30. Updated Register Adresses.
255
2548F–AVR–03/2013
ATmega406
37.3 Rev 2548D - 06/05
37.4 Rev 2548C - 05/05
37.5 Rev 2548B - 04/05
1. Updated Section 36. ”Errata” on page 245.
1. Updated Section 36. ”Errata” on page 245.
1. Typos updated, bit “PSRASY” removed, CS12:0 renamed CS1[2:0].
2. Removed “BGEN” bit in BGCCR register. The bandgap voltage reference is always
enabled in ATmega406 revision E.
3. Updated Figure 2-1 on page 3, Figure 6-1 on page 25, Figure 24-9 on page 137, Fig-
ure 21-1 on page 120.
4. Upd ate d Table 7-2 on page 33, Table 7-3 on page 34, Table 8- 1 on page 38, Table
26-5 on page 181, Figure 27-1 on page 188.
5. Updated Section 12.3.2 ”Alternate Functions of Port A” on page 66 and Section 21.
”Battery Protection” on page 118 description.
6. Updated registers ”External Interrupt Flag Register – EIFR” on page 55 and
”Timer/Counter Control Register B – TCCR0B” on page 89.
7. Updated Section 17.1 ”Features” on page 103 and Section 17.2 ”Operation” on page
103.
Updated Section 19.1 ”Features” on page 111.
Updated Section 20.2 ”Register Description for Voltage Reference and Temperature
Sensor” on page 116.
8. Updated Section 29. ”Electrical Characteristics” on page 211.
9. Updated Section 35. ”Errata” on page 225.
256 2548F–AVR–03/2013
ATmega406
i
2548F–AVR–03/2013
ATmega406
Table of Contents
Features..................................................................................................... 1
1 Pin Configurations ................................................................................... 2
1.1 Disclaimer .................................................................................................................2
2 Overview ................................................................................................... 3
2.1 Block Diagram ..........................................................................................................3
2.2 Pin Descriptions .......................................................................................................5
3 Resources ................................................................................................. 7
4 About Code Examples ............................................................................. 7
5 AVR CPU Core ..........................................................................................8
5.1 Introduction ...............................................................................................................8
5.2 Architectural Overview .............................................................................................8
5.3 ALU – Arithmetic Logic Unit .....................................................................................9
5.4 Status Register .......................................................................................................10
5.5 General Purpose Register File ...............................................................................11
5.6 Stack Pointer ..........................................................................................................12
5.7 Instruction Execution Timing ..................................................................................13
5.8 Reset and Interrupt Handling .................................................................................14
6 AVR Memories ........................................................................................ 16
6.1 In-System Reprogrammable Flash Program Memory ............................................16
6.2 SRAM Data Memory ..............................................................................................17
6.3 EEPROM Data Memory .........................................................................................18
6.4 I/O Memory .............................................................................................................24
7 System Clock and Clock Options ......................................................... 25
7.1 Clock Systems and their Distribution .. ....................................................................25
7.2 Clock Sources ........................................................................................................26
7.3 Calibrated Fast RC Oscillator .................................................................................26
7.4 32 kHz Crystal Oscillator ........................................................................................27
7.5 Slow RC Oscillator .................................................................................................27
7.6 Ultra Low Power RC Oscillator ...............................................................................27
7.7 CPU, I/O, Flash, and Voltage ADC Clock ...............................................................27
7.8 Coulomb Counter ADC and Wake-up Timer Clock ................................................28
7.9 Watchdog Timer and Battery Protection Clock .......................................................28
ii 2548F–AVR–03/2013
ATmega406
7.10 Run-Time Clock Source Select ............................ ................... ... ... .... ... ... ... .... ... ...28
7.11 Register Description .............................................................................................29
8 Power Management and Sleep Modes ................................................. 31
8.1 Idle Mode ................................................................................................................32
8.2 ADC Noise Reduction Mode ..................................................................................32
8.3 Power-save Mode ..................................................................................................32
8.4 Power-down Mode .................................................................................................33
8.5 Power-off Mode ......................................................................................................33
8.6 Power Reduction Register ......................................................................................36
8.7 Minimizing Power Consumption .............................................................................37
9 System Control and Reset .................................................................... 39
9.1 Resetting the AVR ..................................................................................................39
9.2 Reset Sources ........................................................................................................39
9.3 Watchdog Timer .....................................................................................................43
9.4 Register Description ...............................................................................................46
10 Wake-up Timer ....................................................................................... 49
10.1 Overview ............................. .... ... ... ... .... ... ... ................ ... .... ... ... ... ... .... ... ................49
10.2 Register Description .............................................................................................49
11 Interrupts ................................................................................................ 51
11.1 Interrupt Vectors in ATmega406 ..........................................................................51
11.2 Moving Interrupts Between Application and Boot Space .....................................54
11.3 Register Description .............................................................................................55
12 External Interrupts ................................................................................. 56
12.1 Overview ............................. .... ... ... ... .... ... ... ................ ... .... ... ... ... ... .... ... ................56
12.2 Register Description .............................................................................................56
13 Low Voltage I/O-Ports ............................................................................ 60
13.1 Introduction .......... ... .... ... ... ... .... ... ................................................ ... .... ... ... ... .... ... ...60
13.2 Low Voltage Ports as General Digital I/O ............. ... ... ... .... ... ... ... ... .... ... ... ... .... ... ...61
13.3 Alternate Port Functions .......................................................................................66
13.4 Register Description .............................................................................................73
14 High Voltage I/O Ports ........................................................................... 75
14.1 High Voltage Ports as General Digital Output s ............. .... ... ... ... ... .... ... ... ... .... ......75
14.2 Configuring the Pin ........... ... .... ... ... ... .... ... ... ... ... .... ... ................... ... .................... ...76
14.3 Register Description for High Voltage Output Ports .............................................76
iii
2548F–AVR–03/2013
ATmega406
15 8-bit Timer/Counter0 with PWM ............................................................ 77
15.1 Overview ............................. .... ... ... ... .... ... ... ................ ... .... ... ... ... ... .... ... ................77
15.2 Timer/Counter Clock Sources ..............................................................................78
15.3 Counter Unit ..................... ... .... ... ... ... .... ... ... ... ... .................................... ................78
15.4 Output Compare Unit ...........................................................................................79
15.5 Compare Match Output Unit .... ............................. ............................. ...................81
15.6 Modes of Operation .......... ... .... ... ... ... .... ................... ................... .................... ......82
15.7 Timer/Counter Timing Diagrams ..........................................................................86
15.8 8-bit Timer/Counter Register Description .............................................................88
16 16-bit Timer/Counter1 ............................................................................ 95
16.1 Overview ............................. .... ... ... ... .... ... ... ................ ... .... ... ... ... ... .... ... ................95
16.2 Accessing 16-bit Registers ...................................................................................96
16.3 Timer/Counter Clock Sources ..............................................................................98
16.4 Counter Unit ..................... ... .... ... ... ... .... ... ... ... ... .................................... ................99
16.5 Output Compare Unit ...........................................................................................99
16.6 16-bit Timer/Counter Register Description .........................................................100
17 Timer/Counter0 and Timer/Counter1 Prescalers .............................. 103
17.1 Internal Clock Source .........................................................................................103
17.2 Prescaler Reset .......... ... ... ... .................... ... ... .................... ... ... ................... .... ... .103
17.3 External Clock Source ......... .................... ... ... .................... ... ................... ... .... ....103
17.4 Register Description ...........................................................................................105
18 Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC ......106
18.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................106
18.2 Operation ............. ... .... ... ... ... ................................................................. ... ... .... ... .107
19 Voltage Regulator ................................................................................ 114
19.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................114
19.2 Operation ............. ... .... ... ... ... ................................................................. ... ... .... ... .114
20 Voltage ADC – 10-channel Gen eral Purpose 12-bit Sigma-Delta ADC ..
116
20.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................116
20.2 Operation ............. ... .... ... ... ... ................................................................. ... ... .... ... .117
20.3 Register Description ...........................................................................................118
21 Voltage Reference and Temperature Sensor .................................... 121
21.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................121
iv 2548F–AVR–03/2013
ATmega406
21.2 Writing to Bandgap Calibration Registers ...........................................................122
21.3 Register Description for Voltage Reference and Temperature Sensor ..............123
22 Battery Protection ................................................................................ 125
22.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................125
22.2 Deep Under-voltage Protection ..........................................................................126
22.3 Discharge Over-current Protection .......... ... ... ... .... ... ... ... .... ... ... ... ... .... ... ... ... .... ... .126
22.4 Charge Over-current Protection .........................................................................126
22.5 Short-circuit Protection .................. ... .... ... ... ... ... .................... ... ... ... .... ... ..............127
22.6 Battery Protection CPU Interface ..................... .... ... ... ... .... ... ... ... ... .... ... ... ... .... ... .127
22.7 Register Description for Battery Protection ........................................................128
23 FET Control .......................................................................................... 133
23.1 FET Driver .. ... ... ... ... .... ... ... ... .... ... ... ... .... ... ................... ... .... ................... ... ... ........134
23.2 Register Description for FET Control ..................................................................134
24 Cell Balancing ...................................................................................... 136
24.1 Register Description ...........................................................................................137
25 2-wire Serial Interface .......................................................................... 138
25.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................138
25.2 Two-wire Serial Interface Bus Definition .............................................................138
25.3 Data Transfer and Frame Format .......................................................................139
25.4 Multi-master Bus Systems, Arbitration and Synchronization ..............................142
25.5 Overview of the TWI Module ..............................................................................144
25.6 TWI Register Description ........ ... ... ... .... ... ... ... ... .... ... ... ... .... ... ... ... ... .... ... ... ... .... ... .147
25.7 Using the TWI ................... .................... ................... ................... ........................150
25.8 Transmission Modes ..........................................................................................153
25.9 Multi-master Systems and Arbitration .................................................................167
25.10 Bus Connect/Disconnect for Two-wire Serial Interface ....................................169
26 JTAG Interface and On-chip Debug System ..................................... 171
26.1 Features ........................... ... .... ... ... ... .... ... ... ................... .................... .................171
26.2 Overview ................ ................................................. ... ... .... ... ... ... ... .... .................171
26.3 Test Access Port – TAP ............................. ................... .... ... ... ... ... .................... .171
26.4 TAP Controller ............ ... ... ... .... ................... ... .................... ... ................... ... ........173
26.5 Using the On-chip Debug System ......................................................................174
26.6 On-chip Debug Specific JTAG Instructions ................... .... ... ... ... ... .... ... ... ... .... ... .175
26.7 On-chip Debug Related Register .......................................................................176
v
2548F–AVR–03/2013
ATmega406
26.8 Using the JTAG Programming Capabilities ....................... ... ... ... ... .... ... ... ... .... ... .177
27 Boot Loader Support – Read-While-Write Self-Programming .........178
27.1 Boot Loader Features .........................................................................................178
27.2 Application and Boot Loader Flash Sections .... .... ... ... ... ....... ... ... ... .... ... ... ... .... ... .178
27.3 Read-While-Write and No Read-While-Write Flash Sections ..... ... .... ... ... ... .... ... .179
27.4 Boot Loader Lock Bits ........................................................................................181
27.5 Entering the Boot Loader Program .....................................................................183
27.6 Addressing the Flash During Self-Programming ................................................185
27.7 Self-Programming the Flash .................... ... ... ... .... ... ... ... .... ... ... ... ... .... ... ... ... .... ... .186
28 Memory Programming ......................................................................... 195
28.1 Program And Data Memory Lock Bits ................................................................195
28.2 Fuse Bits .......... ... ... .... ... ... ... .... ... ................................... .................... .................196
28.3 Signature Bytes ................ ... .... ................................... ................... .................... .198
28.4 Calibration Bytes ........................ ... ................... .... ................... ... .................... ... .198
28.5 Page Size ...................... ... ... .... ... ... ... .... ... ... ................... .................... .................198
28.6 Parallel Programming ................. ... ... ..................................................................199
28.7 Programming via the JTAG Interface ...................... ... ... .... ... ... ... ... .... ... ... ... .... ... .211
29 Operating Circuit .................................................................................. 223
30 Electrical Characteristics .................................................................... 225
30.1 Absolute Maximum Ratings* ..............................................................................225
30.2 DC Characteristics ........... ... .... ... ... ... .... ... ... ... ... .... ................... ................... ........225
30.3 General I/O Lines characteristics .......................................................................228
30.4 2-wire Serial Interface Characteristics ................................................................229
30.5 Reset Characteristics ................................. ... .................... ... ... ................... .... ... .230
30.6 Supply Current of I/O Modules ................... ... ... .... ................... ... ... .... ... ... ... .... ... .231
31 Typical Characteristics – Preliminary ................................................ 232
31.1 Pin Pull-up ..................... ................ ... .... ... ... ... ... .... ... ... ... ................................. ... .232
31.2 Pin Driver Strength ..................... ... ... .... ... ... ... .................... ... ... ................... .... ... .233
31.3 Internal Oscillator Speed ............... ... .... ... ... ................... .... ................... ... ... ........234
32 Register Summary ............................................................................... 236
33 Instruction Set Summary .................................................................... 240
34 Ordering Information ........................................................................... 243
35 Packaging Information ........................................................................ 244
vi 2548F–AVR–03/2013
ATmega406
35.1 48AA ....... .... ... ................................ ... .... ... ... ... ... .... ... ... ... ................................. ... .244
36 Errata ..................................................................................................... 245
36.1 Rev. F ......... ... ... ... ... .... ... ... ... ................. ... ... ... ... .... ... ... ... ................ .... ... ... ... .... ... .245
36.2 Rev. E .. ................ ... .... ... ... ... .... ... ................ ... ... .... ... ... ... .... ... ................ ... ... .... ... .248
36.3 Rev. D .... .... ... ................ ... ... .... ... ... ... .... ... ... ... ................................ .... ... ... ... .... ... .250
37 Datasheet Revision History ................................................................ 254
37.1 Rev 2548F - 03/13 ...... ... ... ... .... ... ... ... .................... ... ................... ... .... .................254
37.2 Rev 2548E - 07/06 .............................................................................................254
37.3 Rev 2548D - 06/05 .............................................................................................255
37.4 Rev 2548C - 05/05 .............................................................................................255
37.5 Rev 2548B - 04/05 .............................................................................................255
Table of Contents....................................................................................... i
Atmel Corporation
1600 Techno logy Drive
San Jose, CA 95110
USA
Tel: (+1) (408) 441-0311
Fax: (+1) (408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-3 19 70 -0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kang yo Bldg
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81) (3) 6417-0300
Fax: (+81) (3) 6417-0370
© 2013 Atmel Corpo ration. All r ights reserved. / Rev.: 2548F–AVR–03/201 3
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is gr anted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representa ti on s or w arr ant ie s w it h resp ect to the accuracy or completeness o f the contents of this docum ent and reserves the right to make chan ges to sp ecificatio ns a nd pro ducts descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless spe c ifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
Atmel®, Atmel logo and combin ations the reof, Ena bling Unlimi ted Po ssibilit ies®, AVR®, and others are registered trademarks or trademarks of Atmel Corporation or
its subsidiaries. Other terms and product names may be trademarks of others.