ATmega406 - Preliminary

Features
• High Performance, Low Power AVR® 8-bit Microcontroller
• 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 and Data Memories
– 40K Bytes of In-System Self-Programmable Flash, Endurance: 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 Debugging
– Extensive On-chip Debug 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
Special Microcontroller Features
– Power-on Reset
– On-chip Voltage Regulator
– External and Internal Interrupt Sources
– Four Sleep Modes: Idle, Power-save, Power-down, and Power-off
Packages
– 48-pin LQFP
Operating Voltage: 4.0 - 25V
Maximum Withstand Voltage (High-voltage 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
1. Pin Configurations
Figure 1-1.
Pinout ATmega406.
48
47
46
45
44
43
42
41
40
39
38
37
NNI
NI
PI
PPI
VREFGND
VREF
NV
PV1
PV2
PV3
PV4
GND
Top View
36
35
34
33
32
31
30
29
28
27
26
25
1
2
3
4
5
6
7
8
9
10
11
12
PVT
OD
VFET
OC
OPC
BATT
PC0
GND
PD1
PD0 (T0)
PB7 (OC0B/PCINT15)
PB6 (OC0A/PCINT14)
RESET
XTAL1
XTAL2
GND
(TDO/PCINT8) PB0
(TDI/PCINT9) PB1
(TMS/PCINT10) PB2
(TCK/PCINT11) PB3
(PCINT12) PB4
(PCINT13) PB5
SCL
SDA
13
14
15
16
17
18
19
20
21
22
23
24
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
1.1
Disclaimer
Typical values contained in this datasheet are based on simulations and characterization of
other AVR microcontrollers manufactured on the same process technology. Min and Max values
will be available after the device is characterized.
2
ATmega406
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
PD1..0
PB7..0
PORTD (2)
PORTB (8)
XTAL1
Oscillator
Circuits /
Clock
Generation
XTAL2
Watchdog
Oscillator
VCC
RESET
OPC
OC
OD
FET
Control
Battery
Protection
PPI
NNI
PVT
PV4
PV3
PV2
PV1
NV
Wake-Up
Timer
JTAG
8 bit T/C0
Cell
Balancing
Flash
SRAM
16 bit T/C1
Voltage
ADC
EEPROM
Voltage
Reference
Watchdog
Timer
Power
Supervision
POR &
RESET
CPU
SGND
VREF
VREFGND
GND
BATT
VFET
VREG
Coulumb
Counter ADC
Charger
Detect
PI
NI
DATA BUS
Voltage
Regulator
TWI
PORTC (1)
PORTA (8)
PA3..0
SCL
SCA
PC0
PA7..0
The ATmega406 provides the following features: a Voltage Regulator, dedicated Battery Protection 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 regulated to a constant supply voltage of nominally 3.3 volts for the integrated logic and analog
functions.
The battery protection monitors the battery voltage and charge/discharge current to detect illegal
conditions and protect the battery from these when required. The illegal conditions are deep
under-voltage during discharging, short-circuit during discharging and over-current during charging and discharging.
3
2548F–AVR–03/2013
The integrated cell balancing FETs allow cell balancing algorithms to be implemented in
software.
The MCU provides the following features: 40K bytes 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-up Timer, an SM-Bus compliant TWI module, internal and external interrupts,
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 achieving throughputs up to ten times faster than conventional CISC microcontrollers.
The Idle mode stops the CPU while allowing the other chip function to continue functioning. The
Power-down mode allows the voltage regulator, battery protection, regulator current detection,
Watchdog Timer, and Wake-up Timer to operate, while disabling all other chip functions until the
next Interrupt or Hardware Reset. In Power-save mode, the Wake-up Timer and Coulomb Counter ADC continues to run.
The device is manufactured using Atmel’s high voltage high density non-volatile memory technology. 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 updated, providing true Read-While-Write operation. By combining
an 8-bit RISC CPU with In-System Self-Programmable Flash, fuel gauging ADCs, dedicated battery protection circuitry, 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.
4
ATmega406
2548F–AVR–03/2013
ATmega406
2.2
2.2.1
Pin Descriptions
VFET
High voltage supply pin. This pin is used as supply for the internal voltage regulator, described in
”Voltage Regulator” on page 114. In addition the voltage level on this pin is monitored by the battery protection circuit, for deep-under-voltage protection. For details, see ”Battery Protection” 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 regulator operation. For details, see ”Voltage Regulator” on page 114.
2.2.4
VREF
Internal Voltage Reference for external decoupling. For details, see ”Voltage Reference and
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-directional 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 pins are tri-stated when a reset condition becomes
active, even if the clock is not running.
Port A also serves the functions of various special features of the ATmega406 as listed in ”Alternate 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. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port B also serves the functions of various special features of the ATmega406 as listed in ”Alternate Functions of Port B” on page 70.
5
2548F–AVR–03/2013
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 ”Alternate 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 from external current sense resistor, used by the battery protection 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 General Purpose 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 generate 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.
6
ATmega406
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 documentation contains simple code examples that briefly show how to use various parts of
the device. These code examples assume that the part specific header file is included before
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details.
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”.
7
2548F–AVR–03/2013
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
Data Bus 8-bit
Flash
Program
Memory
Program
Counter
Status
and Control
32 x 8
General
Purpose
Registrers
Control Lines
Direct Addressing
Instruction
Decoder
Indirect Addressing
Instruction
Register
Interrupt
Unit
Watchdog
Timer
ALU
I/O Module1
I/O Module 2
Data
SRAM
I/O Module n
EEPROM
I/O Lines
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction 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.
8
ATmega406
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 typical ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program 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 calls, 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 regular 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 position. The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F. In addition, the 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 register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction Set” section for a detailed description.
9
2548F–AVR–03/2013
5.4
Status Register
The Status Register contains information about the result of the most recently executed arithmetic 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 interrupt. This must be handled by software.
5.4.1
SREG – AVR Status Register
The AVR Status Register – SREG – is defined as:
Bit
7
6
5
4
3
2
1
0
0x3F (0x5F)
I
T
H
S
V
N
Z
C
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
SREG
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt 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 the 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 destination for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
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 negative 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 result in an arithmetic or logic operation. See the ”AVR
Instruction Set” for detailed information.
10
ATmega406
2548F–AVR–03/2013
ATmega406
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the ”AVR Instruction 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 instruction set. In order to achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 5-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 5-2.
AVR CPU General Purpose Working Registers
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
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 data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
11
2548F–AVR–03/2013
5.5.1
The X-register, Y-register, and Z-register
The registers R26:R31 have some added functions to their general purpose usage. These registers 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
15
X-register
XH
7
XL
0
R27 (0x1B)
15
Y-register
YH
7
YL
0
0
7
0
R28 (0x1C)
15
ZH
7
0
R31 (0x1F)
0
R26 (0x1A)
R29 (0x1D)
Z-register
0
7
ZL
7
0
0
R30 (0x1E)
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic 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 Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the 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. The 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 incremented by two when
data is popped from the Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
12
ATmega406
2548F–AVR–03/2013
ATmega406
5.6.1
SPH and SPL – Stack Pointer Register
Bit
15
14
13
12
11
10
9
8
0x3E (0x5E)
SP15
SP14
SP13
SP12
SP11
SP10
SP9
SP8
SPH
0x3D (0x5D)
SP7
SP6
SP5
SP4
SP3
SP2
SP1
SP0
SPL
7
6
5
4
3
2
1
0
Read/Write
Initial Value
5.7
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
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
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 from 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 Harvard architecture and the fast-access 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
T1
T2
T3
T4
clkCPU
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
Figure 5-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination register.
Figure 5-5.
Single Cycle ALU Operation
T1
T2
T3
T4
clkCPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
13
2548F–AVR–03/2013
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 written logic one together with the Global Interrupt
Enable bit in the Status Register in order to enable the interrupt. Depending on the Program
Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12
are programmed. This feature improves software security. See the section ”Memory Programming” on page 195 for details.
The lowest addresses in the program 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 Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR). Refer to
”Interrupts” on page 51 for more information. The Reset Vector can also be moved to the start of
the Boot Flash section by programming the BOOTRST Fuse, see ”Boot Loader Support – ReadWhile-Write Self-Programming” on page 178.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. 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 automatically 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 corresponding interrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be
cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared,
the interrupt flag 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. These
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 served.
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
14
ATmega406
2548F–AVR–03/2013
ATmega406
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.
Assembly Code Example
in r16, SREG
cli
; store SREG value
; 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) */
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example.
Assembly Code Example
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) */
5.8.1
Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine
is executed. During this four clock cycle 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 by 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.
15
2548F–AVR–03/2013
6. AVR Memories
This section describes the different memories in the ATmega406. The AVR architecture 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 Counter (PC) is 15 bits wide, thus addressing the 20K program memory locations. The
operation of Boot Program section and associated Boot Lock bits for software protection are
described in detail in ”Boot Loader Support – Read-While-Write Self-Programming” on page
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 Timing” on page 13.
Figure 6-1.
Program Memory Map
Program Memory
0x0000
Application Flash Section
Boot Flash Section
0x4FFF
16
ATmega406
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/STD and LD/LDS/LDD instructions 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 Displacement, 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 mode reaches 63 address locations from the base address given
by the Y- or Z-register.
When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented.
The 32 general purpose working registers, 64 I/O Registers, 160 Extended I/O Registers, and
the 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 Memory Map
Data Memory
32 Registers
64 I/O Registers
160 Ext I/O Reg.
0x0000 - 0x001F
0x0020 - 0x005F
0x0060 - 0x00FF
0x0100
Internal SRAM
(2048 x 8)
0x08FF
17
2548F–AVR–03/2013
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 Figure 6-3.
Figure 6-3.
On-chip Data SRAM Access Cycles
T1
T2
T3
clkCPU
Address
Compute Address
Address valid
Write
Data
WR
Read
Data
RD
Memory Access Instruction
6.3
Next Instruction
EEPROM Data Memory
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 the user code contains instructions 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.
18
ATmega406
2548F–AVR–03/2013
ATmega406
6.3.2
EEARH and EEARL – The EEPROM Address Register
Bit
15
14
13
12
11
10
9
8
0x22 (0x42)
–
–
–
–
–
–
–
EEAR8
EEARH
0x21 (0x41)
EEAR7
EEAR6
EEAR5
EEAR4
EEAR3
EEAR2
EEAR1
EEAR0
EEARL
7
6
5
4
3
2
1
0
Read/Write
Initial Value
R
R
R
R
R
R
R
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
0
0
0
0
0
0
0
X
X
X
X
X
X
X
X
X
• 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
Bit
7
6
5
4
3
2
1
0
0x20 (0x40)
MSB
LSB
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
EEDR
• Bits 7:0 – EEDR7:0: EEPROM Data
For the EEPROM write operation, the EEDR Register contains the data to be written to the
EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the
EEDR contains the data read out from the EEPROM at the address given by EEAR.
6.3.4
EECR – The EEPROM Control Register
Bit
7
6
5
4
3
2
1
0
0x1F (0x3F)
–
–
EEPM1
EEPM0
EERIE
EEMPE
EEPE
EERE
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
EECR
• 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 triggered 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 Programming times for the different modes are 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.
19
2548F–AVR–03/2013
Table 6-1.
EEPROM Mode Bits
EEPM1
EEPM0
Programming
Time
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
–
Operation
Reserved for future use
• Bit 3 – EERIE: EEPROM Ready Interrupt Enable
Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set. Writing
EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant interrupt 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, otherwise 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 the Flash is never being updated by the CPU, step 2 can be omitted. See ”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.
20
ATmega406
2548F–AVR–03/2013
ATmega406
When the write access time has elapsed, the EEPE bit is cleared by hardware. The user software 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 read 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 accesses. Table 6-2 lists the typical programming time for EEPROM access from the CPU.
Table 6-2.
EEPROM Programming Time
Symbol
EEPROM write
(from CPU)
Number of Calibrated RC Oscillator Cycles
Typ Programming Time
26,368
3.3 ms
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 globally) so that no interrupts will occur during execution of these functions. The examples also
assume that no Flash Boot Loader is present in the software. If such code is present, the
EEPROM write function must also wait for any ongoing SPM command to finish.
21
2548F–AVR–03/2013
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);
}
The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of
these functions.
22
ATmega406
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;
}
23
2548F–AVR–03/2013
6.4
I/O Memory
The I/O space definition of the ATmega406 is shown 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/LDS/LDD and ST/STS/STD instructions, transferring data 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 instructions. 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 and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in
SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used.
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 cleared by writing a logical one to them. Note that, unlike most other
AVRs, the CBI and SBI instructions will only operate 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 General Purpose I/O Registers. These registers 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 bitaccessible using the SBI, CBI, SBIS, and SBIC instructions.
6.4.2
GPIOR2 – General Purpose I/O Register 2
Bit
6.4.3
5
4
3
2
1
0
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
LSB
5
4
3
2
1
GPIOR2
GPIOR1 – General Purpose I/O Register 1
7
6
0
0x2A (0x4A)
MSB
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
LSB
5
4
3
2
1
GPIOR1
GPIOR0 – General Purpose I/O Register 0
Bit
24
6
MSB
Bit
6.4.4
7
0x2B (0x4B)
7
6
0
0x1E (0x3E)
MSB
LSB
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
GPIOR0
ATmega406
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 reduce power consumption, the clocks to modules
not being used can be halted by using different sleep modes, as described in ”Power Management and Sleep Modes” on page 31. The clock systems are detailed below.
Figure 7-1.
Clock Distribution
CPU
CORE
RAM
FLASH and
EEPROM
clkFLASH
Voltage
ADC
Other I/O
Modules
Watchdog Timer
Battery Protection
& FET Control
clkTWI
clkI/O
AVR
Clock Control
clkCCADC
AVR
Clock Control
clkWUT
AVR
Clock Control
Reset Logic
0
Sync
Delay
1/4
Ultra Low Power
RC Oscillator
Wake-up
Timer
Coulomb Counter
ADC
clkVADC
clkCPU
TWI Disconnect
Delay
TWI
Fast RC
Oscillator
Clock
Multiplexer
1
Run-Time
Selection
1/4
Slow RC
Oscillator
32 kHz Crystal
Oscillator
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 Clock - clkTWI
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 TWI communication is not used. Note that address
match detection in the TWI 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 External Interrupt module, but note that some external interrupts are detected by asynchronous logic,
allowing such interrupts to be detected even if the I/O clock is halted.
7.1.4
Flash Clock – clkFLASH
The Flash clock controls operation of the Flash interface. The Flash clock is usually active simultaneously with the CPU clock.
25
2548F–AVR–03/2013
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 provided with a dedicated 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 utilizing an Ultra Low Power RC Oscillator dedicated to this purpose.
7.2
Clock Sources
The 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 clock, which is divided down to
1.0 MHz to all modules except the TWI. The frequency is nominal value at 25C. This clock 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 25C, 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 on the pre-programmed calibration value, see the section ”Calibration Bytes” on
page 198.
The start-up times for the Fast RC Oscillator are determined by the SUT Fuses as shown in
Table 7-1 on page 26.
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
Note:
26
Reserved
1. The device is shipped with this option selected.
ATmega406
2548F–AVR–03/2013
ATmega406
7.4
32 kHz Crystal Oscillator
XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier which can be configured 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 environment. For information on how to choose capacitors and other details on Oscillator operation,
refer to the 32 kHz Crystal Oscillator application note.
Figure 7-2.
32 kHz Crystal Oscillator Connections
C2
C1
XTAL2
XTAL1
GND
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 Oscillator failure. It can also be used as the only
Run-Time clock source in systems where the resulting 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 expense 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 provide 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, ensuring a stable clock before instruction execution starts. 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 timing this real-time part of the start-up time. Start-up times are determined by the SUT Fuses as
27
2548F–AVR–03/2013
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.
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
Table 7-3.
7.8
Reserved
Number of Ultra Low Power RC Oscillator Cycles
Typ Time-out
Number of Cycles
3.9 ms
500
62.5 ms
8000
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 power operation in sleep modes. The clock source is either the 32 kHz Crystal
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 Timer 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 functional, backup solution.
28
ATmega406
2548F–AVR–03/2013
ATmega406
7.11
7.11.1
Register Description
FOSCCAL – Fast RC Oscillator Calibration Register
Bit
(0x66)
Read/Write
7
6
5
4
3
2
1
0
FCAL7
FCAL6
FCAL5
FCAL4
FCAL3
FCAL2
FCAL1
FCAL0
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
FOSCCAL
Device Specific Calibration Value
• 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 process 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 oscillator can
be calibrated to any frequency in the range 3.7 - 4.0 MHz within ±1% accuracy. Calibration outside that range is not guaranteed.
Note that this oscillator is used to time EEPROM and Flash write accesses, 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 frequency 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 frequency in that range, and 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 frequency range 3.7 - 4.0 MHz.
7.11.2
CCSR – Clock Control and Status Register
Bit
7
6
5
4
3
2
1
0
(0xC0)
–
–
–
–
–
–
XOE
ACS
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
CCSR
• 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 stabilize, this must be timed by the user software. If the software
tries to write a one to ACS and a zero to XOE 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 .
29
2548F–AVR–03/2013
• Bit 0 - ACS: Asynchronous Clock 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.
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
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 interrupt with significantly
longer time-out, and checking that the Wake-up Timer time-out occurs 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).
30
ATmega406
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 various sleep modes allowing the user to tailor the power consumption 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 Power-off) will be activated by
the SLEEP instruction. See Table 8-1 for a summary. 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, executes the interrupt routine, and resumes 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 sleep mode, the MCU
wakes up and executes from the Reset Vector. The MCU will reset when returning from Poweroff mode.
Figure 7-1 on page 25 presents the different clock systems in the ATmega406, and their distribution. 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.
Bit
7
6
5
4
3
2
1
0
0x33 (0x53)
–
–
–
–
SM2
SM1
SM0
SE
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
SMCR
• 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 available sleep modes as shown in Table 8-1.
Table 8-1.
Note:
Sleep Mode Select
SM2
SM1
SM0
Sleep Mode
0
0
0
Idle
0
0
1
ADC Noise Reduction
0
1
0
Power-down
0
1
1
Power-save
1
0
0
Power-off(1)
1
0
1
Reserved
1
1
0
Reserved
1
1
1
Reserved
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.
31
2548F–AVR–03/2013
• 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 sleep mode unless it is the programmer’s
purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of
the SLEEP instruction and to clear it immediately after waking up.
8.1
Idle Mode
When the SM2:0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode,
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 triggered interrupts as well as internal ones like the Timer Overflow 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 Battery Protection (VBP), Wake-up on Regular Current (WURC), 32 kHz crystal
Oscillator (XOSC_32K) or Slow RC Oscillator (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 instruction makes the MCU enter Powersave mode. In this mode, the internal Fast RC Oscillator (RCOSC_FAST) is stopped, while
Wake-up Timer (WUT), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection (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 detection should be enabled to reduce power consumption. 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.
32
ATmega406
2548F–AVR–03/2013
ATmega406
8.4
Power-down Mode
When the SM2:0 bits are written to 010, the SLEEP instruction makes the MCU enter Powerdown mode. In this mode, the Fast RC Oscillator (RCOSC_FAST), 32 kHz Crystal Oscillator
(XOSC_32K), and Slow RC Oscillator (RCOSC_SLOW) are stopped, while the the Ultra Low
Power RC Oscillator (RCOSC_ULP), External Interrupts, the Battery Protection and the Watchdog 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. For 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 page 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 Charger Detect Circuitry to be operational. To ensure that the MCU enters Power-off mode only when 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. Otherwise interrupts may prevent the SLEEP instruction from being executed within the time limit.
Table 8-2.
Active modules in different Sleep Modes
Mode
Active
Idle
ADC
NRM
Powersave
Powerdown
RCOSC_FAST
X
X
X
RCOSC_ULP
X
X
X
X
X
XOSC_32K/
RCOSC_SLOW
X
X
X
X
CPU
X
Flash
X
8-bit Timer/16-bit Timer
X
X
SMBus
X
X
X(1)
X(1)
V-ADC
X
X
X
CC-ADC
X
X
X
X
External Interrupts
X
X
X
X
X
CBP(2)
X
X
X
X
X
VBP
X
X
X
X
X
WDT
X
X
X
X
X
Module
Poweroff
X(1)
33
2548F–AVR–03/2013
Table 8-2.
Active modules in different Sleep Modes (Continued)
Mode
Active
Idle
ADC
NRM
Powersave
WUT
X
X
X
X
VREG
X
X
X
X
Module
Powerdown
Poweroff
X
X
CHARGER_DETECT
Note:
X
1. Address Match and Bus Connect/Disconnect Wake-up only.
2. When Discharge-FET is switched off, Short-circuit Protection is automatically disabled to
reduce current consumption.
Table 8-3.
Wake-up Sources for Sleep Modes
X
X
X
X
ADC NRM
X
X
X
X
X
X
X
X
X
Power-save
X
X
X
X
X
X
X
X
X
X
Power-down
Power-off
Charger Connect
X
Other I/O
X
V-ADC
X
CC-ADC
X
SPM/EEPROM
Ready
X
WUT
Idle
Mode
WDT
Battery Protection
Interrupts
SMBus Address
Match and Bus
Connect/Disconnect
Wake-up on
Regular Current
External Interrupts
Wake-up sources
X
X
X
The sleep mode state diagram is shown in Figure 8-1.
34
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 8-1.
Sleep Mode State Diagram
Reset From all States
RESET
Reset Time-out
Interrupt
Sleep
Deep
Under-voltage
Interrupt
Sleep
Interrupt
ADC NRM
Interrupt
Active
Sleep
Sleep
Sleep or
Deep Under-voltage
Idle
Power-save
Deep
Under-voltage
Deep
Under-voltage
Power-down
Deep
Under-voltage
Power-off
Charger Connected
Regulator-on
35
2548F–AVR–03/2013
8.6
Power Reduction Register
The Power Reduction Register, PRR, provides a method to stop the clock to individual peripherals 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
6
5
4
3
2
1
0
(0x64)
–
–
–
–
PRTWI
PRTIM1
PRTIM0
PRVADC
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
PRR0
• Bit 7:4 - Res: Reserved 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.
36
ATmega406
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 possible 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. If the
Watchdog Timer is enabled, it will be enabled in all sleep modes except Power-off. The Watchdog 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 Sleep Modes” on page 64 for details on which pins are
enabled. If the input buffer is enabled and the input signal is left floating 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 current 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 the Battery Protection features is not needed by the application, this feature should be
disabled, see ”BPCR – Battery Protection Control Register” on page 128. When the 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 significant in Power-down mode.
8.7.5
Voltage ADC
If enabled, the V-ADC will consume power independent of sleep mode. To save power, the VADC 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.
37
2548F–AVR–03/2013
8.7.6
38
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-down sleep mode. See
”Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC” on page 106 for details on CCADC operation.
ATmega406
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 versa. The circuit diagram in Figure 9-1 shows the reset
logic.
The I/O ports of the AVR are immediately reset to their initial state when 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 regulator to reach a stable level before normal operation starts.
The time-out period of the delay counter is defined by the user through the SUT Fuses. The different selections for the delay period are presented in ”Clock Sources” on page 26.
9.2
Reset Sources
The ATmega406 has several reset sources:
• Power-on Reset. If the chip is in Power-off mode, the Charger Detect module generates a
reset pulse when a charger is connected.See ”Power-on Reset and Charger Connect” on page
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.
39
2548F–AVR–03/2013
Figure 9-1.
Reset Logic
DATA BUS
PORF
EXTRF
WDRF
JTRF
BODRF
MCU Status
Register (MCUSR)
VREG
Brown-out
Detection
Power-on
Reset
Circuit/
Charger
Detect
BATT
POR
VREG
Pull-up Resistor
RESET
SPIKE
FILTER
JTAG Reset
Register
Reset Circuit
Watchdog
Timer
COUNTER RESET
Ultra Low Power
RC Oscillator
Clock
Generator
Delay Counters
TIMEOUT
CK
SUT[1:0]
9.2.1
40
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. When the Delay Counter
times out, the chip will enter Active mode. Table 30-3 on page 230 shows the Power-on Reset
characteristics.
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 9-2.
Power-on Reset in Operation.
VCOT
VBATT
tTOUT
POR
TIMEOUT
INTERNAL_RESET
SLEEP_MODE
9.2.2
Power-off
Reset
Active
External Reset
An 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
FET
41
2548F–AVR–03/2013
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
FET
CK
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. The trigger level has a hysteresis 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 decreases to a value below the trigger level (VBOT- in Figure 9-5), the Brown-out 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
VREG
VBOT-
VBOT+
RESET
TIME-OUT
tTOUT
INTERNAL
RESET
42
ATmega406
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
Watchdog Timer
Ultra Low Power RC
OSCILLATOR
WATCHDOG
RESET
WDE
16ms
32ms
64ms
125ms
250ms
0.5s
1.0s
2.0s
4.0s
8.0s
Figure 9-6.
WDP0
WDP1
WDP2
WDP3
MCU RESET
WDIF
WDIE
INTERRUPT
The Watchdog Timer (WDT) is a timer counting cycles of the Ultra Low Power RC Oscillator that
runs at 128 kHz. The WDT gives an interrupt or a system reset when the counter reaches a
given time-out value. In normal operation mode, it is required that the system uses the WDR Watchdog Timer Reset - instruction to restart the counter before the time-out value is reached. If
the system doesn't restart the counter, an interrupt or system reset will be issued.
In Interrupt mode, the WDT gives an interrupt when the timer expires. This interrupt can be 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 expected. 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 interrupt 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 (WDTON) fuse, if programmed, will force the Watchdog Timer to System Reset mode. With the fuse programmed the System Reset mode bit (WDE) and Interrupt
mode bit (WDIE) are locked to 1 and 0 respectively. To further ensure program security, alterations to the Watchdog set-up must follow timed sequences. The sequence for clearing WDE and
changing time-out configuration is as follows:
43
2548F–AVR–03/2013
1. In the same operation, 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 Watchdog 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.
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();
}
Note:
44
1. See ”About Code Examples” on page 7.
ATmega406
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 the code is not
set up to handle the Watchdog, this might 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.
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();
}
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.
45
2548F–AVR–03/2013
9.4
9.4.1
Register Description
MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU reset.
Bit
7
6
5
4
3
2
1
0
0x34 (0x54)
–
–
–
JTRF
WDRF
BODRF
EXTRF
PORF
Read/Write
R
R
R
R/W
R/W
R/W
R/W
R/W
Initial Value
0
0
0
MCUSR
See Bit Description
• 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 early as possible in the program. If the register is cleared before another reset
occurs, the source of the reset can be found by examining the reset flags.
46
ATmega406
2548F–AVR–03/2013
ATmega406
9.4.2
WDTCSR – Watchdog Timer Control Register
Bit
7
6
5
4
3
2
1
0
(0x60)
WDIF
WDIE
WDP3
WDCE
WDE
WDP2
WDP1
WDP0
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
WDTCSR
• Bit 7 - WDIF: Watchdog Interrupt Flag
This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt
handling vector. Alternatively, WDIF is cleared by writing a logic one to the flag. When 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 Register is set, the Watchdog Interrupt is
enabled. If WDE is cleared in combination with this setting, the Watchdog Timer is in Interrupt
Mode, and the corresponding 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 useful for keeping the Watchdog Timer security while using the interrupt. To stay in Interrupt and
System Reset Mode, WDIE must be 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 System Reset will be applied.
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
0
1
1
Interrupt and System Reset
Mode
Interrupt, then go to System
Reset Mode
1
x
x
System Reset Mode
Reset
• 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.
47
2548F–AVR–03/2013
• 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 cleared first. This feature ensures multiple resets during conditions 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
1
0
1
0
1
0
1
1
1
1
0
0
1
1
0
1
1
1
1
0
1
1
1
1
Reserved
48
ATmega406
2548F–AVR–03/2013
ATmega406
10. Wake-up Timer
The following section describes the Wake-up Timer in the ATmega406.
•
•
•
•
10.1
One Wake-up Timer Interrupt
8 Selectable Time-out Periods
Separate Wake-up Timer Calibration Flag
Separate Clock Source
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 Timer prescaler, the Wake-up interval can be adjusted from 31.25 ms to 4 s. Eight different clock cycle periods can be selected to determine the Time-out period.
Figure 10-1. Wake-up Timer
32 kHz
OSCILLATOR
clkWUT
clkWUT/64
clkWUT/64K
clkWUT/128K
clkWUT/32K
clkWUT/8K
clkWUT/16K
1/4
clkWUT/4K
clkWUT/1K
SLOW RC
OSCILLATOR
clkWUT/2K
WAKE-UP
PRESCALER
WUTR
WUTP0
WUTP1
WUTP2
WUTE
WUTCF
WUTIF
10.2
10.2.1
Register Description
WUTCSR – Wake-up Timer Control and Status Register
Bit
7
6
5
4
3
2
1
0
WUTIF
WUTIE
WUTCF
WUTR
WUTE
WUTP2
WUTP1
WUTP0
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
(0x62)
WUTCSR
• Bit 7 – WUTIF: Wake-up Timer Interrupt Flag
The WUTIF bit is set (one) when an overflow occurs in the Wake-up Timer. WUTIF is cleared 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.
49
2548F–AVR–03/2013
• 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 interrupt is enabled. The corresponding interrupt is executed if a Wake-up Timer overflow occurs,
i.e., when the WUTIF 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 Oscillator 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 reset, and starts counting from 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 values and their corresponding time-out
periods are shown in Table 10-1. The Wake-up Timer should always be reset when changing
these bits.
Table 10-1.
50
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)
1s
1
1
0
256K(262144)
64K(65536)
2s
1
1
1
512K(524288)
128K(131072)
4s
ATmega406
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
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
Store Program Memory Ready
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
51
2548F–AVR–03/2013
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 versa.
Table 11-2.
Reset and Interrupt Vectors Placement(1)
BOOTRST
IVSEL
1
Note:
Reset Address
Interrupt Vectors Start Address
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
1. The Boot Reset Address is shown in Table 27-7 on page 193. 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:
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
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
0x0033
<instr>
xxx
...
...
0x0034
RESET:
...
; Enable interrupts
;
52
ATmega406
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 Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector
Addresses is:
Address Labels
0x0000
RESET:
Code
Comments
ldi
r16,high(RAMEND); Main program start
0x0001
out
SPH,r16
0x0002
ldi
r16,low(RAMEND)
0x0003
0x0004
out
sei
SPL,r16
0x0005
<instr>
; Set Stack Pointer to top of RAM
; Enable interrupts
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 programmed and the Boot section size set to 2K bytes, the most typical and general 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
0x4C02
ldi
r16,low(RAMEND)
0x4C03
0x4C04
out
sei
SPL,r16
0x4C05
<instr>
; Set Stack Pointer to top of RAM
; Enable interrupts
xxx
When the BOOTRST Fuse is programmed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register
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
;
.org 0x4C00
0x4C00
0x4C02
jmp
jmp
RESET
BPINT
; Reset handler
; Battery Protection Interrupt Handler
0x4C04
jmp
EXT_INT0
; External Interrupt Request 0 Handler
...
...
...
;
0x4C2C
jmp
SPM_RDY
; Store Program Memory Ready Handler
ldi
r16,high(RAMEND); Main program start
;
0x4C2E
RESET:
53
2548F–AVR–03/2013
0x4C2F
out
SPH,r16
0x4C30
ldi
r16,low(RAMEND)
0x4C31
0x4C32
out
sei
SPL,r16
0x4C33
<instr>
11.2
; Set Stack Pointer to top of RAM
; Enable interrupts
xxx
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);
}
54
ATmega406
2548F–AVR–03/2013
ATmega406
11.3
11.3.1
Register Description
MCUCR – MCU Control Register
Bit
7
6
5
4
3
2
1
0
0x35 (0x55)
JTD
–
–
PUD
–
–
IVSEL
IVCE
Read/Write
R/W
R
R
R/W
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
MCUCR
• 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 address of the start of the Boot Flash Section is determined by the BOOTSZ Fuses. Refer to the section ”Boot Loader Support – Read-While-Write
Self-Programming” on page 178 for details. To avoid unintentional changes of Interrupt Vector
tables, a special write procedure must be followed to change the IVSEL bit:
a. Write the Interrupt 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 programmed, interrupts are disabled while executing from the Application section. If Interrupt Vectors
are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled 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 above. See Code Example below.
55
2548F–AVR–03/2013
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 generating 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 Register – 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 25C. The MCU will wake up if the input has the
required level during this sampling or if it is held until the end of the start-up time. The start-up
time is defined by the SUT fuses as described in ”System Clock and Clock Options” on page 25.
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 level interrupt.
12.2
12.2.1
Register Description
EICRA – External Interrupt Control Register A
Bit
7
6
5
4
3
2
1
0
ISC31
ISC30
ISC21
ISC20
ISC11
ISC10
ISC01
ISC00
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
(0x69)
EICRA
• 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
corresponding interrupt mask in the EIMSK is set. The level and edges on the external pins that
activate the interrupts are defined in Table 12-1 on page 57. Edges on INT3:INT0 are registered
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 interrupt. 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 Register before the interrupt is re-enabled.
56
ATmega406
2548F–AVR–03/2013
ATmega406
Table 12-1.
Description(1)
ISCn1
ISCn0
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.
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.
Table 12-2.
Symbol
tINT
12.2.2
Interrupt Sense Control
Asynchronous External Interrupt Characteristics
Parameter
Condition
Min
Typ
Minimum pulse width for asynchronous
external interrupt
Max
50
Units
ns
EIMSK – External Interrupt Mask Register
Bit
7
6
5
4
3
2
1
0
0x1D (0x3D)
–
–
–
–
INT3
INT2
INT1
INT0
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
EIMSK
• 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 Interrupt Request 3 - 0 Enable
When an INT3 – INT0 bit is written to one and the I-bit in the Status Register (SREG) is set
(one), the corresponding external pin interrupt is enabled. The Interrupt Sense Control bits in the
External Interrupt Control Register – EICRA – defines whether the external interrupt 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 way of generating a software
interrupt.
12.2.3
EIFR – External Interrupt Flag Register
Bit
7
6
5
4
3
2
1
0
0x1C (0x3C)
–
–
–
–
INTF3
INTF2
INTF1
INTF0
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
EIFR
• 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 Interrupt Flags 3 - 0
When an edge or logic change on the INT3:0 pin triggers an interrupt request, INTF3:0 becomes
set (one). If the I-bit in SREG and the corresponding interrupt enable bit, INT3:0 in EIMSK, are
57
2548F–AVR–03/2013
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
6
5
4
3
2
1
0
(0x68)
–
–
–
–
–
–
PCIE1
PCIE0
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
PCICR
• 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 interrupt. The corresponding interrupt of Pin Change Interrupt 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 Interrupt Vector. PCINT7:0 pins are enabled individually by the PCMSK0 Register.
12.2.5
PCIFR – Pin Change Interrupt Flag Register
Bit
7
6
5
4
3
2
1
0
0x1B (0x3B)
–
–
–
–
–
–
PCIF1
PCIF0
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
PCIFR
• 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. Alternatively, 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
58
ATmega406
2548F–AVR–03/2013
ATmega406
corresponding 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.
12.2.6
PCMSK1 – Pin Change Mask Register 1
Bit
7
6
5
4
3
2
1
0
PCINT15
PCINT14
PCINT13
PCINT12
PCINT11
PCINT10
PCINT9
PCINT8
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
(0x6C)
PCMSK1
• 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
6
5
4
3
2
1
0
(0x6B)
PCINT7
PCINT6
PCINT5
PCINT4
PCINT3
PCINT2
PCINT1
PCINT0
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
PCMSK0
• 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 corresponding I/O pin. If PCINT7:0 is cleared, pin change interrupt on the corresponding I/O pin is
disabled.
59
2548F–AVR–03/2013
13. Low Voltage I/O-Ports
13.1
Introduction
All low voltage AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally
changing the direction of any other pin with the SBI and CBI instructions. The same applies
when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if
configured as input). All low voltage port pins have individually selectable pull-up resistors with a
supply-voltage invariant resistance. All I/O pins have protection diodes to both 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
Rpu
Logic
Pxn
Cpin
See Figure
"General Digital I/O" for
Details
All registers and bit references in this section are written in general form. A lower case “x” represents the numbering letter for the port, and a lower case “n” represents the bit number. However,
when using the register or bit defines in a program, the precise form must be used. For example,
PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in ”Register Description” on page 73.
Three I/O memory address locations are allocated 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 read only, while the Data Register and the Data Direction 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 voltage pins in all ports when set.
Using the I/O port as General 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 alternate functions for the
peripheral features on the device. How each alternate function interferes 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 functions.
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.
60
ATmega406
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)
PUD
Q
D
DDxn
Q CLR
WDx
RESET
1
Q
Pxn
D
0
PORTxn
Q CLR
WPx
DATA BUS
RDx
RESET
WRx
SLEEP
RRx
SYNCHRONIZER
D
Q
L
Q
D
RPx
Q
PINxn
Q
clk I/O
PUD:
SLEEP:
clkI/O:
Note:
13.2.1
PULLUP DISABLE
SLEEP CONTROL
I/O CLOCK
WDx:
RDx:
WRx:
RRx:
RPx:
WPx:
WRITE DDRx
READ DDRx
WRITE PORTx
READ PORTx REGISTER
READ PORTx PIN
WRITE PINx REGISTER
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.
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 pin has to
be configured as an output pin. The port pins are tri-stated when reset condition becomes active,
even if no clocks are running.
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).
61
2548F–AVR–03/2013
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 acceptable, 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.
Table 13-1.
13.2.4
62
Port Pin Configurations
DDxn
PORTxn
PUD
(in MCUCR)
I/O
Pull-up
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)
Comment
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 Figure 13-2, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value
near the edge of the internal clock, but it also introduces a delay. Figure 13-3 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and
minimum propagation delays are denoted tpd,max and tpd,min respectively.
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 13-3. Synchronization when Reading an Externally Applied Pin value
SYSTEM CLK
INSTRUCTIONS
XXX
XXX
in r17, PINx
SYNC LATCH
PINxn
r17
0x00
0xFF
t pd, max
t pd, min
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 indicated 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 indicated 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
SYSTEM CLK
r16
INSTRUCTIONS
0xFF
out PORTx, r16
nop
in r17, PINx
SYNC LATCH
PINxn
r17
0x00
0xFF
t pd
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.
63
2548F–AVR–03/2013
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;
...
Note:
13.2.5
1. For the assembly program, two temporary registers are used to minimize the time from pullups 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.
Digital Input Enable and Sleep Modes
As shown in Figure 13-2, the digital input 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 signals 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 interrupt
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.
64
ATmega406
2548F–AVR–03/2013
ATmega406
13.2.6
Unconnected Pins
If some pins are unused, it is recommended to ensure that these pins have a defined level. Even
though most of the digital inputs are disabled in the deep sleep modes as described above, floating 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 external pull-up or pull-down. Connecting unused pins
directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is
accidentally configured as an output.
65
2548F–AVR–03/2013
13.3
Alternate Port Functions
Many low voltage port pins have alternate functions in addition to being general digital I/Os. Figure 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 not be present in all port pins, but
the figure serves as a generic description applicable to all port pins in the AVR microcontroller
family.
Figure 13-5. Alternate Port Functions(1)
PUOExn
PUOVxn
1
PUD
0
DDOExn
DDOVxn
1
Q
D
DDxn
0
Q CLR
WDx
PVOExn
RESET
RDx
1
1
Pxn
Q
0
D
0
PORTxn
PTOExn
Q CLR
DIEOExn
DATA BUS
PVOVxn
WPx
DIEOVxn
RESET
WRx
1
0
RRx
SLEEP
SYNCHRONIZER
D
SET
Q
D
RPx
Q
PINxn
L
CLR
Q
CLR
Q
clk I/O
DIxn
AIOxn
PUOExn:
PUOVxn:
DDOExn:
DDOVxn:
PVOExn:
PVOVxn:
DIEOExn:
DIEOVxn:
SLEEP:
PTOExn:
Note:
66
Pxn PULL-UP OVERRIDE ENABLE
Pxn PULL-UP OVERRIDE VALUE
Pxn DATA DIRECTION OVERRIDE ENABLE
Pxn DATA DIRECTION OVERRIDE VALUE
Pxn PORT VALUE OVERRIDE ENABLE
Pxn PORT VALUE OVERRIDE VALUE
Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE
Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE
SLEEP CONTROL
Pxn, PORT TOGGLE OVERRIDE ENABLE
PUD:
WDx:
RDx:
RRx:
WRx:
RPx:
WPx:
clkI/O:
DIxn:
AIOxn:
PULLUP DISABLE
WRITE DDRx
READ DDRx
READ PORTx REGISTER
WRITE PORTx
READ PORTx PIN
WRITE PINx
I/O CLOCK
DIGITAL INPUT PIN n ON PORTx
ANALOG INPUT/OUTPUT PIN n ON PORTx
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.
ATmega406
2548F–AVR–03/2013
ATmega406
Table 13-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 13-5 are not shown in the succeeding tables. The overriding signals are generated internally
in the modules having the alternate function.
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 enabled 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 Direction
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 Direction
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 Digital Input Enable
is determined by MCU state (Normal mode, sleep mode).
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 bidirectionally.
The following subsections shortly describe the alternate functions for each port, and relate the
overriding signals to the alternate function. Refer to the alternate function description for further
details.
67
2548F–AVR–03/2013
13.3.1
Alternate Functions of Port A
The Port A has an alternate function as input pins to the Voltage ADC.
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)
The alternate pin configuration 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 Change 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 Change Interrupt Sources 3:0. The PA3:0 pins can serve as external
interrupt sources to the MCU.
68
ATmega406
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
PUOE
0
0
0
0
PUOV
0
0
0
0
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
PUOE
0
0
0
0
PUOV
0
0
0
0
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 INPUT
ADC0 INPUT
69
2548F–AVR–03/2013
13.3.2
Alternate Functions of Port B
The Port B pins with alternate functions are shown in Table 13-6.
Table 13-6.
Port Pin
Port B Pins Alternate Functions
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)
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 the
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 output 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 the
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 output 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 Interrupt Source 13:12. The PB5:4 pinS can serve as external
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.
70
ATmega406
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 not 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 Register or Data
Register (scan chains). When the JTAG Interface is enabled, 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: Serial output data from Instruction Register or Data Register.
When the JTAG Interface is enabled, 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
PUOE
0
0
0
0
PUOV
0
0
0
0
DDOE
0
0
0
0
DDOV
0
0
0
0
PVOE
OC0B Enable
OC0A Enable
0
PVOV
OC0B
OC0A
0
PTOE
–
–
–
–
DIEOE
0
0
0
0
DIEOV
0
0
0
0
DI
PCINT15 INPUT
PCINT14 INPUT
PCINT13 INPUT
PCINT12 INPUT
AIO
–
–
–
–
71
2548F–AVR–03/2013
.
Table 13-8.
13.3.3
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
PUOV
1
1
1
0
DDOE
JTAGEN
JTAGEN
JTAGEN
JTAGEN
DDOV
0
0
0
SHIFT_IR + SHIFT_DR
PVOE
0
0
0
JTAGEN
PVOV
0
0
0
TDO
PTOE
–
–
–
–
DIEOE
JTAGEN
JTAGEN
JTAGEN
JTAGEN
DIEOV
0
0
0
0
DI
TCK/PCINT11
INPUT
TMS/PCINT10
INPUT
TDI/PCINT9
INPUT
PCINT8
INPUT
AIO
–
–
–
–
Alternate Functions of Port D
The Port D pins with alternate functions are shown in Table 13-9.
Table 13-9.
Port Pin
PD0
Port D Pins Alternate Functions
Alternate Function
T0 (Timer/Counter0 Clock Input)
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.
72
ATmega406
2548F–AVR–03/2013
ATmega406
Table 13-10. Overriding Signals for Alternate Functions in PD1:PD0
13.4
13.4.1
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
–
–
Register Description
MCUCR – MCU Control Register
Bit
7
6
5
4
3
2
1
0
0x35 (0x55)
JTD
–
–
PUD
–
–
IVSEL
IVCE
Read/Write
R/W
R
R
R/W
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
MCUCR
• 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 ”Configuring the Pin” on page 61 for more details about this feature.
13.4.2
PORTA – Port A Data Register
Bit
13.4.3
7
6
5
4
3
2
1
0
0x02 (0x22)
PORTA7
PORTA6
PORTA5
PORTA4
PORTA3
PORTA2
PORTA1
PORTA0
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
DDRA – Port A Data Direction Register
Bit
13.4.4
PORTA
7
6
5
4
3
2
1
0
0x01 (0x21)
DDA7
DDA6
DDA5
DDA4
DDA3
DDA2
DDA1
DDA0
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
DDRA
PINA – Port A Input Pins Address
Bit
7
6
5
4
3
2
1
0
0x00 (0x20)
PINA7
PINA6
PINA5
PINA4
PINA3
PINA2
PINA1
PINA0
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
PINA
73
2548F–AVR–03/2013
13.4.5
PORTB – Port B Data Register
Bit
13.4.6
7
6
5
4
3
2
1
0
0x05 (0x25)
PORTB7
PORTB6
PORTB5
PORTB4
PORTB3
PORTB2
PORTB1
PORTB0
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
DDRB – Port B Data Direction Register
Bit
13.4.7
7
6
5
4
3
2
1
0
0x04 (0x24)
DDB7
DDB6
DDB5
DDB4
DDB3
DDB2
DDB1
DDB0
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
13.4.9
13.4.10
74
DDRB
PINB – Port B Input Pins Address
Bit
13.4.8
PORTB
7
6
5
4
3
2
1
0
0x03 (0x23)
PINB7
PINB6
PINB5
PINB4
PINB3
PINB2
PINB1
PINB0
Read/Write
R
R
R
R
R
R
R
R
Initial Value
N/A
N/A
N/A
N/A
N/A
N/A
N/A
N/A
PINB
PORTD – Port D Data Register
Bit
7
6
5
4
3
2
1
0
0x0B (0x2B)
–
–
–
–
–
–
PORTD1
PORTD0
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
PORTD
DDRD – Port D Data Direction Register
Bit
7
6
5
4
3
2
1
0
0x0A (0x2A)
–
–
–
–
–
–
DDD1
DDD0
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
DDRD
PIND – Port D Input Pins Address
Bit
7
6
5
4
3
2
1
0
0x09 (0x29)
–
–
–
–
–
–
PIND1
PIND0
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
N/A
N/A
PIND
ATmega406
2548F–AVR–03/2013
ATmega406
14. High Voltage I/O Ports
All high voltage AVR ports have true Read-Modify-Write functionality when used as general digital 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 diodes to Ground as indicated in Figure 14-1. See ”Electrical Characteristics” on page 225 for a complete list of parameters.
Figure 14-1. High Voltage I/O Pin Equivalent Schematic
Logic
Pxn
Cpin
See Figure
"General High Voltage
Digital I/O" for Details
All registers and bit references in this section are written in general form. A lower case “x” represents the numbering letter for the port, and a lower case “n” represents the bit number. However,
when using the register or bit defines in a program, the precise form must be used. For example,
PORTC3 for bit number three in Port C, here documented generally as 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 Digital Outputs” on page 75.
14.1
High Voltage Ports as General Digital Outputs
The high voltage ports are high voltage tolerant open collector output ports. Figure 14-2 shows a
functional description of one output port pin, here generically called Pxn.
75
2548F–AVR–03/2013
Figure 14-2. General High Voltage Digital I/O(1)
Pxn
Q
D
PORTxn
Q CLR
WRx
RESET
WRx:
RRx:
Note:
14.2
DATA BUS
RRx
WRITE PORTx
READ PORTx REGISTER
1. WRx and RRx are common to all pins within the same port.
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 are tri-stated when a reset condition becomes active, even if no clocks
are running.
14.3
14.3.1
76
Register Description for High Voltage Output Ports
PORTC – Port C Data Register
Bit
7
0x08 (0x28)
–
6
5
4
3
2
1
0
Read/Write
R
R
R
R
R
R
R
R/W
Initial Value
0
0
0
0
0
0
0
0
PORTC0
PORTC
ATmega406
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 program execution timing (event management) and wave generation. The main features are:
•
•
•
•
•
•
•
15.1
Two Independent Output Compare Units
Double Buffered Output Compare Registers
Clear Timer on Compare Match (Auto Reload)
Glitch Free, Phase Correct Pulse Width Modulator (PWM)
Variable PWM Period
Frequency Generator
Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B)
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 bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations 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 Diagram
Count
Clear
Direction
TOVn
(Int.Req.)
Control Logic
clkTn
TOSC1
T/C
Oscillator
TOP
BOTTOM
TOSC2
Prescaler
clkI/O
Timer/Counter
TCNTn
=
=0
OCnA
(Int.Req.)
Waveform
Generation
=
OCnA
DATA BUS
OCRnA
Fixed
TOP
Value
Waveform
Generation
=
OCnB
OCRnB
TCCRnA
15.1.1
OCnB
(Int.Req.)
TCCRnB
Definitions
Many register and bit references in this section are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Compare 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.
77
2548F–AVR–03/2013
The definitions in Table 15-1 are also used extensively throughout the document.
Table 15-1.
15.1.2
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 the
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 dependent on the mode of operation.
Registers
The 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 (TIFR0). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/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 Generator 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 Register (TCCR0B). For details on clock sources and prescaler, 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
TOVn
(Int.Req.)
DATA BUS
Clock Select
count
TCNTn
clear
Control Logic
clkTn
Edge
Detector
Tn
direction
( From Prescaler )
bottom
top
Signal description (internal signals):
78
ATmega406
2548F–AVR–03/2013
ATmega406
count
Increment or decrement TCNT0 by 1.
direction
Select between increment and decrement.
clear
Clear TCNT0 (set all bits to zero).
clkTn
Timer/Counter clock, referred to as clkT0 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 internal 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 priority 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 mode of operation selected 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 comparator signals a
match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock
cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output
Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing 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 Compare 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.
79
2548F–AVR–03/2013
Figure 15-3. Output Compare Unit, Block Diagram
DATA BUS
OCRnx
TCNTn
= (8-bit Comparator )
OCFnx (Int.Req.)
top
bottom
Waveform Generator
OCnx
FOCn
WGMn1:0
COMnx1:0
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) modes of operation, the double buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare
Registers to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR0x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is disabled 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 initialized to the same value as TCNT0 without triggering an interrupt when the Timer/Counter 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 using 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 counter 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-
80
ATmega406
2548F–AVR–03/2013
ATmega406
pare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even 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 have two functions. The Waveform 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 Registers, I/O bits, and I/O
pins in the figure 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
COMnx1
COMnx0
FOCn
Waveform
Generator
D
Q
1
OCnx
DATA BUS
D
0
OCnx
Pin
Q
PORT
D
Q
DDR
clk I/O
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 output) 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 visible on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin logic allows initialization of the OC0x state before the output 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 the COM0x1:0 bits differently in Normal, CTC, and PWM modes.
For all modes, setting the COM0x1:0 = 0 tells the Waveform Generator that no action on the
OC0x Register is to be performed on the next compare match. For compare output actions in the
non-PWM modes refer to Table 15-2 on page 88. For fast PWM mode, refer to Table 15-3 on
page 88, and for phase correct PWM refer to Table 15-4 on page 89.
81
2548F–AVR–03/2013
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 combination of the Waveform Generation mode (WGM02:0) and Compare Output
mode (COM0x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM0x1:0 bits control whether the PWM output 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 bottom (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. However, 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 generate interrupts at some given time. Using the Output 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 mode allows greater control of the compare match output frequency. It
also simplifies the operation of counting external events.
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.
82
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 15-5. CTC Mode, Timing Diagram
OCnx Interrupt Flag Set
TCNTn
OCn
(Toggle)
Period
(COMnx1:0 = 1)
1
2
3
4
An interrupt can be generated 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 running with none or a low prescaler 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 toggle its logical
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:
f clk_I/O
f OCnx = -------------------------------------------------2  N   1 + OCRnx 
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, 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 frequency 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 BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7. In noninverting 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 output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the
operating frequency of the fast PWM mode can be twice as high as the phase correct 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 physically 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
83
2548F–AVR–03/2013
PWM mode is shown in Figure 15-6. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-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-6. Fast PWM Mode, Timing Diagram
OCRnx Interrupt Flag Set
OCRnx Update and
TOVn Interrupt Flag Set
TCNTn
OCn
(COMnx1:0 = 2)
OCn
(COMnx1:0 = 3)
Period
1
2
3
4
5
6
7
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value.
In fast 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 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 available
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 for the port pin is set as output. The PWM waveform is generated 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:
f clk_I/O
f OCnxPWM = -----------------N  256
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represents special cases when generating a PWM
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) waveform output in fast PWM mode can be achieved by setting 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
84
ATmega406
2548F–AVR–03/2013
ATmega406
feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Output 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 counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM. TOP is defined as 0xFF when WGM2:0 = 1, and OCR0A when WGM2:0 = 5. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the compare match
between TCNT0 and OCR0x while upcounting, and set on the compare match while downcounting. 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 symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
In phase correct PWM mode the counter is incremented until the counter value 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 for the phase correct PWM mode is shown
on Figure 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, Timing Diagram
OCnx Interrupt Flag Set
OCRnx Update
TOVn Interrupt Flag Set
TCNTn
OCnx
(COMnx1:0 = 2)
OCnx
(COMnx1:0 = 3)
Period
1
2
3
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches 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
85
2548F–AVR–03/2013
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 for the port pin is set as output. The PWM waveform is
generated by clearing (or setting) the OC0x Register at the compare match 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:
f clk_I/O
f OCnxPCPWM = -----------------N  510
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR0A 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 OCnx has a transition from high to low even though
there is no Compare Match. The point of this transition is to guarantee symmetry around BOTTOM. 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 upcounting 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
clkI/O
clkTn
(clkI/O /1)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 15-9 shows the same timing data, but with the prescaler enabled.
86
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 15-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O /8)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
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)
clkI/O
clkTn
(clkI/O /8)
TCNTn
OCRnx - 1
OCRnx
OCRnx + 1
OCRnx + 2
OCRnx Value
OCRnx
OCFnx
Figure 15-11 shows the setting of OCF0A 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 Match mode, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O /8)
TCNTn
(CTC)
OCRnx
TOP - 1
TOP
BOTTOM
BOTTOM + 1
TOP
OCFnx
87
2548F–AVR–03/2013
15.8
8-bit Timer/Counter Register Description
15.8.1
TCCR0A – Timer/Counter Control Register A
Bit
7
6
5
4
3
2
1
0
0x24 (0x44)
COM0A1
COM0A0
COM0B1
COM0B0
–
–
WGM01
WGM00
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
TCCR0A
• 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 functionality 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-2.
Compare Output Mode, non-PWM Mode
COM0A1
COM0A0
Description
0
0
Normal port operation, OC0A disconnected.
0
1
Toggle OC0A on Compare Match
1
0
Clear OC0A on Compare Match
1
1
Set OC0A on Compare Match
Table 15-3 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM
mode.
Table 15-3.
COM0A1
COM0A0
0
0
Normal port operation, OC0A disconnected.
0
1
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
Note:
88
Compare Output Mode, Fast PWM Mode(1)
Description
1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See ”Fast PWM Mode” on page 83
for more details.
ATmega406
2548F–AVR–03/2013
ATmega406
Table 15-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode.
Table 15-4.
Compare Output Mode, Phase Correct PWM Mode(1)
COM0A1
COM0A0
0
0
Normal port operation, OC0A disconnected.
0
1
WGM02 = 0: Normal Port Operation, OC0A Disconnected.
WGM02 = 1: Toggle OC0A on Compare Match.
1
0
Clear OC0A on Compare Match when up-counting. Set OC0A on
Compare Match when down-counting.
1
1
Set OC0A on Compare Match when up-counting. Clear OC0A on
Compare Match when down-counting.
Note:
Description
1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare 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 functionality 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-5.
Compare Output Mode, non-PWM Mode
COM0B1
COM0B0
Description
0
0
Normal port operation, OC0B disconnected.
0
1
Toggle OC0B on Compare Match
1
0
Clear OC0B on Compare Match
1
1
Set OC0B on Compare Match
Table 15-6 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM
mode.
Table 15-6.
Compare Output Mode, Fast PWM Mode(1)
COM0B1
COM0B0
0
0
Normal port operation, OC0B disconnected.
0
1
Reserved
1
0
Clear OC0B on Compare Match, set OC0B at TOP
1
1
Set OC0B on Compare Match, clear OC0B at TOP
Note:
Description
1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See ”Fast PWM Mode” on page 83
for more details.
89
2548F–AVR–03/2013
Table 15-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode.
Compare Output Mode, Phase Correct PWM Mode(1)
Table 15-7.
COM0B1
COM0B0
0
0
Normal port operation, OC0B disconnected.
0
1
Reserved
1
0
Clear OC0B on Compare Match when up-counting. Set OC0B on
Compare Match when down-counting.
1
1
Set OC0B on Compare Match when up-counting. Clear OC0B on
Compare Match when down-counting.
Note:
Description
1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare 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 waveform generation to be used, see Table 15-8. Modes of operation supported by the Timer/Counter
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).
Table 15-8.
Timer/Counter
Mode of Operation
TOP
Update of
OCRx at
TOV Flag
Set on(1)(2)
0
Normal
0xFF
Immediate
MAX
0
1
PWM, Phase Correct
0xFF
TOP
BOTTOM
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
Mode
WGM02
WGM01
WGM00
0
0
0
1
0
2
Notes:
90
Waveform Generation Mode Bit Description
1. MAX
= 0xFF
2. BOTTOM = 0x00
ATmega406
2548F–AVR–03/2013
ATmega406
15.8.2
TCCR0B – Timer/Counter Control Register B
Bit
7
6
5
4
3
2
1
0
0x25 (0x45)
FOC0A
FOC0B
–
–
WGM02
CS02
CS01
CS00
Read/Write
W
W
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TCCR0B
• 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 that 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 as 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 that 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 as 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 description 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.
91
2548F–AVR–03/2013
Table 15-9.
Clock Select Bit Description
Description
CS02
CS01
CS00
0
0
0
No clock source (Timer/Counter stopped)
0
0
1
clkI/O/(No prescaling)
0
1
0
clkI/O/8 (From prescaler)
0
1
1
clkI/O/64 (From prescaler)
1
0
0
clkI/O/256 (From prescaler)
1
0
1
clkI/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.
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
Bit
7
6
5
0x26 (0x46)
4
3
2
1
0
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
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 the following timer clock. Modifying 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
Bit
7
6
5
0x27 (0x47)
4
3
2
1
0
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
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
Bit
7
6
5
0x28 (0x48)
4
3
2
1
0
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
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.
92
ATmega406
2548F–AVR–03/2013
ATmega406
15.8.6
TIMSK0 – Timer/Counter Interrupt Mask Register 0
Bit
7
6
5
4
3
2
1
0
(0x6E)
–
–
–
–
–
OCIE0B
OCIE0A
TOIE0
Read/Write
R
R
R
R
R
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TIMSK0
• 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 interrupt is enabled. The corresponding 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/Counter0 Compare Match A interrupt is enabled. The corresponding interrupt is executed
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 Interrupt Flag Register – TIFR0.
93
2548F–AVR–03/2013
15.8.7
TIFR0 – Timer/Counter 0 Interrupt Flag Register
Bit
7
6
5
4
3
2
1
0
0x15 (0x35)
–
–
–
–
–
OCF0B
OCF0A
TOV0
Read/Write
R
R
R
R
R
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TIFR0
• 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 Compare B Match Flag
The OCF0B bit is set when a Compare Match occurs between the Timer/Counter and the data in
OCR0B – Output Compare Register0 B. OCF0B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0B is cleared 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 corresponding interrupt handling vector. Alternatively, OCF0A is cleared by writing a logic one 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 WGM02:0 bit setting. Refer to Table 15-8, ”Waveform
Generation Mode Bit Description” on page 90.
94
ATmega406
2548F–AVR–03/2013
ATmega406
16. 16-bit Timer/Counter1
The 16-bit Timer/Counter unit allows accurate program execution timing (event management).
The main features 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 register 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 accessible
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
TOVn
(Int.Req.)
Count
Clear
Control Logic
clkTn
OCFnA
(Int.Req.)
DATA BUS
Timer/Counter
TCNTn
=0xFFFF
=
OCRnA
TCCRnB
16.1.1
Registers
The Timer/Counter (TCNT1) and the Output Compare Register (OCR1A) are both 16-bit registers. 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 restrictions. 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 increment 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 (clkT1).
95
2548F–AVR–03/2013
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 generate 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 for 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 register is read by the CPU, the high byte of the 16-bit 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 timer 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.
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;
...
Note:
1. See ”About Code Examples” on page 7.
The assembly code example 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
96
ATmega406
2548F–AVR–03/2013
ATmega406
updates the temporary register by accessing the same or any other of the 16-bit timer registers,
then the result of the access outside 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 during the 16-bit access.
The following code examples show how to do an atomic read of the TCNT1 Register contents.
Reading the OCR1A Register can be done using the same principle.
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;
}
Note:
1. See ”About Code Examples” on page 7.
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
97
2548F–AVR–03/2013
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.
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;
}
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 written to TCNT1.
16.2.1
16.3
Reusing the Temporary High Byte Register
If writing to more than one 16-bit register where the high byte is the same for all registers written,
then the high byte only needs to be written once. However, note that the same rule of atomic
operation described previously also applies in this case.
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.
98
ATmega406
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
DATA BUS (8-bit)
TOVn
(Int.Req.)
TEMP (8-bit)
Count
TCNTnH (8-bit)
TCNTnL (8-bit)
Clear
Control Logic
clkTn
TCNTn (16-bit Counter)
Signal description (internal signals):
Count
Increment TCNT1 by 1.
Clear
Clear TCNT1 (set all bits to zero).
clkT1
Timer/Counter clock.
The 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNT1H) containing the upper eight bits of the counter, and Counter Low (TCNT1L) containing the lower eight
bits. The TCNT1H Register can only be indirectly accessed by the CPU. When the CPU does an
access to the TCNT1H I/O location, the CPU accesses the high byte temporary register (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 of whether clkT1 is present 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 the next timer clock cycle. If enabled (OCIE1A = 1), the output compare 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.
99
2548F–AVR–03/2013
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/Counter1), 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 shaded.
Figure 16-3. Output Compare Unit, Block Diagram
DATA BUS
(8-bit)
TEMP (8-bit)
OCRnxH (8-bit)
OCRnxL (8-bit)
TCNTnH (8-bit)
OCRnx (16-bit Register)
TCNTnL (8-bit)
TCNTn (16-bit Counter)
= (16-bit Comparator )
OCFnx (Int.Req.)
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
6
5
4
3
2
1
0
(0x81)
–
–
–
–
CTC1
CS12
CS11
CS10
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
TCCR1B
• 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 compare match.
100
ATmega406
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.
Table 16-1.
16.6.2
CS1[2:0] - Clock Select Bit Description
CS12
CS11
CS10
Description
0
0
0
No clock source (Timer/counter stopped).
0
0
1
clkI/O/1 (No prescaling)
0
1
0
clkI/O/8 (From prescaler)
0
1
1
clkI/O/32 (From prescaler)
1
0
0
clkI/O/64 (From prescaler)
1
0
1
clkI/O/128 (From prescaler)
1
1
0
clkI/O/256 (From prescaler)
1
1
1
clkI/O/1024 (From prescaler)
TCNT1H and TCNT1L – Timer/Counter1
Bit
7
6
5
4
3
(0x85)
TCNT1[15:8]
(0x84)
TCNT1[7:0]
2
1
0
TCNT1H
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
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 compare 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
Bit
7
6
5
4
3
(0x89)
OCR1A[15:8]
(0x88)
OCR1A[7:0]
2
1
0
OCR1AH
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
The Output Compare Register contains 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 performed using an
8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16bit registers. See “Accessing 16-bit Registers” on page 96.
101
2548F–AVR–03/2013
16.6.4
TIMSK1 – Timer/Counter Interrupt Mask Register 1
Bit
7
6
5
4
3
2
1
0
(0x6F)
–
–
–
–
–
–
OCIE1A
TOIE1
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TIMSK1
• 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/Counter1 Output Compare A Match interrupt is enabled. The corresponding
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
6
5
4
3
2
1
0
0x16 (0x36)
–
–
–
–
–
–
OCF1A
TOV1
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TIFR1
• 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 Interrupt Vector is executed.
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.
102
ATmega406
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 directly by the system clock (by setting 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 the prescaler can be used as a
clock source by setting the CSn2:0. See Table 15-9 on page 92 for Timer/Counter0 settings and
Table 16-1 on page 101 for Timer/Counter1 settings. The prescaled clock has 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 by Timer/Counter1 and Timer/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 prescaler (6 > CSn2:0 > 1). The number 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 synchronizing the Timer/Counter to program execution. 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 synchronized (sampled) signal is then passed through the edge detector. Figure 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 generates one clkT0 pulse for each positive (CSn2:0 = 7) or negative (CSn2:0
= 6) edge it detects.
Figure 17-1. T1/T0 Pin Sampling
Tn
D
Q
D
Q
D
Tn_sync
(To Clock
Select Logic)
Q
LE
clk I/O
Synchronization
Edge Detector
103
2548F–AVR–03/2013
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 pin 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 system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 17-2. Prescaler for Timer/Counter0 and Timer/Counter1(1)
PSRSYNC
CK/1024
CK/256
CK/128
CK/64
CK/8
CK/32
Clear
clk I/O
T0
Synchronization
clkT1
Note:
104
clkT0
1. The synchronization logic on the input pins (T1/T0) is shown in Figure 17-1.
ATmega406
2548F–AVR–03/2013
ATmega406
17.4
17.4.1
Register Description
GTCCR – General Timer/Counter Control Register
Bit
7
6
5
4
3
2
1
0
0x23 (0x43)
TSM
–
–
–
–
–
–
PSRSYNC
Read/Write
R/W
R
R
R
R
R
R
R/W
Initial Value
0
0
0
0
0
0
0
0
GTCCR
• 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 normally cleared immediately by hardware, 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.
105
2548F–AVR–03/2013
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 Measurement of more than ± 30A @ 5 m
13-bit Resolution (including sign) corresponding to 53.7 µV (10.7 mA @ 5 m) for Instantaneous
Current Output
18-bit Resolution (including 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 Complete
Interrupt on Accumulate Current Conversion Complete
Interrupt on Regular Current with Programmable Compare Level and Programmable Sampling
Interval: 250/500/1000/2000 ms
ATmega406 features a dedicated 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 Accumulate 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 provides 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
INSTANTANEOUS
CURRENT
ACCUMULATE
CURRENT
8-BIT DATABUS
Regular
Current IRQ
Level
Control &
Status
Register
Current
Comparator
IRQ
IRQ
PI
Sigma Delta
modulator
R SENSE
Decimation
IRQ
Decimation
NI
106
ATmega406
2548F–AVR–03/2013
ATmega406
18.2
Operation
When enabled, the CC-ADC continuously measures the voltage over the external sense resistor
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 interrupt 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 losing conversion data, both the low and high byte must be read within a 3,9 ms timing window after
the corresponding interrupt is given. When the low byte register is read, updating of the Instantaneous 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 within the limited period.
Figure 18-2. Instantaneous Current Conversion
Enable
~12 ms settling
3.9 ms
3.9 ms
Setting of Digital Filters
DATA1
DATA2
7.8 ms
Instantaneous Interrupt
Instantaneous Data
DATA 3
DATA5
Read low byte
Read high byte
The Accumulate Current output is a high-resolution, high accuracy output with programmable
conversion time selected by the CADAS bits in CADCSRA. The converted value is an accurate
measurement of the average current flow during one conversion period. The CC-ADC generates
an interrupt each time a new Accumulate Current conversion has finished if the interrupt 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 conversion 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 Accumulation Current conversion example, where DATA4 will be lost because DATA3 reading is not completed within the
limited period.
107
2548F–AVR–03/2013
Figure 18-3. Accumulation Current Conversion
Enable
125, 250, 500,
or 1000 ms
125, 250, 500,
or 1000 ms
250, 500, 1000,
or 2000 ms
Accumulation Interrupt
Accumulation Data
Setting of Digital Filters
DATA1
DATA2
DATA 3
DATA5
Read byte 1
Read byte 2
Read byte 3
Read byte 4
While the CC-ADC is converting, the CPU can enter sleep mode and wait for an interrupt from
the Accumulate Current conversion. After adding the new Accumulate Current value for Coulomb Counting, the CPU can go back to sleep again. This reduces the CPU workload, and
allows more time spent in low power modes, reducing power consumption. The CC-ADC can
generate an interrupt if the result of an Instantaneous Current conversion is greater than a programmable 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 setting 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 halted in Power-down 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 setting 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 automatically 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 clearing the CADSE bit.
In-system offset voltage for the CC-ADC is typically 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 recommended to estimate the charge flow instead of using the CC-ADC for Coloumb Counting. The
108
ATmega406
2548F–AVR–03/2013
ATmega406
charge flow estimation should be based on the self-discharge rate of the battery and the standby
current of the battery system.
18.2.1
CADCSRA – CC-ADC Control and Status Register A
Bit
7
6
5
4
3
2
1
0
CADEN
–
CADUB
CADAS1
CADAS0
CADSI1
CADSI0
CADSE
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
(0xE4)
CADCSRA
• Bit 7 – CADEN: CC-ADC Enable
When the CADEN bit is cleared (zero), the CC-ADC is disabled, 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 disabled. Note that the bandgap voltage reference 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 written 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. Synchronization of one of the registers, will block updating of 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 time for the Accumulate Current output as shown in Table
18-1.
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
1s
109
2548F–AVR–03/2013
• 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.
Table 18-2.
Notes:
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)
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 aborted, and the CCADC enters Regular Current detection mode.
18.2.2
CADCSRB – CC-ADC Control and Status Register B
Bit
7
6
5
4
3
2
1
0
(0xE5)
–
CADACIE
CADRCIE
CADICIE
–
CADACIF
CADRCIF
CADICIF
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
CADCSRB
• 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-bit 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 CCADC 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
110
ATmega406
2548F–AVR–03/2013
ATmega406
The CADRCIF bit is set (one) when the absolute value of the result of the last CC-ADC conversion 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 executing 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 Interrupt Handling vector. Alternatively, CADICIF is cleared by writing a logic one to the flag.
18.2.3
CADICH and CADICL – CC-ADC Instantaneous Current
Bit
15
14
13
12
11
(0xE9)
CADIC[15:8]
(0xE8)
CADIC[7:0]
10
9
8
CADICH
CADICL
Bit
7
6
5
4
3
2
1
0
Read/Write
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Initial Value
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 extended
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 values are read.
18.2.4
CADAC3, CADAC2, CADAC1 and CADAC0 – CC-ADC Accumulate Current
Bit
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
(0xE3)
CADAC[31:24]
CADAC3
(0xE2)
CADAC[23:16]
CADAC2
(0xE1)
CADAC[15:8]
CADAC1
(0xE0)
CADAC[7:0]
CADAC0
Read/Write
Initial Value
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
The CADAC3, CADAC2, CADAC1 and CADAC0 Registers contain the Accumulate Current
measurements in 2’s complement format, sign extended to 32 bits.
111
2548F–AVR–03/2013
When CADAC0 is read, the CC-ADC Accumulate Current register is not updated until CADAC3
is read. Reading the registers in the sequence CADAC0, CADAC1, CADAC2, CADAC3 will
ensure that consistent values are read.
18.2.5
CADRCC – CC-ADC Regular Charge Current
Bit
7
6
5
4
(0xE6)
3
2
1
0
CADRCC[7:0]
CADRCC
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
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 significant bits of the Regular Charge Current level. The most significant bits of the Regular Charge
Current level are always zero. The programmable range for the Regular Charge Current level is
given in Table 18-3.
Table 18-3.
Programmable Range for the Regular Charge Current Level
Minimum
Maximum
Step Size
0
13700
53.7
RSENSE = 5 m
0
2740
10.7
RSENSE = 7 m
0
1957
7.7
Voltage (µV)
Current (mA)
The CC-ADC Regular Charge Current Register does not affect the setting of the CC-ADC Conversion Complete Interrupt Flag.
18.2.6
CADRDC – CC-ADC Regular Discharge Current
Bit
7
6
5
(0xE7)
4
3
2
1
0
CADRDC[7:0]
CADRDC
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
The CC-ADC Regular Discharge Current Register determines the threshold level for the Regular
Discharge Current detection. When the result of a CC-ADC Instantaneous Current conversion is
negative with an absolute value greater than, or 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 significant bits of the Regular Discharge Current level. The most significant bits of the Regular
112
ATmega406
2548F–AVR–03/2013
ATmega406
Charge Current level are always one. The programmable range for the Regular Discharge Current level is given in Table 18-4.
Table 18-4.
Programmable Range for the Regular Discharge Current Level
Minimum
Maximum
Step Size
0
13700
53.7
RSENSE = 5 m
0
2740
10.7
RSENSE = 7 m
0
1957
7.7
Voltage (µV)
Current (mA)
The CC-ADC Regular Discharge Current Register does not affect the setting of the CC-ADC
Conversion Complete Interrupt Flag.
113
2548F–AVR–03/2013
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 Internal Voltage Regulator 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
VFET
Voltage Regulator
RN
PVT
PV1
Regulator
Control
LDO_ON
VREG
LDO
Regulator
Creg > 1 uF
RP
POWER_OFF
Power
Distributor
Rsense
Digital
Supply
19.2
Analog
Supply
Operation
The Regulator will operate in all sleep modes, including Power-off. In this mode the regulator will
automatically reduce the ATmega406's power consumption by turning off supply for all peripheral 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 present, the voltage between the VFET and the PVT pin must
be above a Charge-Threshold voltage, VCHT.
114
ATmega406
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 consumption). 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.
115
2548F–AVR–03/2013
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-scaling of Cell Voltages and VREG
Interrupt on V-ADC Conversion Complete
The ATmega406 features a 12-bit Sigma-Delta ADC. Automatic offset cancellation technique
reduces the input offset voltage to less than 0.5 mV.
The Voltage ADC (V-ADC) is connected to ten different sources through the Input Multiplexer.
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 fullscale reading corresponds to 5.5 V. The ADC4 input can be used to measure the voltage at the
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, calibration registers for the individual cell voltage gain in the analog front-end is provided. A factory
calibration value is stored in the signature row, see Section 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 calibration 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 be written to zero to
enable V-ADC module.
116
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 20-1. Voltage ADC Block Schematic
V-ADC CONVERSION COMPLETE IRQ
V-ADC MULTIPLEXER
SEL. REG (VADMUX)
ADC3
VADCCIE
VADCCIF
8-BIT DATA BUS
V-ADC CONTROL AND
STATUS REG (VADCSR)
ADC2
ADC1
ADC0
V-ADC CONTROL
VTEMP
INPUT
MUX
ADC4
PV4
V-ADC DATA REGISTER
(VADCL/ADCH)
12-BIT
SIGMA-DELTA ADC
PV3
PV2
PV1
NV
VREF
SGND
Note:
The shaded signals are scaled by 0.2,
other signals are scaled by 1.0
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
519 us
Start Conversion
Interrupt
Conversion Result
OLD DATA
INVALID DATA
VA L I D
D ATA
INVALID DATA
To perform a V-ADC conversion, the analog input channel 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 current conversion before performing the channel change. When a conversion is finished the V-
117
2548F–AVR–03/2013
ADC Conversion Complete Interrupt Flag – VADCCIF is set. One 12-bit conversion takes 519 µs
to complete from the start bit is set to the interrupt 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
20.3.1
Register Description
VADMUX – V-ADC Multiplexer Selection Register
Bit
7
6
5
4
3
2
1
0
(0x7C)
–
–
–
–
VADMUX3
VADMUX2
VADMUX1
VADMUX0
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
VADMUX
• 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.
Table 20-1.
VADMUX channel selection
VADMUX3:0
20.3.2
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
VADCSR – V-ADC Control and Status Register
Bit
7
6
5
4
3
2
1
0
(0x7A)
–
–
–
–
VADEN
VADSC
VADCCIF
VADCCIE
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
VADCSR
• 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 Calibration C Register” on page 123.
118
ATmega406
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 complete, 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 VADC 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 vector. 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
Bit
15
14
13
12
(0x79)
–
–
–
–
(0x78)
11
10
9
8
VADC[11:8]
VADCH
VADC[7:0]
Read/Write
Initial Value
VADCL
7
6
5
4
3
2
1
0
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
R
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
When a V-ADC conversion is complete, the result 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-ADC Conversion Result
These bits represent the result from the conversion.
To obtain the best absolute accuracy for the cell voltage measurements, gain and offset compensation 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:
cell n result  cell n gain calibration word
Cell n voltage  mV  = --------------------------------------------------------------------------------------------------- – cell n offset calibration word
TBD
When performing a Vtemp conversion, the result must be adjusted by the factory calibration
value stored in the signature row, refer to section ”Reading the Signature Row from Software” on
page 189 for details. The absolute temperature in Kelvin is given by:
V temp result  VPTAT calibration word
T(K) = -----------------------------------------------------------------------------------------------TBD
119
2548F–AVR–03/2013
20.3.4
DIDR0 – Digital Input Disable Register 0
Bit
7
6
5
4
3
2
1
0
(0x7E)
–
–
–
–
VADC3D
VADC2D
VADC1D
VADC0D
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
DIDR0
• Bits 7:4 – Res: Reserved Bits
These bits are reserved for future use. To ensure compatibility with future devices, these bits
must be written to zero when DIDR0 is written.
• Bit 3:0 – VADC3D:VADC0D: V-ADC3:0 Digital Input Disable
When this bit is written logic one, the digital input buffer on the corresponding V-ADC pin is disabled. 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.
120
ATmega406
2548F–AVR–03/2013
ATmega406
21. Voltage Reference and Temperature Sensor
21.1
Features
•
•
•
•
•
•
Accurate Voltage Reference 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 Onchip Oscillators
• External Decoupling for Optimum Noise Performance
• Low Power Consumption
A low power band-gap reference provides ATmega406 with an accurate On-chip voltage reference V REF 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 reference voltage VREF_P/VREF_N to the CC-ADC is scaled to match the full scale requirement at the current sense input pins. This configuration also enables concurrent operation of
both V-ADC and CC-ADC.
To guaranty ultra low temperature drift after factory calibration, ATmega406 features a two-step
calibration algorithm. The first step is performed at 85C and the second at room temperature.
By default, Atmel factory calibration is performed at 85C, and the result is stored in Flash. The
customer can easily implement the second calibration step in their test flow. This 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 0C to 60C and 100
ppm/C from 0C to 85C. The BG Calibration C Register can also be altered runtime to implement temperature compensation in software. Very high accuracy for any temperature 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 regulator whenever the band-gap voltage reference is disabled. This voltage reference source is not available for the V-ADC and CC-ADC.
ATmega406 has an On-chip temperature sensor for monitoring the die temperature. A voltage
Proportional-To-Absolute-Temperature, VPTAT, is generated in the voltage reference circuit and
connected to the multiplexer at the V-ADC input. This temperature sensor can be used for runtime 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 value stored in the signature row. See ”Reading the Signature
Row from Software” on page 189 for details.
121
2548F–AVR–03/2013
Figure 21-1. Reference Circuitry
1.1V
VREF
BG Reference
VREF_P
VPTAT
0.22V
CREF
VREF_N
VREF_GND
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 change 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.
Table 21-1.
Hold-off Times depending on CREG.
Regulator Cap
122
Hold-off Time BGCCR
Hold-off Time BGCRR
1 F
1.2 s
3.0 s
2 F
2.4 s
6.0 s
3 F
3.6 s
9.0 s
4 F
4.8 s
12.0 s
5 F
6.0 s
15.0 s
6 F
7.2 s
18.0 s
7 F
8.4 s
21.0 s
8 F
9.6 s
24.0 s
9 F
10.8 s
27.0 s
10 F
12.0 s
30.0 s
ATmega406
2548F–AVR–03/2013
ATmega406
21.3
21.3.1
Register Description for Voltage Reference and Temperature Sensor
BGCCR – Bandgap Calibration C Register
Bit
7
6
5
4
3
2
1
0
BGEN
–
BGCC5
BGCC4
BGCC3
BGCC2
BGCC1
BGCC0
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
(0xD0)
BGCCR
• 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 approximately 2 mV.
21.3.2
BGCRR – Bandgap Calibration R Register
Bit
7
6
5
4
3
2
1
0
BGCR7
BGCR6
BGCR5
BGCR4
BGCR3
BGCR2
BGCR1
BGCR0
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
(0xD1)
BGCRR
• 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 coefficient 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 temperature range of interest. The BGCRR bits are
temperature coded resulting in 9 possible settings: 00000000, 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.
123
2548F–AVR–03/2013
Figure 21-2. Illustration of VREF as a function of temperature.
1.5
BGCRR is used to move the top of the VREF
curve to the center of the tempearture range of
interest.
Temperature range of interest
VREF [V]
1
0.5
0
-40
-20
0
20
40
60
80
100
Temperature [o C]
124
ATmega406
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 Operation Independent of CPU
If the voltage at the VFET pin falls below the programmable Deep Under-voltage detection level,
C-FET, PC-FET, and D-FET are disabled and the chip is set in Power-off mode to reduce 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 levels: Discharge Over-current Detection
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 separate 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 Protection hardware provides a hold-off time of 1
second before software can re-enable the discharge FET. This provides safety in case the application 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 interrupts can be individually enabled and disabled by the CPU.
The effect of the various battery protection types is given in Table 22-1.
Table 22-1.
Effect of Battery Protection Types
Battery Protection Type
Interrupt Requests
C-FET
D-FET
PC-FET
Cell Balancing 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
In order to reduce power consumption, both 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-FET and the PC-FET are disabled. Note however that Charge Overcurrent Protection is never automatically disabled when any of the C-FET or PC-FETs are controlled by PWM.
125
2548F–AVR–03/2013
22.2
Deep Under-voltage 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 longer than the programmable delay time, C-FET, PC-FET and D-FET
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 Battery 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 the operational amplifier is compared to an accurate, programmable 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 Reaction 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 Protection. This ensures a
reliable clock source, off-set cancellation and low power consumption.
When the Discharge Over-current Protection is activated, the external D-FET, PC-FET, and CFET are disabled and a Current Protection Timer is started. This timer ensures 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 Status Register to re-enable normal operation. If the D-FET is re-enabled
while the loading of the battery still is too large, the Discharge 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-current Protection is activated, the external D-FET, PC-FET, and C-FET
are disabled and a Current Protection Timer is started. This timer ensures 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 Status Register to re-enable normal operation. If the C-FET is re-enabled
and the charger continues to supply too high currents, the Charge Over-current Protection will
be activated again.
126
ATmega406
2548F–AVR–03/2013
ATmega406
22.5
Short-circuit Protection
A second level of high current detection is provided to enable a faster response time 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 disabled 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. 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 D-FET
is re-enabled before the cause of the short-circuit condition is removed, the Short-circuit Protection will be activated again.
The Over-current and Short-circuit Protection parameters are programmable to adapt to different
types of batteries. The parameters are set by writing to I/O Registers. 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.6
Battery Protection CPU Interface
The Battery Protection CPU Interface is illustrated in Figure 22-1.
Figure 22-1. Battery Protection CPU Interface
8-BIT DATA BUS
Battery Protection
Parameter Lock
Register
LOCK?
LOCK?
LOCK?
8
/
Interrupt
Request
Battery Protection
Level Register
Battery Protection
Timing Register
Battery Protection
Control Register
Interrupt
Acknowledge
4
/
PPI
NNI
Current
Battery
Protection
VFET
Voltage
Battery
Protection
Battery
Protection
Interrupt
Register
4
/
Current
Protection
FET
Control
Deep Under-voltage
Power-off
Each protection has an Interrupt Flag. Each Flag can be read and cleared by the CPU, and each
flag has an individual interrupt enable. All enabled flags are combined into a single battery protection 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 nor status bits indicating that the chip has entered the Power Off
mode. This is because the CPU is powered down in this mode. The CPU will, however be able
127
2548F–AVR–03/2013
to detect that it came from a Power-off situation by monitoring CPU reset flags 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 synchronized 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
6
5
4
3
2
1
0
(0xF8)
–
–
–
–
–
–
BPPLE
BPPL
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
BPPLR
• 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 Battery Protection Parameter 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
6
5
4
3
2
1
0
(0xF7)
–
–
–
–
DUVD
SCD
DCD
CCD
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
BPCR
• 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
128
ATmega406
2548F–AVR–03/2013
ATmega406
When the DUVD bit is set, the Deep Under-voltage Protection is disabled. The Deep Under-voltage 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 Detection 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 Discharge
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-current Detection will be disabled, and any Charge Over-current condition will be ignored.
22.7.3
CBPTR – Current Battery Protection Timing Register
Bit
7
6
(0xF6)
5
4
3
2
SCPT[3:0]
1
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
• Bit 7:4 – SCPT3:0: Short-circuit Protection Timing
These bits control the delay of the Short-circuit Protection. See Table 22-2.
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
• 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.
Table 22-3.
OCPT[3:0] with Corresponding Over-current Delay Time
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
129
2548F–AVR–03/2013
22.7.4
BPOCD – Battery Protection Over-current Detection Level Register
Bit
7
6
(0xF5)
5
4
3
2
DCDL[3:0]
1
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
• Bits 7:4 – DCDL3:0: Discharge Over-current Detection Level
These bits set the RSENSE voltage level for detection of Discharge Over-current, as defined in
Table 22-4.
Table 22-4.
DCDL[3:0] with Corresponding RSENSE Voltage for Discharge Over-current Detection 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
• Bits 3:0 – CCDL3:0: Charge Over-current Detection Level
These bits set the RSENSE voltage level for detection of Charge Over-current, as defined in Table
22-5.
Table 22-5.
CCDL[3:0] with Corresponding RSENSE Voltage for Charge Over-current Detection
Level
Charge Over-current Protection Detection Level
22.7.5
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
BPSCD – Battery Protection Short-circuit Detection Level Register
Bit
7
6
5
4
(0xF4)
–
–
–
–
3
Read/Write
R
R
R
R
R/W
Initial Value
0
0
0
0
0
2
1
0
R/W
R/W
R/W
0
0
0
SCDL[3:0]
BPSCD
• 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.
130
ATmega406
2548F–AVR–03/2013
ATmega406
Table 22-6.
SCDL[3:0] with Corresponding RSENSE Voltage for Short-circuit Detection Level
Short-circuit Protection Detection Level
22.7.6
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
BPDUV – Battery Protection Deep Under Voltage Register
Bit
7
6
(0xF3)
–
–
5
4
3
Read/Write
R
R
R/W
R/W
R/W
Initial Value
0
0
0
0
0
2
1
0
R/W
R/W
R/W
0
0
0
DUVT[1:0]
DUDL[3:0]
BPDUV
• 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.
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
• Bits 3:0 – DUDL3:0: Deep Under-voltage Detection Level
These bits set the Deep Under-voltage detection level.
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
131
2548F–AVR–03/2013
22.7.7
BPIR – Battery Protection Interrupt Register
Bit
7
6
5
4
3
2
1
0
DUVIF
COCIF
DOCIF
SCIF
DUVIE
COCIE
DOCIE
SCIE
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
(0xF2)
BPIR
• Bit 7 – DUVIF: Deep Under-voltage Early Warning Interrupt Flag
If the voltage at VFET pin is below the Deep Under-voltage detection 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 Over-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 Protection is activated, DOCIF becomes set. The flag must 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 caused by the Deep Under-voltage Early 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 Interrupt Flag.
• Bit 1 – DOCIE: Discharge Over-current Protection Activated Interrupt Enable
The DOCIE bit enables interrupt caused by the Discharge 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 Battery Protection Interrupt Flags is set, and the corresponding Interrupt Enable bit
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 flags will not be cleared when the interrupt
routine is executed, they must be cleared by writing a logical one to them.
132
ATmega406
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-FET), 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 battery 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 output. 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 through a current limiting 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 voltages have risen enough to allow normal charging, it should enable the
C-FET and D-FET control outputs and disable the PC-FET control output.
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
Power-off Mode
CURRENT_PROTECTION
Current Protection
Timer
OC0B
PWMOC
1
8-BIT D ATA BU S
CFE
FET
Control
and
Status
Register
0
FET
Driver
OC
FET
Driver
OPC
FET
Driver
OD
PWMOPC
1
PFD
DFE
0
133
2548F–AVR–03/2013
23.1
FET Driver
Figure 23-2. Connection of external FETs
Rpc
Rpf
+
Rdf
Rcf
RN
PVT
OD
OC
OPC
BATT
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 changes operation mode in order to reduce
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 domain than the CPU. Whenever a new value is
written to the FCSR, the value must be synchronized to the FET Controller clock domain. Subsequent 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 Interrupt (BPINT).
23.2.1
FCSR – FET Control and Status Register
Bit
7
6
5
4
3
2
1
0
(0xF0)
–
–
PWMOC
PWMOPC
CPS
DFE
CFE
PFD
Read/Write
R
R
R/W
R/W
R
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
FCSR
• 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
134
ATmega406
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 AND of the PWM output
from the 8-bit Timer/Counter0 and the inverse of CURRENT_PROTECTION 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 (one), the Discharge FET state is determined
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 cleared (zero), the Charge FET will be disabled regardless of the state of
the Battery Protection circuitry. When this bit is set (one), the Charge FET state 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)
135
2548F–AVR–03/2013
24. Cell Balancing
ATmega406 incorporates cell balancing 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 cannot be simultaneously enabled. If trying to
enable two neighbouring FETs, both will be disabled.
Figure 24-1. Cell Balancing
PV4
RP
Level
Shift
8-BIT DATA BUS
TCB
PV3
RP
TCB
Level
Shift
Cell Balancing
Control Register
PV2
RP
TCB
Level
Shift
PV1
RP
Level
Shift
TCB
RP
136
NV
ATmega406
2548F–AVR–03/2013
ATmega406
24.1
24.1.1
Register Description
CBCR – Cell Balancing Control Register
Bit
7
6
5
4
3
2
1
0
(0xF1)
–
–
–
–
CBE4
CBE3
CBE2
CBE1
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
CBCR
• 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 Balancing FETs are always disabled in Power-off mode. CBE1 cannot be set if CBE2 is set.
137
2548F–AVR–03/2013
25. 2-wire Serial Interface
25.1
Features
•
•
•
•
•
•
•
•
•
•
25.2
Simple yet Powerful and Flexible Communication Interface, 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 Different Slave Addresses
Multi-master Arbitration Support
Operates on 4 MHz Clock, achieving up to 100 kHz Data Transfer Speed
Slew-rate Limited Output Drivers
Noise Suppression Circuitry Rejects Spikes on Bus Lines
Fully Programmable Slave Address with General Call Support
Address Recognition Causes Wake-up when AVR is in Sleep Mode
Two-wire Serial Interface Bus Definition
The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The
TWI protocol allows the systems designer 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 hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All
devices connected to the bus have individual addresses, and mechanisms for resolving 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
VBUS
Device 1
Device 2
Device 3
........
Device n
R1
R2
SDA
SCL
138
ATmega406
2548F–AVR–03/2013
ATmega406
25.2.1
TWI Terminology
The following definitions are frequently encountered in this section.
Table 25-1.
25.2.2
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.
Electrical Interconnection
As depicted in Figure 25-1, both bus lines are connected to the positive supply voltage through
pull-up resistors. 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 order 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 characteristics of the TWI is given in ”2-wire Serial Interface Characteristics” on page 229.
25.3
25.3.1
Data Transfer and Frame Format
Transferring Bits
Each data bit transferred on the TWI bus is accompanied by a pulse on the clock line. The level
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
SDA
SCL
Data Stable
Data Stable
Data Change
139
2548F–AVR–03/2013
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 relinquishing 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 and STOP conditions are signalled by changing the level of the SDA
line when the SCL line is high.
Figure 25-3. START, REPEATED START, and STOP Conditions
SDA
SCL
START
25.3.3
STOP START
REPEATED START
STOP
Address Packet Format
All address packets transmitted on the TWI bus are nine bits long, consisting of seven address
bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read
operation is to be performed, otherwise a write operation should be performed. 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 Master’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 acknowledge 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.
140
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 25-4. Address Packet Format
Addr MSB
Addr LSB
R/W
ACK
7
8
9
SDA
SCL
1
2
START
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 Receiver leaves the SDA line high, a NACK is signalled. When the 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
Data MSB
Data LSB
ACK
8
9
Aggregate
SDA
SDA from
Transmitter
SDA from
Receiver
SCL from
Master
1
SLA+R/W
25.3.5
2
7
Data Byte
STOP, REPEATED
START, or Next
Data Byte
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 empty message, consisting of a START followed by a STOP condition, 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 condition, depending on the software protocol implemented by the application software.
141
2548F–AVR–03/2013
Figure 25-6. Typical Data Transmission
Addr MSB
Addr LSB
R/W
ACK
Data MSB
7
8
9
1
Data LSB
ACK
8
9
SDA
SCL
1
START
25.4
2
SLA+R/W
2
7
Data Byte
STOP
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 allowing 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 arbitration 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 used to solve both these problems. The serial clocks from
all masters will be wired-ANDed, yielding a combined 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.
142
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 25-7. SCL Synchronization between Multiple Masters
TA low
TA high
SCL from
Master A
SCL from
Master B
SCL bus
Line
TB low
Masters Start
Counting Low Period
TB high
Masters Start
Counting High Period
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 lose arbitration when it outputs 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 master 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 Masters
START
SDA from
Master A
Master A Loses
Arbitration, SDA A SDA
SDA from
Master B
SDA Line
Synchronized
SCL Line
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.
143
2548F–AVR–03/2013
It is the user software’s responsibility to ensure that these illegal arbitration conditions never
occur. This implies that in multi-master systems, all data transfers must use the same composition of SLA+R/W and data packets. 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 submodules, as shown in Figure 25-9. The shaded registers are accessible through the AVR data bus.
Figure 25-9. Overview of the TWI Module
Slew-rate
Control
SDA
Spike
Filter
Slew-rate
Control
Spike
Filter
Bus Interface Unit
START / STOP
Control
Spike Suppression
Arbitration Detection
Address/Data Shift
Register (TWDR)
Address Match Unit
Address Register
(TWAR)
Address Comparator
25.5.1
144
Bit Rate Generator
Prescaler
Bit Rate Register
(TWBR)
Ack
Control Unit
Status Register
(TWSR)
Control Register
(TWCR)
TWI Unit
SCL
State Machine and
Status Control
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.
ATmega406
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. The SCL period is controlled 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 the
CPU clock frequency in the slave must be at least 16 times higher than the SCL frequency. 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:
TWI Clock frequency
SCL frequency = ----------------------------------------------------------TWPS
16 + 2(TWBR)  4
• TWBR = Value of the TWI Bit Rate Register.
• TWPS = Value of the prescaler bits in the TWI Status Register.
Notes:
25.5.3
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.
Bus Interface Unit
This unit contains the Data and Address Shift Register (TWDR), a START/STOP Controller and
Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted,
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)ACK bit to be transmitted or received. This (N)ACK Register is not directly accessible by the application software. However, when receiving, 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 modes, enabling the MCU to wake up
if addressed by a Master.
If the TWI has initiated a transmission as Master, the Arbitration Detection hardware continuously monitors the transmission trying to determine 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 Match 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.
145
2548F–AVR–03/2013
25.5.5
Control Unit
The Control unit monitors the TWI bus and generates responses corresponding to settings in the
TWI Control Register (TWCR). When an event requiring the attention of the application occurs
on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Status Register (TWSR) is updated with a status code identifying the event. The TWSR only
contains relevant status information when the TWI interrupt flag is asserted. At all other times,
the TWSR contains a special status code indicating that no relevant status information is available. 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 arbitration.
• 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.
146
ATmega406
2548F–AVR–03/2013
ATmega406
25.6
25.6.1
TWI Register Description
TWBR – TWI Bit Rate Register
Bit
7
6
5
4
3
2
1
0
TWBR7
TWBR6
TWBR5
TWBR4
TWBR3
TWBR2
TWBR1
TWBR0
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
(0xB8)
TWBR
• 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
Bit
7
6
5
4
3
2
1
0
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
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
(0xBC)
TWCR
The TWCR is used to control the operation of the TWI. It is used to enable 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 by writing a logic one to it. Note that this flag is not automatically 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 Status 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 byte has been received in Master Receiver or Slave Receiver mode.
By writing the TWEA bit to zero, the device can be virtually disconnected from the Two-wire
Serial Bus temporarily. Address recognition 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 Twowire Serial Bus. The TWI hardware checks if the bus is available, and generates a START con-
147
2548F–AVR–03/2013
dition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition
is detected, and then generates a new START 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 Master 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 automatically. 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 TWINT 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 activates 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 switched off and all 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 activated for as long as the TWINT flag is high.
25.6.3
TWSR – TWI Status Register
Bit
7
6
5
4
3
2
1
0
TWS7
TWS6
TWS5
TWS4
TWS3
–
TWPS1
TWPS0
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
1
1
1
1
1
0
0
0
(0xB9)
TWSR
• Bits 7:3 – TWS: TWI Status
These five bits reflect the status of the TWI logic and the Two-wire Serial Bus. The different status codes are described in Table 25-3 on page 156 through Table 25-6 on page 165. Note that
the value read from TWSR contains both the 5-bit status value and the 2-bit prescaler value. The
application designer should mask the prescaler bits to zero when checking the status bits. This
makes status checking independent of prescaler setting. This approach is used in this datasheet, 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.
148
ATmega406
2548F–AVR–03/2013
ATmega406
Table 25-2.
TWI Bit Rate Prescaler
TWPS1
TWPS0
Prescaler Value
0
0
1
0
1
4
1
0
16
1
1
64
To calculate bit rates, see ”Bit Rate Generator Unit” on page 145. The value of TWPS1:0 is used
in the equation.
25.6.4
TWDR – TWI Data Register
Bit
7
6
5
4
3
2
1
0
TWD7
TWD6
TWD5
TWD4
TWD3
TWD2
TWD1
TWD0
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
(0xBB)
TWDR
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 shifting a byte.
This occurs when the TWI Interrupt Flag (TWINT) is set by hardware. Note that the data register
cannot be initialized by the user before the first interrupt occurs. The data in TWDR remains stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted
in. TWDR always contains the last byte present on the bus, except after a wake-up from a sleep
mode by the TWI interrupt. In this case, the contents of TWDR is undefined. In the case 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 eight bits constitute the next data byte to be transmitted, or the latest data byte received
on the Two-wire Serial Bus.
25.6.5
TWAR – TWI (Slave) Address Register
Bit
7
6
5
4
3
2
1
0
TWA6
TWA5
TWA4
TWA3
TWA2
TWA1
TWA0
TWGCE
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
(0xBA)
TWAR
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, TWAR must be set in masters which
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.
149
2548F–AVR–03/2013
• 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
Bit
7
6
5
(0xBD)
4
3
2
1
0
–
TWAM[6:0]
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
TWAMR
• 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) the corresponding 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
TWAR0
Address
Match
Address
Bit 0
TWAMR0
Address Bit Comparator 0
Address Bit Comparator 6..1
• Bit 0 – Res: Reserved Bit
This bit is an unused bit in the ATmega406, and will always read as zero.
25.7
Using the TWI
The AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all bus events, like
reception of a byte or transmission of a START condition. Because the TWI is interrupt-based,
the application software is free to carry on other operations during a TWI byte transfer. 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 generate 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 interface to the TWI hardware. In
this example, a Master wishes to transmit a single data byte to a Slave. This description is quite
abstract, a more detailed explanation follows later in this section. A simple code example implementing the desired behavior is also presented.
150
ATmega406
2548F–AVR–03/2013
ATmega406
Application
Action
Figure 25-11. Interfacing the Application to the TWI in a Typical Transmission
1. Application
writes to TWCR to
initiate
transmission of
START
TWI
Hardware
Action
TWI bus
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
START
SLA+W
2. TWINT set.
Status code indicates
START condition sent
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
A
4. TWINT set.
Status code indicates
SLA+W sent, ACK
received
Data
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
A
6. TWINT set.
Status code indicates
data sent, ACK received
STOP
Indicates
TWINT set
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 successfully 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 application 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 software might take 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
151
2548F–AVR–03/2013
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 data packet has been transmitted, the TWINT flag in TWCR is set, and TWSR
is updated with a status code indicating that the data packet has successfully been sent.
The status code will also reflect whether 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 software might take 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. 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 STOP condition. Note that TWINT is NOT set after a STOP condition has been sent.
Even though this example 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 value 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 example(1)
ldi r16,
(1<<TWINT)|(1<<TWSTA)|
1
in
r16,TWCR
3
andi r16, 0xF8
cpi
r16, START
brne ERROR
152
(1<<TWEN)
Send START condition
while (!(TWCR & (1<<TWINT)))
;
sbrs r16,TWINT
rjmp wait1
in
r16,TWSR
Comments
TWCR = (1<<TWINT)|(1<<TWSTA)|
(1<<TWEN)
out TWCR, r16
wait1:
2
C example(1)
if ((TWSR & 0xF8) != START)
ERROR();
Wait for TWINT flag set. This
indicates that the START
condition has been transmitted
Check value of TWI Status
Register. Mask prescaler bits. If
status different from START go to
ERROR
ATmega406
2548F–AVR–03/2013
ATmega406
Assembly code example(1)
ldi
r16, SLA_W
TWDR = SLA_W;
out
TWDR, r16
TWCR = (1<<TWINT) |
(1<<TWEN);
ldi r16, (1<<TWINT) |
(1<<TWEN)
4
C example(1)
out TWCR, r16
wait2:
in
while (!(TWCR & (1<<TWINT)))
;
r16,TWCR
sbrs r16,TWINT
rjmp wait2
in
r16,TWSR
if ((TWSR & 0xF8) !=
MT_SLA_ACK)
andi r16, 0xF8
cpi
5
r16, MT_SLA_ACK
brne ERROR
ldi r16, DATA
out
TWDR, r16
out TWCR, r16
wait3:
6
while (!(TWCR & (1<<TWINT)))
Wait for TWINT flag set. This
indicates that the DATA has been
transmitted, and ACK/NACK has
been received.
if ((TWSR & 0xF8) !=
MT_DATA_ACK)
andi r16, 0xF8
r16, MT_DATA_ACK
brne ERROR
ldi r16,
(1<<TWINT)|(1<<TWEN)|
(1<<TWSTO)
out
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
MT_SLA_ACK go to ERROR
Load DATA into TWDR Register.
Clear TWINT bit in TWCR to start
transmission of data
;
r16,TWCR
rjmp wait3
in
r16,TWSR
7
Wait for TWINT flag set. This
indicates that the SLA+W has
been transmitted, and
ACK/NACK has been received.
TWCR = (1<<TWINT) |
(1<<TWEN);
sbrs r16,TWINT
cpi
Load SLA_W into TWDR
Register. Clear TWINT bit in
TWCR to start transmission of
address
TWDR = DATA;
ldi r16, (1<<TWINT) |
(1<<TWEN)
in
ERROR();
Comments
ERROR();
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
MT_DATA_ACK go to ERROR
TWCR = (1<<TWINT)|(1<<TWEN)|
(1<<TWSTO);
Transmit STOP condition
TWCR, r16
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 used in the same application. 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:
153
2548F–AVR–03/2013
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 Figure 25-13 to Figure 25-19, circles are used to indicate that the TWINT flag is set. The numbers 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 software action. For each status code, the required software action and details of the following serial
transfer are given in Table 25-3 to Table 25-6. Note that the prescaler bits are masked to zero in
these tables.
25.8.1
Master Transmitter Mode
In the Master Transmitter mode, a number of data bytes are transmitted to a slave receiver (see
Figure 25-12). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master 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
VBUS
Device 1
Device 2
MASTER
TRANSMITTER
SLAVE
RECEIVER
Device 3
........
Device n
R1
R2
SDA
SCL
154
ATmega406
2548F–AVR–03/2013
ATmega406
A START condition is sent by writing the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
1
0
X
1
0
X
TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to
transmit a START condition and TWINT must be written to one 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 hardware, and the status code in TWSR will be 0x08 (see Table 25-3). In order to enter MT mode,
SLA+W must be transmitted. This is done by writing SLA+W to TWDR. Thereafter 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:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
0
0
X
1
0
X
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. Possible status codes in Master
mode are 0x18, 0x20, or 0x38. The appropriate action to be taken for each of these status codes
is detailed in Table 25-3.
When SLA+W has been successfully transmitted, 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 Register. 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:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
0
0
X
1
0
X
This scheme is repeated until the last byte has been sent and the transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing
the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
0
1
X
1
0
X
A REPEATED START condition is generated by writing the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
1
0
X
1
0
X
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 Transmitter mode and Master Receiver
mode without losing control of the bus.
155
2548F–AVR–03/2013
Table 25-3.
Status Code
(TWSR)
Prescaler Bits
are 0
Status Codes for Master Transmitter Mode
Application Software Response
Status of the Two-wire Serial
Bus and Two-wire Serial Interface Hardware
To TWCR
To/from TWDR
STA
STO
TWINT
TWEA
Next Action Taken by TWI Hardware
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
X
0
1
X
Load SLA+R
X
0
1
X
SLA+W will be transmitted;
ACK or NOT ACK will be received
SLA+R will be transmitted;
Logic will switch to Master Receiver mode
Load data byte or
0
0
1
X
No TWDR action or
No TWDR action or
1
0
0
1
1
1
X
X
No TWDR action
1
1
1
X
Load data byte or
0
0
1
X
No TWDR action or
No TWDR action or
1
0
0
1
1
1
X
X
No TWDR action
1
1
1
X
Load data byte or
0
0
1
X
No TWDR action or
No TWDR action or
1
0
0
1
1
1
X
X
No TWDR action
1
1
1
X
Load data byte or
0
0
1
X
No TWDR action or
No TWDR action or
1
0
0
1
1
1
X
X
No TWDR action
1
1
1
X
No TWDR action or
0
0
1
X
No TWDR action
1
0
1
X
0x18
0x20
0x28
0x30
0x38
156
SLA+W has been transmitted;
ACK has been received
SLA+W has been transmitted;
NOT ACK has been received
Data byte has been transmitted;
ACK has been received
Data byte has been transmitted;
NOT ACK has been received
Arbitration lost in SLA+W or
data bytes
Data byte will be transmitted and ACK 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 condition will be
transmitted and TWSTO flag will be reset
Data byte will be transmitted and ACK 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 condition will be
transmitted and TWSTO flag will be reset
Data byte will be transmitted and ACK 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 condition will be
transmitted and TWSTO flag will be reset
Data byte will be transmitted and ACK 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 condition will be
transmitted and TWSTO flag will be reset
Two-wire Serial Bus will be released and not addressed slave mode entered
A START condition will be transmitted when the bus
becomes free
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 25-13. Formats and States in the Master Transmitter Mode
MT
Successfull
transmission
to a slave
receiver
S
SLA
$08
W
A
DATA
$18
A
P
$28
Next transfer
started with a
repeated start
condition
RS
SLA
W
$10
Not acknowledge
received after the
slave address
A
R
P
$20
MR
Not acknowledge
received after a data
byte
A
P
$30
Arbitration lost in slave
address or data byte
A or A
Other master
continues
$38
Arbitration lost and
addressed as slave
A
$68
From master to slave
From slave to master
25.8.2
A or A
Other master
continues
$38
Other master
continues
$78
DATA
To corresponding
states in slave mode
$B0
A
n
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
Master Receiver Mode
In the Master Receiver mode, a number of data bytes are received from a slave transmitter (see
Figure 25-14). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master 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.
157
2548F–AVR–03/2013
Figure 25-14. Data Transfer in Master Receiver Mode
VBUS
Device 1
Device 2
MASTER
RECEIVER
SLAVE
TRANSMITTER
........
Device 3
R1
Device n
R2
SDA
SCL
A START condition is sent by writing the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
1
0
X
1
0
X
TWEN must be written 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 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 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 the transfer. This is accomplished by writing the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
0
0
X
1
0
X
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 codes in Master
mode are 0x38, 0x40, or 0x48. The appropriate action to be taken for each of these status codes
is detailed in Table 25-13. Received data can 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 transfer is ended by generating a STOP condition or a repeated START
condition. A STOP condition is generated by writing the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
0
1
X
1
0
X
A REPEATED START condition is generated by writing the following value to TWCR:
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
1
X
1
0
X
1
0
X
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
158
ATmega406
2548F–AVR–03/2013
ATmega406
enables the master to switch between slaves, Master Transmitter mode and Master Receiver
mode without losing control over the bus.
Table 25-4.
Status Code
(TWSR)
Prescaler Bits
are 0
Status Codes for Master Receiver Mode
Application Software Response
Status of the Two-wire Serial
Bus and Two-wire Serial Interface Hardware
To TWCR
To/from TWDR
STA
STO
TWINT
TWEA
Next Action Taken by TWI Hardware
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
X
0
1
X
Load SLA+W
X
0
1
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
No TWDR action or
0
0
1
X
No TWDR action
1
0
1
X
0
0
1
0
0x38
Arbitration lost in SLA+R or
NOT ACK bit
0x40
SLA+R has been transmitted;
ACK has been received
No TWDR action or
No TWDR action
0
0
1
1
0x48
SLA+R has been transmitted;
NOT ACK has been received
No TWDR action or
No TWDR action or
1
0
0
1
1
1
X
X
No TWDR action
1
1
1
X
0
0x50
Data byte has been received;
ACK has been returned
Read data byte or
0
0
1
Read data byte
0
0
1
1
0x58
Data byte has been received;
NOT ACK has been returned
Read data byte or
Read data byte or
1
0
0
1
1
1
X
X
Read data byte
1
1
1
X
Two-wire Serial Bus will be released and not addressed Slave mode will be entered
A START condition will be transmitted when the bus
becomes free
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
Repeated START will be transmitted
STOP condition will be transmitted and TWSTO flag
will be reset
STOP condition followed by a START condition will be
transmitted and TWSTO flag will be reset
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
Repeated START will be transmitted
STOP condition will be transmitted and TWSTO flag
will be reset
STOP condition followed by a START condition will be
transmitted and TWSTO flag will be reset
159
2548F–AVR–03/2013
Figure 25-15. Formats and States in the Master Receiver Mode
MR
Successfull
reception
from a slave
receiver
S
SLA
R
A
DATA
A
$40
$08
DATA
A
$50
P
$58
Next transfer
started with a
repeated start
condition
RS
SLA
R
$10
Not acknowledge
received after the
slave address
A
W
P
$48
MT
Arbitration lost in slave
address or data byte
A or A
Other master
continues
A
$38
Arbitration lost and
addressed as slave
A
$68
From slave to master
25.8.3
$38
Other master
continues
$78
DATA
From master to slave
Other master
continues
To corresponding
states in slave mode
$B0
A
n
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
Slave Receiver Mode
In the Slave Receiver mode, a number of data bytes are received from a master transmitter (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
VBUS
Device 1
Device 2
SLAVE
RECEIVER
MASTER
TRANSMITTER
Device 3
........
Device n
R1
R2
SDA
SCL
To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows:
160
ATmega406
2548F–AVR–03/2013
ATmega406
TWAR
TWA6
TWA5
Value
TWA4
TWA3
TWA2
TWA1
TWA0
TWGCE
Device’s Own Slave Address
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 TWI will respond to the general call address (0x00),
otherwise it will ignore the general call address.
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
0
1
0
0
0
1
0
X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable
the acknowledgment of the device’s own slave address or the general call address. 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 general call address if enabled) followed by the data direction bit. If the
direction bit is “0” (write), the TWI will operate in SR mode, otherwise ST mode is entered. After
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 software action. The appropriate action to be taken for each status code is detailed in Table 25-5.
The Slave Receiver mode may also be entered if arbitration is lost while the TWI is in the Master
mode (see states 0x68 and 0x78).
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 TWEA is zero, the TWI does not acknowledge its own slave
address. 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 modes other than Idle mode, the 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 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 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.
161
2548F–AVR–03/2013
Table 25-5.
Status Code
(TWSR)
Prescaler Bits
Are 0
Status Codes for Slave Receiver Mode
Application Software Response
Status of the Two-wire Serial Bus
and Two-wire Serial Interface
Hardware
To TWCR
STA
STO
TWINT
TWEA
No TWDR action or
X
0
1
0
To/from TWDR
0x60
Own SLA+W has been received;
ACK has been returned
No TWDR action
X
0
1
1
0x68
Arbitration lost in SLA+R/W as
master; own SLA+W has been
received; ACK has been returned
No TWDR action or
X
0
1
0
No TWDR action
X
0
1
1
0x70
General call address has been
received; ACK has been returned
No TWDR action or
X
0
1
0
No TWDR action
X
0
1
1
0x78
Arbitration lost in SLA+R/W as
master; General call address has
been received; ACK has been
returned
No TWDR action or
X
0
1
0
No TWDR action
X
0
1
1
0x80
Previously addressed with own
SLA+W; data has been received;
ACK has been returned
Read data byte or
X
0
1
0
Read data byte
X
0
1
1
0x88
Previously addressed with own
SLA+W; data has been received;
NOT ACK has been returned
Read data byte or
0
0
1
0
Read data byte or
0
0
1
1
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
0
1
0
0x90
Previously addressed with
general call; data has been received; ACK has been returned
Read data byte or
X
Read data byte
X
0
1
1
0x98
Previously addressed with
general call; data has been
received; NOT ACK has been
returned
Read data byte or
0
0
1
0
Read data byte or
0
0
1
1
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
Read data byte or
0
0
1
0
Read data byte or
0
0
1
1
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
0xA0
162
A STOP condition or repeated
START condition has been
received while still addressed as
slave
Next Action Taken by TWI Hardware
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
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
Data byte will be received and NOT ACK will be
returned
Data byte will be received and ACK will be returned
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
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
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 25-17. Formats and States in the Slave Receiver Mode
Reception of the own
slave address and one or
more data bytes. All are
acknowledged
S
SLA
W
A
DATA
$60
A
DATA
$80
Last data byte received
is not acknowledged
A
P or S
$80
$A0
A
P or S
$88
Arbitration lost as master
and addressed as slave
A
$68
Reception of the general call
address and one or more data
bytes
General Call
A
DATA
$70
A
DATA
$90
Last data byte received is
not acknowledged
A
P or S
$90
$A0
A
P or S
$98
Arbitration lost as master and
addressed as slave by general call
A
$78
From master to slave
From slave to master
DATA
A
n
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
163
2548F–AVR–03/2013
25.8.4
Slave Transmitter Mode
In the Slave Transmitter mode, a number of data bytes are transmitted to a master receiver (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
VBUS
Device 1
Device 2
SLAVE
TRANSMITTER
MASTER
RECEIVER
Device 3
........
R1
Device n
R2
SDA
SCL
To initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows:
TWAR
TWA6
TWA5
Value
TWA4
TWA3
TWA2
TWA1
TWA0
TWGCE
Device’s Own Slave Address
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 TWI will respond to the general call address (0x00),
otherwise it will ignore the general call address.
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
Value
0
1
0
0
0
1
0
X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable
the acknowledgment of the device’s own slave address or the general call address. 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 general call address if enabled) followed by the data direction bit. If the
direction bit is “1” (read), the TWI will operate in ST mode, otherwise SR mode is entered. After
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 software action. The appropriate action to be taken for each status code is detailed in Table 25-6.
The Slave Transmitter 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 transfer. State 0xC0 or state 0xC8 will be entered, depending on whether the master receiver
transmits a NACK or ACK after the final byte. The TWI is switched to the not addressed Slave
mode, and will ignore the master if it continues the transfer. Thus the master 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 expecting NACK from the master).
164
ATmega406
2548F–AVR–03/2013
ATmega406
While TWEA is zero, the TWI does not respond to its own slave address. 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 modes other than Idle mode, the 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 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 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.
Table 25-6.
Status Code
(TWSR)
Prescaler
Bits are 0
0xA8
0xB0
0xB8
0xC0
0xC8
Status Codes for Slave Transmitter Mode
Application Software Response
Status of the Two-wire Serial Bus
and Two-wire Serial Interface
Hardware
To TWCR
To/from TWDR
STA
STO
TWINT
TWEA
Load data byte or
X
0
1
0
Load data byte
X
0
1
1
Arbitration lost in SLA+R/W as
master; own SLA+R has been
received; ACK has been returned
Load data byte or
X
0
1
0
Load data byte
X
0
1
1
Data byte in TWDR has been
transmitted; ACK has been
received
Load data byte or
X
0
1
0
Load data byte
X
0
1
1
Data byte in TWDR has been
transmitted; NOT ACK has been
received
No TWDR action or
0
0
1
0
No TWDR action or
0
0
1
1
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
No TWDR action or
0
0
1
0
No TWDR action or
0
0
1
1
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
Own SLA+R has been received;
ACK has been returned
Last data byte in TWDR has been
transmitted (TWEA = “0”); ACK
has been received
Next Action Taken by TWI Hardware
Last data byte will be transmitted and NOT ACK should
be received
Data byte will be transmitted and ACK should be received
Last data byte will be transmitted and NOT ACK should
be received
Data byte will be transmitted and ACK should be received
Last data byte will be transmitted and NOT ACK should
be received
Data byte will be transmitted and ACK should be received
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
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
165
2548F–AVR–03/2013
Figure 25-19. Formats and States in the Slave Transmitter Mode
Reception of the own
slave address and one or
more data bytes
S
SLA
R
A
DATA
$A8
Arbitration lost as master
and addressed as slave
A
DATA
$B8
A
P or S
$C0
A
$B0
Last data byte transmitted.
Switched to not addressed
slave (TWEA = '0')
A
All 1's
P or S
$C8
From master to slave
From slave to master
25.8.5
DATA
A
n
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
Miscellaneous States
There are two status codes that do not correspond to a defined TWI state, see Table 25-7.
Status 0xF8 indicates that no relevant information is available 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 bus error has occurred 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. This causes the
TWI to enter the not addressed Slave mode and to clear the TWSTO flag (no other bits in TWCR
are affected). The SDA and SCL lines are released, and no STOP condition is transmitted.
166
ATmega406
2548F–AVR–03/2013
ATmega406
Table 25-7.
Miscellaneous States
Status Code
(TWSR)
Prescaler Bits
are 0
Status of the Two-wire Serial
Bus and Two-wire Serial Interface hardware
Application Software Response
To TWCR
To/from TWDR
0xF8
No relevant state information
available; TWINT = “0”
No TWDR action
0x00
Bus error due to an illegal
START or STOP condition
No TWDR action
25.8.6
STA
STO
TWINT
TWEA
No TWCR action
0
1
Next Action Taken by TWI Hardware
Wait or proceed current transfer
1
X
Only the internal hardware is affected, no STOP condition is sent on the bus. In all cases, the bus is released
and TWSTO is cleared.
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 from Master to Slave and vice versa. The Master must instruct
the slave what location it wants to read, requiring the use of the MT mode. Subsequently, data
must be read from the slave, implying 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 system, 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 master 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
Master Transmitter
S
SLA+W
A
ADDRESS
S = START
Transmitted from master to slave
25.9
Master Receiver
A
Rs
SLA+R
A
Rs = REPEATED START
DATA
A
P
P = STOP
Transmitted from slave to master
Multi-master Systems and Arbitration
If multiple masters are connected to the same bus, transmissions may be initiated simultaneously 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.
167
2548F–AVR–03/2013
Figure 25-21. An Arbitration Example
VBUS
Device 1
Device 2
Device 3
MASTER
TRANSMITTER
MASTER
TRANSMITTER
SLAVE
RECEIVER
........
Device n
R1
R2
SDA
SCL
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 data 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
START
SLA
Data
Arbitration lost in SLA
Own
Address / General Call
received
No
STOP
Arbitration lost in Data
38
TWI bus will be released and not addressed slave mode will be entered
A START condition will be transmitted when the bus becomes free
Yes
Direction
Write
68/78
Read
B0
168
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
ATmega406
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 configuration 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 simultaneously. 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 disconnected, and prevents repetitive interrupts every time both the SDA and SCL lines are high (e.g.
bus IDLE state).
When the TWI bus is disconnected, both the SDA and the SCL lines will become low simultaneously. 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 adding this time constraint, unwanted interrupts caused by
both lines going low during normal bus communication is prevented.
Figure 25-23. Overview of Bus Connect/Disconnect.
SCL
SDA
DELAY ELEMENT
START
OUTPUT
TWBDT
DELAY
TWBCIP
SET TWBCIF
TWBCSR
IRQ
8-BIT DATA BUS
25.10.1
TWBCSR – TWI Bus Control and Status Register
Bit
7
6
5
4
3
2
1
0
TWBCIF
TWBCIE
–
–
–
TWBDT1
TWBDT0
TWBCIP
Read/Write
R/W
R/W
R
R
R
R/W
R/W
R/W
Initial Value
X
0
0
0
0
0
0
0
(0xBE)
TWBCSR
• 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 disconnected. TWBCIF is cleared by hardware when executing the corresponding interrupt handling
vector. Alternatively, TWBCIF is cleared by writing 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
169
2548F–AVR–03/2013
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/Disconnect Interrupt Enable
When the TWBCIE bit and the I-bit in the Status Register are set, the TWI Bus Connect/Disconne ct In terr upt is e nab le d. Th e corre spon ding inte rrup t is execu ted 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.
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
• 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.
170
ATmega406
2548F–AVR–03/2013
ATmega406
26. JTAG Interface and On-chip Debug System
26.1
Features
• JTAG (IEEE std. 1149.1 Compliant) Interface
• Debugger Access to:
– All Internal Peripheral Units
– Internal and External 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 debugging
A brief description is given in the following sections. Detailed descriptions 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 private JTAG instructions, and distributed
within ATMEL and to selected third party vendors only.
Figure 26-1 shows a block diagram of the JTAG interface and the On-chip Debug 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) between the TDI – input and TDO – output. The Instruction Register holds JTAG
instructions controlling the behavior of a Data Register.
The JTAG Programming Interface (actually consisting of several physical and virtual Data Registers) 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 four 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.
171
2548F–AVR–03/2013
The IEEE std. 1149.1 also specifies an optional TAP signal; TRST – Test ReSeT – which is not
provided.
When the JTAGEN Fuse is unprogrammed, these four TAP pins are normal port 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 monitored 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
TDI
TDO
TCK
TMS
JTAG PROGRAMMING
INTERFACE
TAP
CONTROLLER
AVR CPU
INSTRUCTION
REGISTER
ID
REGISTER
M
U
X
FLASH
MEMORY
Address
Data
BREAKPOINT
UNIT
BYPASS
REGISTER
INTERNAL
SCAN
CHAIN
PC
Instruction
FLOW CONTROL
UNIT
DIGITAL
PERIPHERAL
UNITS
BREAKPOINT
SCAN CHAIN
ADDRESS
DECODER
172
OCD STATUS
AND CONTROL
JTAG / AVR CORE
COMMUNICATION
INTERFACE
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 26-2. TAP Controller State Diagram
1
Test-Logic-Reset
0
0
Run-Test/Idle
1
Select-DR Scan
1
Select-IR Scan
0
1
0
1
Capture-DR
Capture-IR
0
0
0
Shift-DR
1
1
Exit1-DR
0
0
Pause-DR
0
Pause-IR
1
1
0
Exit2-DR
Exit2-IR
1
1
Update-DR
26.4
1
Exit1-IR
0
1
0
Shift-IR
1
0
1
Update-IR
0
1
0
TAP Controller
The TAP controller is a 16-state finite state machine that controls the operation of the JTAG programming 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, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the Shift
Instruction Register – Shift-IR state. While in this state, shift the four bits of the JTAG
instructions into the JTAG Instruction 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 pin, 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.
173
2548F–AVR–03/2013
• Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched
onto the parallel output from the Shift Register path in the Update-IR state. The Exit-IR, PauseIR, and Exit2-IR states are only used for navigating the state machine.
• At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the Shift Data
Register – Shift-DR state. While in this state, upload the selected data register (selected 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 Shift-DR state, the TMS input must be held low during input 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 register is shifted in from the TDI pin, the parallel inputs to the data
register captured in the Capture-DR state 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 functions 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 Interface 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 between 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 Points + 1 Data Memory Break Point with mask (“range Break
Point”).
A debugger, like the AVR Studio, may however use one or more of these resources for its internal purpose, leaving less flexibility to the end-user.
A list of the On-chip Debug specific JTAG instructions is given in ”On-chip Debug Specific JTAG
Instructions” on page 175.
174
ATmega406
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 LB1 or
LB2 Lock bits are set. Otherwise, the On-chip debug system would have provided 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 Corporation’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 highlights are presented in this document.
All necessary execution commands are available in AVR Studio, both on source level and on
disassembly level. The user can execute the program, single step through the 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 debug support is considered being private JTAG instructions, and distributed within
ATMEL and to selected third party vendors only. Instruction opcodes are listed for reference.
26.6.1
PRIVATE0; 0x8
Private JTAG instruction for accessing On-chip debug system.
26.6.2
PRIVATE1; 0x9
Private JTAG instruction for accessing On-chip debug system.
26.6.3
PRIVATE2; 0xA
Private JTAG instruction for accessing On-chip debug system.
26.6.4
PRIVATE3; 0xB
Private JTAG instruction for accessing On-chip debug system.
175
2548F–AVR–03/2013
26.7
26.7.1
On-chip Debug Related Register
OCDR – On-chip Debug Register
Bit
7
6
5
0x31 (0x51)
4
3
2
1
0
OCDR
On-Chip Debug Register
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
The OCDR Register provides a communication channel from the running program in the microcontroller 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 debugger that the register has been written. When the CPU reads the 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 programmed, 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
6
5
4
3
0x35 (0x55)
JTD
Read/Write
R/W
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
2
1
0
IVSEL
IVCE
R/W
R/W
R/W
0
0
0
PUD
MCUCR
• 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.
176
ATmega406
2548F–AVR–03/2013
ATmega406
26.8
Using the JTAG Programming Capabilities
Programming of AVR parts via JTAG is performed 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 programming (in addition to power pins). It is not required to apply 12V externally. The 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.
177
2548F–AVR–03/2013
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 uploading program code by the MCU itself. This feature allows flexible application 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 memory. 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 unique flexibility to select different 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:
27.2
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.
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 since the SPM instruction is disabled 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 software 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.
178
ATmega406
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 software update is dependent on which address that is being programmed. 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-WhileWrite (NRWW) section. The limit between the RWW- and NRWW sections is given in Table 278 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 NRWW section can be
read during the operation.
• When erasing or writing a page located inside the NRWW section, the CPU is halted during the
entire operation.
Note that the user software can never read any code that is located inside the RWW section during a Boot Loader software operation. The syntax “Read-While-Write section” refers 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 ongoing 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 section. 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 completed, 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 Programming?
Which Section Can be Read
During Programming?
CPU
Halted?
Read-While-Write
Supported?
RWW Section
NRWW Section
No
Yes
NRWW Section
None
Yes
No
179
2548F–AVR–03/2013
Figure 27-1. Read-While-Write vs. No Read-While-Write
Read-While-Write
(RWW) Section
Z-pointer
Addresses RWW
Section
Z-pointer
Addresses NRWW
Section
No Read-While-Write
(NRWW) Section
CPU is Halted
During the Operation
Code Located in
NRWW Section
Can be Read During
the Operation
180
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 27-2. Memory Sections
Program Memory
BOOTSZ = '10'
Program Memory
BOOTSZ = '11'
0x0000
No Read-While-Write Section
Read-While-Write Section
Application Flash Section
End RWW
Start NRWW
Application Flash Section
Boot Loader Flash Section
End Application
Start Boot Loader
Flashend
No Read-While-Write Section
Read-While-Write Section
0x0000
Program Memory
BOOTSZ = '01'
Application Flash Section
End RWW
Start NRWW
Application Flash Section
End Application
Start Boot Loader
Boot Loader Flash Section
Flashend
Program Memory
BOOTSZ = '00'
27.4
Read-While-Write Section
Application Flash Section
No Read-While-Write Section
Note:
0x0000
End RWW
Start NRWW
Application Flash Section
End Application
Start Boot Loader
Boot Loader Flash Section
Flashend
No Read-While-Write Section
Read-While-Write Section
0x0000
Application Flash Section
End RWW, End Application
Start NRWW, Start Boot Loader
Boot Loader Flash Section
Flashend
1. The parameters in the figure above are given in Table 27-7 on page 193.
Boot Loader Lock Bits
If no Boot Loader capability is needed, the entire Flash is available for application code. The
Boot Loader has two separate sets of Boot Lock bits which can be set independently. 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 control the programming of the Flash
memory by SPM instruction. Similarly, the general Read/Write Lock (Lock Bit mode 1) does not
control reading nor writing by LPM/SPM, if it is attempted.
181
2548F–AVR–03/2013
Table 27-2.
BLB0 Mode
BLB02
BLB01
1
1
1
No restrictions for SPM or LPM accessing the Application
section.
2
1
0
SPM is not allowed to write to the Application section.
0
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.
1
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.
3
4
Note:
0
0
Protection
1. “1” means unprogrammed, “0” means programmed
Table 27-3.
Boot Lock Bit1 Protection Modes (Boot Loader Section)(1)
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.
0
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.
1
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.
3
4
Note:
182
Boot Lock Bit0 Protection Modes (Application Section)(1)
0
0
Protection
1. “1” means unprogrammed, “0” means programmed
ATmega406
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 trigger such as a command received via the TWI interface. Alternatively, the
Boot Reset Fuse can be programmed so that the Reset Vector is pointing to the Boot Flash start
address after a reset. In this case, the Boot Loader is started after a reset. After the application
code is loaded, the program can start executing the application code. Note that the fuses cannot
be changed by the MCU itself. This means 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 programming interface.
Table 27-4.
Boot Reset Fuse(1)
BOOTRST
Note:
27.5.1
Reset Address
1
Reset Vector = Application Reset (address 0x0000)
0
Reset Vector = Boot Loader Reset (see Table 27-7 on page 193)
1. “1” means unprogrammed, “0” means programmed
SPMCSR – Store Program Memory Control and Status Register
The Store Program Memory Control and Status Register contains the control bits needed to control the Boot Loader operations.
Bit
7
6
5
4
3
2
1
0
0x37 (0x57)
SPMIE
RWWSB
SIGRD
RWWSRE
BLBSET
PGWRT
PGERS
SPMEN
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
SPMCSR
• 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 Section Busy
When a Self-Programming (Page Erase or Page Write) operation to the RWW section is initiated, 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 operation 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.
183
2548F–AVR–03/2013
• Bit 4 – RWWSRE: Read-While-Write Section Read Enable
When programming (Page Erase or Page Write) to the RWW section, the RWW section 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 written 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 address in the Zpointer 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 Register, 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, BLBSET, PGWRT’ or PGERS, the following SPM instruction will have a special 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 four clock 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.
184
ATmega406
2548F–AVR–03/2013
ATmega406
27.6
Addressing the Flash During Self-Programming
The Z-pointer is used to address the SPM commands.
Bit
15
14
13
12
11
10
9
8
ZH (R31)
Z15
Z14
Z13
Z12
Z11
Z10
Z9
Z8
ZL (R30)
Z7
Z6
Z5
Z4
Z3
Z2
Z1
Z0
7
6
5
4
3
2
1
0
Since the Flash is organized in pages (see ”Fuse Bits” on page 196), the Program Counter can
be treated as having two different sections. One section, consisting 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 and Page Write operation. Once a programming operation is initiated, the address is latched and the Z-pointer can be used for other
operations.
The only SPM operation that does not 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-by-byte, also the LSB (bit Z0) of the Z-pointer is used.
Figure 27-3. Addressing the Flash During SPM(1)
BIT
15
ZPCMSB
ZPAGEMSB
Z - REGISTER
1 0
0
PCMSB
PROGRAM
COUNTER
PAGEMSB
PCPAGE
PAGE ADDRESS
WITHIN THE FLASH
PROGRAM MEMORY
PAGE
PCWORD
WORD ADDRESS
WITHIN A PAGE
PAGE
INSTRUCTION WORD
PCWORD[PAGEMSB:0]:
00
01
02
PAGEEND
Note:
1. The different variables used in Figure 27-3 are listed in Table 27-9 on page 193.
185
2548F–AVR–03/2013
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 temporary page buffer, the page must be erased. The temporary page buffer is filled one word at a time using SPM and the buffer can be filled either before the Page
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 effective Read-Modify-Write feature which allows the user software
to first read the page, do the necessary changes, and then write back the modified data. If alternative 2 is used, it is not possible 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. Other 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 during the operation.
27.7.2
186
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. The
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.
ATmega406
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 recommended to program 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-Programming the Interrupt Vector table should be moved 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 Lock Bits by SPM
To set the Boot Loader Lock bits, write the desired data to R0, write “X0001001” 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 software update by the MCU.
Bit
7
6
5
4
3
2
1
0
R0
1
1
BLB12
BLB11
BLB02
BLB01
1
1
See Table 27-2 and Table 27-3 for how the different settings of the Boot Loader bits affect the
Flash access.
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 for reading the lOck bits). For future compatibility it
187
2548F–AVR–03/2013
is also recommended to set bits 7, 6, 1, and 0 in R0 to “1” when writing the Lock bits. When programming 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 user 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 possible to read both the Fuse and Lock bits from software. To read the Lock bits, load the
Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCSR. When an LPM instruction 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 BLBSET and SPMEN are cleared, LPM will work as described in the ”AVR Instruction Set”
description.
Bit
7
6
5
4
3
2
1
0
Rd
–
–
BLB12
BLB11
BLB02
BLB01
LB2
LB1
The algorithm for reading the Fuse Low byte is similar to the one described above for reading
the Lock bits. To read the Fuse Low byte, load the Z-pointer with 0x0000 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.
Bit
7
6
5
4
3
2
1
0
Rd
FLB7
FLB6
FLB5
FLB4
FLB3
FLB2
FLB1
FLB0
Similarly, when reading the Fuse High byte, load 0x0003 in the Z-pointer. 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 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.
Bit
7
6
5
4
3
2
1
0
Rd
FHB7
FHB6
FHB5
FHB4
FHB3
FHB2
FHB1
FHB0
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are
unprogrammed, will be read as one.
188
ATmega406
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 Lock 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
Slow RC H
0x06
(3)
0x07
Slow RC Temp Prediction L
Slow RC Temp Prediction H
0x0C
(7)
0x0D
ULP RC FRQ(5)
0x08
ULP RC L
0x0A
(6)
ULP RC H
0x0B
(4)
Bandgap PTAT Current Calibration Byte
0x09
V-ADC RAW Cell 1 L
0x0E
V-ADC RAW Cell 1 H(8)
0x0F
V-ADC Cell1 Gain Calibration Word L
V-ADC Cell1 Gain Calibration Word H
0x10
(9)
V-ADC Cell2 Gain Calibration Word L
V-ADC Cell2 Gain Calibration Word H
0x12
(9)
V-ADC Cell3 Gain Calibration Word L
V-ADC Cell3 Gain Calibration Word H
0x13
0x14
(9)
V-ADC Cell4 Gain Calibration Word L
V-ADC Cell4 Gain Calibration Word H
0x11
0x15
0x16
(9)
V-ADC ADC0 Gain Calibration Word L
0x17
0x18
(10)
V-ADC ADC0 Gain Calibration Word H
0x19
V-ADC Cell1 Offset(12)
0x1C
189
2548F–AVR–03/2013
Table 27-5.
Signature Row Addressing
Signature Byte
Z-Pointer Address
V-ADC Cell2 Offse
(12)
t
0x1D
V-ADC Cell3 Offse
(12)
t
0x1E
(12)
V-ADC Cell4 Offset
0x1F
VPTAT CAL L
0x1A
VPTAT CAL H(11)
0x1B
Notes:
1.
2.
3.
4.
5.
6.
7.
Default FOSCCAL value after reset.
Slow RC oscillator Frequency in kHz
Slow RC Oscillator fastest timeout in µs.
Calibration value found for BGCCR which gives 1.1V at VREF when BGCRR = 0x0F.
ULP RC Oscillator Frequency in kHz.
ULP RC Oscillator fastest timeout in µs.
Slow RC Oscillator Frequency Temperature drift prediction value (word). Measured over several lots. Not implemented.
8. Calibration Word used for the second step of VREF calibration. This step is performed by the
customer at 25C. Value stored is VADCH/L when Cell1 had 4096 mV at 85C.
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 temperature in Kelvin from VTEMP conversion. 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.
190
ATmega406
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 programming time for Flash accesses from the CPU.
Table 27-6.
SPM Programming Time
Symbol
Flash write (Page Erase, Page Write, and
write Lock bits by SPM)
27.7.12
Min Programming Time
Max Programming Time
3.7 ms
4.5 ms
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
191
2548F–AVR–03/2013
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
192
ATmega406
2548F–AVR–03/2013
ATmega406
ATmega406 Boot Loader Parameters
In Table 27-7 through Table 27-9, the parameters used in the description of the Self-Programming are given
Note:
Boot Reset
Address
(Start Boot
Loader Section)
End Application
Section
Boot Loader
Flash Section
BOOTSZ0
Application
Flash Section
Boot Size Configuration(1)
BOOTSZ1
Table 27-7.
1
1
256
words
4
0x0000 0x4EFF
0x4F00 0x4FFF
0x4EFF
0x4F00
1
0
512
words
8
0x0000 0x4DFF
0x4E00 0x4FFF
0x4DFF
0x4E00
0
1
1024
words
16
0x0000 0x4BFF
0x4C00 0x4FFF
0x4BFF
0x4C00
0
0
2048
words
32
0x0000 0x47FF
0x4800 0x4FFF
0x47FF
0x4800
Pages
Boot Size
27.7.13
1. The different BOOTSZ Fuse configurations are shown in Figure 27-2
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
0x4800 - 0x4FFF
Note:
1. For details about these two section, see ”NRWW – No Read-While-Write Section” on page
179 and ”RWW – Read-While-Write Section” on page 179.
Table 27-9.
Explanation of different variables used in Figure 27-3 and the mapping to the Zpointer(1)
Corresponding
Z-value
Variable
Description
PCMSB
14
Most significant bit in the Program Counter. (The
Program Counter is 13 bits 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 ZPAGEMSB 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)
193
2548F–AVR–03/2013
Note:
194
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.
ATmega406
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 programmed (“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.
Lock Bit Byte(1)
Table 28-1.
Lock Bit Byte
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)
Note:
Bit No
1. “1” means unprogrammed, “0” means programmed
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.
2
1
0
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)
Further programming and verification of the Flash 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)
3
0
0
BLB0
Mode
BLB02
BLB01
1
1
1
No restrictions for SPM or LPM accessing the Application section.
2
1
0
SPM is not allowed to write to the Application section.
0
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.
1
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.
3
4
0
0
195
2548F–AVR–03/2013
Table 28-2.
Lock Bit Protection Modes(1)(2) (Continued)
Memory Lock Bits
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.
0
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.
1
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.
3
0
4
Notes:
28.2
Protection Type
0
1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2.
2. “1” means unprogrammed, “0” means programmed
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 logical zero, “0”, if they are programmed.
28.2.1
High Byte
Table 28-3.
Fuse High Byte
Fuse High Byte
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)
Notes:
196
Bit No
1. Never ship a product with the OCDEN Fuse programmed regardless of the setting of Lock bits
and JTAGEN Fuse. A programmed OCDEN Fuse enables some parts of the clock system to
be running in all sleep modes. This may increase the power consumption.
ATmega406
2548F–AVR–03/2013
ATmega406
28.2.2
Low Byte
Table 28-4.
Fuse Low Byte
Fuse Low Byte
(3)
Bit No
Description
Default Value
WDTON
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 Table 27-7 on
page 193 for details)
0 (programmed)(2)
BOOTSZ0
4
Select Boot Size (see Table 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)
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 purpose 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.
197
2548F–AVR–03/2013
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 space.
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 address space. During Reset, the calibration 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 Signature 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
20K words (40K bytes)
Table 28-6.
198
Page Size
PCWORD
No. of Pages
PCPAGE
PCMSB
64 words
PC[5:0]
320
PC[14:6]
14
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
ATmega406
2548F–AVR–03/2013
ATmega406
28.6
Parallel Programming
This section describes parameters, pin mapping, and commands used to parallel program and
verify Flash Program memory, EEPROM 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 window in Flash or 256 byte EEPROM. This consideration also applies to Signature bytes reading.
28.6.2
Signal Names
In this section, some pins of the ATmega406 are referenced by signal names describing 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 command loaded determines the action executed. The different
Commands are shown in Table 28-10 on page 201. Table 28-11 on page 210 shows the Parallel
programming characteristics.
Figure 28-1. Parallel Programming
+4 - 25V
VFET
VREG
RDY/BSY
OE
WR
VCC
(3.3V)
BS1
XA0
BATT
XA1
PVT
PAGEL
PV1
VPP
See "Enter Programming Mode"
RESET
BS2
XTAL1
DATA
GND
199
2548F–AVR–03/2013
Table 28-7.
Pin Name Mapping
Signal Name in
Programming Mode
Pin
Name
I/O
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.
PB7:0
I/O
Bi-directional Data bus (Output when OE is low).
DATA
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.
200
Function
XA1 and XA0 Coding
XA1
XA0
Action when XTAL1 is Pulsed
0
0
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
ATmega406
2548F–AVR–03/2013
ATmega406
Table 28-10. Command Byte Bit Coding
Command Byte
28.6.3
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
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 Charger
Connect” on page 40.
2. Set RESET to “0” and toggle XTAL1 at least six times.
3. Set the Prog_enable pins listed in Table 28-8 on page 200 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.
201
2548F–AVR–03/2013
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 programmed 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 high 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 data within the page is loaded.
While the lower bits in the address are mapped to words within the page, the higher bits address
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.
202
ATmega406
2548F–AVR–03/2013
ATmega406
H. Program Page
1. Give WR a negative pulse. This starts programming of the entire page of data. 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 loads the command, and the internal write signals are
reset.
Figure 28-2. Addressing the Flash Which is Organized in Pages(1)
PCMSB
PROGRAM
COUNTER
PAGEMSB
PCPAGE
PAGE ADDRESS
WITHIN THE FLASH
PROGRAM MEMORY
PAGE
PCWORD
WORD ADDRESS
WITHIN A PAGE
PAGE
INSTRUCTION WORD
PCWORD[PAGEMSB:0]:
00
01
02
PAGEEND
Note:
1. PCPAGE and PCWORD are listed in Table 28-5 on page 198.
203
2548F–AVR–03/2013
Figure 28-3. Programming the Flash Waveforms(1)
F
DATA
A
B
0x10
ADDR. LOW
C
DATA LOW
D
E
DATA HIGH
XX
B
ADDR. LOW
C
D
DATA LOW
DATA HIGH
E
XX
G
ADDR. HIGH
H
XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
Note:
28.6.6
1. “XX” is don’t care. The letters refer to the programming description above.
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 Flash” on page 202 for details on 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. Wait until to RDY/BSY goes high before programming the next page (See Figure 28-4 for
signal waveforms).
204
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 28-4. Programming the EEPROM Waveforms
K
DATA
A
G
0x11
ADDR. HIGH
B
ADDR. LOW
C
DATA
E
XX
B
ADDR. LOW
C
DATA
E
L
XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
28.6.7
Reading the Flash
The algorithm for reading the Flash memory 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”.
205
2548F–AVR–03/2013
28.6.9
Programming the Fuse Low Bits
The algorithm for programming the Fuse Low 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. Give WR a negative pulse and wait for RDY/BSY 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/BSY to go high.
5. Set BS1 to “0”. This selects low data byte.
Figure 28-5. Programming the FUSES Waveforms
Write Fuse Low byte
DATA
A
C
0x40
DATA
XX
Write Fuse high byte
A
C
0x40
DATA
XX
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
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/BSY to go high.
The Lock bits can only be cleared by executing Chip Erase.
206
ATmega406
2548F–AVR–03/2013
ATmega406
28.6.12
Reading the Fuse and Lock Bits
The algorithm for reading 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 read 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
Fuse Low Byte
0
0
1
0
DATA
BS2
0
Lock Bits
1
Fuse High Byte
1
BS1
BS2
28.6.13
Reading the Signature Bytes
The algorithm for reading the Signature bytes is as follows (refer to ”Programming the Flash” 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 ”Programming the Flash” on
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”.
207
2548F–AVR–03/2013
28.6.15
Parallel Programming Characteristics
Figure 28-7. Parallel Programming Timing, Including some General Timing Requirements
tXLWL
tXHXL
XTAL1
tDVXH
tXLDX
Data & Contol
(DATA, XA0/1, BS1, BS2)
tPLBX t BVWL
tBVPH
PAGEL
tWLBX
tPHPL
tWLWH
WR
tPLWL
WLRL
RDY/BSY
tWLRH
Figure 28-8. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
LOAD ADDRESS
(LOW BYTE)
LOAD DATA LOAD DATA
(HIGH BYTE)
LOAD DATA
(LOW BYTE)
t XLXH
tXLPH
LOAD ADDRESS
(LOW BYTE)
tPLXH
XTAL1
BS1
PAGEL
DATA
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
208
1. The timing requirements shown in Figure 28-7 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation.
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 28-9. Parallel Programming Timing, Reading Sequence (within the Same Page) with
Timing Requirements(1)
LOAD ADDRESS
(LOW BYTE)
READ DATA
(LOW BYTE)
READ DATA
(HIGH BYTE)
LOAD ADDRESS
(LOW BYTE)
tXLOL
XTAL1
tBVDV
BS1
tOLDV
OE
DATA
tOHDZ
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 28-7 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading operation.
209
2548F–AVR–03/2013
Table 28-11. Parallel Programming Characteristics
Symbol
Parameter
Min
VPP
Programming Enable Voltage (RESET input)
11.5
IPP
Programming Enable Current
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
Max
Units
12.5
V
250
A
tWLRH
0
1
s
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
tBVDV
BS1 Valid to DATA valid
0
tOLDV
tOHDZ
Notes:
210
Typ
ns
250
ns
OE Low to DATA Valid
250
ns
OE High to DATA Tri-stated
250
ns
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.
ATmega406
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 programmed. In addition, the JTD bit in MCUCSR must be cleared.
Alternatively, if the JTD bit is set, the external reset can be forced 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-System Programming via the JTAG interface. Note that this technique can not be used when using
the JTAG pins for Boundary-scan or On-chip Debug. In these cases the JTAG pins must be dedicated 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.
211
2548F–AVR–03/2013
Figure 28-10. State Machine Sequence for Changing the Instruction Word
1
Test-Logic-Reset
0
0
Run-Test/Idle
1
Select-DR Scan
1
Select-IR Scan
0
1
0
1
Capture-DR
Capture-IR
0
0
0
Shift-DR
1
1
Exit1-DR
0
0
Pause-DR
0
Pause-IR
1
1
0
Exit2-DR
Exit2-IR
1
1
Update-DR
28.7.2
1
Exit1-IR
0
1
0
Shift-IR
1
0
1
Update-IR
0
1
0
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 reset by 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 16bit 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.
212
ATmega406
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 data 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 Data Byte Register is copied into a temporary register. A
write sequence is initiated that within 11 TCK cycles loads the content 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 preincremented before writing the low byte, except 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 location
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 and the high byte for each
new Capture-DR state, starting with the low byte for the first Capture-DR encountered after
entering 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.
• Shift-DR: The Flash Data Byte Register is shifted by the TCK input.
28.7.7
Data Registers
The data registers are selected by the JTAG instruction registers described in section ”Programming Specific JTAG Instructions” on page 211. The data registers relevant for programming
operations are:
• Reset Register
• Programming Enable Register
• Programming Command Register
• Flash Data Byte Register
213
2548F–AVR–03/2013
28.7.8
Reset Register
The 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 output from this data register is not
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 contents 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
TDI
D
A
T
A
0xA370
=
D
Q
Programming Enable
ClockDR & PROG_ENABLE
TDO
28.7.10
214
Programming Command Register
The Programming Command Register is a 15-bit register. This register is used to serially shift in
programming commands, and to serially shift out the result of the previous command, if 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.
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 28-12. Programming Command Register
TDI
S
T
R
O
B
E
S
A
D
D
R
E
S
S
/
D
A
T
A
Flash
EEPROM
Fuses
Lock Bits
TDO
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
2a. Enter Flash Write
0100011_00010000
xxxxxxx_xxxxxxxx
2b. Load Address High Byte
0000111_aaaaaaaa
xxxxxxx_xxxxxxxx
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
3c. Load Address Low Byte
0000011_bbbbbbbb
xxxxxxx_xxxxxxxx
(2)
(9)
(9)
215
2548F–AVR–03/2013
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 = data in, x
Instruction
TDI Sequence
TDO Sequence
Notes
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
xxxxxxx_xxxxxxxx
4b. Load Address High Byte
0000111_aaaaaaaa
xxxxxxx_xxxxxxxx
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
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
0100011_01000000
xxxxxxx_xxxxxxxx
6b. Load Data High Byte
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
xxxxxxx_xxxxxxxx
7b. Load Data Byte(8)
0010011_11iiiiii
xxxxxxx_xxxxxxxx
6a. Enter Fuse Write
(6)
216
(9)
(9)
(4)
ATmega406
2548F–AVR–03/2013
ATmega406
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 = data in, x
Instruction
TDI Sequence
TDO Sequence
Notes
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_00000100
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
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” = unprogrammed.
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 Table 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...).
217
2548F–AVR–03/2013
Figure 28-13. State Machine Sequence for Changing/Reading the Data Word
1
Test-Logic-Reset
0
0
Run-Test/Idle
1
Select-DR Scan
1
Select-IR Scan
0
1
0
1
Capture-DR
Capture-IR
0
0
Shift-DR
Shift-IR
0
1
Exit1-DR
0
Pause-DR
0
0
Pause-IR
1
1
0
Exit2-DR
Exit2-IR
1
1
Update-DR
28.7.11
1
Exit1-IR
0
1
0
1
1
0
1
Update-IR
0
1
0
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 Register actually consists of the 8-bit scan chain and a 8-bit temporary register. During page load, the Update-DR state copies the content of the scan chain over to the
temporary register and initiates a write sequence that within 11 TCK cycles loads the content 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, except 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 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 state, starting with the low byte for the first Cap-
218
ATmega406
2548F–AVR–03/2013
ATmega406
ture-DR encountered after entering 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
STROBES
TDI
State
Machine
ADDRESS
Flash
EEPROM
Fuses
Lock Bits
D
A
T
A
TDO
The state machine controlling the Flash Data Byte Register is clocked by TCK. During normal
operation in which eight bits are shifted for each Flash byte, the clock cycles needed to navigate
through the TAP controller automatically feeds the state machine for the Flash Data Byte Register 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 that there are 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 Programming 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 programming Enable Register.
4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register.
219
2548F–AVR–03/2013
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 wait 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 instruction words in the page.
7. Write the page using programming instruction 2g.
8. Poll for Flash write complete using programming 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 page 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 Register 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 programming 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 data 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.
220
ATmega406
2548F–AVR–03/2013
ATmega406
4. Enter JTAG instruction PROG_PAGEREAD.
5. Read the entire page (or Flash) by shifting out all instruction words in the page (or Flash),
starting with the LSB of the first instruction in the page (Flash) and ending with the MSB
of the last instruction in the page (Flash). The Capture-DR state both captures the data
from the Flash, and also auto-increments the program counter after each word is read.
Note that Capture-DR comes before 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 data using programming instructions 4d and 4e.
6. Repeat steps 4 and 5 for all data 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 data 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 (refer 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 (refer to
Table 28-11 on page 210).
221
2548F–AVR–03/2013
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 corresponding 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 instruction 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.
222
ATmega406
2548F–AVR–03/2013
ATmega406
29. Operating Circuit
Figure 29-1. Operating Circuit Diagram
Rpc
Rpf
+
Rdf
Rcf
OD
OC
OPC
VFET
BATT
RN
PVT
Rled
PB0
RP
PV4
Rled
PB1
CP
Rled
PB2
RP
PB3
PV3
PB4
CP
Rled
Rled
RP
PV2
CP
100
SMB Clock
SCK
RP
PV1
RP
100
SDA
CP
SMB Data
NV
RP1
RP2
Rppi
PPI
Ci
ATmega406
VREG
Rpi
PI
V CC
Ci
Rsense
CREG 1
Rni
CREG 2
NI
Ci
Rnni
NNI
CXTAL2
XTAL1
RT4
PA4
CXTAL 2
RT3
XTAL2
PA3
RT2
PA2
CRESET
RT1
RESET
PA1
PA0/ADC0
VREF
VREFGND
SGND
GND
R1
CREF
223
2548F–AVR–03/2013
Table 29-1.
Recommended values for external devices
Symbol
Use
Parameter
Min
Typ
Max
unit
R1
Pull-up resistor for thermistors
R
10
k
[email protected]C
10
k
RT1
RT2
RT3
RT4
NTC Thermistor
RS
Source Impedance when
using PA0...4 as V-ADC inputs
Rnni
Rppi
Current protection LP-filter
resistor
R
Rni
Rpi
Current sense LP-filter
resistors
R
10
100
500

Ci
Current sense LP-filter
capasitor
C
0.01
0.1
0.4
µF
(Rpi-Rni)*Ci
Current sense LP-filter time
constant

10
20
µs
Rsense(1)
Current sense resistor
R
5
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
CREG1
CREG2
VREG charge-storage
C
RP1
RP2
TWI Pull-up resistors
B-constant
4000
K
R
0
3
7
k
Worst Gain-error due to RS
0
1
2
%
1
1
1
k
m
22
µF
0.1
µF
1
CRESET
Note:
3000
C
2.2
M
C
0.1
µF
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.
224
ATmega406
2548F–AVR–03/2013
ATmega406
30. Electrical Characteristics
30.1
Absolute Maximum Ratings*
Operating Temperature......................................-30C to +85C
*NOTICE:
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
Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage 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.
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
30.2
DC Characteristics
DC Characteristics, TA = -30C to 85C, VCC = 3.3V
Parameter
Supply Current
Condition
Max
Unit
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
3.3
3.35
V
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
Temperature Stability
(2)
IOUT = 5 mA
Reference voltage
VREF
Typ
Power Supply Current
Regulated Output Voltage(2)
Voltage
Regulator(1)
Min
3.25
1.1
Ref. Voltage Accuracy
After calibration, at calibration
temperature
Temperature Drift(3)
TA = -30 – 60 C
±0.1
80
V
± 0.2
%
ppm/C
225
2548F–AVR–03/2013
DC Characteristics, TA = -30C to 85C, VCC = 3.3V (Continued)
Parameter
Condition
Min
Reference Voltage
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
0
1
V
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
(5)
±1
Reference Voltage
53.7 V Resolution
Conversion Time and
Resolution
1.68 V Resolution
INL
1000 ms conversion time
(6)
CC-ADC Offset Drift
(4)
mV
± 0.5
%
± 220
mV
3.9
ms
125
1000
ms
±4
LSB
Uncompensated
± 50
± 200
V
TA = 0 - 60C
±1
± 15
V
±1

CC-ADC Gain Error
VPTAT, Voltage Proportional to
Absolute Temperature
0.6
Absolute Accuracy(3)
|VGS_ON|
226
LSB
1.6
Gain Error Cell Inputs
CC-ADC Offset
±3
ADC0, ADC1, ADC2, ADC3,
VTEMP
Offset
FET Driver
Unit
V
Input Voltage Range
Temperature
Sensor
Max
1.100
V-ADC
CC-ADC
Typ
11
mV/K
±4
K
15
V
50
µs
100
µs
OC/OD Rise time (10 - 90%)
(Switching OFF)
CL = 10 nF
OC/OD Fall time
(VGS = 0 - VGS = -5V)
(Switching ON)
CL = 10 nF
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
10
ATmega406
2548F–AVR–03/2013
ATmega406
DC Characteristics, TA = -30C to 85C, VCC = 3.3V (Continued)
Parameter
Condition
Slow RC
Oscillator
Frequency
TA = - 30 – 85C
Ultra Low Power
RC Oscillator
Frequency
Notes:
Temperature Drift
Temperature Drift
TA = - 30 – 85C
Min
Typ
Max
Unit
165
kHz
5
%
124
kHz
8
%
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.
227
2548F–AVR–03/2013
30.3
General I/O Lines characteristics
30.3.1
Low voltage ports
Figure 30-1. TA = -30C to 85C, VCC = 3.3V (unless otherwise noted) (1)
Symbol
Parameter
Condition
Min.
Typ.
Max.
Units
V
VIL
Input Low Voltage
VCC = 3.3V
-0.5
0.3VCC(2)
VIH
Input High Voltage
VCC = 3.3V
0.6VCC(3)
VCC + 0.5
V
0.5
V
Output Low Voltage
VOL
(4)
(5)
IOL = 5mA, VCC = 3.3V
VOH
Output High Voltage
IOH = 2 mA, VCC = 3.3V
IIL
Input Leakage
Current I/O Pin
VCC = 3.3V, pin low
(absolute value)
1
µA
IIH
Input Leakage
Current I/O Pin
VCC = 3.3V, pin high
(absolute value)
1
µA
Notes:
2.3
V
1.
2.
3.
4.
Applicable for all except PC0.
“Max” means the highest value where the pin is guaranteed to be read as low.
“Min” means the lowest value where the pin is guaranteed to be read as high.
Although each I/O port can sink more than the test conditions (5 mA at VCC = 3.3V) under steady state conditions (non-transient, 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 (nontransient, the following must be observed:
- The sum of all IOH should not exceed 2 mA.
30.3.2
High voltage ports
Figure 30-2. TA = -30C to 85C, VCC = 3.3V (unless otherwise noted)
Symbol
Parameter
Condition
Output Low Voltage
tr(1)
tof(1)
VOL
(1)
Notes:
228
Min.
Typ.
Max.
Units
VCC = 3.3V
0.5
V
Rise Time
VCC = 3.3V
300
ns
Output Fall Time from
VIHmin to VILmax
Cb < 400 pF(2)
200
ns
1. Parameter characterized and not tested.
2. Cb = capacitance of one bus line in pF
ATmega406
2548F–AVR–03/2013
ATmega406
30.4
2-wire Serial Interface Characteristics
Table 30-1 describes the requirements for devices connected to the Two-wire Serial Bus. The ATmega406 Two-wire Serial
Interface meets or exceeds these requirements under the noted conditions.
Timing symbols refer to Figure 30-3.
Table 30-1.
Two-wire Serial Bus Requirements
Symbol
Parameter
VIL
VIH
VOL
tr
(1)
Min
Max
Units
Input Low-voltage
-0.5
0.8
V
Input High-voltage
2.1
5.5
V
0
0.4
V
300
ns
250
ns
0
50
ns
-5
5
µA
–
10
pF
fCK(3) > max(16fSCL, 450 kHz)(4)
0
100
kHz
fSCL  100 kHz
V BUS – 0,4V
------------------------------350µA
V BUS – 0,4V
------------------------------100µA

Output Low-voltage
(1)
Condition
350 µA sink current
Rise Time for both SDA and SCL
(2)
(1)
tof
Output Fall Time from VIHmin to VILmax
(1)
tSP
Spikes Suppressed by Input Filter
Ii
Input Current each I/O Pin
Ci(1)
Capacitance for each I/O Pin
fSCL
SCL Clock Frequency
Rp
Value of Pull-up resistor
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 time
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
Notes:
1.
2.
3.
4.
Cb < 400 pF
0.1VBUS < Vi < 0.9VBUS
In ATmega406, this parameter is characterized and not tested.
Cb = capacitance of one bus line in pF.
fCK = CPU clock frequency
This requirement applies to all ATmega406 Two-wire Serial Interface operation. Other devices connected to the Two-wire
Serial Bus need only obey the general fSCL requirement.
229
2548F–AVR–03/2013
Figure 30-3. Two-wire Serial Bus Timing
tof
tHIGH
tr
tLOW
tLOW
SCL
tSU;STA
tHD;STA
tHD;DAT
tSU;DAT
tSU;STO
SDA
tBUF
30.5
Reset Characteristics
Table 30-2.
Symbol(2)
Characteristics for Powering-up the LDO(1)
Parameter
Min
Typ
Max
Units
4.0
V
Charger Present
VROT
Regulator Power-on Threshold
VCHT
Charge Voltage Threshold
3.0
1.0
V
No Charger Present
VROT
Regulator Power-on Threshold
VPVIT
Voltage Threshold on Battery Cell 1
Notes:
Symbol
VCOT
2.0
V
Parameter
Condition
Min
Typ
Max
Units
Regulator must operate
6
7
8
V
Condition
Min
Typ
Max
Units
VREG = 3.3V
0.66
2.8
V
Internal Voltage Regulator must be on.
Symbol
230
V
Power-on Reset Characteristics
Charger-on Thresholt Voltage
Table 30-4.
Note:
4.0
1. Power-on Reset is issued when a charger is connected and the regulator has stable work conditions.
2. Values based on characterization.
Table 30-3.
Note:
3.0
External Reset Characteristics
Parameter
VRST
RESET Pin Threshold Voltage
tRST
Minimum pulse width on RESET Pin
900
ns
Internal Voltage Regulator must be on.
ATmega406
2548F–AVR–03/2013
ATmega406
30.6
Supply Current of I/O Modules
Table 30-5 on page 231 is showing the additional current consumption 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 page 36 for details. The tables and formulas below can be used
to calculate the additional current consumption for the different I/O modules in Active and Idle
mode.
Table 30-5.
Additional Current
Consumption 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
PRR0 bit
30.6.0.1
Additional Current Consumption for the different I/O modules
Example 1
Calculate the expected current consumption in idle mode with TIMER1, V-ADC and Battery Protection 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:
I CC total  1.2mA   1 + 0.017 + 0.019 + 0.252   1.55mA
231
2548F–AVR–03/2013
31. Typical Characteristics – Preliminary
The following charts are tested on a few microcontrollers only. These figures are not tested during 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)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
VCC = 3.3V
90
80
70
IOP (uA)
60
50
40
30
20
25 ˚C
10
85 ˚C
-30 ˚C
0
0
0,5
1
1,5
2
2,5
3
3,5
V I (V)
Figure 31-2. Reset Pull-Up Resistor Current vs. Input Voltage (VCC = 3.3V)
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE
VCC = 3.3V
80
70
IRESET(uA)
60
50
40
30
20
-30 ˚C
10
25 ˚C
85 ˚C
0
0
0,5
1
1,5
2
2,5
3
3,5
VRESET(V)
232
ATmega406
2548F–AVR–03/2013
ATmega406
31.2
Pin Driver Strength
Figure 31-3. I/O Pin Putput Voltage vs. Sink Current (VCC = 3.3V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT
VCC = 3.3V
1.3
85 ˚C
1.2
1.1
25 ˚C
1
VOL (V)
-30 ˚C
0.9
0.8
0.7
0.6
0.5
0.4
0
5
10
15
20
25
IOL (mA)
Figure 31-4. I/O Pin output Voltage vs. Source Current (VCC = 3.3V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT
VCC = 3.3V
2.9
2.7
VOH (V)
2.5
2.3
-30 ˚C
25 ˚C
85 ˚C
2.1
1.9
1.7
1.5
0
5
10
15
20
25
IOH (mA)
233
2548F–AVR–03/2013
31.3
Internal Oscillator Speed
Figure 31-5. Watchdog Oscillator Frequency vs. Temperature (VCC = 3.3V)
WATCHDOG OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
126
125
124
FRC (kHz)
123
122
121
120
119
118
117
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
100
Temperature
Figure 31-6. Calibrated 1 MHz RC Oscillator Frequency vs. Temperature (VCC = 3.3V)
CALIBRATED 1 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
1.025
1.02
1.015
FRC (MHz)
1.01
1.005
1
0.995
0.99
0.985
0.98
0.975
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
100
Temperature
234
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 31-7. Calibrated 1 MHz RC Oscillator Frequency vs. OSCCAL Value (VCC = 3.3V)
CALIBRATED 1 MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE
2.5
85 ˚C
2
25 ˚C
FRC (MHz)
-30 ˚C
1.5
1
0.5
0
0
16
32
48
64
80
96
112
128
144
160
176
192
208
224
240
256
OSCCAL (X1)
Figure 31-8. Slow RC Oscillator Frequency vs. Temperature (VCC = 3.3V)
SLOW RC OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
156.5
156
FRC (kHz)
155.5
155
154.5
154
153.5
153
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
100
Temperature
235
2548F–AVR–03/2013
32. Register Summary
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
(0xFF)
Reserved
–
–
–
–
–
–
–
–
236
Page
(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]
(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]
(0xDF)
Reserved
–
–
–
–
–
–
–
–
112
111
(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
–
–
–
–
–
–
XOE
ACS
29
ATmega406
2548F–AVR–03/2013
ATmega406
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
(0xBF)
Reserved
–
–
–
–
–
–
–
–
TWBCIF
TWBCIE
–
–
–
TWBDT1
TWBDT0
TWBCIP
169
–
150
(0xBE)
TWBCSR
(0xBD)
TWAMR
(0xBC)
TWCR
(0xBB)
TWDR
TWAM[6:0]
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
TWIE
2–wire Serial Interface Data Register
Page
147
149
(0xBA)
TWAR
(0xB9)
TWSR
TWA[6:0]
TWGCE
(0xB8)
TWBR
(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
(0x80)
Reserved
–
–
–
–
–
–
–
–
(0x7F)
Reserved
–
–
–
–
–
–
–
–
(0x7E)
DIDR0
–
–
–
–
VADC3D
VADC2D
VADC1D
VADC0D
TWS[7:3]
–
TWPS1
TWPS0
2–wire Serial Interface Bit Rate Register
149
148
147
–
100
120
237
2548F–AVR–03/2013
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
(0x7D)
Reserved
–
–
–
–
–
–
–
–
(0x7C)
VADMUX
–
–
–
–
VADMUX3
VADMUX2
VADMUX1
VADMUX0
(0x7B)
Reserved
–
–
–
–
–
–
–
–
(0x7A)
VADCSR
–
–
–
–
VADEN
VADSC
VADCCIF
VADCCIE
(0x79)
VADCH
–
–
–
–
(0x78)
VADCL
(0x77)
Reserved
–
–
–
–
–
–
–
–
(0x76)
Reserved
–
–
–
–
–
–
–
–
(0x75)
Reserved
–
–
–
–
–
–
–
–
(0x74)
Reserved
–
–
–
–
–
–
–
–
(0x73)
Reserved
–
–
–
–
–
–
–
–
(0x72)
Reserved
–
–
–
–
–
–
–
–
(0x71)
Reserved
–
–
–
–
–
–
–
–
(0x70)
Reserved
–
–
–
–
–
–
–
–
(0x6F)
TIMSK1
–
–
–
–
–
–
OCIE1A
TOIE1
102
(0x6E)
TIMSK0
–
–
–
–
–
OCIE0B
OCIE0A
TOIE0
93
(0x6D)
Reserved
–
–
–
–
–
–
–
–
VADC Data Register High byte
Page
118
118
119
VADC Data Register Low byte
119
(0x6C)
PCMSK1
PCINT[15:8]
(0x6B)
PCMSK0
PCINT[7:0]
59
(0x6A)
Reserved
–
–
–
–
–
–
(0x69)
EICRA
ISC31
ISC30
ISC21
ISC20
ISC11
ISC10
ISC01
ISC00
56
(0x68)
PCICR
–
–
–
–
–
–
PCIE1
PCIE0
58
(0x67)
Reserved
–
–
–
–
–
–
–
–
(0x66)
FOSCCAL
(0x65)
Reserved
–
–
–
–
–
–
–
–
(0x64)
PRR0
–
–
–
–
PRTWI
PRTIM1
PRTIM0
PRVADC
(0x63)
Reserved
–
–
–
–
–
–
–
–
(0x62)
WUTCSR
WUTIF
WUTIE
WUTCF
WUTR
WUTE
WUTP2
WUTP1
WUTP0
(0x61)
Reserved
–
–
–
–
–
–
–
–
59
–
–
Fast Oscillator Calibration Register
29
36
49
(0x60)
WDTCSR
WDIF
WDIE
WDP3
WDCE
WDE
WDP2
WDP1
WDP0
0x3F (0x5F)
SREG
I
T
H
S
V
N
Z
C
47
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
0x36 (0x56)
Reserved
–
–
–
–
–
–
–
–
183
0x35 (0x55)
MCUCR
JTD
–
–
PUD
–
–
IVSEL
IVCE
0x34 (0x54)
MCUSR
–
–
–
JTRF
WDRF
BODRF
EXTRF
PORF
46
0x33 (0x53)
SMCR
–
–
–
–
SM2
SM1
SM0
SE
31
–
–
–
–
–
–
–
–
0x32 (0x52)
Reserved
0x31 (0x51)
OCDR
0x30 (0x50)
Reserved
–
–
–
–
–
–
–
–
On-Chip Debug Register
55/73/176
176
0x2F (0x4F)
Reserved
–
–
–
–
–
–
–
–
0x2E (0x4E)
Reserved
–
–
–
–
–
–
–
–
0x2D (0x4D)
Reserved
–
–
–
–
–
–
–
–
0x2C (0x4C)
Reserved
–
–
–
–
–
–
–
–
0x2B (0x4B)
GPIOR2
General Purpose I/O Register 2
0x2A (0x4A)
GPIOR1
General Purpose I/O Register 1
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/Counter0 (8 Bit)
0x25 (0x45)
TCCR0B
FOC0A
FOC0B
–
–
WGM02
CS02
CS01
CS00
0x24 (0x44)
TCCR0A
COM0A1
COM0A0
COM0B1
COM0B0
–
–
WGM01
WGM00
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
–
–
–
EEPM1
–
EEPM0
24
–
EERIE
–
–
–
92
EEMPE
EEPE
EERE
91
0x1F (0x3F)
EECR
0x1E (0x3E)
GPIOR0
0x1D (0x3D)
EIMSK
–
–
–
–
INT3
INT2
INT1
INT0
57
0x1C (0x3C)
EIFR
–
–
–
–
INTF3
INTF2
INTF1
INTF0
57
238
–
–
24
General Purpose I/O Register 0
19
24
ATmega406
2548F–AVR–03/2013
ATmega406
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
0x1B (0x3B)
PCIFR
–
–
–
–
–
–
PCIF1
PCIF0
Page
0x1A (0x3A)
Reserved
–
–
–
–
–
–
–
–
0x19 (0x39)
Reserved
–
–
–
–
–
–
–
–
0x18 (0x38)
Reserved
–
–
–
–
–
–
–
–
0x17 (0x37)
Reserved
–
–
–
–
–
–
–
–
0x16 (0x36)
TIFR1
–
–
–
–
–
–
OCF1A
TOV1
102
0x15 (0x35)
TIFR0
–
–
–
–
–
OCF0B
OCF0A
TOV0
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
74
0x03 (0x23)
PINB
PINB7
PINB6
PINB5
PINB4
PINB3
PINB2
PINB1
PINB0
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
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 directly bit-accessible using the SBI and CBI instructions. In these registers, 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 registers 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 the 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.
239
2548F–AVR–03/2013
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
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
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
1
AND
Rd, Rr
Logical AND Registers
Rd Rd  Rr
Z,N,V
ANDI
Rd, K
Logical 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
Rd  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 Multiply Unsigned
R1:R0  (Rd x Rr) <<
Z,C
2
FMULS
Rd, Rr
Fractional Multiply Signed
Z,C
2
FMULSU
Rd, Rr
Fractional Multiply Signed with Unsigned
1
R1:R0  (Rd x Rr) << 1
R1:R0  (Rd x Rr) << 1
Z,C
2
Relative Jump
PC PC + k + 1
None
2
Indirect Jump to (Z)
PC  Z
None
2
3
BRANCH INSTRUCTIONS
RJMP
k
IJMP
JMP
k
Direct Jump
PC k
None
RCALL
k
Relative Subroutine Call
PC  PC + k + 1
None
3
Indirect Call to (Z)
PC  Z
None
3
ICALL
Direct Subroutine Call
PC  k
None
4
RET
Subroutine Return
PC  STACK
None
4
RETI
Interrupt Return
PC  STACK
I
if (Rd = Rr) PC PC + 2 or 3
None
CALL
k
4
CPSE
Rd,Rr
Compare, Skip if Equal
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
SBRC
Rr, b
Skip if Bit in Register Cleared
if (Rr(b)=0) PC  PC + 2 or 3
None
1
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 PCPC+k + 1
None
1/2
BRBC
s, k
Branch if Status Flag Cleared
if (SREG(s) = 0) then PCPC+k + 1
None
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
240
ATmega406
2548F–AVR–03/2013
ATmega406
33. Instruction Set Summary (Continued)
Mnemonics
Operands
Description
Operation
Flags
#Clocks
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)  1
None
2
CBI
P,b
Clear Bit in I/O Register
I/O(P,b)  0
None
2
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),CRd(7)
Z,C,N,V
1
ROR
Rd
Rotate Right Through Carry
Rd(7)C,Rd(n) Rd(n+1),CRd(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)  T
None
1
1
SEC
Set Carry
C1
C
CLC
Clear Carry
C0
C
1
SEN
Set Negative Flag
N1
N
1
CLN
Clear Negative Flag
N0
N
1
SEZ
Set Zero Flag
Z1
Z
1
CLZ
Clear Zero Flag
Z0
Z
1
SEI
Global Interrupt Enable
I1
I
1
CLI
Global Interrupt Disable
I 0
I
1
1
SES
Set Signed Test Flag
S1
S
CLS
Clear Signed Test Flag
S0
S
1
SEV
Set Twos Complement Overflow.
V1
V
1
CLV
Clear Twos Complement Overflow
V0
V
1
SET
Set T in SREG
T1
T
1
CLT
Clear T in SREG
T0
T
1
SEH
CLH
Set Half Carry Flag in SREG
Clear Half Carry Flag in SREG
H1
H0
H
H
1
1
None
1
None
1
DATA TRANSFER INSTRUCTIONS
MOV
Rd, Rr
Move Between Registers
MOVW
Rd, Rr
Copy Register Word
Rd  Rr
Rd+1:Rd  Rr+1:Rr
LDI
Rd, K
Load Immediate
Rd  K
None
1
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
2
LD
Rd, Y
Load Indirect
Rd  (Y)
None
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
2
LDS
Rd, k
Load Direct from SRAM
Rd  (k)
None
ST
X, Rr
Store Indirect
(X) Rr
None
2
ST
X+, Rr
Store Indirect and Post-Inc.
(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
Store Indirect
(Y)  Rr
None
2
ST
Y+, Rr
Store Indirect and Post-Inc.
(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 with Displacement
(Y + q)  Rr
None
2
ST
Z, Rr
Store Indirect
(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 Displacement
(Z + q)  Rr
None
2
STS
k, Rr
Store Direct to SRAM
(k)  Rr
None
2
Load Program Memory
R0  (Z)
None
3
LPM
LPM
Rd, Z
Load Program Memory
Rd  (Z)
None
3
LPM
Rd, Z+
Load Program Memory and Post-Inc
Rd  (Z), Z  Z+1
None
3
Store Program Memory
(Z)  R1:R0
None
-
In Port
Rd  P
None
1
SPM
IN
Rd, P
241
2548F–AVR–03/2013
33. Instruction Set Summary (Continued)
Mnemonics
Operands
Description
Operation
Flags
#Clocks
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)
None
1
WDR
BREAK
Watchdog Reset
Break
(see specific descr. for WDR/timer)
For On-chip Debug Only
None
None
1
N/A
242
ATmega406
2548F–AVR–03/2013
ATmega406
34. Ordering Information
Speed (MHz)
Power Supply
1
4.0 - 25V
Notes:
Ordering Code
Package(1)
ATmega406-1AAU(2)
48AA
Operation Range
Industrial
(-30C to 85C)
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 directive). Also Halide free and fully Green.
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)
243
2548F–AVR–03/2013
35. Packaging Information
35.1
48AA
PIN 1
B
PIN 1 IDENTIFIER
e
E1
E
D1
D
C
0°~7°
A1
A2
A
L
COMMON DIMENSIONS
(Unit of Measure = mm)
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.
SYMBOL
MIN
NOM
MAX
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
E
8.75
9.00
9.25
E1
6.90
7.00
7.10
B
0.17
–
0.27
C
0.09
–
0.20
L
0.45
–
0.75
e
NOTE
Note 2
Note 2
0.50 TYP
2010-10-19
R
244
2325 Orchard Parkway
San Jose, CA 95131
TITLE
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)
DRAWING NO.
48AA
REV.
D
ATmega406
2548F–AVR–03/2013
ATmega406
36. Errata
36.1
Rev. F
• Voltage-ADC Common Mode Offset
• Voltage Reference Spike
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 worst-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 voltage 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% unbalanced cells.
245
2548F–AVR–03/2013
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 VTEMP 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 Voltage Reference spike.
246
ATmega406
2548F–AVR–03/2013
ATmega406
Figure 36-2. Voltage Reference Spike
Voltage
V~50mV
1.1 V
VREF
t ~< 5ms
time
VADEN
VADMUX3:0
XXX
VTEMP
Problem workaround:
To get correct temperature measurement, the VADSC bit should not be written until the
spike has settled (external decoupling capacitor of 1F).
247
2548F–AVR–03/2013
36.2
Rev. E
• Voltage ADC not functional below 0°C
• Voltage-ADC Common Mode Offset
• Voltage Reference Spike
1. Voltage-ADC Failing at Low Temperatures
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 worst-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 voltage 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% unbalanced cells.
248
ATmega406
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 each time a temperature measurement is started
with the Voltage-ADC.
Problem Fix/Workaround
An accurate temperature measurement could be obtained by doing 10 temperature conversions 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 temperature conversions in a row (external decoupling capacitor of 1F).
249
2548F–AVR–03/2013
Figure 36-4. Voltage Reference Spike
Voltage
V~50mV
1.1 V
VREF
t ~< 5ms
time
VADSC
VADMUX3:0
(10 VTEMP conversion in a row)
XXX
VTEMP
If the CC-ADC is doing current accumulation while the V-ADC is doing temperature measurement, both the Instantaneous and the Accumulated conversion results will be affected.
The spike on VREF will be visible on 1 Accumulated Current (CADAC3…0) and 2 Instantaneous Current (CADIC1…0) conversion results.
36.3
Rev. D
•
•
•
•
•
•
Voltage ADC not functional below 0°C
Voltage-ADC Common Mode Offset
Voltage Reference Spike
Voltage Regulator Start-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 Temperatures
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:
250
ATmega406
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 worst-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 voltage 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% unbalanced cells.
Figure 36-5. CM Offset with unbalanced cells.
Problem Fix/Workaround
Avoid getting unbalanced cells by using the internal cell balancing FETs.
251
2548F–AVR–03/2013
3. Voltage Reference Spike
The Voltage Reference, VREF, will spike each time a temperature measurement is started
with the Voltage-ADC.
Problem Fix/Workaround
An accurate temperature measurement could be obtained by doing 10 temperature conversions 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 conversions in a row (external decoupling capacitor of 1F).
Figure 36-6. Voltage Reference Spike
Voltage
V~50mV
1.1 V
VREF
t ~< 5ms
time
VADSC
VADMUX3:0
(10 VTEMP conversion in a row)
XXX
VTEMP
If the CC-ADC is doing current accumulation while the V-ADC is doing temperature measurement, both the Instantaneous and the Accumulated conversion results will be affected.
The spike on VREF will be visible on 1 Accumulated Current (CADAC3…0) and 2 Instantaneous Current (CADIC1…0) conversion results.
252
ATmega406
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 regulator.
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 Regulator will normally start up properly in Power-off mode (VREG appr. 2.8 volts).
c.
After all cells have been assembled as described in step 2, a charger 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 initialize 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 ensure proper start up and initialization. In this case the charger source 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-circuit inactive. This will increase VREF voltage with typical 1 mV compared 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 Status Register (FCSR) is set.
This will increase VREF voltage with typical 8 mV compared to a condition with shortcircuit 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 Discharge 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 mode 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.
253
2548F–AVR–03/2013
37. Datasheet Revision History
37.1
Rev 2548F - 03/13
1.
2.
3.
37.2
Rev 2548E - 07/06
1.
2.
3.
4.
5
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23
24.
25.
26
27.
28.
29.
30.
254
Updated heading titles of “PPI/NNI” and ”PI/NI” on page 6.
Updated Note 10 in Table 27-5 on page 189
Updated Section 30.2 on page 225.
Updated ”Pin Configurations” on page 2.
Updated ”ADC Noise Reduction Mode” on page 32.
Updated ”Power-save Mode” on page 32.
Updated ”Power-down Mode” on page 33.
Updated ”Power-off Mode” on page 33.
Updated ”Power Reduction Register” on page 36.
Added ”Voltage ADC” on page 37 and ”Coloumb Counter” on page 38.
Updated ”Reset Sources” on page 39.
Updated ”Power-on Reset and Charger Connect” on page 40.
Updated ”External Reset” on page 41.
VCC replaced by VREG in ”Brown-out Detection” on page 42.
Updated ”Alternate Port Functions” on page 66.
Updated ”Internal Clock Source” on page 103.
Updated ”External Clock Source” on page 103.
Updated Features in ”Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC”
on page 106.
Updated Operation in Section 18. ”Coulomb Counter - Dedicated Fuel Gauging
Sigma-delta ADC” on page 106.
Updated Features in ”Voltage Regulator” on page 114.
Updated Operation in ”Voltage Regulator” on page 114.
Updated Bit description in ”VADCL and VADCH – The V-ADC Data Register” on page
119.
Updated ”Writing to Bandgap Calibration Registers” on page 122.
Updated Text in ”Register Description for FET Control” on page 134.
Added ”MCUCR – MCU Control Register” on page 176.
Updated ”Operating Circuit” on page 223
Updated ”Electrical Characteristics” on page 225.
Added ”Typical Characteristics – Preliminary” on page 232.
Updated ”Register Summary” on page 236.
Updated ”Errata” on page 245.
Updated Table 9-2 on page 48, Table 27-5 on page 189.
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.
Updated Register Adresses.
ATmega406
2548F–AVR–03/2013
ATmega406
37.3
Rev 2548D - 06/05
1.
37.4
Rev 2548C - 05/05
1.
37.5
Updated Section 36. ”Errata” on page 245.
Updated Section 36. ”Errata” on page 245.
Rev 2548B - 04/05
1.
2.
3.
4.
5.
6.
7.
8.
9.
Typos updated, bit “PSRASY” removed, CS12:0 renamed CS1[2:0].
Removed “BGEN” bit in BGCCR register. The bandgap voltage reference is always
enabled in ATmega406 revision E.
Updated Figure 2-1 on page 3, Figure 6-1 on page 25, Figure 24-9 on page 137, Figure 21-1 on page 120.
Updated 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.
Updated Section 12.3.2 ”Alternate Functions of Port A” on page 66 and Section 21.
”Battery Protection” on page 118 description.
Updated registers ”External Interrupt Flag Register – EIFR” on page 55 and
”Timer/Counter Control Register B – TCCR0B” on page 89.
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.
Updated Section 29. ”Electrical Characteristics” on page 211.
Updated Section 35. ”Errata” on page 225.
255
2548F–AVR–03/2013
256
ATmega406
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
i
2548F–AVR–03/2013
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 Outputs ....................................................75
14.2 Configuring the Pin ...............................................................................................76
14.3 Register Description for High Voltage Output Ports .............................................76
ii
ATmega406
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 General 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
iii
2548F–AVR–03/2013
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
iv
ATmega406
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
v
2548F–AVR–03/2013
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
vi
ATmega406
2548F–AVR–03/2013
Atmel Corporation
1600 Technology Drive
Atmel Asia Limited
Unit 01-5 & 16, 19F
Atmel Munich GmbH
Business Campus
Atmel Japan G.K.
16F Shin-Osaki Kangyo Bldg
San Jose, CA 95110
BEA Tower, Millennium City 5
Parkring 4
1-6-4 Osaki, Shinagawa-ku
USA
418 Kwun Tong Roa
D-85748 Garching b. Munich
Tokyo 141-0032
Tel: (+1) (408) 441-0311
Kwun Tong, Kowloon
GERMANY
JAPAN
Fax: (+1) (408) 487-2600
HONG KONG
Tel: (+49) 89-31970-0
Tel: (+81) (3) 6417-0300
www.atmel.com
Tel: (+852) 2245-6100
Fax: (+49) 89-3194621
Fax: (+81) (3) 6417-0370
Fax: (+852) 2722-1369
© 2013 Atmel Corporation. All rights reserved. / Rev.: 2548F–AVR–03/2013
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, AVR®, and others are registered trademarks or trademarks of Atmel Corporation or
its subsidiaries. Other terms and product names may be trademarks of others.
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 granted 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
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically 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.