ATMEL ATMEGA16HVB

Features
• High Performance, Low Power AVR® 8-bit Microcontroller
• Advanced RISC Architecture
•
•
•
•
•
•
•
•
•
•
– 131 Powerful Instructions - Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 8 MIPS Throughput at 8 MHz
High Endurance Non-volatile Memory Segments
– 16K/32K Bytes of In-System Self-Programmable Flash (ATmega16HVB/32HVB)
– 512/1K Bytes EEPROM
– 1K/2K Bytes Internal SRAM
– Write/Erase Cycles 10,000 Flash/100,000 EEPROM
– Data retention: 20 years at 85°C/100 years at 25°C(1)
– Optional Boot Code Section with Independent Lock Bits
In-System Programming by On-chip Boot Program
True Read-While-Write Operation
– Programming Lock for Software Security
Battery Management Features
– Two, three or Four Cells in Series
– High-current Protection (Charge and Discharge)
– Over-current Protection (Charge and Discharge)
– Short-circuit Protection (Discharge)
– High Voltage Outputs to Drive N-Channel Charge/Discharge FETs
– Optional Deep Under Voltage Recovery mode - allowing 0-volt charging without
external Precharge FET
– Optional High Voltage Open Drain ouput - allowing 0-volt charging with external
Precharge FET
– Integrated Cell Balancing FETs
Peripheral Features
– Two configurable 8- or 16-bit Timers with Separate Prescaler, Optional Input Capture
(IC), Compare Mode and CTC
– SPI - Serial Peripheral Interface
– 12-bit Voltage ADC, Six External and One Internal ADC Input
– High Resolution Coulomb Counter ADC for Current Measurements
– TWI Serial Interface supporting SMBus implementation
– Programmable Watchdog Timer
Special Microcontroller Features
– debugWIRE On-chip Debug System
– In-System Programmable via SPI ports
– Power-on Reset
– On-chip Voltage Regulator with Short-circuit Monitoring Interface
– External and Internal Interrupt Sources
– Sleep Modes: Idle, ADC Noise Reduction, Power-save, and Power-off
Additional Secure Authentication Features available only under NDA
Packages
– 44-pin TSSOP
Operating Voltage: 4 - 25V
Maximum Withstand Voltage (High-voltage pins): 35V
Temperature Range: -40°C to 85°C
Speed Grade: 1-8 MHz
Note:
8-bit
Microcontroller
with 16K/32K
Bytes In-System
Programmable
Flash
ATmega16HVB
ATmega32HVB
Preliminary
1. See ”Data Retention” on page 8 for details.
8042B–AVR–06/10
ATmega16HVB/32HVB
1. Pin Configurations
1.1
TSSOP
Figure 1-1.
1.2
1.2.1
TSSOP - pinout ATmega16HVB/32HVB
NI
1
44
PI
NNI
2
43
PPI
VREFGND
3
42
NV
VREF
4
41
PV1
GND
5
40
PV2
VREG
6
39
PV3
PA0(ADC0/SGND/PCINT0)
7
38
PV4
PA1(ADC1/SGND/PCINT1)
8
37
PVT
PA2(PCINT2/T0)
9
36
VCC
PA3(PCINT3/T1)
10
35
GND
VCLMP10
11
34
PC5
VFET
12
33
PC4(SCL)
BATT
13
32
PC3(INT3/SDA)
VCC
14
31
PC2(INT2)
GND
15
30
PC1(INT1)
OD
16
29
PC0(INT0/EXTPROT)
NC
17
28
PB7(MISO/PCINT11)
OC
18
27
NC
RESET/dw
19
26
PB6(MOSI/PCINT10)
PB0(PCINT4/ICP00)
20
25
PB5(SCK/PCINT9)
PB1(PCINT5/CKOUT)
21
24
PB4(SS/PCINT8)
PB2(PCINT6)
22
23
PB3(PCINT7)
Pin Descriptions
VFET
High voltage supply pin. This pin is used as supply for the internal voltage regulator, described in
”Voltage Regulator” on page 132.
1.2.2
VCLMP10
Internal 10V clamping of VFET voltage for external decoupling.
1.2.3
VCC
Digital supply voltage. Normally connected to VREG.
2
8042B–AVR–06/10
ATmega16HVB/32HVB
1.2.4
VREG
Output from the internal Voltage Regulator. Used for external decoupling to ensure stable regulator operation. For details, see ”Voltage Regulator” on page 132.
1.2.5
VREF
Internal Voltage Reference for external decoupling. For details, see ”Voltage Reference and
Temperature Sensor” on page 123.
1.2.6
VREFGND
Ground for decoupling of Internal Voltage Reference. For details, see ”Voltage Reference and
Temperature Sensor” on page 123. Do not connect to GND or SGND on PCB.
1.2.7
GND
Ground
1.2.8
Port A (PA3..PA0)
Port A serves as a low-voltage 4-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 ATmega16HVB/32HVB as
listed in ”Alternate Functions of Port A” on page 74.
1.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 ATmega16HVB/32HVB as
listed in ”Alternate Functions of Port B” on page 75.
1.2.10
Port C (PC5)
Port C (PC5) is a high voltage Open Drain output port.
1.2.11
Port C (PC4..PC0)
Port C is a 5-bit high voltage Open Drain bi-directional I/O port.
1.2.12
OC/OD
High voltage output to drive Charge/Discharge FET. For details, see ”FET Driver” on page 148.
1.2.13
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 108.
3
8042B–AVR–06/10
ATmega16HVB/32HVB
1.2.14
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 135.
1.2.15
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 – 7-channel General Purpose
12-bit Sigma-Delta ADC” on page 117.
1.2.16
PVT
Defines the source voltage level for the Charge FET driver. For details, see ”FET Driver” on
page 148.
1.2.17
BATT
Input for detecting when a charger is connected. Defines the source voltage level for the Discharge FET driver. For details, see ”FET Driver” on page 148.
1.2.18
RESET/dw
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. This pin is also used as debugWIRE
communication pin.
4
8042B–AVR–06/10
ATmega16HVB/32HVB
2. Overview
The ATmega16HVB/32HVB is a monitoring and protection circuit for 3 and 4-cell Li-ion applications with focus on highest safety including safe authentication, low cost and high utilization of
the cell energy. The device contains secure authentication features as well as autonomous battery protection during charging and discharging. The External Protection Input can be used to
implement other battery protection mechanisms using external components, e.g. protection
against chargers with too high charge voltage can be easily implemented with a few low cost
passive components. The feature set makes the ATmega16HVB/32HVB a key component in
any system focusing on high security, battery protection, high system utilization and low cost.
Figure 2-1.
Block Diagram
PB7..0
PC5..0
PORTB (8)
PORTC (6)
PB0
Oscillator
Circuits /
Clock
Generation
VCC
RESET/dW
SPI
TWI
8/16-bit T/C0
Cell
Balancing
Program
Logic
Power
Supervision
POR &
RESET
Flash
SRAM
8/16-bit T/C1
Voltage
ADC
VFET
VREG
PPI
NNI
PV4
PV3
PV2
PV1
NV
Watchdog
Timer
VPTAT
debugWIRE
CPU
EEPROM
Security
Module
GND
BATT
OD
Current
Protection
Oscillator
Sampling
Interface
Watchdog
Oscillator
OC
FET
Control
Charger
Detect
Voltage
Reference
Coulomb
Counter ADC
VREF
VREFGND
PI
NI
DATA BUS
Voltage
Regulator
Voltage Regulator
Monitor Interface
PORTA (4)
PA1..0
PA3..0
ATmega16HVB/32HVB provides the necessary redundancy on-chip to make sure that the battery is protected in critical failure modes. The chip is specifically designed to provide safety for
the battery cells in case of pin shorting, loss of power (either caused by battery pack short or
VCC short), illegal charger connection or software runaway. This makes ATmega16HVB/32HVB
the ideal 1-chip solution for applications with focus on high safety.
The ATmega16HVB/32HVB features an integrated voltage regulator that operates at a wide
range of input voltages, 4 - 25 volts. This voltage is regulated to a constant supply voltage of
nominally 3.3 volts for the integrated logic and analog functions. The regulator capabilities, com-
5
8042B–AVR–06/10
ATmega16HVB/32HVB
bined with an extremely low power consumption in the power saving modes, greatly enhances
the cell energy utilization compared to existing solutions.
The chip utilizes Atmel's patented Deep Under-voltage Recovery (DUVR) mode that supports
pre-charging of deeply discharged battery cells without using a separate Pre-charge FET. DUVR
mode cannot be used in 2-cell applications. Optionally, Pre-charge FETs are supported for integration into many existing battery charging schemes.
The battery protection monitors the charge and discharge current to detect illegal conditions and
protect the battery from these when required. A 12-bit Voltage ADC allows software to monitor
each cell voltage individually with high accuracy. The ADC also provides one internal input channel to measure on-chip temperature and two input channels intended for external thermistors.
An 18-bit ADC optimized for Coulomb Counting accumulates charge and discharge currents and
reports accumulated current with high resolution and accuracy. It can also be used to provide
instantaneous current measurements with 13 bit resolution. Integrated Cell Balancing FETs
allow cell balancing algorithms to be implemented in software.
The MCU provides the following features: 16K/32K bytes of In-System Programmable Flash with
Read-While-Write capabilities, 512/1K bytes EEPROM, 1K/2K bytes SRAM. 32 general purpose
working registers, 12 general purpose I/O lines, 5 general purpose high voltage open drain I/O
lines, one general purpose super high voltage open drain output, debugWIRE for On-chip
debugging and SPI for In-system Programming, a SM-Bus compliant TWI module, two flexible
Timer/Counters with Input Capture and compare modes.
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, integrated cell balancing FETs, Additional Secure Authentication Features, an
autonomous Battery Protection module, a programmable Watchdog Timer with internal Oscillator, and 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 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,
through an SPI serial interface, by a conventional non-volatile memory programmer or by an Onchip 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 ReadWhile-Write operation. By combining an 8-bit RISC CPU with In-System Self-ProgrammableFlash and highly accurate analog front-end in a monolithic chip.
The Atmel ATmega16HVB/32HVB is a powerful microcontroller that provides a highly flexible
and cost effective solution. It is part of the AVR Battery Management family that provides secure
authentication, highly accurate monitoring and autonomous protection for Lithium-ion battery
cells.
The ATmega16HVB/32HVB AVR is supported with a full suite of program and system development tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators, and Onchip Debugger.
6
8042B–AVR–06/10
ATmega16HVB/32HVB
2.1
Comparison Between ATmega16HVB and ATmega32HVB
The ATmega16HVB and ATmega32HVB differ only in memory size for Flash, EEPROM and
internal SRAM. Table 2-1 summarizes the different configuration for the two devices.
Table 2-1.
Configuration summary
Device
Flash
EEPROM
SRAM
ATmega16HVB
16K
512
1K
ATmega32HVB
32K
1K
2K
7
8042B–AVR–06/10
ATmega16HVB/32HVB
3. Disclaimer
All parameters contained in this datasheet are preliminary and based on characterization of
ATmega16/32HVB.
4. Resources
A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr
Note:
1.
5. 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”.
6. Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.
8
8042B–AVR–06/10
ATmega16HVB/32HVB
7. AVR CPU Core
7.1
Overview
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.
Figure 7-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.
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typ-
9
8042B–AVR–06/10
ATmega16HVB/32HVB
ical 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.
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
ATmega16HVB/32HVB has Extended I/O space from 0x60 - 0xFF in SRAM where only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
7.2
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.
7.3
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 Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored
when returning from an interrupt. This must be handled by software.
10
8042B–AVR–06/10
ATmega16HVB/32HVB
7.3.1
SREG – AVR Status Register
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 instruction set reference.
• 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 “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N ⊕ V
The S-bit is always an exclusive or between the negative flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
11
8042B–AVR–06/10
ATmega16HVB/32HVB
7.4
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 7-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 7-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 7-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.
7.4.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 7-3 on page 13.
12
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 7-3.
The X-, Y-, and Z-registers
15
X-register
XH
XL
7
0
R27 (0x1B)
YH
YL
7
0
R29 (0x1D)
Z-register
0
R26 (0x1A)
15
Y-register
0
7
0
7
0
R28 (0x1C)
15
ZH
7
0
ZL
7
R31 (0x1F)
0
0
R30 (0x1E)
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
7.5
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.
7.5.1
SPH and SPL – Stack Pointer High and Stack Pointer Low
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
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
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
RAMEND
Read/Write
Initial Value
13
8042B–AVR–06/10
ATmega16HVB/32HVB
7.6
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 7-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 7-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 7-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 7-5.
Single Cycle ALU Operation
T1
T2
T3
T4
clkCPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
7.7
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.
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 52. 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.
14
8042B–AVR–06/10
ATmega16HVB/32HVB
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
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, EEMPE
; start EEPROM write
sbi EECR, EEPE
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<<EEMPE); /* start EEPROM write */
EECR |= (1<<EEPE);
SREG = cSREG; /* restore SREG value (I-bit) */
15
8042B–AVR–06/10
ATmega16HVB/32HVB
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) */
7.7.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.
16
8042B–AVR–06/10
ATmega16HVB/32HVB
8. AVR Memories
8.1
Overview
This section describes the different memories in the ATmega16HVB/32HVB. The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In
addition, the ATmega16HVB/32HVB features an EEPROM Memory for data storage. All three
memory spaces are linear and regular.
8.2
In-System Reprogrammable Flash Program Memory
The ATmega16HVB/32HVB contains 16K/32K 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 8K/16K x 16.
The Flash memory has an endurance of at least 10,000 write/erase cycles. The
ATmega16HVB/32HVB Program Counter (PC) is 13/14 bits wide, thus addressing the 8K/16K
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 191. ”Memory Programming” on page 208 contains a detailed
description on Flash programming.
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 14.
Figure 8-1.
Program Memory Map
Program Memory
0x0000
Application Flash Section
Boot Flash Section
0x1FFF/0x3FFF
8.3
SRAM Data Memory
Figure 8-2 on page 18 shows how the ATmega16HVB/32HVB SRAM Memory is organized.
17
8042B–AVR–06/10
ATmega16HVB/32HVB
The ATmega16HVB/32HVB 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 1280/2304 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 1K/2K 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 1K/2K bytes of internal data SRAM in the ATmega16HVB/32HVB are all accessible through
all these addressing modes. The Register File is described in ”General Purpose Register File”
on page 12.
Figure 8-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
(1K/2K x 8)
0x04FF/0x08FF
8.3.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 8-3.
18
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 8-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
8.4
Next Instruction
EEPROM Data Memory
The ATmega16HVB/32HVB contains 512/1K 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 EEPROM programming, see page 211 and page 216 respectively.
8.4.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 8-1 on page 21. 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.
8.5
I/O Memory
The I/O space definition of the ATmega16HVB/32HVB is shown in ”Register Summary” on page
256.
All ATmega16HVB/32HVB 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,
19
8042B–AVR–06/10
ATmega16HVB/32HVB
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
ATmega16HVB/32HVB 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 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.
8.5.1
General Purpose I/O Registers
The ATmega16HVB/32HVB 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 bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
8.6
8.6.1
Register Description
EEARH and EEARL– The EEPROM Address Register High and Low
Bit
15
14
13
12
11
10
0x22 (0x42)
0x21 (0x41)
Bit
Read/Write
Initial Value
9
8
EEAR9
EEAR8
EEARH
EEARL
EEAR7
EEAR6
EEAR5
EEAR4
EEAR3
EEAR2
EEAR1
EEAR0
7
6
5
4
3
2
1
0
R
R
R
R
R
R
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
X
X
X
X
X
X
X
X
X
X
• Bits 15:10 – Reserved
These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero.
• Bits 9:0 – EEAR9:0: EEPROM Address
The EEPROM Address Registers – EEAR specify the EEPROM address in the 512/1K bytes
EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511/1023.
The initial value of EEAR is undefined. A proper value must be written before the EEPROM may
be accessed.
8.6.2
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
20
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bits 7:0 – EEDR[7: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.
8.6.3
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 – Reserved
These bits are reserved in the ATmega16HVB/32HVB 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 8-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.
Table 8-1.
EEPROM Mode Bits
EEPM1
EEPM0
Typ. Programming Time(1)
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
–
Note:
Operation
Reserved for future use
1. Actual timing depends on frequency of the Calibrated Fast RC Oscillator.
• 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 Write 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 Write 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
21
8042B–AVR–06/10
ATmega16HVB/32HVB
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 2 and 3 is not essential):
1. Wait until EEPE becomes zero.
2. Write new EEPROM address to EEAR (optional).
3. Write new EEPROM data to EEDR (optional).
4. Write a logical one to the EEMPE bit while writing a zero to EEPE in EECR.
5. Within four clock cycles after setting EEMPE, write a logical one to EEPE.
Caution:
An interrupt between step 4 and step 5 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.
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.
Caution:
A BOD reset during EEPROM write will invalidate the result of the ongoing operation.
• 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 and the programming time will
therefore depend on the calibrated oscillator frequency. Table 8-2 lists the typical programming
time for EEPROM access from the CPU.
Table 8-2.
EEPROM Programming Time
Symbol
EEPROM write
(from CPU)
Number of Calibrated RC
Oscillator Cycles
Typ Programming Time,
fOSC = 8 MHz
27200
3.4 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.
22
8042B–AVR–06/10
ATmega16HVB/32HVB
Assembly Code Example
EEPROM_write:
; Wait for completion of previous write
sbic EECR,EEPE
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 EEMPE
sbi EECR,EEMPE
; Start eeprom write by setting EEPE
sbi EECR,EEPE
ret
C Code Example
void EEPROM_write(unsigned int uiAddress, unsigned char ucData)
{
/* Wait for completion of previous write */
while(EECR & (1<<EEPE))
;
/* Set up address and data registers */
EEAR = uiAddress;
EEDR = ucData;
/* Write logical one to EEMPE */
EECR |= (1<<EEMPE);
/* Start eeprom write by setting EEPE */
EECR |= (1<<EEPE);
}
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.
23
8042B–AVR–06/10
ATmega16HVB/32HVB
Assembly Code Example
EEPROM_read:
; Wait for completion of previous write
sbic EECR,EEPE
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<<EEPE))
;
/* Set up address register */
EEAR = uiAddress;
/* Start eeprom read by writing EERE */
EECR |= (1<<EERE);
/* Return data from data register */
return EEDR;
}
8.6.4
GPIOR2 – General Purpose I/O Register 2
Bit
8.6.5
6
5
4
3
2
1
0
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
GPIOR2
GPIOR1 – General Purpose I/O Register 1
Bit
8.6.6
7
0x2B (0x4B)
7
6
0
0x2A (0x4A)
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
5
4
3
2
1
GPIOR1
GPIOR0 – General Purpose I/O Register 0
Bit
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
24
8042B–AVR–06/10
ATmega16HVB/32HVB
9. System Clock and Clock Options
9.1
Clock Systems and their Distribution
Figure 9-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 35. The clock systems are detailed below.
Figure 9-1.
Clock Distribution
Coulomb Counter
ADC
CPU
CORE
FLASH and
EEPROM
RAM
clkCCADC
clkFLASH
1/4
Watchdog Timer
TWI Disconnect
delay
Other I/O
Modules
clkVADC
VADC
Prescaler
clkCPU
Oscillator Sampling
Interface
Voltage
ADC
clkI/O
AVR
Clock Control
Battery Protection
Reset Logic
System Clock
Prescaler
Slow RC
Oscillator
9.1.1
Ultra Low Power
RC Oscillator
Fast RC
Oscillator
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.
9.1.2
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.
9.1.3
Flash Clock – clkFLASH
The Flash clock controls operation of the Flash interface. The Flash clock is usually active simultaneously with the CPU clock.
25
8042B–AVR–06/10
ATmega16HVB/32HVB
9.1.4
Voltage ADC Clock – clkVADC
The Voltage ADC is provided with a dedicated clock domain. The VADC clock is automatically
prescaled relative to the System Clock Prescalers setting by the VADC Prescaler, giving a fixed
VADC clock at 1 MHz.
9.1.5
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.
9.1.6
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.
9.2
Clock Sources
The following section describes the clock sources available in the device. The clocks are input to
the AVR clock generator, and routed to the appropriate modules.
The ATmega16HVB/32HVB has 3 on-board oscillator used to clock the internal logic. Table 9-1
shows the clock sources and their usage.
Table 9-1.
Available Clock Sources.
Clock Source
9.2.1
Usage
Calibrated Fast RC Oscillator
The clock source for the CPU, I/O, Flash, and Voltage ADC.
Ultra Low Power RC Oscillator
The clock source for the Watchdog Timer, Battery Protection,
Bandgap Buffer Short Circuit Detector, and SMBus
Connect/Disconnect.
Slow RC Oscillator
Used by the Coulomb Counter ADC and Oscillator Sampling
Interface (OSI).
Calibrated Fast RC Oscillator
The calibrated Fast RC Oscillator by default provides a 8.0 MHz clock. 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 8 MHz ± 1%. The oscillator can
be calibrated to any frequency in the range 7.3 - 8.1 MHz by changing the FOSCCAL register.
For more information on the pre-programmed calibration value, see the section ”Reading the
Signature Row from Software” on page 199. Note that the frequency of the system clock is given
by the ”System Clock Prescaler” on page 28.
26
8042B–AVR–06/10
ATmega16HVB/32HVB
When this Oscillator is selected, start-up times are determined by the SUT Fuses as shown in
Table 9-2 on page 27.
Table 9-2.
SUT2:0
Start-up Time from
Power-save
Additional Delay from Reset, Typical Values(2)
000
6 CK
14 CK + 4 ms
001
6 CK
14 CK + 8 ms
010
6 CK
14 CK + 16 ms
011
6 CK
14 CK + 32 ms
100
6 CK
14 CK + 64 ms
101
6 CK
14 CK + 128 ms
110
6 CK
14 CK + 256 ms
6 CK
14 CK + 512 ms
111
Notes:
9.2.2
Start-up times for the calibrated Fast RC Oscillator clock selection
(1)
1. The device is shipped with this option selected.
2. The actual value of the added, selectable 4- 512 ms delay depends on the actual frequency of
the ”Ultra Low Power RC Oscillator” on page 27. See Table 9-3 on page 28 and ”Electrical
Characteristics” on page 230
Slow RC Oscillator
The Slow RC Oscillator provides a 131 kHz clock (typical value, refer to section ”Electrical Characteristics” on page 230). This oscillator provides the clock for the CC-ADC module. It can also
be used as a timing reference for run-time calibration of the Fast RC Oscillator and for accurately determining the actual ULP Oscillator frequency, refer to ”OSI – Oscillator Sampling
Interface” on page 29 for details.
To provide good accuracy when used as a timing reference, the Slow RC Oscillator has calibration bytes stored in the signature address space, refer to section ”Reading the Signature Row
from Software” on page 199 for details. The actual clock period of the Slow RC Oscillator in μs
as a function of temperature is given by:
(T – T HOT )
Slow RC word - Slow RC temp prediction word ⋅ --------------------------64
Slow RC period = -----------------------------------------------------------------------------------------------------------------------------------------------------------1024
where T is the die temperature in Kelvin and THOT is the calibration temperature stored in the signature row. The die temperature can be found using the Voltage ADC, refer to section ”Voltage
ADC – 7-channel General Purpose 12-bit Sigma-Delta ADC” on page 117 for details.
9.2.3
Ultra Low Power RC Oscillator
The Ultra Low Power RC Oscillator (ULP Oscillator) provides a 128 kHz clock (typical value,
refer to section ”Electrical Characteristics” on page 230). This oscillator provides the clock for
the Watchdog Timer and Battery Protection modules. The actual ULP Oscillator frequency
depends on process variations and temperature, see ”Electrical Characteristics” on page 230.
The Oscillator is automatically enabled in all operational modes. It is also enabled during reset.
There are two alternative methods for determining the actual clock period of the ULP Oscillator:
27
8042B–AVR–06/10
ATmega16HVB/32HVB
1. To determine the accurate clock period as a function of die temperature, if needed by the
application, the Oscillator Sampling Interface should be used. Refer to section ”OSI –
Oscillator Sampling Interface” on page 29 for details.
2. To determine a fixed value for the actual clock period independent of the die temperature,
for example to determine the best setting of the Battery Protection timing, use the calibration byte ULP_RC_FRQ stored in the signature address space, refer to section ”Reading
the Signature Row from Software” on page 199 for details.
9.3
Clock Startup Sequence
When the CPU wakes up from 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 shown in Table 9-2
on page 27. The number of Ultra Low Power RC Oscillator cycles used for each time-out is
shown in Table 9-3.
Table 9-3.
Note:
9.4
Number of Ultra Low Power RC Oscillator Cycles
Typ Time-out(1)
Number of Cycles
4 ms
512
8 ms
1K
16 ms
2K
32 ms
4K
64 ms
8K
128 ms
16K
256 ms
32K
512 ms
64K
1. The actual value depends on the actual clock period of the Ultra Low Power RC Oscillator,
refer to ”Ultra Low Power RC Oscillator” on page 27 for details.
Clock Output
The CPU clock divided by 2 can be output to the PB1 pin. The CPU can enable the clock output
function by setting the CKOE bit in the MCU Control Register. The clock will not run in any sleep
modes.
9.5
System Clock Prescaler
The ATmega16HVB/32HVB has a System Clock Prescaler, used to prescale the Calibrated Fast
RC Oscillator. The system clock can be divided by setting the ”CLKPR – Clock Prescale Register” on page 32, and this enables the user to decrease or increase the system clock frequency
as the requirement for power consumption and processing power changes. This system clock
will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkCPU and clkFLASH are divided by a factor as shown in Table 9-4 on page 33.
When switching between prescaler settings, the System Clock Prescaler ensures that no
glitches occurs in the clock system. It also ensures that no intermediate frequency is higher than
28
8042B–AVR–06/10
ATmega16HVB/32HVB
neither the clock frequency corresponding to the previous setting, nor the clock frequency corresponding to the new setting.
The ripple counter that implements the prescaler runs at the frequency of the undivided clock,
and may be faster than the CPU's clock frequency. It is not possible to determine the state of the
prescaler, and the exact time it takes to switch from one clock division to the other cannot be
exactly predicted. From the time the CLKPS values are written, it takes between T1 + T2 and T1
+ 2*T2 before the new clock frequency is active. In this interval, two active clock edges are produced. Here, T1 is the previous clock period, and T2 is the period corresponding to the new
prescaler setting.
To avoid unintentional changes of clock frequency, a special write procedure must be followed
to change the CLKPS bits:
1. Write the Clock Prescaler Change Enable (CLKPCE) bit to one and all other bits in
CLKPR to zero.
2. Within four cycles, write the desired value to CLKPS while writing a zero to CLKPCE.
Interrupts must be disabled when changing prescaler setting to make sure the write procedure is
not interrupted.
9.6
VADC Clock Prescaler
The VADC clock will be automatically prescaled relative to the System Clock Prescaler settings,
see ”System Clock Prescaler” on page 28. Depending on the Clock Prescale Select bits,
CLKPS1..0, the VADC clock, clkVADC, will be prescaled by 8, 4, 2 or 1 as shown in Table 9-5 on
page 33.
9.7
9.7.1
OSI – Oscillator Sampling Interface
Features
•
•
•
•
9.7.2
Runtime selectable oscillator input (Slow RC or ULP RC Oscillator)
7 bit prescaling of the selected oscillator
Software read access to the phase of the prescaled clock
Input capture trigger source for Timer/Counter0
Overview
The Oscillator Sampling Interface (OSI) enables sampling of the Slow RC and Ultra Low Power
RC (ULP) oscillators in ATmega16HVB/32HVB. OSI can be used to calibrate the Fast RC Oscillator runtime with high accuracy. OSI can also provide an accurate reference for compensating
the ULP Oscillator frequency drift.
The prescaled oscillator phase can be continuously read by the CPU through the OSICSR register. In addition, the input capture function of Timer/Counter0 can be set up to trigger on the rising
edge of the prescaled clock. This enables accurate measurements of the oscillator frequencies
relative to the Fast RC Oscillator.
A simplified block diagram of the Oscillator Sampling Interface is shown in Figure 9-2 on page
30.
29
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 9-2.
Oscillator Sampling Interface Block Diagram
Databus
OSICSR
Ultra Low
Power RC
Oscillator
Slow RC
Oscillator
OSCILLATOR SELECT
OSISEL0
7 bit prescaler
Edge
Detector
osi_posedge
Fast RC
Oscillator
The osi_posedge signal pulses on each rising edge of the prescaled clock. This signal is not
directly accessible by the CPU, but can be used to trigger the input capture function of
Timer/Counter0. Using OSI in combination with the input capture function of Timer/Counter0
facilitates accurate measurement of the oscillator frequencies with a minimum of CPU calculation. Refer to ”Timer/Counter (T/C0,T/C1)” on page 82 for details on how to enable the Input
Capture function.
30
8042B–AVR–06/10
ATmega16HVB/32HVB
9.7.3
Usage
The Slow RC oscillator represents a highly predictable and accurate clock source over the entire
temperature range and provides an excellent reference for calibrating the Fast RC oscillator runtime. Typically, runtime calibration is needed to provide an accurate Fast RC frequency for
asynchronous serial communication in the complete temperature range.
The Slow RC frequency at 85°C and the Slow RC temperature coefficient are stored in the signature row. These characteristics can be used to calculate the actual Slow RC clock period at a
given temperature with high precision. Refer to ”Slow RC Oscillator” on page 27 for details.
By measuring the number of CPU cycles of one or more prescaled Slow RC clock periods, the
actual Fast RC oscillator clock period can be determined. The Fast RC clock period can then be
adjusted by writing to the FOSCCAL register. The new Fast RC clock period after calibration
should be verified by repeating the measurement and repeating the calibration if necessary. The
Fast RC clock period as a function of the Slow RC clock period is given by:
128 ⋅ n
T FastRC = T SlowRC ⋅ ------------------------------------------------------------------------------------------------------------------------------------------------number of CPU cycles in n prescaled Slow RC periods
where n is the number of prescaled Slow RC periods that is used in the measurement. Using
more prescaled Slow RC periods decreases the measurement error, but increases the time consumed for calibration. Note that the Slow RC Oscillator needs very short time to stabilize after
being enabled by the OSI module. Hence, the calibration algorithm may use the time between
the first and second osi_posedge as time reference for calculations.
Another usage of OSI is determining the ULP frequency accurately. The ULP frequency at 85°C
and the ULP temperature coefficient are stored in the signature row, allowing the ULP frequency
to be calculated directly. However, the ULP frequency is less predictable over temperature than
the Slow RC oscillator frequency, therefore a more accurate result can be obtained by calculating the ratio between the Slow RC and ULP oscillators. This is done by sampling both the ULP
and Slow RC oscillators and comparing the results. When the ratio is known, the actual ULP frequency can be determined with high accuracy. The ULP RC clock period as a function of the
Slow RC clock period is given by:
number of CPU cycles in n prescaled ULP RC periods
T ULPRC = T SlowRC ⋅ ------------------------------------------------------------------------------------------------------------------------------------------------number of CPU cycles in n prescaled Slow RC periods
where n is the number of prescaled ULP RC and Slow RC periods that is used in the measurement. Using more prescaled ULP RC and Slow RC periods decreases the measurement error,
but increases the time consumed for calibration. Note that the FOSCCAL register must be kept
at a constant value during this operation to ensure accurate results.
These clock period calculations should be performed again when there is a significant change in
die temperature since the previous calculation. The die temperature can be found using the Voltage ADC, refer to section ”Voltage ADC – 7-channel General Purpose 12-bit Sigma-Delta ADC”
on page 117 for details.
31
8042B–AVR–06/10
ATmega16HVB/32HVB
9.8
9.8.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 – FCAL[7: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 approximately 8.0 MHz
at 25°C. The application software can write this register to change the oscillator frequency. The
oscillator can be run-time calibrated to any frequency in the range 7.3 - 8.1 MHz. 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 8.1 MHz. Otherwise, the EEPROM or Flash write may fail.
The FCAL[7:5] bits determine the range of operation for the oscillator. Setting these bits to
0b000 gives the lowest frequency range, setting this bit to 0b111 gives the highest frequency
range. The frequency ranges are overlapping. A setting of for instance FOSCCAL = 0x1F gives
a higher frequency than FOSCCAL = 0x20.
The FCAL[4: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 0x1F gives the highest frequency in the
range. Incrementing FCAL[4:0] by 1 will give a frequency increment of less than 1% in the frequency range 7.3 - 8.1 MHz. With an accurate time reference, an oscillator accuracy of ±0.5%
can be achieved after calibration. The frequency will drift with temperature, so run-time calibration will be required to maintain the accuracy. Refer to ”OSI – Oscillator Sampling Interface” on
page 29 for details.
9.8.2
MCUCR – MCU Control Register
Bit
7
6
5
4
0x35 (0x55)
-–
–
CKOE
PUD
Read/Write
R
R
R/W
Initial Value
0
0
0
3
2
1
0
–
–
IVSEL
IVCE
R/W
R
R
R/W
R/W
0
0
0
0
0
MCUCR
• Bit 5 – CKOE: Clock Output
When this bit is written to one, the CPU clock divided by 2 is output on the PB1 pin.
9.8.3
CLKPR – Clock Prescale Register
Bit
7
6
5
4
3
2
1
0
CLKPCE
–
–
–
–
–
CLKPS1
CLKPS0
Read/Write
R/W
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
1
1
(0x61)
CLKPR
32
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bit 7 – CLKPCE: Clock Prescaler Change Enable
The CLKPCE bit must be written to logic one to enable change of the CLKPS bits. The CLKPCE
bit is only updated when the other bits in CLKPR are simultaneously written to zero. CLKPCE is
cleared by hardware four cycles after it is written or when CLKPS bits are written. Rewriting the
CLKPCE bit within this time-out period does neither extend the time-out period, or clear the CLKPCE bit.
• Bit 1:0 – CLKPS[1:0]: Clock Prescaler Select Bit[1:0]
These bits define the division factor between the selected clock source and the internal system
clock. These bits can be written run-time to vary the clock frequency to suit the application
requirements. As the divider divides the master clock input to the MCU, the speed of all synchronous peripherals is reduced when a division factor is used. The division factors are given in
Table 9-4 on page 33. Note that writing to the System Clock Prescaler Select bits will abort any
ongoing VADC conversion.
Table 9-4.
Table 9-5.
Note:
9.8.4
System Clock Prescaler Select
CLKPS1
CLKPS0
Clock Division Factor
0
0
1
0
1
2
1
0
4
1
1
8
CLKPS1
CLKPS0
VADC Division Factor
0
0
8
0
1
4
1
0
2
1
1
1
VADC Clock Prescaling(1)
1. When changing Prescaler value, the VADC Prescaler will automatically change frequency of
the VADC clock and abort any ongoing conversion.
OSICSR – Oscillator Sampling Interface Control and Status Register
Bit
7
6
5
4
3
2
1
0
0x17 (0x37)
–
–
–
OSISEL0
–
–
OSIST
OSIEN
Read/Write
R
R
R
R/W
R
R
R
R/W
Initial Value
0
0
0
0
0
0
0
0
OSICSR
• Bits 7:5, 3:2 – Reserved
These bits are reserved in the ATmega16HVB/32HVB and will always read as zero.
33
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bit 4 – OSISEL0: Oscillator Sampling Interface Select 0
Table 9-6.
OSISEL Bit Description
OSISEL0
Oscillator source
0
ULP Oscillator
1
Slow RC Oscillator
• Bit 1 – OSIST: Oscillator Sampling Interface Status
This bit continuously displays the phase of the prescaled clock. This bit can be polled by the
CPU to determine the rising and falling edges of the prescaled clock.
• Bit 0 – OSIEN: Oscillator Sampling Interface Enable
Setting this bit enables the Oscillator Sampling Interface. When this bit is cleared, the Oscillator
Sampling Interface is disabled.
Notes:
1. The prescaler is reset each time the OSICSR register is written, and hence each time a new
oscillator source is selected.
2. Enabling the OSI module and selecting Slow RC Oscillator as input source is the only way to
enable the Slow RC Oscillator. The Slow RC Oscillator will not run in any other modes.
34
8042B–AVR–06/10
ATmega16HVB/32HVB
10. 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.
10.1
Sleep Modes
Figure 9-1 on page 25 presents the different clock systems in the ATmega16HVB/32HVB, and
their distribution. The figure is helpful in selecting an appropriate sleep mode. The different sleep
modes and their wake up sources is summarized in Table 10-1, and Figure 10-1 on page 36
shows a sleep mode state diagram.
Table 10-1.
Wake-up Sources for Sleep Modes
X
ADC Noise Reduction
X
X
X
X
X
X
X
X
Power-save
X
X
X
X
X
Power-off
Notes:
X
X
Voltage Regulator warning
X
SMBus Address match and
Bus Connect/Disconnect
X
Charger Detect(1)(2)
X
Other I/O
X
V-ADC
X
CC-ADC
X
SPM/EEPROM Ready
Battery Protection
Interrupts
X
WDT
Wake-up on
Regular Current
Idle
External Interrupts
Mode
Bandgap Buffer
Short Circuit Detection
Wake-up sources
X
X
X
X
X
X
X
X
X
1. Discharge FET must be switched off for Charge Detect to be active.
2. When waking from Power-off the Charger Detect will generate a Power-on Reset (POR). From other sleep modes a charger
detect interrupt will wake-up chip.
To enter any of the sleep modes, the SE bit in SMCR, see ”SMCR – Sleep Mode Control Register” on page 39, 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 will be activated by the SLEEP
instruction. See Table 10-3 on page 40 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.
35
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 10-1. Sleep Mode State Diagram
Reset From all States
Except Power-on Reset
RESET
Reset Time-out
Active
Interrupt
Sleep
Sleep
Interrupt
Interrupt
ADC NRM
Sleep
Sleep
or
Black-out
Detection
Idle
Black-out
Detection
Power-save
Black-out
Detection
Black-out
Detection
Power-off
Charger Connected
.
Table 10-2.
Active modules in different Sleep Modes
Mode
Active
Idle
ADC Noise
Reduction
Power-save
RCOSC_FAST
X
X
X
X
RCOSC_ULP
X
X
X
X
X(1)
X(1)
X(2)
X(2)
OSI
X
X
CPU
X
Flash
X
8-bit Timer/16-bit Timer
X
X
TWI/SMBus
X
X
X(3)
X(3)
SPI
X
X
V-ADC
X
X
X
CC-ADC
X
X
X
Module
RCOSC_SLOW
Power-off
X
36
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 10-2.
Active modules in different Sleep Modes (Continued)
Mode
Active
Idle
ADC Noise
Reduction
Power-save
External Interrupts
X
X
X
X
Battery Protection
X
X
X
X
Watchdog Timer
X
X
X
X
Voltage Regulator
X
X
X
X(5)
Bandgap Reference
X
X
X
X
X
X
X
X
X
X
X
X
Module
FET Driver
(4)
CHARGER_DETECT
Notes:
1.
2.
3.
4.
5.
10.2
Idle Mode
Power-off
X
Runs only when CC-ADC is enabled, or OSI is enabled and RCOSC_SLOW is selected as source for OSI.
Runs only when CC-ADC is enabled
Address Match and Bus Connect/Disconnect Wake-up only
Discharge FET must be switched off for Charger Detect to be enabled.
VREGMON interrupt (Regulator Operation Condition Warning) not available.
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.
10.3
ADC Noise Reduction
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), Voltage Regulator Monitor (VREGMON), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery
Protection (CBP), Slow RC Oscillator (RCOSC_SLOW) (if CC is enabled), and the Ultra Low
Power RC Oscillator (RCOSC_ULP) 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 accuracy on
measurements.
10.4
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
Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection (CBP) , Slow RC
Oscillator (RCOSC_SLOW) (if CC is enabled), 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 peripheral units running at the Fast internal Oscillator (RCOSC_FAST).
37
8042B–AVR–06/10
ATmega16HVB/32HVB
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
WDT 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 58
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.
10.5
Power-off Mode
When the SM2..0 bits are written to 100 and the SE bit is set, the SLEEP instruction makes the
CPU shut down the Voltage Regulator, leaving only the Charger Detect Circuitry 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. The MCU will reset when returning from Power-off mode.
Note:
10.6
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.
Power Reduction Register
The Power Reduction Register (PRR), see ”PRR0 – Power Reduction Register 0” on page 40,
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 read or 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.
10.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.
10.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-save mode. Refer to ”Watchdog
Timer” on page 46 for details on how to configure the Watchdog Timer.
10.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
38
8042B–AVR–06/10
ATmega16HVB/32HVB
some cases, the input logic is needed for detecting wake-up conditions, and it will then be
enabled. Refer to the section ”Digital Input Enable and Sleep Modes” on page 71 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 122 for details.
10.7.3
On-chip Debug System
A programmed DWEN Fuse enables some parts of the clock system to be running in all sleep
modes. This will increase the power consumption while in sleep. Thus, the DWEN Fuse should
be disabled when debugWire is not used.
10.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 141. The current consumption in the Battery Protection circuitry is only significant in Power-save mode. Disabling both
FETs will automatically disable the Battery Protection module in order to save power. The bandgap reference should always be enabled whenever Battery Protection is enabled.
10.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 sleep mode. See
”Voltage ADC – 7-channel General Purpose 12-bit Sigma-Delta ADC” on page 117 for details on
V-ADC operation.
10.7.6
Coulomb 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, or set in Regular Current detection mode. See
”Coulomb Counter – Dedicated Fuel Gauging Sigma-delta ADC” on page 108 for details on CCADC operation.
10.7.7
Bandgap Voltage Reference
If enabled, the Bandgap reference will consume power independent of sleep mode. To save
power, the Bandgap reference should be disabled when not used as reference for the Voltage
ADC, the Coloumb Counter or Battery Protection. See ”Voltage Reference and Temperature
Sensor” on page 123 for details.
10.8
10.8.1
Register Description
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
39
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bits 7:4 – Reserved
These bits are reserved in the ATmega16HVB/32HVB, and will always read as zero.
• Bits 3:1 – SM2:0: Sleep Mode Select Bits 2, 1 and 0
These bits select between the four available sleep modes as shown in Table 10-3.
Table 10-3.
Sleep Mode Select
SM2
SM1
SM0
Sleep Mode
0
0
0
Idle
0
0
1
ADC Noise Reduction
0
1
0
Reserved
0
1
1
Power-save
1
0
0
Power-off
1
0
1
Reserved
1
1
0
Reserved
1
1
1
Reserved
• 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.
10.8.2
PRR0 – Power Reduction Register 0
Bit
7
6
5
4
3
2
1
0
(0x64)
–
PRTWI
PRVRM
–
PRSPI
PRTIM1
PRTIM0
PRVADC
Read/Write
R
R/W
R/W
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
PRR0
• Bit 7, 4 – Reserved
These bits are reserved for future use. For compatibility with future devices, these bits must be
written to zero when PRR0 is written.
• Bit 6 – 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 5 – PRVRM: Power Reduction Voltage Regulator Monitor
Writing a logic one to this bit shuts down the Voltage Regulator Monitor interface by stopping the
clock of the module.
• Bit 3 – PRSPI: Power Reduction Serial Peripheral Interface
Writing logic one to this bit shuts down the Serial Peripheral Interface by stopping the clock to
the module. When waking up the SPI again, the SPI should be reinitialized to ensure proper
operation.
40
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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. Before writing the PRVADC bit, make sure
that the VADEN bit is cleared to minimize the power consumption.
Note:
V-ADC control registers can be updated even if the PRVADC bit is set.
41
8042B–AVR–06/10
ATmega16HVB/32HVB
11. System Control and Reset
11.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. The circuit diagram in ”Reset Logic” on page 43 shows the reset logic. Table 12-1 on
page 52 defines the electrical parameters of the reset circuitry.
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.
11.2
Reset Sources
The ATmega16HVB/32HVB has five sources of reset:
• The Power-on Reset module generates a Power-on Reset when the Voltage Regulator starts
up.
• External Reset. The MCU is reset when a low level is present on the RESET pin for longer than
the minimum pulse length.
• Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the
Watchdog is enabled.
• Brown-out Reset. The MCU is reset when VREG is below the Brown-out Reset Threshold, VBOT.
See “Brown-out Detection” on page 45.
• debugWIRE Reset. In On-chip Debug mode, the debugWIRE resets the MCU when giving the
Reset command.
42
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 11-1. Reset Logic
DATA BUS
PORF
OCDRF
EXTRF
WDRF
BODRF
MCU Status
Register (MCUSR)
VREG
Brown-out
Detection
Power-on
Reset
Circuit/
Charger
Detect
VFET
BATT
POR
VREG
Pull-up Resistor
RESET
/dW
SPIKE
FILTER
Reset Circuit
debugWIRE
Watchdog
Timer
COUNTER RESET
Ultra Low Power
RC Oscillator
Clock
Generator
Delay Counters
TIMEOUT
CK
SUT[1:0]
11.2.1
Power-on Reset and Charger Connect
The Voltage Regulator will not start up until the Charger Detect module has enabled it. Before
this happens the chip will be in Power-off mode and only the Charger Detect module is enabled.
In order for the Charger Detect module to enable the Voltage Regulator, the voltage at the BATT
pin must exceed the Power-On Threshold Voltage, VPOT. When the voltage at the BATT pin
exceeds VPOT, the Voltage Regulator starts up and the chip enters RESET mode. When the
Delay Counter times out, the chip will enter Active mode. See Figure 10-1 on page 36. For
details on Charger Detect, see ”Charger Detect” on page 129.
43
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 11-2. Powering up ATmega16HVB/32HVB
V BATT
V POT
V REG
3.3 V
POR
INTERNAL_RESET
SLEEP_MODE
11.2.2
t TOUT
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 32-3 on page 232) 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 11-3. External Reset During Operation
11.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 46 for details on operation of the Watchdog Timer.
44
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 11-4. Watchdog Reset During Operation
FET
CK
11.2.4
Brown-out Detection
ATmega16HVB/32HVB has an On-chip Brown-out Detection (BOD) circuit for monitoring the
VCC level during operation by comparing it to a fixed trigger level VBOT. 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 VCC decreases to a value below the trigger level (VBOT- in Figure
11-5), the Brown-out Reset is immediately activated. When VCC increases above the trigger
level (VBOT+ in Figure 11-5), the delay counter starts the MCU after the Time-out period tTOUT has
expired.
Figure 11-5. Brown-out Reset During Operation
VCC
VBOT-
VBOT+
RESET
TIME-OUT
tTOUT
INTERNAL
RESET
11.3
Reset and the Voltage Reference
The Voltage Reference is important for the performance of the system as the VREF voltage will
be used as reference voltage for several modules. It is therefore important to notice that after a
reset condition the Voltage Reference needs calibration and settling before the VREF voltage is
accurate. For details on Voltage Reference calibration and settling time, See ”Voltage Reference
and Temperature Sensor” on page 123.
45
8042B–AVR–06/10
ATmega16HVB/32HVB
11.4
11.4.1
Watchdog Timer
Features
• Clocked from separate On-chip Oscillator
• 3 Operating modes
– Interrupt
– System Reset
– Interrupt and System Reset
• Selectable Time-out period from 16 ms to 8s
• Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode
11.4.2
Overview
ATmega16HVB/32HVB has an Enhanced Watchdog Timer (WDT). The WDT counts cycles of
the Ultra Low Power RC Oscillator. 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.
Ultra Low Power RC
OSCILLATOR
WATCHDOG
RESET
WDE
16 ms
32 ms
64 ms
0.13s
0.26s
0.51s
1.0s
2.0s
4.1s
8.2s
Figure 11-6. Watchdog Timer
WDP0
WDP1
WDP2
WDP3
MCU RESET
WDIF
WDIE
INTERRUPT
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:
46
8042B–AVR–06/10
ATmega16HVB/32HVB
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:
1. See “About Code Examples” on page 8.
47
8042B–AVR–06/10
ATmega16HVB/32HVB
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 initialization 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. See “About Code Examples” on page 8.
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.
48
8042B–AVR–06/10
ATmega16HVB/32HVB
11.5
11.5.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)
–
–
–
OCDRF
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 – Reserved
These bits are reserved in the ATmega16HVB/32HVB, and will always read as zero.
• Bit 4 – OCDRF: OCD Reset Flag
This bit is set if a debugWIRE Reset occurs. The 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. In the case of a Power-on Reset, both the BODRF
and the PORF will be set. The BODRF is reset 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.
11.5.2
WDTCSR – Watchdog Timer Control Register
Bit
7
6
5
4
3
2
1
0
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
(0x60)
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.
49
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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 11-1.
Watchdog Timer Configuration
WDTON(1)
WDE
WDIE
1
0
1
Note:
Mode
Action on Time-out
0
Stopped
None
0
1
Interrupt Mode
Interrupt
1
1
0
System Reset Mode
Reset
1
1
1
Interrupt and System Reset
Mode
Interrupt, then go to System Reset
Mode
0
x
x
System Reset Mode
Reset
1. WDTON Fuse set to “0” means programmed, “1” means unprogrammed.
• 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 11-2.
• Bit 4 – WDCE: Watchdog Change Enable
This bit is used in timed sequences for changing WDE and prescaler bits. To clear the WDE bit,
and/or change the prescaler bits, WDCE must be set.
Once written to one, hardware will clear WDCE after four clock cycles.
• Bit 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 11-2 on page 51.
50
8042B–AVR–06/10
ATmega16HVB/32HVB
.
Table 11-2.
Watchdog Timer Prescale Select
WDP3
WDP2
WDP1
WDP0
Number of WDT
Oscillator Cycles
Typical
Time-out(1)
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.13s
0
1
0
0
32K cycles
0.26s
0
1
0
1
64K cycles
0.51s
0
1
1
0
128K cycles
1.0s
0
1
1
1
256K cycles
2.0s
1
0
0
0
512K cycles
4.1s
1
0
0
1
1024K cycles
8.2s
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
Note:
1. The actual timeout value depends on the actual clock period of the Ultra Low Power RC Oscillator, refer to ”Ultra Low Power RC Oscillator” on page 27” for details.
51
8042B–AVR–06/10
ATmega16HVB/32HVB
12. Interrupts
12.1
Overview
This section describes the specifics of the interrupt handling as performed in
ATmega16HVB/32HVB. For a general explanation of the AVR interrupt handling, refer to ”Reset
and Interrupt Handling” on page 14.
12.2
Interrupt Vectors in ATmega16HVB/32HVB
.
Table 12-1.
Vector
No.
Reset and Interrupt Vectors
Program
Address(1)
Source
Interrupt Definition
1
0x0000
RESET
External Pin, Power-on Reset, Brown-out Reset,
Watchdog Reset, and debugWIRE Reset
2
0x0002
BPINT
Battery Protection Interrupt
3
0x0004
VREGMON
Voltage Regulator Monitor Interrupt
4
0x0006
INT0
External Interrupt Request 0
5
0x0008
INT1
External Interrupt Request 1
6
0x000A
INT2
External Interrupt Request 2
7
0x000C
INT3
External interrupt Request 3
8
0x000E
PCINT0
Pin Change Interrupt 0
9
0x0010
PCINT1
Pin Change Interrupt 1
10
0x0012
WDT
Watchdog Time-out Interrupt
11
0x0014
BGSCD
Bandgap Buffer Short Circuit Detected
12
0x0016
CHDET
Charger Detect
13
0x0018
TIMER1 IC
Timer/Counter 1 input Capture
14
0x001A
TIMER1 COMPA
Timer/Counter 1 Compare Match A
15
0x001C
TIMER1 COMPB
Timer/Counter 1 Compare Match B
16
0x001E
TIMER1 OVF
Timer/Counter 1 Overflow
17
0x0020
TIMER0 IC
Timer/Counter 0 input Capture
18
0x0022
TIMER0 COMPA
Timer/Counter 0 Compare Match A
19
0x0024
TIMER0 COMPB
Timer /Counter0 Compare Match B
20
0x0026
TIMER0 OVF
Timer/Counter 0 Overflow
21
0x0028
TWI BUS C/D
Two-wire Bus Connect/Disconnect
22
0x002A
TWI
Two-wire Serial Interface
23
0x002C
SPI, STC
SPI, Serial Transfer Complete
24
0x002E
VADC
Voltage ADC Conversion Complete
25
0x0030
CCADC CONV
CC-ADC Instantaneous Current Conversion
Complete
26
0x0032
CCADC REG CUR
CC-ADC Regular Current
52
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 12-1.
Vector
No.
Reset and Interrupt Vectors (Continued)
Program
Address(1)
Source
Interrupt Definition
27
0x0034
CCADC ACC
CC-ADC Accumulate Current Conversion Complete
28
0x0036
EE READY
EEPROM Ready
29
0x0038
SPM
SPM Ready
Notes:
1. 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.
2. When the BOOTRST Fuses are programmed, the device will jump to the Boot Loader address
at reset, see ”Boot Loader Support – Read-While-Write Self-Programming” on page 191.
If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular
program code can be placed at these locations.
Table 12-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
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 12-2.
Reset and Interrupt Vectors Placement(1)
BOOTRST
IVSEL
Reset Address
Interrupt Vectors Start Address
1
0
0x0000
0x0002
1
1
0x0000
Boot Reset Address + 0x0002
0
0
Boot Reset Address
0x0002
0
1
Boot Reset Address
Boot Reset Address + 0x0002
Note:
1. The Boot Reset Address is shown in Table 29-5 on page 204. 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
ATmega16HVB/32HVB is:
Address
Labels
Code
Comments
0x0000
jmp
RESET
; Reset Handler
0x0002
jmp
BPINT
; Battery Protection Interrupt Handler
0x0004
jmp
VREGMON_INT
; Voltage Regulator Monitor Interrupt Handler
0x0006
jmp
EXT_INT0
; External Interrupt Request 0 Handler
0x0008
jmp
EXT_INT1
; External Interrupt Request 1 Handler
0x000A
jmp
EXT_INT2
; External Interrupt Request 2 Handler
0x000C
jmp
EXT_INT3
; External Interrupt Request 3 Handler
0x000E
jmp
PCINT0
; Pin Change Interrupt 0 Handler
0x0010
jmp
PCINT1
; Pin Change Interrupt 1 Handler
0x0012
jmp
WDT
; Watchdog Time-out Interrupt
0x0014
jmp
BGSCD
; Bandgap Buffer Short Circuit Detected
0x0016
jmp
CHDET
; Charger Detect
0x0018
jmp
TIM1_IC
; Timer1 Input Capture Handler
0x001A
jmp
TIM1_COMPA
; Timer1 Compare A Handler
53
8042B–AVR–06/10
ATmega16HVB/32HVB
0x001C
jmp
TIM1_COMPB
; Timer1 Compare B Handler
0x001E
jmp
TIM1_OVF
; Timer1 Overflow Handler
0X0020
jmp
TIM0_IC
; Timer0 Input Capture Handler
0x0022
jmp
TIM0_COMPA
; Timer0 CompareA Handler
0x0024
jmp
TIM0_COMPB
; Timer0 CompareB Handler
0x0026
jmp
TIM0_OVF
; Timer0 Overflow Handler
0x0028
jmp
TWI_BUS_CD
; Two-wire Bus Connect/Disconnect Handler
0x002A
jmp
TWI
; Two-wire Serial Interface Handler
0x002C
jmp
SPI, STC
; SPI, Serial Transfer Complete
0x002E
jmp
VADC
; Voltage ADC Conversion Complete Handler
0x0030
jmp
CCADC_CONV
; CC-ADC Instantaneous Current Conversion Complete Handler
0x0032
jmp
CCADC_REC_CUR
; CC-ADC Regular Current Handler
0x0034
jmp
CCADC_ACC
; CC-ADC Accumulate Current Conversion Complete Handler
0x0036
jmp
EE_RDY
; EEPROM Ready Handler
0x0038
jmp
SPM
; Store Program Memory Ready Handler
;
0x003A
ldi
r16, high(RAMEND)
; Main program start
0x003B
out
SPH,r16
; Set Stack Pointer to top of RAM
0x003C
ldi
r16, low(RAMEND)
0x003D
out
SPL,r16
0x003E
sei
0x003F
<instr>
xxx
...
...
0x0040
RESET:
...
; Enable interrupts
;
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 4K 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 4K 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
54
8042B–AVR–06/10
ATmega16HVB/32HVB
...
...
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 4K 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
0x4C2F
out
SPH,r16
0x4C30
ldi
r16,low(RAMEND)
0x4C31
0x4C32
out
sei
SPL,r16
0x4C33
<instr>
;
0x4C2E
RESET:
; Set Stack Pointer to top of RAM
; Enable interrupts
xxx
55
8042B–AVR–06/10
ATmega16HVB/32HVB
12.3
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);
}
12.4
12.4.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 191 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
56
8042B–AVR–06/10
ATmega16HVB/32HVB
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-WhileWrite Self-Programming” on page 191 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.
57
8042B–AVR–06/10
ATmega16HVB/32HVB
13. External Interrupts
13.1
Overview
The External Interrupts are triggered by the INT3:0 pin or any of the PCINT11:0 pins. Observe
that, if enabled, the interrupts will trigger even if the INT3:0 or PCINT11: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 ”EICRA – External Interrupt Control Register A” on page
58. 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.
The Pin change interrupt PCI1 will trigger if any enabled PCINT11:4 pin toggles and Pin change
interrupts PCI0 will trigger if any enabled PCINT3:0 pin toggles. PCMSK1 and PCMSK0 Registers control which pins contribute to the pin change interrupts. Pin change interrupts on
PCINT11:0 are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode.
Note that if a level triggered interrupt is used for wake-up from Power-save, the required level
must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If
the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined by the SUT fuses as described in ”Clock
Systems and their Distribution” on page 25.
13.2
13.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 – ISCn: External Interrupt 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 13-1 on page 59. Edges on INT3..INT0 are registered
asynchronously. Pulses on INT3:0 pins wider than the minimum pulse width given in Table 3211 on page 235 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.
58
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 13-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:
13.2.2
Interrupt Sense Control
Description
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.
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 – Reserved
These bits are reserved ins the ATmega16HVB/32HVB, 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.
13.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 – Reserved
These bits are reserved ins the ATmega16HVB/32HVB, 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
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 71 for more information.
59
8042B–AVR–06/10
ATmega16HVB/32HVB
13.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
• Bits 7:2 – Reserved
These bits are reserved in the ATmega16HVB/32HVB, 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 PCINT11..4 pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI1
Interrupt Vector. PCINT11..4 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 PCINT3..0 pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Interrupt
Vector. PCINT3..0 pins are enabled individually by the PCMSK0 Register.
13.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
• Bits 7:2 – Reserved
These bits are reserved in the ATmega16HVB/32HVB, and will always read as zero.
• Bit 1 – PCIF1: Pin Change Interrupt Flag 1
When a logic change on any PCINT11..4 pin triggers an interrupt request, PCIF1 becomes set
(one). If the I-bit in SREG and the PCIE1 bit in EIMSK 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 PCINT3:0 pin triggers an interrupt request, PCIF0 becomes set
(one). If the I-bit in SREG and the PCIE0 bit in EIMSK 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.
13.2.6
PCMSK1 – Pin Change Mask Register 1
Bit
7
6
5
4
3
2
1
0
PCINT11
PCINT10
PCINT9
PCINT8
PCINT7
PCINT6
PCINT5
PCINT4
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
60
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bit 7:0 – PCINT[11:4]: Pin Change Enable Mask 15:8
These bits select whether pin change interrupt is enabled on the corresponding I/O pin. If
PCINT[11:4] is set and the PCIE1 bit in EIMSK is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT[11:4] is cleared, pin change interrupt on the corresponding I/O pin
is disabled.
13.2.7
PCMSK0 – Pin Change Mask Register 0
Bit
7
6
5
4
3
2
1
0
(0x6B)
–
–
–
–
PCINT3
PCINT2
PCINT1
PCINT0
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
PCMSK0
• Bits 7:4 – Reserved
These bits are reserved in the ATmega16HVB/32HVB, and will always read as zero.
• Bit 3:0 – PCINT[3:0]: Pin Change Enable Mask 3:0
Each PCINT[3:0] bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT[3:0] is set and the PCIE0 bit in PCICR is set, pin change interrupt is enabled on the
corresponding I/O pin. If PCINT[3:0] is cleared, pin change interrupt on the corresponding I/O
pin is disabled.
61
8042B–AVR–06/10
ATmega16HVB/32HVB
14. High Voltage I/O Ports
14.1
Overview
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 230 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” on page 66.
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 I/O” on page 63.
62
8042B–AVR–06/10
ATmega16HVB/32HVB
14.2
High Voltage Ports as General Digital I/O
The high voltage ports are high voltage tolerant open collector output ports. In addition they can
be used as general digital inputs. Figure 14-2 shows a functional description of one output port
pin, here generically called Pxn.
Figure 14-2. General High Voltage Digital I/O(1)
Pxn
Q
D
PORTxn
_
Q
CLR
WRx
RESET
DATABUS
RRx
SLEEP
RPx
SYNCHRONIZER
D
L
SET
CLR
Q
D
_
Q
PINxn
_
CLR Q
Q
clkI/O
HIGH VOLTAGE DIGITAL INPUT (2)
SLEEP:
clkI/O:
Notes:
14.2.1
SLEEP CONTROL
I/O CLOCK
RRx:
WRx:
RPx:
READ PORTx REGISTER
WRITE PORTx REGISTER
READ PINx REGISTER
1. WRx, RRx and RPx are common to all pins within the same port. clkI/O and SLEEP are common to all ports.
2. The High Voltage Digital Input is not present on PC5.
Configuring the Pin
Each port pin consist of two register bits: PORTxn and PINxn. As shown in ”Register Description” on page 66, the PORTxn bits are accesed at the PORTx I/O address, and the PINxn bits at
the PINx 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.2.2
Reading the Pin
The port pin can be read through the PINxn Register bit. As shown in Figure 14-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.
63
8042B–AVR–06/10
ATmega16HVB/32HVB
14.3
Overview
14.4
Alternate Port Functions
The High Voltage I/O has alternate port functions in addition to being general digital I/O. Figure
14-3 shows how the port pin control signals from the simplified Figure 14-2 on page 63 can be
overridden by alternate functions.
Figure 14-3. High Voltage Digital I/O(1)(2)
Pxn
PVOExn
PVOVxn
1
0
Q
D
PORTxn
_
Q
CLR
WRx
RRx
DIEOVxn
1
0
SLEEP
RPx
SYNCHRONIZER
D
L
SET
CLR
DATABUS
RESET
DIEOExn
Q
D
_
Q
PINxn
_
CLR Q
Q
clkI/O
DIxn
PVOExn:
PVOVxn:
DIEOExn:
DIEOVxn:
Notes:
Pxn PORT VALUE OVERRIDE ENABLE
Pxn PORT VALUE OVERRIDE VALUE
Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE
Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE
RRx:
WRx:
RPx:
clkI/O:
DIxn:
SLEEP:
READ PORTx REGISTER
WRITE PORTx REGISTER
READ PINx REGISTER
I/O CLOCK
DIGITAL INPUT PIN n ON PORTx
SLEEP CONTROL
1. WRx, RRx and RPx are common to all pins within the same port. clkI/O and SLEEP are common to all ports. All other signals are unique for each pin.
2. The High Voltage Digital Input is not present on PC5.
Table 14-1 on page 65 summarizes the function of the overriding signals. The pin and port
indexes from Figure 14-3 are not shown in the succeeding tables. The overriding signals are
generated internally in the modules having the alternate function.
64
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 14-1.
Generic Description of Overriding Signals for Alternate Functions
Signal Name
Full Name
Description
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.
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).
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.
DI
14.4.1
Alternate Functions of Port C
The Port C pins with alternate functions are shown in Table 14-2.
Table 14-2.
Port Pin
Port C Pins Alternate Functions
Alternate Function
PC0
INT0/ EXTPROT(External Interrupt 0 or External Battery Protection Input)
PC1
INT1 (External interrupt 1)
PC2
INT1 (External interrupt 2)
PC3
INT3/ SDA (External Interrupt 3 or SM Bus Data line)
PC4
SCL (SM Bus Clock line)
The alternate pin configuration is as follows:
• INT0/ EXTPROT – Port C, Bit 0
INT0: External Interrupt Source 0. This pin can serve as external interrupt source. INT0 can be
used as an interrupt pin regardless of whether another function is enabled or not.
EXTPROT: External Battery Protection Input. This pin can serve as external battery protection
input to be able to override the FET controller externally.
• INT1 – Port C, Bit1
INT1: External Interrupt Source 1. This pin can serve as external interrupt source. INT1 can be
used as an interrupt pin regardless of whether another function is enabled or not.
• INT2 – Port C, Bit2
INT2: External Interrupt Source 2. This pin can serve as external interrupt source. INT2 can be
used as an interrupt pin regardless of whether another function is enabled or not.
65
8042B–AVR–06/10
ATmega16HVB/32HVB
• INT3/ SDA – Port C, Bit3
INT3: External Interrupt Source 3. This pin can serve as external interrupt source. INT3 can be
used as an interrupt pin regardless of whether another function is enabled or not.
SDA: SM Bus Data. This pin can serve as bidirectional serial data line for the 2-wire Serial
Interface.
• SCL – Port C, Bit4
SCL: SM Bus Clock. This pin can serve as bidirectional clock line for the 2-wire Serial Interface
Table 14-3 on page 66 relates the alternate functions of Port C to the overriding signals shown in
Figure 14-3 on page 64.
Table 14-3.
Overriding Signals for Alternate Functions in PC4:0
Signal
Name
PC4/SCL
PC3/INT3/SDA
PVOE
SM BUS ENABLED
SM BUS ENABLED
EXTPROT ENABLE
PVOV
SM BUS CLOCK
SM BUS DATA
1
DIEOE
SM BUS ENABLED
INT3 ENABLE
SM BUS ENABLED
INT2 ENABLE
INT1ENABLE
INT0 ENABLE
EXTPROT ENABLE
DIEOV
1
1
1
1
1
SM BUS CLOCK
INT3 INPUT
SM BUS DATA
INT2 INPUT
INT1 INPUT
INT0 INPUT
EXTPROT INPUT
DI
PC2/INT2
PC1/INT1
PC0/INT0/EXTPROT
DIDR
14.5
14.5.1
14.5.2
Register Description
PORTC – Port C Data Register
Bit
7
6
5
4
3
2
1
0
0x08 (0x28)
–
–
PORTC5
PORTC4
PORTC3
PORTC2
PORTC1
PORTC0
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
PORTC
PINC – Port C Input Pins Address
Bit
7
6
5
4
3
2
1
0
0x06 (0x26)
–
–
–
PINC4
PINC3
PINC2
PINC1
PINC0
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
PINC
66
8042B–AVR–06/10
ATmega16HVB/32HVB
15. Low Voltage I/O-Ports
15.1
Overview
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 15-1. Refer to ”Electrical Characteristics” on page 230 for a complete list
of parameters.
Figure 15-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 78.
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 68. 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 72. Refer to the individual module sections for a
full description of the alternate functions.
67
8042B–AVR–06/10
ATmega16HVB/32HVB
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.
15.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 15-2
shows a functional description of one I/O-port pin, here generically called Pxn.
Figure 15-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:
15.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 78, 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.
68
8042B–AVR–06/10
ATmega16HVB/32HVB
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).
15.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.
15.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 15-1 summarizes the control signals for the pin value.
Table 15-1.
15.2.4
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 15-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 15-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.
69
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 15-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 15-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 15-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.
70
8042B–AVR–06/10
ATmega16HVB/32HVB
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:
15.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 15-2 on page 68, the digital input signal can be clamped to ground at the
input of the schmiSchmidtt-trigger. The signal denoted SLEEP in the figure, is set by the MCU
Sleep Controller in 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 72.
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.
71
8042B–AVR–06/10
ATmega16HVB/32HVB
15.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.
15.3
Alternate Port Functions
Many low voltage port pins have alternate functions in addition to being general digital I/Os. Figure 15-5 shows how the port pin control signals from the simplified Figure 15-2 on page 68 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 15-5. Alternate Port Functions(1)
PUOExn
PUOVxn
1
PUD
0
DDOExn
DDOVxn
1
D
Q
DDxn
0
Q CLR
WDx
PVOExn
RESET
RDx
1
1
Pxn
Q
0
D
0
PORTxn
PTOExn
Q CLR
DIEOExn
DATA BUS
PVOVxn
WPx
RESET
DIEOVxn
WRx
1
0
RRx
SLEEP
SYNCHRONIZER
D
SET
Q
RPx
Q
D
PINxn
L
CLR
Q
CLR
Q
clk I/O
DIxn
AIOxn
PUOExn:
PUOVxn:
DDOExn:
DDOVxn:
PVOExn:
PVOVxn:
DIEOExn:
DIEOVxn:
SLEEP:
PTOExn:
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
72
8042B–AVR–06/10
ATmega16HVB/32HVB
Note:
1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O,
SLEEP, and PUD are common to all ports. All other signals are unique for each pin.
Table 15-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 15-5 on page 72 are not shown in the succeeding tables. The overriding signals are
generated internally in the modules having the alternate function.
Table 15-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.
73
8042B–AVR–06/10
ATmega16HVB/32HVB
15.3.1
Alternate Functions of Port A
The Port A pins with alternate functions are shown in Table 15-3.
Table 15-3.
Port A Pins Alternate Functions
Port Pin
Alternate Function
PA3
T1/PCINT3 (Timer/Counter1 Clock Input or Pin Change Interrupt 3)
PA2
T0/PCINT2 (Timer/Counter0 Clock Input or Pin Change Interrupt 2)
PA1
ADC1/SGND/PCINT1
(ADC Input Channel 1, Signal Ground or Pin Change Interrupt 1)
PA0
ADC0/SGND/PCINT0
(ADC Input Channel 0, Signal Ground or Pin Change Interrupt 0)
The alternate pin configuration is as follows:
• ADC0/SGND/PCINT0 – Port A, Bit0
ADC0: Voltage ADC Channel0. This pin can serve as Channel 0 Input for the Voltage ADC.
SGND: Voltage ADC Signal Ground. This pin can serve as Channel 1 Signal Ground for the
Voltage ADC.
PCINT0. Pin Change Interrupt 0. This pin can serve as external interrupt source.
• ADC1/SGND/PCINT1 – Port A, Bit1
ADC1: Voltage ADC Channel 1: This pin can serve as Channel 1 for the Voltage ADC.
SGND: Voltage ADC Signal Ground. This pin can serve as Channel 0 Signal Ground for the
Voltage ADC.
PCINT1: Pin Change Interrupt 1. This pin can serve as external interrupt source.
• T0/PCINT2 – Port A, Bit2
T0: Timer/Counter0. This pin can serve as Timer/Counter0 clock source.
PCINT2: Pin Change Interrupt 2. This pin can serve as external interrupt source.
• T1/PCINT3 – Port A, Bit3
T1: Timer/Counter1. This pin can serve as Timer/Counter1 clock source.
PCINT3: Pin Change Interrupt 3.
74
8042B–AVR–06/10
ATmega16HVB/32HVB
These pins can serve as external interrupt sourceTable 15-4 relates the alternate functions of
Port A to the overriding signals shown in Figure 15-5 on page 72.
Table 15-4.
Signal Name
Overriding Signals for Alternate Functions in PA3:PA0
PA3/T1/PCINT3
PA2/T0/PCINT2
PA1/ADC1/SGND/PCINT1
PA0/ADC0/SGND/PCINT0
PUOE
0
0
0
0
PUOV
0
0
0
0
DDOE
0
0
VADSC • VADMUX=ADC0
VADSC • VADMUX=ADC1
DDOV
0
0
1
1
PVOE
0
0
VADSC • VADMUX=ADC0
VADSC • VADMUX=ADC1
PVOV
0
0
0
0
PTOE
-
-
-
-
DIEOE
PCINT3 • PCIE0
PCINT2 • PCIE0
DIDR1| (PCINT1 • PCIE0)
DIDR0 | (PCINT0 • PCIE0)
DIEOV
1
1
DIDR1
DIDR0
T1 INPUT
PCINT3 INPUT
T0 INPUT
PCINT2 INPUT
PCINT1 INPUT
PCINT0 INPUT
-
-
ADC1 INPUT/ SGND
ADC0 INPUT/ SGND
DI
AIO
15.3.2
Alternate Functions of Port B
The Port B pins with alternate functions are shown in Table 15-5.
Table 15-5.
Port Pin
Port B Pins Alternate Functions
Alternate Functions
PB7
MISO/PCINT11 (SPI Bus Master Input/Slave Output or Pin Change Interrupt 11)
PB6
MOSI/PCINT10 (SPI Bus Master Output/Slave Input or Pin Change Interrupt 10)
PB5
SCK/PCINT9 (SPI Bus Serial Clock or Pin Change Interrupt 9)
PB4
SS/PCINT8 (SPI Bus Slave Select input or Pin Change Interrupt 8)
PB3
PCINT7 (Pin Change Interrupt 7)
PB2
PCINT6 (Pin Change Interrupt 6)
PB1
CKOUT/PCINT5 (Clock output or Pin Change Interrupt 5)
PB0
PCINT4/ICP00 (Pin Change Interrupt 4 or Timer/Counter0 Input Capture Trigger)
The alternate pin configuration is as follows:
• MISO/PCINT11 – Port B, Bit7
MISO, Master Data input: Slave Data output pin for SPI channel. When the SPI is enabled as a
Master, this pin is configured as an input regardless of the setting of DDB7. When the SPI is
enabled as a Slave, the data direction of this pin is controlled by DDB7. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB7 bit. When not operating in SPI mode, this pin can serve as an external interrupt source.
PCINT11: Pin Change Interrupt 11. This pin can serve as external interrupt source.
75
8042B–AVR–06/10
ATmega16HVB/32HVB
• MOSI/PCINT10 – Port B, Bit6
MOSI, SPI Master Data output: Slave Data input for SPI channel. When the SPI is enabled as a
Slave, this pin is configured as an input regardless of the setting of DDB6. When the SPI is
enabled as a Master, the data direction of this pin is controlled by DDB6. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB6 bit. When not operating in SPI mode, this pin can serve as an external interrupt source.
PCINT10: Pin Change Interrupt 10. This pin can serve as external interrupt source.
• SCK/PCINT9 – Port B, Bit5
SCK, Master Clock output: Slave Clock input pin for SPI channel. When the SPI is enabled as a
Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is
enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.
PCINT9: Pin Change Interrupt 9. This pin can serve as external interrupt source.
• SS/PCINT8 – Port B, Bit4
SS, Slave Select input: When the SPI is enabled as a Slave, this pin is configured as an input
regardless of the setting of DDB4. As a Slave, the SPI is activated when this pin is driven low.
When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB4. When
the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.
When not operating in SPI mode, this pin can serve as Clock Output, CPU Clock divided by 2.
See ”Clock Output” on page 28.
PCINT8: Pin Change Interrupt 8. This pin can serve as external interrupt source.
• PCINT7 – Port B, Bit3
PCINT7: Pin Change Interrupt 7. This pin can serve as external interrupt source.
• PCINT6 – Port B, Bit2
PCINT6: Pin Change Interrupt 6. This pin can serve as external interrupt source.
• CKOUT/PCINT5 – Port B, Bit1
CKOUT: Clock output. This pin can serve as clock output pin.
PCINT5: Pin Change Interrupt 5. This pin can serve as external interrupt source.
• ICP00/PCINT4 – Port B, Bit0
ICP00: Input Capture Timer/Counter0. This pin can serve as Input Capture Trigger for
Timer/Counter0
PCINT4: Pin Change Interrupt 4. This pin can serve as external interrupt source.
76
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 15-6.
Signal Name
Overriding Signals for Alternate Functions in PB7:PB4
PB7/MISO/PCINT11
PB6/MOSI/PCINT10
PB5/SCK/PCINT9
PB4/SS/PCINT8
PUOE
SPE • MSTR
SPE • MSTR
SPE • MSTR
SPE • MSTR
PUOV
PORTB7 • PUD
PORTB6 • PUD
PORTB5 • PUD
PORTB0 • PUD
DDOE
SPE • MSTR
SPE • MSTR
SPE • MSTR
SPE • MSTR
DDOV
0
0
0
0
PVOE
SPE • MSTR
SPE • MSTR
SPE • MSTR
0
PVOV
SPI SLAVE OUTPUT
SPI MSTR OUTPUT
SCK OUTPUT
0
PTOE
–
–
–
–
DIEOE
PCINT11 • PCIE1
PCINT10 • PCIE1
PCINT9 • PCIE1
PCINT8 • PCIE1
DIEOV
1
1
–
1
SPI MSTR INPUT
PCINT11 INPUT
SPI SLAVE INPUT
PCINT10 INPUT
SCK INPUT
PCINT9 INPUT
SS INPUT
PCINT8 INPUT
–
–
–
–
DI
AIO
Table 15-7.
Signal Name
Overriding Signals for Alternate Functions in PB3:PB0
PB3/PCINT7
PB2/PCINT6
PB1/CKOE/PCINT5
PB0/PCINT4
PUOE
0
0
CKOE
0
PUOV
0
0
0
0
DDOE
0
0
CKOE
0
DDOV
0
0
CKOE
0
PVOE
0
0
CKOE
0
PVOV
0
0
CKOUT
0
PTOE
–
–
–
–
DIEOE
PCINT7 • PCIE1
PCINT6 • PCIE1
(PCINT6 • PCIE1)|CKOE
PCINT4 • PCIE1
DIEOV
1
1
(PCINT6 • PCIE1)|CKOE
1
PCINT7 INPUT
PCINT6 INPUT
PCINT5 INPUT
IPC0 INPUT
PCINT4 INPUT
–
–
–
–
DI
AIO
77
8042B–AVR–06/10
ATmega16HVB/32HVB
15.4
15.4.1
Register Description
MCUCR – MCU Control Register
Bit
7
6
5
4
3
2
1
0
0x35 (0x55)
–
–
CKOE
PUD
–
–
IVSEL
IVCE
Read/Write
R
R
R/W
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 68 for more details about this feature.
15.4.2
15.4.3
15.4.4
15.4.5
PORTA – Port A Data Register
Bit
7
6
5
4
3
2
1
0
0x02 (0x22)
–
–
–
–
PORTA3
PORTA2
PORTA1
PORTA0
Read/Write
R
R
R
R
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
7
6
5
4
3
2
1
0
0x01 (0x21)
–
–
–
–
DDA3
DDA2
DDA1
DDA0
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
Bit
7
6
5
4
3
2
1
0
0x00 (0x20)
–
–
–
–
PINA3
PINA2
PINA1
PINA0
Read/Write
R
R
R
R
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
PORTB – Port B Data Register
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
PORTB
DDRB – Port B Data Direction Register
Bit
15.4.7
DDRA
PINA – Port A Input Pins Address
Bit
15.4.6
PORTA
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
DDRB
PINB – Port B Input Pins Address
Bit
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
78
8042B–AVR–06/10
ATmega16HVB/32HVB
16. Timer/Counter0 and Timer/Counter1 Prescalers
16.1
Overview
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.
16.1.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 four taps from the prescaler can be used as a
clock source. The prescaled clock has a frequency of either fCLK_I/O/8, fCLK_I/O/64, fCLK_I/O/256, or
fCLK_I/O/1024.
16.1.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 (8, 64, 256, or 1024).
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.
Figure 16-1. Prescaler for Timer/Counter
clk I/O
Clear
PSRSYNC
Tn
Synchronization
CSn0
CSn1
CSn2
n
clkTn
79
8042B–AVR–06/10
ATmega16HVB/32HVB
16.2
External Clock Source
An external clock source applied to the Tn pin can be used as Timer/Counter clock (clkTn). The
Tn 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 16-2 shows a functional
equivalent block diagram of the Tn 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 clkTn pulse for each positive (CSn2:0 = 7) or negative (CSn2:0
= 6) edge it detects. See Table 16-1 on page 81 for details.
Figure 16-2. Tn Pin Sampling
Tn
D
Q
D
Q
D
Tn_sync
(To Clock
Select Logic)
Q
LE
clk I/O
Synchronization
Edge Detector
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 Tn pin to the counter is updated.
Enabling and disabling of the clock input must be done when Tn 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.
Note:
The synchronization logic on the input pins (Tn) is shown in Figure 16-2.
80
8042B–AVR–06/10
ATmega16HVB/32HVB
16.3
16.3.1
Register Description
TCCRnB – Timer/Counter n Control Register B
Bit
7
6
5
4
3
2
1
0
(0x80)(0x81)
–
–
–
–
–
CSn2
CSn1
CSn0
Read/Write
R
R
R
R
R
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TCCRnB
• Bits 2, 1, 0 – CSn2, CSn1, CSn0: Clock Select0, Bit 2, 1, and 0
The Clock Select n bits 2, 1, and 0 define the prescaling source of Timer n.
Table 16-1.
Clock Select Bit Description
CSn2
CSn1
CSn0
Description
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 Tn pin. Clock on falling edge.
1
1
1
External clock source on Tn pin. Clock on rising edge.
If external pin modes are used for the Timer/Counter n, transitions on the Tn pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
16.3.2
General Timer/Counter Control Register – GTCCR
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.
81
8042B–AVR–06/10
ATmega16HVB/32HVB
17. Timer/Counter (T/C0,T/C1)
17.1
Features
•
•
•
•
•
17.2
Clear Timer on Compare Match (Auto Reload)
Input Capture unit
Four Independent Interrupt Sources (TOVn, OCFnA, OCFnB, ICFn)
8-bit Mode with Two Independent Output Compare Units
16-bit Mode with One Independent Output Compare Unit
Overview
Timer/Counter n is a general purpose 8-/16-bit Timer/Counter module, with two/one Output
Compare units and Input Capture feature.
ATmega16HVB/32HVB has two Timer/Counters, Timer/Counter0 and Timer/Counter1. The
functionality for both Timer/Counters is described below. Timer/Counter0 and Timer/Counter1
have different Timer/Counter registers, as shown in ”Register Summary” on page 256.
The Timer/Counter general operation is described in 8-/16-bit mode. A simplified block diagram
of the 8-/16-bit Timer/Counter is shown in Figure 17-1. 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 ”Register Description” on page 94.
Figure 17-1. 8-/16-bit Timer/Counter Block Diagram
TOVn (Int. Req.)
Count
Clock Select
Control Logic
Clear
clkTn
Edge
Detector
Tn
( From Prescaler )
TOP
Timer/Counter
TCNTnH
TCNTnL
=
Fixed TOP value
=
OCnA (Int. Req.)
=
DATA BUS
OCnB (Int. Req.)
ICFn (Int. Req.)
OCRnB
TCCRnA
17.2.1
OCRnA
TCCRnB
Edge
Detector
Noise
Canceler
ICPn1
ICPn0
Registers
The Timer/Counter Low Byte Register (TCNTnL) and Output Compare Registers (OCRnA and
OCRnB) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in Figure 17-1 on page 82)
signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually
masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the
figure.
In 16-bit mode the Timer/Counter consists one more 8-bit register, the Timer/Counter High Byte
Register (TCNTnH). Furthermore, there is only one Output Compare Unit in 16-bit mode as the
two Output Compare Registers, OCRnA and OCRnB, are combined to one 16-bit Output Com82
8042B–AVR–06/10
ATmega16HVB/32HVB
pare Register. OCRnA contains the low byte of the word and OCRnB contains the higher byte of
the word. When accessing 16-bit registers, special procedures described in section ”Accessing
Registers in 16-bit Mode” on page 90 must be followed.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the Tn pin. The Clock Select logic block controls which clock source and edge 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 (clkTn).
17.2.2
Definitions
Many register and bit references in this section are written in general form. A lower case “n”
replaces the module number, e.g. Timer/Counter number. A lower case “x” replaces the unit,
e.g. OCRnx and ICPnx describes OCRnA/B and ICP1/0x . However, when using the register or
bit defines in a program, the precise form must be used, i.e., TCNT0L for accessing
Timer/Counter0 counter value and so on.
The definitions in Table 17-1 are also used extensively throughout the document.
Table 17-1.
17.3
Definitions
BOTTOM
The counter reaches the BOTTOM when it becomes 0.
MAX
The counter reaches its MAXimum when it becomes 0xFF (decimal 255) in 8-bit mode or
0xFFFF (decimal 65535) in 16-bit mode.
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/0xFFFF (MAX) or
the value stored in the OCRnA Register.
Timer/Counter Clock Sources
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source.
The Clock Select logic is controlled by the Clock Select (CSn2:0) bits located in the Timer/Counter Control Register n B (TCCRnB), and controls which clock source and edge 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 (clkTn). For
details on clock sources and prescaler, see ”Timer/Counter0 and Timer/Counter1 Prescalers” on
page 79
17.4
Counter Unit
The main part of the 8-bit Timer/Counter is the counter unit. Figure 17-2 on page 83 shows a
block diagram of the counter and its surroundings.
Figure 17-2. Counter Unit Block Diagram
TOVn
(Int.Req.)
DATA BUS
Clock Select
TCNTn
count
Control Logic
clkTn
Edge
Detector
Tn
( From Prescaler )
top
83
8042B–AVR–06/10
ATmega16HVB/32HVB
Signal description (internal signals):
count
Increment or decrement TCNTn by 1.
clkTn
Timer/Counter clock, referred to as clkTn in the following.
top
Signalize that TCNTn has reached maximum value.
The counter is incremented at each timer clock (clkTn) until it passes its TOP value and then
restarts from BOTTOM. The counting sequence is determined by the setting of the WGMn0 bits
located in the Timer/Counter Control Register (TCCRnA). For more details about counting
sequences, see ”Timer/Counter Timing Diagrams” on page 89. clkTn can be generated from an
external or internal clock source, selected by the Clock Select bits (CSn2:0). When no clock
source is selected (CSn2:0 = 0) the timer is stopped. However, the TCNTn value can be
accessed by the CPU, regardless of whether clkTn is present or not. A CPU write overrides (has
priority over) all counter clear or count operations. The Timer/Counter Overflow Flag (TOVn) is
set when the counter reaches the maximum value and it can be used for generating a CPU
interrupt.
17.5
Modes of Operation
The mode of operation is defined by the Timer/Counter Width (TCWn), Input Capture Enable
(ICENn) and the Waveform Generation Mode (WGMn0)bits in ”TCCRnA – Timer/Counter n
Control Register A” on page 94. Table 17-2 on page 84 shows the different Modes of Operation.
Table 17-2.
Modes of Operation
Timer/Counter Mode
of Operation
TOP
Update of
OCRx at
TOV Flag
Set on
0
Normal 8-bit Mode
0xFF
Immediate
MAX (0xFF)
0
1
8-bit CTC
OCRnA
Immediate
MAX (0xFF)
0
1
0
16-bit Mode
0xFFFF
Immediate
MAX (0xFFFF)
3
0
1
1
16-bit CTC
OCRnB,
OCRnA
Immediate
MAX (0xFFFF)
4
1
0
0
8-bit Input Capture
mode
0xFF
–
MAX (0xFF)
5
1
1
0
16-bit Input Capture
mode
0xFFFF
–
MAX (0xFFFF)
Mode
ICENn
TCWn
WGMn0
0
0
0
1
0
2
17.5.1
Normal 8-bit Mode
In the normal mode, the counter (TCNTnL) is incrementing until it overruns when it passes its
maximum 8-bit value (MAX = 0xFF) and then restarts from the bottom (0x00), see Table 17-2 on
page 84 for bit settings. The Overflow Flag (TOVn) will be set in the same timer clock cycle as
the TCNTnL becomes zero. The TOVn 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 TOVn Flag, the timer resolution can be increased by software. There are no special
cases to consider in the Normal 8-bit mode, a new counter value can be written anytime. The
Output Compare Unit can be used to generate interrupts at some given time.
17.5.2
Clear Timer on Compare Match (CTC) 8-bit Mode
In Clear Timer on Compare or CTC mode, the OCRnA Register is used to manipulate the counter resolution, see Table 17-2 on page 84 for bit settings. In CTC mode the counter is cleared to
84
8042B–AVR–06/10
ATmega16HVB/32HVB
zero when the counter value (TCNTn) matches the OCRnA. The OCRnA 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 17-3 on page 85. The counter value
(TCNTn) increases until a Compare Match occurs between TCNTn and OCRnA, and then counter (TCNTn) is cleared.
Figure 17-3. CTC Mode, Timing Diagram
OCnx Interrupt Flag Set
TCNTn
Period
1
2
3
4
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCFnA 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 OCRnA is lower than the current
value of TCNTn, 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. As for the Normal mode of operation, the TOVn Flag is set in the same timer clock cycle
that the counter counts from MAX to 0x00.
17.5.3
16-bit Mode
In 16-bit mode, the counter (TCNTnH/L) is a incrementing until it overruns when it passes its
maximum 16-bit value (MAX = 0xFFFF) and then restarts from the bottom (0x0000), see Table
17-2 on page 84 for bit settings. The Overflow Flag (TOVn) will be set in the same timer clock
cycle as the TCNTnH/L becomes zero. The TOVn Flag in this case behaves like a 17th bit,
except that it is only set, not cleared. However, combined with the timer overflow interrupt that
automatically clears the TOVn 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.
17.5.4
Clear Timer on Compare Match (CTC) 16-bit Mode
In Clear Timer on Compare 16-bit mode, OCRAnA/B Registers are used to manipulate the counter resolution, see Table 17-2 on page 84 for bit settings. In CTC mode the counter is cleared to
zero when the counter value (TCNTn) matches OCRnA/B, where OCRnB represents the eight
most significant bits and OCRnA represents the eight least significant bits. OCRnA/B defines the
top value of 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.
An interrupt can be generated each time the counter reaches the TOP value by using the
OCFnA flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the
TOP value. However, changing the TOP to a value close the 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 OCRnA/B is lower than the current
85
8042B–AVR–06/10
ATmega16HVB/32HVB
value of TCNTn, the counter will miss the Compare Match. The counter will then have to count to
its maximum value (0xFFFF) and wrap around starting at 0x0000 before Compare Match can
occur. As for the 16-bit Mode, the TOVn Flag is set in the same timer clock cycle that the counter
counts from MAX to 0x0000.
17.5.5
8-bit Input Capture Mode
The Timer/Counter can be used in a 8-bit Input Capture mode, see Table 17-2 on page 84 for bit
settings. For full description, see ”Input Capture Unit” on page 86.
17.5.6
16-bit Input Capture Mode
The Timer/Counter can also be used in a 16-bit Input Capture mode, see Table 17-2 on page 84
for bit settings. For full description, see ”Input Capture Unit” on page 86.
17.6
Input Capture Unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give
them a time-stamp indicating time of occurrence. The external signal indicates an event, or multiple events. For Timer/Counter0, the events can be applied via the PB0 pin (ICP00), or
alternatively via the osi_posedge pin on the Oscillator Sampling Interface (ICP01). For
Timer/Counter1, the events can be applied by the Battery Protection Interrupt (ICP10) or alternatively by the Voltage Regulator Interrupt (ICP11). The time-stamps can then be used to
calculate frequency, duty-cycle, and other features of the signal applied. Alternatively the timestamps can be used for creating a log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 17-4 on page 86. The
elements of the block diagram that are not directly a part of the Input Capture unit are gray
shaded.
Figure 17-4. Input Capture Unit Block Diagram
DATA BUS
(8-bit)
TEMP (8-bit)
OCRnB (8-bit)
WRITE
OCRnA (8-bit)
ICRn (16-bit Register)
TCNTnL (8-bit)
TCNTn (16-bit Counter)
ICSn
ICPn1
TCNTnH (8-bit)
ICNCn
ICESn
Noise
Canceler
Edge
Detector
ICFn (Int.Req.)
ICPn0
The Output Compare Register OCRnA is a dual-purpose register that is also used as an 8-bit
Input Capture Register ICRn. In 16-bit Input Capture mode the Output Compare Register
OCRnB serves as the high byte of the Input Capture Register ICRn. In 8-bit Input Capture mode
the Output Compare Register OCRnB is free to be used as a normal Output Compare Register,
86
8042B–AVR–06/10
ATmega16HVB/32HVB
but in 16-bit Input Capture mode the Output Compare Unit cannot be used as there are no free
Output Compare Register(s). Even though the Input Capture register is called ICRn in this section, it is referring to the Output Compare Register(s). For more information on how to access
the 16-bit registers refer to ”Accessing Registers in 16-bit Mode” on page 90.
When a change of the logic level (an event) occurs on the Input Capture pin (ICPx), and this
change confirms to the setting of the edge detector, a capture will be triggered. When a capture
is triggered, the value of the counter (TCNTn) is written to the Input Capture Register (ICRn).
The Input Capture Flag (ICFn) is set at the same system clock as the TCNTn value is copied into
Input Capture Register. If enabled (TICIEn=1), the Input Capture Flag generates an Input Capture interrupt. The ICFn flag is automatically cleared when the interrupt is executed. Alternatively
the ICFn flag can be cleared by software by writing a logical one to its I/O bit location.
17.6.1
Input Capture Trigger Source
The default trigger source for the Input Capture unit is the I/O port PB0 in Timer/Counter0 and
the Battery Protection Interrupt in Timer/Counter1. Alternatively can the osi_posedge pin on the
Oscillator Sampling Interface in Timer/Counter0 and Voltage Regulator Interrupt in
Timer/Counter1 be used as trigger sources. The osi_posedge pin in Timer/Counter0 Control
Register A (TCCR0A) and the Voltage Regulator Interrupt bit in the Timer/Counter1 Control
Register A (TCCR1A) is selected as trigger sources by setting the Input Capture Select (ICS0/1)
bit. Be aware that changing trigger source can trigger a capture. The Input Capture Flag must
therefore be cleared after the change.
Both Input Capture inputs are sampled using the same technique. The edge detector is also
identical. However, when the noise canceler is enabled, additional logic is inserted before the
edge detector, which increases the delay by four system clock cycles. An Input Capture on
Timer/Counter0 can also be triggered by software by controlling the port of the PB0 pin.
17.6.2
Noise Canceler
The noise canceler improves noise immunity by using a simple digital filtering scheme. The
noise canceler input is monitored over four samples, and all four must be equal for changing the
output that in turn is used by the edge detector.
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNCn) bit in
Timer/Counter Control Register n B (TCCRnB). When enabled the noise canceler introduces
additional four system clock cycles of delay from a change applied to the input, to the update of
the ICRn Register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.
17.6.3
Using the Input Capture Unit
The main challenge when using the Input Capture unit is to assign enough processor capacity
for handling the incoming events. The time between two events is critical. If the processor has
not read the captured value in the ICRn Register before the next event occurs, the ICRn will be
overwritten with a new value. In this case the result of the capture will be incorrect.
When using the Input Capture interrupt, the ICRn Register should be read as early in the interrupt handler routine as possible. The maximum interrupt response time is dependent on the
maximum number of clock cycles it takes to handle any of the other interrupt requests.
Measurement of an external signal duty cycle requires that the trigger edge is changed after
each capture. Changing the edge sensing must be done as early as possible after the ICRn
Register has been read. After a change of the edge, the Input Capture Flag (ICFn) must be
87
8042B–AVR–06/10
ATmega16HVB/32HVB
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the trigger edge change is not required.
Table 17-3.
ICS0
Timer/Counter0 Input Capture Source (ICS)
Source
0
ICP00: Port PB0
1
ICP01: osi_posedge pin from OSI module(1)(2)
Note:
1. See ”OSI – Oscillator Sampling Interface” on page 29 for details.
2. The noise canceler cannot be used with this source.
Table 17-4.
ICS1
Note:
17.7
Timer/Counter1 Input Capture Source (ICS)
Source
0
ICP10: Battery Protection Interrupt(1)
1
ICP11: Voltage Regulator Interrupt(1)
1. The noise canceller will filter out the input capture and it is therefore not recommended to use
noise canceler with these sources.
Output Compare Unit
The comparator continuously compares the Timer/Counter (TCNTn) with the Output Compare
Registers (OCRnA and OCRnB), and whenever the Timer/Counter equals to the Output Compare Registers, the comparator signals a match. A match will set the Output Compare Flag at
the next timer clock cycle. In 8-bit mode the match can set either the Output Compare Flag
OCFnA or OCFnB, but in 16-bit mode the match can set only the Output Compare Flag OCFnA
as there is only one Output Compare Unit. 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. Figure 17-5 on page 88 shows a block diagram of the
Output Compare unit.
Figure 17-5. Output Compare Unit, Block Diagram
DATA BUS
OCRnx
TCNTn
= (8/16-bit Comparator )
OCFnx (Int.Req.)
88
8042B–AVR–06/10
ATmega16HVB/32HVB
17.7.1
Compare Match Blocking by TCNT0 Write
All CPU write operations to the TCNTnH/L Register will block any Compare Match that occur in
the next timer clock cycle, even when the timer is stopped. This feature allows OCRnA/B to be
initialized to the same value as TCNTn without triggering an interrupt when the Timer/Counter
clock is enabled.
17.7.2
Using the Output Compare Unit
Since writing TCNTnH/L will block all Compare Matches for one timer clock cycle, there are risks
involved when changing TCNTnH/L when using the Output Compare Unit, independently of
whether the Timer/Counter is running or not. If the value written to TCNTnH/L equals the
OCRnA/B value, the Compare Match will be missed.
17.8
Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkTn) is therefore shown as a
clock enable signal in the following figures. The figures include information on when Interrupt
Flags are set. Figure 17-6 on page 89 contains timing data for basic Timer/Counter operation.
The figure shows the count sequence close to the MAX value.
Figure 17-6. Timer/Counter Timing Diagram, no Prescaling
clkI/O
clkTn
(clkI/O /1)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 17-7 on page 89 shows the same timing data, but with the prescaler enabled.
Figure 17-7. 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 17-8 on page 90 shows the setting of OCFnA and OCFnB in Normal mode.
89
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 17-8. Timer/Counter Timing Diagram, Setting of OCFnx, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O /8)
TCNTn
OCRnx - 1
OCRnx
OCRnx
OCRnx + 1
OCRnx + 2
OCRnx Value
OCFnx
Figure 17-9 on page 90 shows the setting of OCFnA and the clearing of TCNTn in CTC mode.
Figure 17-9. Timer/Counter Timing Diagram, CTC mode, with Prescaler (fclk_I/O/8)
clkPCK
clkTn
(clkPCK /8)
TCNTn
(CTC)
TOP - 1
OCRnx
TOP
BOTTOM
BOTTOM + 1
TOP
OCFnx
17.9
Accessing Registers in 16-bit Mode
In 16-bit mode (the TCWn bit is set to one) the TCNTnH/L and OCRnA/B or TCNTnL/H and
OCRnB/A 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. The 16-bit
Timer/Counter 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. 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.
There is one exception in the temporary register usage. In the Output Compare mode the 16-bit
Output Compare Register OCRnA/B is read without the temporary register, because the Output
Compare Register contains a fixed value that is only changed by CPU access. However, in 16bit Input Capture mode the ICRn register formed by the OCRnA and OCRnB registers must be
accessed with 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.
90
8042B–AVR–06/10
ATmega16HVB/32HVB
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 OCRnA/B registers.
Assembly Code Example
...
; Set TCNTn to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNTnH,r17
out TCNTnL,r16
; Read TCNTn into r17:r16
in r16,TCNTnL
in r17,TCNTnH
...
C Code Example
unsigned int i;
...
/* Set TCNTn to 0x01FF */
TCNTn = 0x1FF;
/* Read TCNTn into i */
i = TCNTn;
...
Note:
1. See “About Code Examples” on page 8.
The assembly code example returns the TCNTnH/L 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
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.
91
8042B–AVR–06/10
ATmega16HVB/32HVB
The following code examples show how to do an atomic read of the TCNTn register contents.
Reading any of the OCRn register can be done by using the same principle.
Assembly Code Example
TIMn_ReadTCNTn:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNTn into r17:r16
in r16,TCNTnL
in r17,TCNTnH
; Restore global interrupt flag
out SREG,r18
ret
C Code Example
unsigned int TIMn_ReadTCNTn( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNTn into i */
i = TCNTn;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}
Note:
1. See “About Code Examples” on page 8.
The assembly code example returns the TCNTnH/L value in the r17:r16 register pair.
92
8042B–AVR–06/10
ATmega16HVB/32HVB
The following code examples show how to do an atomic write of the TCNTnH/L register contents. Writing any of the OCRnA/B registers can be done by using the same principle.
Assembly Code Example
TIMn_WriteTCNTn:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNTn to r17:r16
out TCNTnH,r17
out TCNTnL,r16
; Restore global interrupt flag
out SREG,r18
ret
C Code Example
void TIMn_WriteTCNTn( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNTn to i */
TCNTn = i;
/* Restore global interrupt flag */
SREG = sreg;
}
Note:
See “About Code Examples” on page 8.
The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNTnH/L.
17.9.1
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.
93
8042B–AVR–06/10
ATmega16HVB/32HVB
17.10 Register Description
17.10.1
TCCRnA – Timer/Counter n Control Register A
Bit
7
6
5
4
3
2
1
0
0x24 (0x44)
TCWn
ICENn
ICNCn
ICESn
ICSn
–
–
WGMn0
Read/Write
R/W
R/W
R/W
R/W
R/W
R
R
R/W
Initial Value
0
0
0
0
0
0
0
0
TCCRnA
• Bit 7 – TCWn: Timer/Counter Width
When this bit is written to one 16-bit mode is selected. Timer/Counter n width is set to 16-bits
and the Output Compare Registers OCRnA and OCRnB are combined to form one 16-bit Output
Compare Register. Because the 16-bit registers TCNTnH/L and OCRnB/A are accessed by the
AVR CPU via the 8-bit data bus, special procedures must be followed. These procedures are
described in section ”Accessing Registers in 16-bit Mode” on page 90.
• Bit 6 – ICENn: Input Capture Mode Enable
The Input Capture Mode is enabled when this bit is written to one.
• Bit 5 – ICNCn: Input Capture Noise Canceler
Setting this bit activates the Input Capture Noise Canceler. When the noise canceler is activated, the input from the Input Capture Source is filtered. The filter function requires four
successive equal valued samples of the Input Capture Source for changing its output. The Input
Capture is therefore delayed by four System Clock cycles when the noise canceler is enabled.
• Bit 4 – ICESn: Input Capture Edge Select
This bit selects which edge on the Input Capture Source that is used to trigger a capture event.
When the ICESn bit is written to zero, a falling (negative) edge is used as trigger, and when the
ICESn bit is written to one, a rising (positive) edge will trigger the capture. When a capture is triggered according to the ICESn setting, the counter value is copied into the Input Capture
Register. The event will also set the Input Capture Flag (ICFn), and this can be used to cause an
Input Capture Interrupt, if this interrupt is enabled.
• Bit 3 – ICSn: Input Capture Select
When written logic one, this bit enables the input capture function in Timer/Counter n to be triggered by the alternative Input Capture Source. To make the comparator trigger the
Timer/Counter n Input Capture interrupt, the TICIEn bit in the Timer Interrupt Mask Register
(TIMSK) must be set. See Table 17-3 on page 88 and Table 17-4 on page 88.
• Bits 2:1 – Reserved
These bits are reserved in the ATmega16HVB/32HVB and will always read as zero.
• Bit 0 – WGMn0: Waveform Generation Mode
This bit controls the counting sequence of the counter, the source for maximum (TOP) counter
value, see Figure 17-6 on page 89. Modes of operation supported by the Timer/Counter unit are:
Normal mode (counter) and Clear Timer on Compare Match (CTC) mode (see ”Timer/Counter
Timing Diagrams” on page 89).
94
8042B–AVR–06/10
ATmega16HVB/32HVB
17.10.2
TCNTnL – Timer/Counter n Register Low Byte
Bit
7
6
5
0x26 (0x46)
4
3
2
1
0
TCNTnL[7:0]
TCNTnL
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 TCNTnL gives direct access, both for read and write operations, to
the Timer/Counter unit 8-bit counter. Writing to the TCNTnL Register blocks (disables) the Compare Match on the following timer clock. Modifying the counter (TCNTnL) while the counter is
running, introduces a risk of missing a Compare Match between TCNTnL and the OCRnx Registers. In 16-bit mode the TCNTnL register contains the lower part of the 16-bit Timer/Counter n
Register.
17.10.3
TCNTnH – Timer/Counter n Register High Byte
Bit
7
6
5
0x27 (0x47)
4
3
2
1
0
TCNTnH[7:0]
TCNTnH
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
When 16-bit mode is selected (the TCWn bit is set to one) the Timer/Counter Register TCNTnH
combined to the Timer/Counter Register TCNTnL gives direct access, both for read and 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 Registers in 16-bit Mode” on page 90.
17.10.4
OCRnA – Timer/Counter n Output Compare Register A
Bit
7
6
5
0x28 (0x48)
4
3
2
1
0
OCRnA[7:0]
OCRnA
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 (TCNTnL). A match can be used to generate an Output Compare interrupt.
In 16-bit mode the OCRnA register contains the low byte of the 16-bit Output Compare Register.
To ensure that both the high and the 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 16-bit registers. See ”Accessing Registers in
16-bit Mode” on page 90.
17.10.5
OCRnB – Timer/Counter n Output Compare Register B
Bit
7
6
5
0x29 (0x49)
4
3
2
1
0
OCRnB[7:0]
OCRnB
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 (TCNTnL in 8-bit mode and TCNTnH in 16-bit mode). A match can be used to
generate an Output Compare interrupt.
95
8042B–AVR–06/10
ATmega16HVB/32HVB
In 16-bit mode the OCRnB register contains the high byte of the 16-bit Output Compare Register. To ensure that both the high and the 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 16-bit registers. See ”Accessing Registers in 16-bit Mode” on page 90.
17.10.6
TIMSKn – Timer/Counter n Interrupt Mask Register
Bit
7
6
5
4
3
2
1
0
(0x6E)(0x6F)
–
–
–
–
ICIEn
OCIEnB
OCIEnA
TOIEn
Read/Write
R
R
R
R
R/W
R/W
R/W
R
Initial Value
0
0
0
0
0
0
0
0
TIMSKn
• Bit 3 – ICIEn: Timer/Counter n Input Capture Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter n Input Capture interrupt is enabled. The corresponding Interrupt
Vector (See Section “12.” on page 52.) is executed when the ICFn flag, located in TIFRn, is set.
• Bit 2 – OCIEnB: Timer/Counter n Output Compare Match B Interrupt Enable
When the OCIEnB 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 OCFnB bit is set in the Timer/Counter
Interrupt Flag Register – TIFRn.
• Bit 1 – OCIEnA: Timer/Counter n Output Compare Match A Interrupt Enable
When the OCIEnA bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter n Compare Match A interrupt is enabled. The corresponding interrupt is executed
if a Compare Match in Timer/Counter n occurs, i.e., when the OCFnA bit is set in the
Timer/Counter n Interrupt Flag Register – TIFRn.
• Bit 0 – TOIEn: Timer/Counter n Overflow Interrupt Enable
When the TOIEn bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter n Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in
Timer/Counter n occurs, i.e., when the TOVn bit is set in the Timer/Counter n Interrupt Flag Register – TIFRn.
17.10.7
TIFRn – Timer/Counter n Interrupt Flag Register
Bit
7
6
5
4
3
2
1
0
0x15 (0x35)
–
–
–
–
ICFn
OCFnB
OCFnA
TOVn
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
TIFRn
• Bits 3 – ICFn: Timer/Counter n Input Capture Flag
This flag is set when a capture event occurs, according to the setting of ICENn, ICESn and ICSn
bits in the TCCRnA Register.
ICFn is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively,
ICFn can be cleared by writing a logic one to its bit location.
96
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bit 2 – OCFnB: Output Compare Flag n B
The OCFnB bit is set when a Compare Match occurs between the Timer/Counter and the data in
OCRnB – Output Compare Register n B. OCFnB is cleared by hardware when executing the
corresponding interrupt handling vector. Alternatively, OCFnB is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIEnB (Timer/Counter Compare B Match Interrupt Enable),
and OCFnB are set, the Timer/Counter Compare Match Interrupt is executed.
The OCFnB is not set in 16-bit Output Compare mode when the Output Compare Register
OCRnB is used as the high byte of the 16-bit Output Compare Register or in 16-bit Input Capture mode when the Output Compare Register OCRnB is used as the high byte of the Input
Capture Register.
• Bit 1 – OCFnA: Output Compare Flag n A
The OCFnA bit is set when a Compare Match occurs between the Timer/Counter n and the data
in OCRnA – Output Compare Register n. OCFnA is cleared by hardware when executing the
corresponding interrupt handling vector. Alternatively, OCFnA is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIEnA (Timer/Counter n Compare Match Interrupt Enable),
and OCFnA are set, the Timer/Counter n Compare Match Interrupt is executed.
The OCFnA is also set in 16-bit mode when a Compare Match occurs between the Timer/Counter n and 16-bit data in OCRnB/A. The OCFnA is not set in Input Capture mode when the Output
Compare Register OCRnA is used as an Input Capture Register.
• Bit 0 – TOVn: Timer/Counter n Overflow Flag
The bit TOVn is set when an overflow occurs in Timer/Counter n. TOVn is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOVn is cleared by
writing a logic one to the flag. When the SREG I-bit, TOIEn (Timer/Counter n Overflow Interrupt
Enable), and TOVn are set, the Timer/Counter n Overflow interrupt is executed.
97
8042B–AVR–06/10
ATmega16HVB/32HVB
18. SPI – Serial Peripheral Interface
18.1
Features
•
•
•
•
•
•
•
•
18.2
Full-duplex, Three-wire Synchronous Data Transfer
Master or Slave Operation
LSB First or MSB First Data Transfer
Seven Programmable Bit Rates
End of Transmission Interrupt Flag
Write Collision Protection Flag
Wake-up from Idle Mode
Double Speed (CK/2) Master SPI Mode
Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
ATmega16HVB/32HVB and peripheral devices or between several AVR devices.
When the SPI is not used, power consumption can be minimized by writing the PRSPI bit in
PRR0 to one. See ”PRR0 – Power Reduction Register 0” on page 40 for details on how to use
the PRSPI bit.
Figure 18-1. SPI Block Diagram(1)
SPI2X
SPI2X
DIVIDER
/2/4/8/16/32/64/128
Note:
1. Refer to ”Alternate Port Functions” on page 72 for SPI pin placement.
98
8042B–AVR–06/10
ATmega16HVB/32HVB
The interconnection between Master and Slave CPUs with SPI is shown in Figure 18-2. The system consists of two shift Registers, and a Master clock generator. The SPI Master initiates the
communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and
Slave prepare the data to be sent in their respective shift Registers, and the Master generates
the required clock pulses on the SCK line to interchange data. Data is always shifted from Master to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the Master In
– Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling
high the Slave Select, SS, line.
When configured as a Master, the SPI interface has no automatic control of the SS line. This
must be handled by user software before communication can start. When this is done, writing a
byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight
bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of
Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an
interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or
signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be
kept in the Buffer Register for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long
as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin
until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission
Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt
is requested. The Slave may continue to place new data to be sent into SPDR before reading
the incoming data. The last incoming byte will be kept in the Buffer Register for later use.
Figure 18-2. SPI Master-slave Interconnection
SHIFT
ENABLE
The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before
the entire shift cycle is completed. When receiving data, however, a received character must be
read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost.
In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure
correct sampling of the clock signal, the frequency of the SPI clock should never exceed fosc/4.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden
according to Table 18-1 on page 100. For more details on automatic port overrides, refer to
”Alternate Port Functions” on page 72.
99
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 18-1.
Pin
SPI Pin Overrides(1)
Direction, Master SPI
Direction, Slave SPI
MOSI
User Defined
Input
MISO
Input
User Defined
SCK
User Defined
Input
SS
User Defined
Input
Note:
1. See ”Alternate Functions of Port B” on page 75 for a detailed description of how to define the
direction of the user defined SPI pins.
The following code examples show how to initialize the SPI as a Master and how to perform a
simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction
Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the
actual data direction bits for these pins. E.g. if MOSI is placed on pin PB5, replace DD_MOSI
with DDB5 and DDR_SPI with DDRB.
100
8042B–AVR–06/10
ATmega16HVB/32HVB
Assembly Code Example(1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi
r17,(1<<DD_MOSI)|(1<<DD_SCK)
out
DDR_SPI,r17
; Enable SPI, Master, set clock rate fck/16
ldi
r17,(1<<SPE)|(1<<MSTR)|(1<<SPR0)
out
SPCR,r17
ret
SPI_MasterTransmit:
; Start transmission of data (r16)
out
SPDR,r16
Wait_Transmit:
; Wait for transmission complete
in r16,SPSR
sbrs r16,SPIF
rjmp Wait_Transmit
ret
C Code Example(1)
void SPI_MasterInit(void)
{
/* Set MOSI and SCK output, all others input */
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
/* Enable SPI, Master, set clock rate fck/16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
void SPI_MasterTransmit(char cData)
{
/* Start transmission */
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)))
;
}
Note:
1. See “About Code Examples” on page 8.
101
8042B–AVR–06/10
ATmega16HVB/32HVB
The following code examples show how to initialize the SPI as a Slave and how to perform a
simple reception.
Assembly Code Example(1)
SPI_SlaveInit:
; Set MISO output, all others input
ldi
r17,(1<<DD_MISO)
out
DDR_SPI,r17
; Enable SPI
ldi
r17,(1<<SPE)
out
SPCR,r17
ret
SPI_SlaveReceive:
; Wait for reception complete
in r16,SPSR
sbrs r16,SPIF
rjmp SPI_SlaveReceive
; Read received data and return
in
r16,SPDR
ret
C Code Example(1)
void SPI_SlaveInit(void)
{
/* Set MISO output, all others input */
DDR_SPI = (1<<DD_MISO);
/* Enable SPI */
SPCR = (1<<SPE);
}
char SPI_SlaveReceive(void)
{
/* Wait for reception complete */
while(!(SPSR & (1<<SPIF)))
;
/* Return Data Register */
return SPDR;
}
Note:
1. See “About Code Examples” on page 8.
102
8042B–AVR–06/10
ATmega16HVB/32HVB
18.3
18.3.1
SS Pin Functionality
Slave Mode
When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is
held low, the SPI is activated, and MISO becomes an output if configured so by the user. All
other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which
means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin
is driven high.
The SS pin is useful for packet/byte synchronization to keep the slave bit counter synchronous
with the master clock generator. When the SS pin is driven high, the SPI slave will immediately
reset the send and receive logic, and drop any partially received data in the Shift Register.
18.3.2
Master Mode
When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the
direction of the SS pin.
If SS is configured as an output, the pin is a general output pin which does not affect the SPI
system. Typically, the pin will be driving the SS pin of the SPI Slave.
If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin
is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin
defined as an input, the SPI system interprets this as another master selecting the SPI as a
slave and starting to send data to it. To avoid bus contention, the SPI system takes the following
actions:
1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of
the SPI becoming a Slave, the MOSI and SCK pins become inputs.
2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is
set, the interrupt routine will be executed.
Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the
MSTR bit has been cleared by a slave select, it must be set by the user to re-enable SPI Master
mode.
18.4
Data Modes
There are four combinations of SCK phase and polarity with respect to serial data, which are
determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure
18-3 and Figure 18-4 on page 104. Data bits are shifted out and latched in on opposite edges of
the SCK signal, ensuring sufficient time for data signals to stabilize. This is clearly seen by summarizing Table 18-3 on page 105 and Table 18-4 on page 105, as done in Table 18-2.
Table 18-2.
SPI Modes
SPI Mode
Conditions
Leading Edge
Trailing eDge
0
CPOL=0, CPHA=0
Sample (Rising)
Setup (Falling)
1
CPOL=0, CPHA=1
Setup (Rising)
Sample (Falling)
2
CPOL=1, CPHA=0
Sample (Falling)
Setup (Rising)
3
CPOL=1, CPHA=1
Setup (Falling)
Sample (Rising)
103
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 18-3. SPI Transfer Format with CPHA = 0
SCK (CPOL = 0)
mode 0
SCK (CPOL = 1)
mode 2
SAMPLE I
MOSI/MISO
CHANGE 0
MOSI PIN
CHANGE 0
MISO PIN
SS
MSB first (DORD = 0) MSB
LSB first (DORD = 1) LSB
Bit 6
Bit 1
Bit 5
Bit 2
Bit 4
Bit 3
Bit 3
Bit 4
Bit 2
Bit 5
Bit 1
Bit 6
LSB
MSB
Figure 18-4. SPI Transfer Format with CPHA = 1
SCK (CPOL = 0)
mode 1
SCK (CPOL = 1)
mode 3
SAMPLE I
MOSI/MISO
CHANGE 0
MOSI PIN
CHANGE 0
MISO PIN
SS
MSB first (DORD = 0)
LSB first (DORD = 1)
MSB
LSB
Bit 6
Bit 1
Bit 5
Bit 2
Bit 4
Bit 3
Bit 3
Bit 4
Bit 2
Bit 5
Bit 1
Bit 6
LSB
MSB
104
8042B–AVR–06/10
ATmega16HVB/32HVB
18.5
18.5.1
Register Description
SPCR – SPI Control Register
Bit
7
6
5
4
3
2
1
0
0x2C (0x4C)
SPIE
SPE
DORD
MSTR
CPOL
CPHA
SPR1
SPR0
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
SPCR
• Bit 7 – SPIE: SPI Interrupt Enable
This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and the if
the Global Interrupt Enable bit in SREG is set.
• Bit 6 – SPE: SPI Enable
When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI
operations.
• Bit 5 – DORD: Data Order
When the DORD bit is written to one, the LSB of the data word is transmitted first.
When the DORD bit is written to zero, the MSB of the data word is transmitted first.
• Bit 4 – MSTR: Master/Slave Select
This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic
zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared,
and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode.
• Bit 3 – CPOL: Clock Polarity
When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low
when idle. Refer to Figure 18-3 and Figure 18-4 for an example. The CPOL functionality is summarized below:
Table 18-3.
CPOL Functionality
CPOL
Leading Edge
Trailing Edge
0
Rising
Falling
1
Falling
Rising
• Bit 2 – CPHA: Clock Phase
The settings of the Clock Phase bit (CPHA) determine if data is sampled on the leading (first) or
trailing (last) edge of SCK. Refer to Figure 18-3 and Figure 18-4 for an example. The CPOL
functionality is summarized below:
Table 18-4.
CPHA Functionality
CPHA
Leading Edge
Trailing Edge
0
Sample
Setup
1
Setup
Sample
105
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bits 1, 0 – SPR1, SPR0: SPI Clock Rate Select 1 and 0
These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have
no effect on the Slave. The relationship between SCK and the Oscillator Clock frequency fosc is
shown in the following table:
Table 18-5.
18.5.2
Relationship Between SCK and the Oscillator Frequency
SPI2X
SPR1
SPR0
0
0
0
0
0
1
0
1
0
0
1
1
1
0
0
1
0
1
1
1
0
1
1
1
SCK Frequency
fosc/4
fosc/16
fosc/64
fosc/128
fosc/2
fosc/8
fosc/32
fosc/64
SPSR – SPI Status Register
Bit
7
6
5
4
3
2
1
0
SPIF
WCOL
–
–
–
–
–
SPI2X
Read/Write
R
R
R
R
R
R
R
R/W
Initial Value
0
0
0
0
0
0
0
0
0x2D (0x4D)
SPSR
• Bit 7 – SPIF: SPI Interrupt Flag
When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in
SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is
in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the
corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the
SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR).
• Bit 6 – WCOL: Write Collision Flag
The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The
WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set,
and then accessing the SPI Data Register.
• Bit 5:1 – Reserved
These bits are reserved in the ATmega16HVB/32HVB and will always read as zero.
• Bit 0 – SPI2X: Double SPI Speed Bit
When this bit is written logic one the SPI speed (SCK Frequency) will be doubled when the SPI
is in Master mode (see Table 18-5 on page 106). This means that the minimum SCK period will
be two CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to
work at fosc/4 or lower.
106
8042B–AVR–06/10
ATmega16HVB/32HVB
The SPI interface on the ATmega16HVB/32HVB is also used for program memory and
EEPROM downloading or uploading. See Table 30.6 on page 211 for serial programming and
verification.
18.5.3
SPDR – SPI Data Register
Bit
7
6
5
4
3
2
1
0
0x2E (0x4E)
MSB
LSB
Read/Write
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
X
X
X
X
X
X
X
X
SPDR
Undefined
The SPI Data Register is a read/write register used for data transfer between the Register File
and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read.
107
8042B–AVR–06/10
ATmega16HVB/32HVB
19. Coulomb Counter – Dedicated Fuel Gauging Sigma-delta ADC
19.1
Features
• Sampled System Coulomb Counter
• Low Power Sigma-Delta ADC Optimized for Coulomb Counting
• Instantaneous Current Output with 3.9 ms Conversion Time
•
•
•
•
19.2
– 13 bit Resolution (including sign bit)
– Interrupt on Instantaneous Current Conversion Complete
Accumulate Current Output
– Programmable Conversion Time: 128/256/512/1024 ms
– 18-bit Resolution (including sign bit)
– Interrupt on Accumulation Current Conversion Complete
Regular Current Detection Mode
– Programmable Sampling Interval: 256/512/1024/2048 ms
Programmable Input Voltage Range ± 100/200mV
– Allowing Measurement of ± 20/40A @ 5 mΩ
Offset canceling by input polarity switching
Overview
ATmega16/32HVB features a dedicated Sigma-Delta ADC (CC-ADC) optimized for Coulomb
Counting. By sampling the charge or discharge current flowing through an external sense resistor RSENSE, the CC-ADC is used to track the flow of current going into and out of the battery
cells.
Figure 19-1. Coulomb Counter Block Diagram
8-BIT DATABUS
Instantaneous
Current
Register
Regular
Current Level
Control &
Status
Registers
Accumulate
Current
Register
IRQ
Current
Comparator
PI
IRQ
Polarity
Switcher
RSENSE
Sigma Delta
modulator
Decimation
Filter
IRQ
Decimation
Filter
NI
The CC-ADC has a programmable voltage range allowing trade-off to be made between resolution, dynamic range and external sense resistor RSENSE.
108
8042B–AVR–06/10
ATmega16HVB/32HVB
In normal conversion mode 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 CC-ADC also provides a special Regular Current detection mode. This allows ultra-low
power operation in Power-save mode when small charge or discharge currents are flowing.
For offset cancellation the polarity of the input signal could be switched run time. Using this feature, the internal CC-ADC offset could be removed. See application note AVR352.
19.3
Normal Operation
When enabled the CC-ADC continuously measures the voltage over the external sense resistor
RSENSE. Running in normal conversion mode, two data conversion outputs are provided.
• Instantaneous Conversion Result
• Accumulation Conversion Result
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
generated 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 19-2
shows an Instantaneous Current conversion diagram, where DATA4 will be lost because DATA3
reading is not completed within the limited period.
Figure 19-2. Instantaneous Current Conversions
Enable
~12 ms settling
3.9 ms
3.9 ms
7.8 ms
DATA 1
DATA 2
DATA 3
Instantaneous
Interrupt
Instantaneous
Data
INVALID DATA
DATA 5
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 19-3 shows an Accumulation Current conversion example,
where DATA4 will be lost because DATA3 reading is not completed within the limited period.
109
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 19-3. Accumulation Current Conversions
Enable
1, 2, 3, or 4s settling
125, 250, 500,
or 1000 ms
125, 250, 500,
or 1000 ms
250, 500,
1000, or 2000 ms
DATA 1
DATA 2
DATA 3
Accumulation
Interrupt
Accumulation
Data
INVALID DATA
DATA 5
Read byte 1
Read byte 2
Read byte 3
Read byte 4
19.4
Regular Current Detection Operation
By setting the CADSE bit in CADCSRA the CC-ADC will enter a special Regular Current Detection Sampling Mode.
In this mode the CC-ADC will do one Instantaneous Current Conversion on regular sampling
intervals while updating of the Accumulation Current Register is automatically disabled. The
sampling interval is controlled by writing to the CADSI bits in CADCSRA.
Each time a conversion is completed the result is compared with Regular Charge/Discharge
Threshold levels specified in the CADRCC/CADRDC registers. If interrupt is enabled and the
voltage is above/below the specified limit a Regular Current Detection Interrupt will be issued.
Figure 19-4 illustrates the Regular Current Detection Mode.
Figure 19-4. Regular Current Detection Mode (CADSE=1)
Regular Current
Detection Operation
Turn-off
~250, 500, 1000, 2000ms
Measure
Turn-off
Measure
~12ms
~250, 500, 1000, 2000ms
~12ms
Regular Current
Detection Interupt
Regular Charge
Current Threshold
Current through RSENSE
Regular Discharge
Current Threshold
19.5
Offset Canceling by Polarity Switching
The CC-ADC offers Polarity Switching for internal offset canceling. By switching the polarity of
the sampled input signal at selected time intervals, the internal voltage offset of the CC-ADC will
cancel at the output. This feature prevents the CC-ADC from accumulating an offset error over
time.
110
8042B–AVR–06/10
ATmega16HVB/32HVB
19.6
Configuration and Usage
While the CC-ADC is converting, the CPU can enter sleep mode and wait for an interrupt. After
adding the conversion data for the 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.
To use the CC-ADC the bandgap voltage reference must be enabled separately, see ”Voltage
Reference and Temperature Sensor” 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-off mode.
After the CC-ADC is enabled by setting the CADEN bit, the first four conversions do not contain
useful data and should be ignored. This also applies after clearing the CADSE bit, or after
changing the CADPOL or CADVSE bits.
The conversion times and sampling intervals are controlled by the Ultra Low Power RC Oscillator (see ”Ultra Low Power RC Oscillator” on page 27), and will depend on its actual frequency.
To obtain accurate coulomb counting results, the actual conversion time should be calculated.
Refer to ”System Clock and Clock Options” on page 25 for details.
19.7
19.7.1
Register Description
CADCSRA – CC-ADC Control and Status Register A
Bit
7
6
5
4
3
2
1
0
CADEN
CADPOL
CADUB
CADAS1
CADAS0
CADSI1
CADSI0
CADSE
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
(0xE6)
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 R SENSE. In Power-off, the CC-ADC is always
disabled.
Note that the bandgap voltage reference must be enabled separately, see ”Voltage Reference
and Temperature Sensor” on page 123.
• Bit 6 – CADPOL: CC-ADC Polarity
The CADPOL bit is used to change input sampling polarity in the Sigma Delta Modulator. Writing
this bit to one, the polaritiy will be negative. When the bit is zero, the polarity will be positive.
• 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, CADCSRC, 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.
111
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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 the
Table 19-1.
Table 19-1.
Note:
CC-ADC Accumulate Current Conversion Time
CADAS1:0
CC-ADC Accumulate Current
Conversion Time(1)
Number of CC-ADC
clock Cycles
00
128 ms
4096
01
256 ms
8192
10
512 ms
16384
11
1s
32768
1. The actual value of depends on the actual frequency of the ”Ultra Low Power RC Oscillator” on
page 27. See Section “32.” on page 230.
• 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 the Table 19-2.
Table 19-2.
Notes:
CC-ADC Regular Current Sampling Interval
CADSI1:0
CC-ADC Regular Current
Sampling Interval(1)(2)
Number of CC-ADC
clock Cycles
00
256 ms (+ sampling time)
8192 (+ sampling time)
01
512 ms (+ sampling time)
16384 (+ sampling time)
10
1 s (+ sampling time)
32768 (+ sampling time)
11
2 s (+ sampling time)
65536 (+ sampling time)
1. The actual value of depends on the actual frequency of the ”Ultra Low Power RC Oscillator” on
page 27. See ”Electrical Characteristics” on page 230.
2. Sampling time ~ 12 ms.
• Bit 0 – CADSE: CC-ADC 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.
19.7.2
CADCSRB – CC-ADC Control and Status Register B
Bit
7
6
5
4
3
2
1
0
(0xE7)
–
CADACIE
CADRCIE
CADICIE
–
CADACIF
CADRCIF
CADICIF
Read/Write
R
R/W
R
R/W
R
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
CADCSRB
• Bits 7, 3 – Reserved
These bits are reserved in the ATmega16HVB/32HVB 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.
112
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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
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.
19.7.3
CADCSRC – CC-ADC Control and Status Register C
Bit
7
6
5
4
3
2
1
0
(0xE8)
–
–
–
–
–
–
–
CADVSE
Read/Write
R
R
R
R
R
R
R
R/W
Initial Value
0
0
0
0
0
0
0
0
CADCSRC
• Bit 7:1 – Reserved
These bits are reserved and will always read as zero.
• Bit 0 – CADVSE: CC-ADC Voltage Scaling Enable
Setting this bit enables the internal Voltage Scaling. When enabling the internal Voltage Scaling
the internal CC-ADC reference will be divided by 2, affecting the Input Voltage Range and the
resulting step-size. Table 19-3 shows the Input Voltage Range and the conversion value stepsize for the CADVSE settings.
113
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 19-3.
19.7.4
Input Voltage Range and the conversion value step-size for the CADVSE
settings.
CADVSE
Voltage Range
Step-size CADAC
Step-size CADIC
0
± 200 mV
1.67 µV
53.7 µV
1
± 100 mV
0.84 µV
26.9 µV
CADICH and CADICL – CC-ADC Instantaneous Current
Bit
15
14
13
12
11
(0xE5)
CADIC[15:8]
(0xE4)
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. Bits 12:0 are
the 13-bit ADC result (including sign), while bit 15:13 are the sign extension 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. When a conversion is completed, both registers must be read before the next
conversion is completed, otherwise data will be lost.
19.7.5
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. Bits 17:0 are the 18-bit ADC result (including sign),
while bit 31:18 are the sign extension bits.
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. When a conversion is completed, all four registers must
be read before the next conversion is completed, otherwise data will be lost.
114
8042B–AVR–06/10
ATmega16HVB/32HVB
19.7.6
CADRCC – CC-ADC Regular Charge Current
Bit
7
6
5
4
(0xE9)
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 defines the eight least significant bits of the Regular Charge Current
level in 2's complement format, where 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
the Table 19-4.
Table 19-4.
Programmable Range for the Regular Charge Current Level(1)
Minimum
Maximum
Step Size
0
13696/6848
53.7/26.9
RSENSE = 1 mΩ
0
13696/6848
53.7/26.9
RSENSE = 5 mΩ
0
2740/1370
10.7/5.4
RSENSE = 10 mΩ
0
1370/685
5.3/2.7
Voltage (µV)
Current (mA)
Note:
1. Values in the table are shown with the CADVSE set to both 0 and 1.
The CC-ADC Regular Charge Current Register does not affect the setting of the CC-ADC Conversion Complete Interrupt Flag.
19.7.7
CADRDC – CC-ADC Regular Discharge Current
Bit
7
6
5
(0xEA)
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 defines the eight least significant bits of the Regular Discharge Current
level in 2's complement format, where the most significant bits of the Regular Discharge Current
level are always one. The programmable range for the Regular Discharge Current level is given
in the Table 19-5.
115
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 19-5.
Programmable Range for the Regular Discharge Current Level
Minimum
Maximum
Step Size
0
13696/6848
53.7/26.9
RSENSE = 1 mΩ
0
13696/6848
53.7/26.9
RSENSE = 5 mΩ
0
2740/1370
10.7/5.4
RSENSE = 10 mΩ
0
1370/685
5.3/2.7
Voltage (µV)
Current (mA)
Note:
1. Values in the table are shown with the CADVSE set to both 0 and 1.
The CC-ADC Regular Discharge Current Register does not affect the setting of the CC-ADC
Conversion Complete Interrupt Flag.
116
8042B–AVR–06/10
ATmega16HVB/32HVB
20. Voltage ADC – 7-channel General Purpose 12-bit Sigma-Delta ADC
20.1
Features
•
•
•
•
•
•
20.2
12-bit Resolution
519µs Conversion Time @ 1 MHz clkVADC
Four Differential Input Channels for Cell Voltage Measurements
Three Single Ended Input Channels
0.2x Pre-scaling of Cell Voltages
Interrupt on V-ADC Conversion Complete
Overview
The ATmega16HVB/32HVB features a 12-bit Sigma-Delta ADC.
The Voltage ADC (V-ADC) is connected to seven 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 three single
ended channels referenced to SGND. One channel is for measuring the internal temperature
sensor VPTAT and two channels for measuring the voltage at ADC0 and ADC1.
When the V-ADC is not used, power consumption can be minimized by writing the PRVADC bit
in PRR0 to one. See ”PRR0 – Power Reduction Register 0” on page 40 for details on how to use
the PRVADC bit.
Figure 20-1. Voltage ADC Block Schematic
V-ADC CONVERSION COMPLETE IRQ
V-ADC MULTIPLEXER
SEL. REG (VADMUX)
ADC1/SGND
VADCCIE
VADCCIF
8-BIT DATA BUS
V-ADC CONTROL AND
STATUS REG (VADCSR)
ADC0/SGND
VTEMP
V-ADC CONTROL
PV4
INPUT
MUX
PV3
PV2
PV1
12-BIT
SIGMA-DELTA ADC
NV
Note:
The shaded signals are scaled by 0.2,
other signals are scaled by 1.0
20.3
VREF
V-ADC DATA REGISTER
(VADCL/ADCH)
SGND
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 disabled in Power-save and
117
8042B–AVR–06/10
ATmega16HVB/32HVB
Power-off mode. Note that the bandgap voltage reference must be enabled and disabled separately, see ”Bandgap Calibration” on page 124.
Figure 20-2. Voltage ADC Conversion Diagram
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 register. 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. When a
conversion is in progress, the V-ADC Data Register - VADCL and VADCH will be invalid. If the
System Clock Prescaler setting is changed during a V-ADC conversion, the conversion will be
aborted. 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-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. The V-ADC Data Register VADCL and VADCH will be valid until a new conversion is started. To ensure that correct data is
read, both high and low byte data registers should be read before starting a new conversion.
20.3.1
Configuring PA1 and PA0 for V-ADC operation
When one of the single ended channels ADC0 or ADC1 is used as analog input to the VADC,
either PA0 or PA1 are used as signal ground (SGND). When ADC0/1 is selected as input channel, PA1/0 is automatically switched to SGND.
The use of PA1 and PA0 as SGND is efficient for the thermistor configuration shown in ”Operating Circuit” on page 225. Both thermistors, RT32 and RT33 are connected through a common
divider resistor, R31, to PA0 and PA1 respectively.
Both PA0 and PA1 have very high input impedance when used as ADC inputs, which makes it
possible to connect two thermistors in the configuration, shown in ”Operating Circuit” on page
225. However, input impedance is limited and if high accuracy is required, only one thermistor
should be connected between PA0 and PA1. If two thermistors are connected, the configuration
is as follows:
• When measuring RT33, PA1 should be used as input channel and PA0 is automatically
switched to SGND.
• When measuring RT32, PA0 should be used as input channel and PA1 is automatically
switched to SGND.
118
8042B–AVR–06/10
ATmega16HVB/32HVB
20.3.2
Cell inputs
The V-ADC features one input channel for each battery cell to be able to measure each cell individually and to measure the total battery voltage through the input pins NV, PV1, PV2, PV3 and
PV4. Note that the internal Cell Balancing uses the same pins to bypass balancing current (See
”Cell Balancing” on page 154.) for details for balancing the battery cells. When balancing a cell
the V-ADC should not do conversion on the selected channel, as the internal Cell balancing will
affect the conversion result.
The V-ADC is designed to operate on PV1 pin voltages above 2V. If the battery cell voltage on
PV1 input falls below 2V the upper cell voltage appears to be lower than the its actual value. To
avoid that cells get potentially overcharged software should keep the cells in balance using the
internal Cell Balancing. See ”Cell Balancing” on page 154. for details.
When not using all the cell inputs, the unused cells should be connected to the cell below. An
example external coupling in 3-cell mode is shown in Figure 20-3 on page 119. Note that even if
the input is not used, it is recommended to connect the input through an external resistance to
limit inverse coupling current. This is to be able to protect the battery if cells are reversed coupled during production.
Figure 20-3. 1 3-cell mode connection
R
PV4
R
PV3
C
R
PV2
ATmega16HVB/32HVB
C
R
PV1
C
R
NV
119
8042B–AVR–06/10
ATmega16HVB/32HVB
20.4
20.4.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 – Reserved
These bits are reserved in the ATmega16HVB/32HVB and will always read as zero.
• Bit 3:0 – VADMUX[3:0]: V-ADC Channel Selection Bits
The VADMUX bits determine the V-ADC channel selection. See Table 20-1 on page 120.
Table 20-1.
20.4.2
VADMUX channel selection
VADMUX[3:0]
Channel Selected
Scale
0000
RESERVED
–
0001
CELL 1
0.2
0010
CELL 2
0.2
0011
CELL3
0.2
0100
CELL4
0.2
0101
VTEMP
1.0
0110
ADC0
1.0
0111
ADC1
1.0
1000...1111
RESERVED
–
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 – Reserved
These bits are reserved in the ATmega16HVB/32HVB 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 ”Bandgap Calibration” on page
124.
• Bit 2 – VADSC: Voltage ADC Start Conversion
Write this bit to one to start a new conversion of the selected channel.
120
8042B–AVR–06/10
ATmega16HVB/32HVB
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 lost.
• 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.4.3
VADCL and VADCH – V-ADC Data Register
Bit
15
14
13
12
(0x79)
–
–
–
–
(0x78)
11
10
9
8
VADC[11:8]
VADCH
VADC[7:0]
7
Read/Write
Initial Value
6
5
4
VADCL
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, both high and low byte data registers should 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 199 for details. The cell voltage in
mV is given by:
(VADCH/L – VADC Cell n Offset) ⋅ VADC Cell n Gain Calibration Word
Cell n [mV] = ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------16384
The voltage on the ADCn is given by:
1 (VADCH/L – VADC ADCn Offset) ⋅ VADC ADCn Gain Calibration Word
ADCn[mV] = ------ ⋅ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------10
16384
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 199 for details. The absolute temperature in Kelvin is given by:
121
8042B–AVR–06/10
ATmega16HVB/32HVB
⋅ VPTAT CALT(K) = VADCH/L
-------------------------------------------------------------16384
20.4.4
DIDR0 – Digital Input Disable Register 0
Bit
7
6
5
4
3
2
1
0
(0x7E)
–
–
–
–
–
–
PA1DID
PA0DID
Read/Write
R
R
R
R
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
DIDR0
• Bits 7:2 – Reserved
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 1:0 – PA1DID:PA0DID: Digital Input Disable
When this bit is written logic one, the digital input buffer on the corresponding Port A 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 PA1: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.
122
8042B–AVR–06/10
ATmega16HVB/32HVB
21. Voltage Reference and Temperature Sensor
21.1
Features
•
•
•
•
•
•
21.2
Accurate Voltage Reference of 1.100V
Voltage Reference Calibration Interface
Internal Temperature Sensor
External Decoupling for Optimum Noise Performance
Short Circuit Detection on the External Decoupling pin
Low Power Consumption
Overview
ATmega16HVB/32HVB features a highly accurate low power On-chip Bandgap Reference Voltage, VREF of 1.100V. This reference voltage is used as reference for the On-chip Voltage
Regulator, the Brown-out Detector, the internal Cell Balancing, the Battery Protection, the VADC and the CC-ADC. Figure 21-1 shows an overview of the On-chip voltage reference.
Figure 21-1. Bandgap Reference Voltage
8-bit databus
BG Control and Status
VPTAT
Bangap Reference
w/ temperature sensor
BG Calibration
1.1V
BG
Buffer
VREF
VREFGND
IRQ
BG Short Detector
In addition to the Bandgap Reference Voltage, the Voltage Reference includes a Calibration Unit
that enables run time calibration of the Reference Voltage, an On-chip temperature sensor for
monitoring the die temperature, and a Bandgap Short Detector to detect short circuit conditions
on the external VREF pin for highest safety.
123
8042B–AVR–06/10
ATmega16HVB/32HVB
21.3
Operation
When the device is in power-off state, the Voltage Reference will be switched off. After a Poweron reset condition the Voltage Reference will automatically be enabled.
By default the Bandgap Buffer will be enabled as the buffered reference voltage is used as reference for the Battery Protection, the internal Cell Balancing, the V-ADC and the CC-ADC. If any
of these modules are enabled the Bandgap Buffer must be enabled, otherwise it is recommended to disable the buffer by writing to the BGD bit in BGCSR to save power. Note that the
Bandgap Buffer needs settling time before the voltage is stable. For details on settling time, see
”Bandgap Buffer Settling Time” on page 124.
To ensure that the battery protection has safe operation condition, the Voltage Reference
includes a Short-circuit Detector. The Bandgap Short Detector continuously monitors the internal
1.100V reference voltage against the VREF pin voltage to detect potentially external short conditions to VCC or GND. If an external short condition is detected, the Bandgap Short Circuit
Detection is capable of interrupting and waking up the CPU from any sleep mode. If a Bandgap
Short-circuit condition occurs software should immediately disable the C-FET and D-FET. If no
external protection is provided to detect such a condition it is recommended to always enable
this feature, by setting the BGSCDE bit in the Bandgap Control and Status Register.
The Temperature Sensor generates a voltage Proportional-To-Absolute-Temperature, VPTAT.
This voltage is connected to the multiplexer at the V-ADC input and it 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 199 for details. See”Electrical Characteristics” on page 230 for
details on temperature accuracy.
21.4
Bandgap Calibration
To guarantee ultra low temperature drift the Voltage Reference includes two calibration registers
that should be initialized by software after reset. See Section 21.6 ”Register Description” on
page 126 for details. Changing values to the BGCCR IO register will change the nominal value
of the Bandgap Reference Voltage, while changing values to the BGCRR IO register trims the
temperature gradient of the bandgap reference.
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. See ”Electrical Characteristics” on page 230 for details on hold-off time.
Changing VREF will influence the conversion results for the V-ADC and CC-ADC. It is therefore
not recommended to do V-ADC and CC-ADC conversions while calibrating the bandgap.
21.5
Bandgap Buffer Settling Time
After the Voltage Reference have been enabled it needs a settling time before the voltage is stable. The settling time depends on the size of the external decoupling capacitor. With 1 µF
external capacitor a minimum settling time of 2ms should be used. Until settling is done it is not
124
8042B–AVR–06/10
ATmega16HVB/32HVB
recommended to enable the NFET driver (OC/OD or enter DUVR operation), Battery Protection,
V-ADC or CC-ADC.
Settling time is needed when the Buffer is enabled by software, or after a reset condition where
the buffer is automatically enabled.
125
8042B–AVR–06/10
ATmega16HVB/32HVB
21.6
21.6.1
Register Description
BGCCR – Bandgap Calibration C Register
Bit
7
6
5
4
3
2
1
0
(0xD0)
–
–
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
BGCCR
• Bits 7:6 – Reserved
These bits are reserved and will always read as zero.
• Bit 5:0 – BGCC[5: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 is approximately 2 mV. The application software should read the Atmel factory calibration value and store
it to the BGCCR register. See ”Reading the Signature Row from Software” on page 199 for
details.
21.6.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
1
1
1
1
(0xD1)
BGCRR
• Bit 7:0 – BGCR[7: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
thermometer 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. The application software should read the Atmel factory calibration value
and store it to the BGCRR register. See ”Reading the Signature Row from Software” on page
199 for details.
126
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 21-2.
21.6.3
BGCSR – Bandgap control and Status Register
Bit
7
6
5
4
3
2
1
0
(0xD2)
–
–
BGD
BGSCDE
–
–
BGSCDIF
BGSCDIE
Read/Write
R
R
R/W
R/W
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
BGCSR
• Bits 7:6 – Reserved
These bits are reserved and will always read as zero.
• Bit 5 – BGD: Bandgap Disable
Setting this bit to one will disable the bandgap voltage reference. This bit must be cleared (zero)
before enabling Cell Balancing, CC-ADC, V-ADC or Battery Protection, and must remain unset
(zero) while either of these modules are enabled. Note that after clearing this bit, a settling time
is required before the voltage is stable, see ”Bandgap Buffer Settling Time” on page 124.
• Bit 4 – BGSCDE: Bandgap Short Circuit Detection Enabled
Setting this bit to one will enable the bandgap Short Circuit Detector. This bit should be cleared if
the BGD bit in the BGCSR is set to one to avoid false setting of the BGSCDIF bit.
• Bits 3:2 – Reserved
These bits are reserved and will always read as zero.
• Bit 1 – BGSCDIF: Bandgap Short Circuit Detection Interrupt Flag
The bit is set when the Bandgap Short Circuit Detector is enabled and buffered bandgap reference is different from the unbuffered Bandgap reference. The BGSCDIF is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, BGSCDIF is cleared
by writing a logic one to its bit position.
127
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bit 0 – BGSCDIE: Bandgap Short Circuit Detection Interrupt Enable
When this bit is set, the Bandgap Short Circuit Detection Interrupt is enabled. The corresponding
interrupt is executed if a short-circuit is detected on the External Decoupling Pin for the Voltage
Reference.
128
8042B–AVR–06/10
ATmega16HVB/32HVB
22. Charger Detect
22.1
Features
• Operates directly from VFET supply
• Detects when a charger is connected or disconnected by monitoring the BATT pin
• Controls the operation state of the device by automatically enable/disable the internal Voltage
Regulator
• Automatically disabled when Discharge FET is ON.
• Interrupt wake-up from all sleep modes
22.2
Overview
The Charger Detect module has two main functions:
• Control the device operating state (Power-off or normal operation)
• Detect when a charger is connected/disconnected
Figure 22-1 shows a block diagram of the Charger Detect module.
Figure 22-1. Charger Detect block diagram.
+
VFET
BATT
POWER_OFF
DFET_EN
BLOD
Charger Detect
w/Power-on Reset
POR
SLEEP
(power-off)
CHARGER_PRESENT
Charger Detect
Interrupt Logic
IRQ
8-BIT DATABUS
129
8042B–AVR–06/10
ATmega16HVB/32HVB
22.3
Operation
The Charger Detect module is supplied directly from the VFET pin. When operating, the Charger
Detect will monitor the voltage of the BATT pin and detect whether a charger is present or not.
When the voltage on the BATT pin is above the Charger Detect Threshold level VPOT (”Electrical
Characteristics” on page 230) the CHARGER_PRESENT signal will be high. This signal is edge
detected to generate interrupt when a charger is connected or disconnected.
The Charger Detect module will operate as long as the Discharge FET is disabled and is able to
detect a charger in all sleep modes including Power-off.
22.3.1
Device operating state
The Charger Detect module controls the operating state of the ATmega16HVB/32HVB by
enabling/disabling the Voltage Regulator, which supplies the rest of the internal logic on the
chip.
If the chip is in Power-off state the Charger Detect will keep the Voltage Regulator disabled
allowing only the Charger Detect module itself to operate. To be able to start from a Power-off
state a charge voltage above VPOT has to be applied at the BATT pin. When a charger is connected the Charger Detect module will automatically start the Voltage Regulator. When the
VREG voltage rises, a Power-on Reset (POR) is given and the chip enters normal operating
mode after a reset delay corresponding to TTOUT. For details on POR, see ”Power-on Reset and
Charger Connect” on page 43.
When the ATmega16HVB/32HVB is running in normal operation mode software or hardware
could take the chip into Power-off state. For details on entering power-off by software, see
”Power-off Mode” on page 38. To protect the device against software malfunctions the
ATmega16HVB/32HVB has a Black-out Detector (BLOD). When a Black-out condition occurs
the Charger Detect will take the chip automatically into Power-off. For details on Black-out
Detection, see ”Voltage Regulator” on page 132.
Note that after a software power-off the BATT pin voltage has to fall below the Charger Detect
threshold limit, VPOT, before the chip is able to re-enable the Voltage Regulator and start-up the
device.
22.3.2
Interrupt logic
When the ATmega16HVB/32HVB is running in normal operation mode, the Charger Detect is
capable of giving an interrupt to the CPU if a charger is connected/disconnected or both. Interrupt is enabled/disabled by writing to the CHGDIE bit in the ”CHGDCSR – Charger Detect
Control and Status Register” on page 131.
Interrupt is given when a charger is connected, disconnected or both depending on interrupt
sense control settings. Selecting the correct interrupt sensing is done by writing to the CHGDISC
bits in the ”CHGDCSR – Charger Detect Control and Status Register” on page 131.
Charger Detect interrupt works asynchronous and will wake the CPU from any sleep mode.
The Charger Detect is automatically disabled/enabled when changing the state of the Discharge
FET, and any interrupt that occurs when enabling or disabling the Discharge FET has to be
carefully interpreted.
•
When enabling the Discharge-FET the Charger Detect module is automatically disabled.
When disabling the charger detect module a charger appear to be disconnected even if a
charger is present.
130
8042B–AVR–06/10
ATmega16HVB/32HVB
•
22.4
22.4.1
When disabling the Charge-FET the Charger Detect module is automatically enabled and a
charger appear to be connected.
Register Description
CHGDCSR – Charger Detect Control and Status Register
Bit
7
6
5
4
3
2
1
0
(0xD4)
–
–
–
BATTPVL
CHGDISC1
CHGDISC0
CHGDIF
CHGDIE
Read/Write
R
R
R
R
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
CHGDCSR
• Bit 7:5 – Reserved
These bits are reserved and will always read as zero.
• Bit 4 – BATTPVL: BATT pin Voltage Level
BATTPVL will read one as long when the Charger Detect module is enabled and the BATT pin
voltage is above the VPOT level. Otherwise the BATTPVL will read zero.
• Bit 3:2 – CHGDISC[1:0]: Charger Detect Interrupt Sense Control
Edges in the CHARGER_PRESENT signal shown in Figure 22-1 on page 129 are used to activate a Charger Detect Interrupt if the SREG I-flag and the interrupt enable bit in CHGDCSR are
set. By writing the CHGDISC bits to the values shown in Table 22-1 on page 131 the condition
generating interrupt is configured. When changing the CHGDISC bits, an interrupt can occur.
Therefore, it is recommended to first disable the Interrupt by clearing its CHGDIE bit in the
CHGDICSR Register. Finally, the Charger Detect interrupt flag should be cleared by writing a
logical one to CHGDIF bit before the interrupt is re-enabled.
Table 22-1.
Charger Detect Interrupt Sense Control.
CHGISC[1:0]
Detection
00
Charger Connect
01
Charger Disconnect
10
Charger Connect/Disconnect
11
None
• Bit 1 – CHGDIF: Charger Detect Interrupt Flag
Depending on the configuration of the CHGDISC bits in the CHGDCSR, this bit is set when a
charger is either connected or disconnected. The Charger Detect Interrupt is executed if the
CHGDIE bit and the I-bit in SREG are set. This bit is cleared by hardware when executing the
corresponding interrupt handling vector or alternatively by writing a logical one to the CHGDIF. It
is recommended to write this bit to one when setting CHGDIE.
• Bit 0 – CHGDIE: Charger Detect Interrupt Enable
When the CHGDIE bit is set (one), and the I-bit in the Status Register is set (one), the Charger
Detect Interrupt is enabled.
131
8042B–AVR–06/10
ATmega16HVB/32HVB
23. Voltage Regulator
23.1
Features
•
•
•
•
23.2
Input voltage from 4-25V
Fixed output voltage of 3.3V
Battery Pack Short Detection
Black-out Detection (BLOD)
Overview
ATmega16HVB/32HVB get its voltage supply through the VFET terminal. Operating range at the
VFET terminal is 4 - 25V. The on-chip LDO regulator regulates the VFET terminal down to 3.3V,
which is a suitable supply voltage for the internal logic, I/O lines and analog circuitry. Figure 231 illustrates the Voltage Regulator.
Figure 23-1. Voltage Regulator.
Databus
ROCR
Regulator Monitor
and Control Interface
DISABLE VFET
IRQ
BLOD
Battery
Short Detect
Black-out
Detect
POWER-OFF
ENABLE
VREG
VFET
LDO Regulator
CREG
To ensure safe operating condition the Voltage Regulator has built in protection mechanisms to
protect the internal circuitry if the voltage drops on either the input or output terminal. The Regulator Monitoring includes
• Battery Pack Short Detector
• Black-out Detector
An external decoupling capacitor (CREG) of minimum 1 µF is needed to ensure stable regulator
operation. The same capacitor also serves as a reservoir capacitor to ensure that the chip is
able to operate for some time without voltage at the VFET terminal.
132
8042B–AVR–06/10
ATmega16HVB/32HVB
23.3
Regulator Start-up
When the chip is in power-off mode the Voltage Regulator will be off and there will be no connection between VFET and VREG.
The regulator is started when the Charger Detect module detects that a charger is connected
(For details on Charger Detect, see ”Charger Detect” on page 129). When starting the regulator
the Voltage Regulator will stay in a force mode where the VREG output is raised against the
VFET input voltage. As VREG increases to the target voltage level the regulator will automatically enter regulation mode, with a stable output voltage of nominally 3.3V. Figure 11-2 on page
44, in System Control and Reset illustrates the start-up sequence from power-off.
23.4
Battery Pack Short Detection
The Voltage Regulator will continuously monitor the operating condition at the VFET terminal. If
the voltage at VFET drops below the Regulator Short-circuit Level (RSCL), see ”Electrical Characteristics” on page 230, the Voltage Regulator enters the Battery Pack Short mode. In this
mode, VFET is disconnected from VREG to avoid a quick drop in the voltage regulator output.
When the voltage regulator enters this mode, the chip will be completely powered by the external reservoir capacitor (CREG). This allows the chip to operate a certain time without entering
BOD reset, even if the VFET voltage is too low for the voltage regulator to operate.
An interrupt is issued when the regulator enters Battery Pack Short mode, if the ROCWIE bit in
ROCR Register is set. This allows actions to be taken to reduce power consumption and hence
prolonging the time that CREG can be used to power the chip.
In a typical short-circuit situation, VFET will drop as a consequence of high current consumption,
and recover as soon as the Battery Protection module has disabled the FETs. Hence CREG
should be dimensioned so that the chip can sustain operation without entering BOD reset, until
the FETs are disabled either by HW or SW.
To minimize power consumption when the Voltage Regulator enters the Battery Pack Short
mode, the chip should enter Power-save sleep mode as soon as possible after the ROCWIF
interrupt is detected. The Watchdog Timer should be configured to wake up the CPU after a time
that is considered safe, see application note AVR132 for use of enhanced Watchdog Timer.
Software should then check the status of the ROC flag. If the ROCS flag is cleared, normal operation may be resumed.
23.5
Black-Out Detection
To ensure that the internal logic has safe operating condition, the Voltage Regulator has built-in
Black-Out Detector (BLOD). If the voltage at the VREG pin drops below the Black-out Detection
Level, VBLOT, the chip will automatically enter Power-off mode.
133
8042B–AVR–06/10
ATmega16HVB/32HVB
23.6
23.6.1
Register Description
ROCR – Regulator Operating Condition Register
Bit
7
6
5
4
3
2
1
0
ROCS
–
–
ROCD
–
–
ROCWIF
ROCWIE
Read/Write
R
R
R
R/W
R
R
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
(0xC8)
ROCR
• Bit 7 – ROCS: ROC Status
This bit is set when the Voltage Regulator operates in the Battery Pack Short mode, and cleared
otherwise.
• Bit 6:5 – Reserved
These bits are reserved and will always read as zero.
• Bit 4 – ROCD: ROC Disable
Setting this bit will disable the Battery Pack Short Detector and VFET will never be disconnected
from the LDO Regulator.
Note that it is NOT recommended to disable the Battery Pack Short Detector by setting the
ROCD bit unless VFET protection is implemented externally.
• Bit 3:2 – Reserved
These bits are reserved and will always read as zero.
• Bit 1 – ROCWIF: ROC Warning Interrupt Flag
The ROCWIF Flag is set when the Voltage Regulator enters the Battery Pack Short mode. The
flag is cleared by writing logic one to it or by hardware, by executing the corresponding interrupt
handling vector.
• Bit 0 – ROCWIE: ROC Warning Interrupt Enable
The ROCWIE bit enables interrupt caused by the Regulator Operating Condition Warning interrupt flag.
134
8042B–AVR–06/10
ATmega16HVB/32HVB
24. Battery Protection
24.1
Features
•
•
•
•
•
•
•
•
24.2
Short-circuit Protection
Discharge Over-current Protection
Charge Over-current Protection
Discharge High-current Protection
Charge High-current Protection
External Protection Input
Programmable and Lockable Detection Levels and Reaction Times
Autonomous Operation Independent of CPU
Overview
The Current Battery Protection circuitry (CBP) monitors the charge and discharge current and
disables C-FET and D-FET if a Short-circuit, Over-current or High-current condition is detected.
There are five different programmable detection levels: Short-circuit Detection Level, Discharge
Over-current Detection Level, Charge Over-current Detection Level, Discharge High-current
Detection Level, Charge High-current Detection Level. There are three different programmable
delays for activating Current Battery Protection: Short-circuit Reaction Time, Over-current Reaction Time and High-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 FETs. This provides safety in case
the application software should unintentionally try to re-enable the FETs 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.
In addition, the module offers an External Protection Input. The activation of the External Protection Input operates independently of the rest of the battery protection mechanisms. The
activation/deactivation of this protection is instantaneously controlled from the External Protection Input port, and will not deactivate or affect the other battery protection mechanisms.
The effect of the various battery protection types are given in Table 24-1.
Table 24-1.
Effect of Battery Protection Types
Interrupt Requests
PC-FET
C-FET
D-FET
Cell Balancing
FETs
MCU
Short-circuit Protection
Entry
Operational
Disabled
Disabled
Operational
Operational
Discharge Over-current
Protection
Entry
Operational
Disabled
Disabled
Operational
Operational
Charge Over-current
Protection
Entry
Operational
Disabled
Disabled
Operational
Operational
Discharge High-current
Protection
Entry
Operational
Disabled
Disabled
Operational
Operational
Charge High-current
Protection
Entry
Operational
Disabled
Disabled
Operational
Operational
Entry and/or Exit
Operational
Disabled
Disabled
Operational
Operational
Battery Protection Type
External Protection Input
135
8042B–AVR–06/10
ATmega16HVB/32HVB
24.3
Operation
The Current Battery Protections (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 Detection level for a time longer than the corresponding Protection Reaction Time, the chip
activates Current Protection. A sampled system clocked by the internal ULP Oscillator is used
for Short-circuit, Over-current, and High-current Protection. This ensures a reliable clock source,
offset cancellation and low power consumption.
24.3.1
Short-circuit Protection
The Short-circuit detection is provided to enable a fast response time to very large discharge
currents. If the voltage at the PPI/NNI pins is above the Short-circuit Detection Level 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 and C-FET are disabled and a
Current Protection Timer is started. This timer ensures that the D-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.
24.3.2
Discharge Over-current Protection
If the voltage at the PPI/NNI pins 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.
When the Discharge Over-current Protection is activated, the external D-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 D-FET is re-enabled
while the loading of the battery still is too large, the Discharge Over-current Protection will be
activated again.
24.3.3
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 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.
24.3.4
Discharge High-current Protection
If the voltage at the PPI/NNI pins is above the Discharge High-current Detection level for a time
longer than High-current Protection Reaction Time, the chip activates Discharge High-current
Protection.
136
8042B–AVR–06/10
ATmega16HVB/32HVB
When the Discharge High-current Protection is activated, the external D-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 D-FET is re-enabled while the
loading of the battery still is too large, the Discharge High-current Protection will be activated
again.
24.3.5
Charge High-current Protection
If the voltage at the PPI/NNI pins is above the Charge High-current Detection level for a time longer than High-current Protection Reaction Time, the chip activates Charge High-current
Protection.
When the Charge High-current Protection is activated, the external D-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 High-current Protection will be activated again.
The Short-circuit, Over-current and High-current 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 125 for register descriptions.
24.4
External Protection Input
The External Protection Input uses the alternate port function of the General Purpose High Votlage I/O to automatically disabling the external Charge and Discharge-FET. For details, see
”High Voltage I/O Ports” on page 62.
Using this together with the External Interrupt (see ”External Interrupt Characteristics” on page
235) features a highly flexible solution for the customer and it allows the user to customize an
external protection scheme suitable for battery applications.
The External Protection Input disables both the C-FET and D-FET immediately when the voltage
on EXTPROT pin is pulled high (logic ‘1’). It is also used to disable DUVR mode if DUVR mode
is enabled. Note that, unlike a Battery Protection event, the External Protection input does not
affect the status of the FCSR (CFE, DFE, DUVRD, and CPS) bits. When the ‘high’ condition disappears, the FET disabling is released immediately. DUVR mode is automatically re-entered if
previously enabled.
The feature is automatically enabled when the chip starts up, and can be disabled before locking
the BPCR register. When locking the BPCR register, the External Protection feature is also
locked.
When External Protection Input is enabled, an override enable signal is set to EXTPROT pin
configuring the pin as digital input. The port may be set up to give an interrupt when the pin
value changes, and the protection status can be read from the port register.
Note that the External Protection Input is default enabled. This means that after reset (and during reset) the port is default overridden to digital input, independent of the port register setting.
137
8042B–AVR–06/10
ATmega16HVB/32HVB
The user must disable the External Protection Input in the BPCR register before the port can be
used as a normal port.
Also during the reset sequence, the External Protection Input may disable the FETs. Consequently, if the External Protection feature is not used and DUVR mode is enabled in reset, the
External Protection input must be held low until disabled by SW.
It is recommended that the external interrupt on the External Protection Input port is configured
to ‘any edge’ to generate an interrupt to the microcontroller when using this feature, indicating
that the FET protection status has changed. By reading the pin register, the External Protection
status can be determined. If the pin register is set, it means that External Protection is trigged
and the FET control signals in FCSR (CFE, DFE and DUVRD) are overridden and the FETs are
disabled. In the opposite case, External Protection violation is not present.
To ensure a safe exit from the External Protection Input condition, the FETs and DUVR mode
should be disabled by SW when an External Protection condition is detected. This enables software to completely control when the FETs are switched ON again.
Short pulses on the EXTPROT pin, for instance caused by temporary high voltages on the BATT
pin when connecting a charger, may trigger the External Protection Input (refer to ”Operating
Circuit” on page 225). However if the SW does not take any action, the C-FET and D-FET will be
re-enabled automatically once the External Protection condition disappears.
Figure 24-1. External Protection Input example.
FC SR [CFE]
FC SR [DFE]
PC 0
INT0
OC
OD
138
8042B–AVR–06/10
ATmega16HVB/32HVB
24.5
Optimizing Usage for Low Power Consumption
In order to reduce power consumption, Short-circuit, Discharge High-current and Discharge
Over-current Protection are automatically deactivated when the D-FET is disabled. The Charge
Over-current and Charge High-current Protection are disabled when the C-FET is disabled. Note
however that Charge Over-current Protection and Charge High-current Protection are never
automatically disabled when the chip is operated in DUVR mode.
Also note that none of the current protections are deactivated by the External Protection Input.
To save power during an External Protection event, DFE and CFE in the FCSR register should
be cleared and make sure that the chip is not operating in DUVR mode.
139
8042B–AVR–06/10
ATmega16HVB/32HVB
24.6
Battery Protection CPU Interface
The Battery Protection CPU Interface is illustrated in Figure 24-2 on page 140.
Figure 24-2. Battery Protection CPU Interface
8-BIT DATA BUS
10
/
Interrupt
Request
Battery Protection
Parameter Lock
Register
LOCK?
LOCK?
LOCK?
Interrupt
Acknowledge
Battery Protection
Level Register
Battery Protection
Timing Register
Battery Protection
Control Register
Battery
Protection
Interrupt
Register
Current
Battery
Protection
PPI
NNI
5
/
5
/
EXTPROT
Current
Protection
FET
Control
Power-off
Each protection originating from the Current Battery Protection module 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. An interrupt event for the
External Protection Input can be generated by enabling the external interrupt for the input port.
24.7
24.7.1
Register Description
BPPLR – Battery Protection Parameter Lock Register
Bit
7
6
5
4
3
2
1
0
(0xFE)
–
–
–
–
–
–
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 – Reserved
These bits are reserved and will always read as zero.
• Bit 1 – BPPLE: Battery Protection Parameter Lock Enable
• Bit 0 – BPPL: Battery Protection Parameter Lock
The BPCR, BPHCTR, BPOCTR, BPSCTR, BPDHCD, BPCHCD, BPDOCD, BPCOCD and
BPSCD Battery Protection registers can be locked from any further software updates. Once
140
8042B–AVR–06/10
ATmega16HVB/32HVB
locked, these registers cannot be accessed until the next hardware reset. This provides a safe
method for protecting the registers from unintentional modification by software runaway. It is recommended that software sets these registers shortly after reset, and then protect the registers
from 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.
24.7.2
BPCR – Battery Protection Control Register
Bit
7
6
5
4
3
2
1
0
(0xFD)
–
–
EPID
SCD
DOCD
COCD
DHCD
CHCD
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
BPCR
• Bits 7:6 – Reserved
These bits are reserved and will always read as zero.
• Bit 5 – EPID: External Protection Input Disable
When this bit is set, the External Protection Input is disabled and any External Protection Input
will be ignored. Note that this bit overrides the GPIO functionality in the External Protection Input
port. If not using the External Protection Input feature, it is recommended that this bit is always
set.
• Bit 4 – 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 3 – DOCD: Discharge Over-current Protection Disabled
When the DOCD 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 2 – COCD: Charge Over-current Protection Disable
When the COCD bit is set, the Charge Over-current Protection is disabled. The Charge Overcurrent Detection will be disabled, and any Charge Over-current condition will be ignored.
• Bit 1 – DHCD: Discharge High-current Protection Disabled
When the DHCD bit is set, the Discharge High-current Protection is disabled. The Discharge
High-current Detection will be disabled, and any Discharge High-current condition will be
ignored.
• Bit 0 – CHCD: Charge High-current Protection Disable
When the CHCD bit is set, the Charge High-current Protection is disabled. The Charge High-current Detection will be disabled, and any Charge High-current condition will be ignored.
Note:
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPCR register is written. Any writing to the BPCR register during this period will be ignored.
141
8042B–AVR–06/10
ATmega16HVB/32HVB
24.7.3
BPSCTR – Battery Protection Short-current Timing Register
Bit
7
(0xFA)
–
6
5
4
Read/Write
R
R/W
R/W
R/W
Initial Value
0
0
0
1
3
2
1
0
R/W
R/W
R/W
R/W
0
0
0
0
SCPT[6:0]
BPSCTR
• Bit 7 – Reserved
This bit is reserved in the ATmega16HVB/32HVB and will always read as zero.
• Bit 6:0 – SCPT[6:0]: Short-current Protection Timing
These bits control the delay of the Short-circuit Protection. The Short-circuit Timing can be set
with a step size of 62.5 µs as shown in Table 24-2 on page 142.
Table 24-2.
Short-circuit Protection Reaction Time. SCPT[6:0] with corresponding Short-circuit Delay Time.
Short-circuit Protection Reaction Time(1)
24.7.4
SCPT[6:0](2)
Typ
0x00
(15.5 - 70.5 µs) + Td(3)
0x01
(15.5 - 70.5 µs) + Td(3)
0x02
(78.0 - 133.0 µs) + Td(3)
0x03
(140.5 - 195.5 µs) + Td(3)
...
...
0x7E
(7.83 - 7.88 ms) + Td(3)
0x7F
(7.89 - 7.95 ms) + Td(3)
Notes:
1. The actual value depends on the actual frequency of the ”Ultra Low Power RC Oscillator” on
page 27. See ”Electrical Characteristics” on page 230.
2. Initial value: SCPT[0x10](1ms).
3. An additional delay Td can be expected after enabling the Discharge FET due to initialization of
the protection circuit. With nomial ULP frequency this delay is maximum 86 µs.
Note:
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPSCTR register is written. Any
writing to the BPSCTR register during this period will be ignored.
BPOCTR – Battery Protection Over-current Timing Register
Bit
7
6
(0xFB)
–
–
5
4
Read/Write
R
R
R/W
R/W
Initial Value
0
0
0
0
3
2
1
0
R/W
R/W
R/W
R/W
0
0
1
0
OCPT[5:0]
BPOCTR
• Bit 7:6 – Reserved
These bits are reserved in the ATmega16HVB/32HVB and will always read as zero.
• Bit 5:0 – OCPT[5:0]: Over-current Protection Timing
These bits control the delay of the Over-circuit Protection. The Over-current Timing can be set
with a step size of 0.5 ms as shown in Table 24-3 on page 143.
142
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 24-3.
Over-current Protection Reaction Time. OCPT[5:0] with corresponding Over-current Delay Time.
Over-current Protection Reaction Time(1)
24.7.5
OCPT[5:0]
Typ
0x00
(0.0 - 0.5 ms) + Td(3)
0x01
(0.0 - 0.5 ms) + Td(3)
0x02(2)
(0.5 - 1.0 ms) + Td(3)
0x03
(1.0 - 1.5 ms) + Td(3)
...
...
0x3E
(30.5 - 31.0 ms) + Td(3)
0x3F
(31.0 - 31.5 ms) + Td(3)
Notes:
1. The actual value depends on the actual frequency of the ”Ultra Low Power RC Oscillator” on
page 27. See ”Electrical Characteristics” on page 230.
2. Initial value.
3. An additional delay Td can be expected after enabling the corresponding FET. This is related to
the initialization of the protection circuitry. For the Discharge Over-Current protection, this
applies when enabling the Discharge FET. For Charge Over-Current protection, this applies
when enabling the Charge FET. With nominal ULP frequency this delay is maximum 0.1 ms.
Note:
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPOCTR register is written. Any
writing to the BPOCTR register during this period will be ignored.
BPHCTR – Battery Protection High-current Timing Register
Bit
7
6
(0xFC)
–
–
5
4
Read/Write
R
R
R/W
R/W
Initial Value
0
0
0
0
3
2
1
0
R/W
R/W
R/W
R/W
0
0
0
1
HCPT[5:0]
BPHCTR
• Bit 7:6 – Reserved
These bits are reserved in the ATmega16HVB/32HVB and will always read as zero.
• Bit 5:0 – HCPT[5:0]: High-current Protection Timing
These bits control the delay of the High-circuit Protection. The High-current Timing can be set
with a step size of 2 ms as shown in Table 24-4 on page 143.
Table 24-4.
High-current Protection Reaction Time. HCPT[5:0] with corresponding High-current Delay Time.
High-current Protection Reaction Time(1)
HCPT[5:0]
Typ
0x00
(0 - 2 ms) + Td(3)
0x01(2)
(0 - 2 ms) + Td(3)
0x02
(2 - 4 ms) + Td(3)
0x03
(4 - 6 ms) + Td(3)
143
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 24-4.
High-current Protection Reaction Time. HCPT[5:0] with corresponding High-current Delay Time.
High-current Protection Reaction Time(1)
24.7.6
...
...
0x3E
(122 - 124 ms) + Td(3)
0x3F
(124 - 126 ms) + Td(3)
Notes:
1. The actual value depends on the actual frequency of the ”Ultra Low Power RC Oscillator” on
page 27. See ”Electrical Characteristics” on page 230.
2. Initial value.
3. An additional delay Td can be expected after enabling the corresponding FET. This is related to
the initialization of the protection circuitry. For the Discharge High-Current protection, this
applies when enabling the Discharge FET. For Charge High-Current protection, this applies
when enabling the Charge FET. With nominal ULP frequency this delay is maximum 0.2 ms.
Note:
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPHCTR register is written. Any
writing to the BPHCTR register during this period will be ignored.
BPSCD – Battery Protection Short-circuit Detection Level Register
Bit
7
6
5
4
(0xF5)
3
2
1
0
SCDL[7:0]
BPSCD
Read/Write
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
1
1
1
1
0
0
1
1
• Bits 7:0 – SCDL[7:0]: Short-circuit Detection Level
These bits sets the RSENSE voltage level for detection of Short-circuit in the Discharge Direction,
as defined in Table 24-5 on page 145.
Note:
24.7.7
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPSCD register is written. Any
writing to the BPSCD register during this period will be ignored.
BPDOCD – Battery Protection Discharge-Over-current Detection Level Register
Bit
7
6
5
(0xF6)
4
3
2
1
0
DOCDL[7:0]
BPDOCD
Read/Write
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
1
1
1
1
0
0
1
1
• Bits 7:0 – DOCDL[7:0]: Discharge Over-current Detection Level
These bits sets the RSENSE voltage level for detection of Discharge Over-current, as defined in
Table 24-5 on page 145.
Note:
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPDOCD register is written. Any
writing to the BPDOCD register during this period will be ignored.
144
8042B–AVR–06/10
ATmega16HVB/32HVB
24.7.8
BPCOCD – Battery Protection Charge-Over-current Detection Level Register
Bit
7
6
5
(0xF7)
4
3
2
1
0
COCDL[7:0]
BPCOCD
Read/Write
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
1
1
1
1
0
0
1
1
• Bits 7:0 –COCDL[7:0]: Charge Over-current Detection Level
These bits sets the RSENSE voltage level for detection of Charge Over-current, as defined in
Table 24-5 on page 145.
Note:
24.7.9
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPCOCD register is written. Any
writing to the BPCOCD register during this period will be ignored.
BPDHCD – Battery Protection Discharge-High-current Detection Level Register
Bit
7
6
5
(0xF8)
4
3
2
1
0
DHCDL[7:0]
BPDHCD
Read/Write
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
1
1
1
1
0
0
1
1
• Bits 7:0 – DHCDL[7:0]: Discharge High-current Detection Level
These bits sets the RSENSE voltage level for detection of DischargeHigh-current, as defined in
Table 24-5 on page 145.
Note:
24.7.10
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPDHCD register is written. Any
writing to the BPDHCD register during this period will be ignored.
BPCHCD – Battery Protection Charge-High-current Detection Level Register
Bit
7
6
5
(0xF9)
4
3
2
1
0
CHCDL[7:0]
BPCHCD
Read/Write
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
Initial Value
1
1
1
1
0
0
1
1
• Bits 7:0 –CHCDL[7:0]: Charge High-current Detection Level
These bits sets the RSENSE voltage level for detection of Charge High-current, as defined in
Table 24-5 on page 145.
Note:
Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the BPCHCD register is written. Any
writing to the BPCHCD register during this period will be ignored.
Table 24-5.
DL[7:0] with corresponding RSENSE voltage levels for all Current Detection Level
Registers (BPSCD, BPDOCD, BPCOCD, BPDHCD, BPCHCD).
Current Protection Detection Levels
DL[7:0]
Min.
Typ. (mV)
0xF3
20
0xF4
25
0xF5
30
Max.
145
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 24-5.
DL[7:0] with corresponding RSENSE voltage levels for all Current Detection Level
Registers (BPSCD, BPDOCD, BPCOCD, BPDHCD, BPCHCD).
Current Protection Detection Levels
24.7.11
0xF6
35
0xF7
40
0xF8
45
0xF9
50
0xFA
55
0xFB
60
0xFC
65
0xFD
70
0x77
80
0x78
90
0x79
100
0x7A
110
0x7B
120
0x7C
130
0x7D
140
0x37
150
0x38
170
0x39
190
0x3A
210
0x3B
230
0x3C
250
0x3D
270
0x17
310
All other values
Reserved
BPIMSK – Battery Protection Interrupt Mask Register
Bit
7
6
5
4
3
2
1
0
(0xF2)
–
–
–
SCIE
DOCIE
COCIE
DHCIE
CHCIE
Read/Write
R
R
R
R/W
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
BPIMSK
• Bit 7:5 – Reserved
These bits are reserved and will always read as zero.
• Bit 4 – SCIE: Short-circuit Protection Activated Interrupt
The SCIE bit enables interrupt caused by the Short-circuit Protection Activated Interrupt.
146
8042B–AVR–06/10
ATmega16HVB/32HVB
• Bit 3 – DOCIE: Discharge Over-current Protection Activated Interrupt
The DOCIE bit enables interrupt caused by the Discharge Over-current Protection Activated
Interrupt.
• Bit 2 – COCIE: Charge Over-current Protection Activated Interrupt
The COCIE bit enables interrupt caused by the Charge Over-current Protection Activated
Interrupt.
• Bit 1 – DHCIE : Discharger High-current Protection Activated Interrupt
The DHCIE bit enables interrupt caused by the Discharge High-current Protection Activated
Interrupt.
• Bit 0 – CHCIE : Charger High-current Protection Activated Interrupt
The CHCIE bit enables interrupt caused by the Charge High-current Protection Activated
Interrupt.
24.7.12
BPIFR – Battery Protection Interrupt Flag Register
Bit
7
6
5
4
3
2
1
0
(0xF3)
–
–
–
SCIF
DOCIF
COCIF
DHCIF
CHCIF
Read/Write
R
R
R
R/W
R/W
R/W
R/W
R/W
Initial Value
0
0
0
0
0
0
0
0
BPIFR
• Bit 7:5 – Res: Reserved
These bits are reserved and will always read as zero.
• Bit 4 – SCIF: Short-circuit Protection Activated Interrupt
Once Short-circuit violation is detected, SCIF becomes set. The flag is cleared by writing a logic
one to it.
• Bit 3 – DOCIF: Discharge Over-current Protection Activated Interrupt
Once Discharge Over-current violation is detected, DOCIF becomes set. The flag is cleared by
writing a logic one to it.
• Bit 2 – COCIF: Charge Over-current Protection Activated Interrupt
Once Charge Over-current violation is detected, COCIF becomes set. The flag is cleared by
writing a logic one to it.
• Bit 1 – DHCIF: Discharge High-current Protection Activated Interrupt
Once Discharge High-current violation is detected, DHCIF becomes set. The flag is cleared by
writing a logic one to it.
• Bit 0 – CHCIF: Charge High-current Protection Activated Interrupt
Once Charge High-current violation is detected, CHCIF becomes set. The flag is cleared by writing a logic one to it.
147
8042B–AVR–06/10
ATmega16HVB/32HVB
25. FET Driver
25.1
Features
• High side N-channel FET driver for controlling Charge and Discharge FETs in Li-ion battery
application
• Optional Deep Under-voltage Recovery mode allowing normal operation while charging Deeply
discharged battery cells from 0-volt without an external Pre-charge FET
• Optional Pre-charge FET mode that allows chargers without pre-charge functionality to charge a
Deeply discharged battery from 0-volt
25.2
Overview
The ATmega16HVB/32HVB integrates an N-channel FET driver for turning on and off external
high-side Charge and Discharge FETs in Li-ion battery packs. The FET driver is designed for
outputting a high voltage gate overdrive of typically 13V during normal operation.
Figure 25-1. Simplified Block diagram.
OPTIONAL
QPF
RPC
RPF
QCF
QDF
+
2-4
Li-Ion
Cells
Battery
Pack
RCF
RPVT
PC5
RDF
OC
VFET
RBATT
Device
/
Charger
OD
BATT
PVT
CHARGER
DETECT
DISCHARGE_EN
CHARGE_EN
DUVR_OFF
PWRON
FET DRIVER
FET CONTROL
ATmega16HVB/32HVB
In normal operation FET is controlled by software. SW can enable and disable the Charge FET
and the Discharge FET by writing to the FET Control and Status Register (FCSR).
148
8042B–AVR–06/10
ATmega16HVB/32HVB
For safe operation the FET driver automatically turns off both the Charge and Discharge FET if
the autonomous Battery Protection circuitry (see ”Battery Protection” on page 135) detects an
illegal current condition. If such conditions occur, software is not allowed to turn on the FETs
until the current condition has normalized.
To charge deeply discharged cells the ATmega16HVB/32HVB can be configured to run in Deep
Under Voltage Recovery (DUVR) mode. Using chargers with pre-charge current functionality,
this allows charging of deeply discharge cells without an additional pre-charge FET. For chargers without a pre-charge limitation current, an optional pre-charge FET in parallel with a charge
FET is supported to be able to charge deeply discharge cells.
25.3
25.3.1
Operation and Usage
Normal Operation
In normal operation (DUVRD=1), the FET control is used to enable and disable the Charge FET
and Discharge FET. Normally, the FETs are enabled and disabled by SW writing to the FET
Control and Status Register (FCSR). However, the autonomous Battery Protection circuitry will if
necessary override SW settings to protect the battery cells from too high Charge- or Discharge
currents. 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 25-1 on page 148.
Figure 25-2. FET Control module.
External_Protection_Input
Power-off Mode
CURRENT_PROTECTION
Current Protection
Timer
DUVR_OFF
8-BIT D ATA BU S
DUVRD
FET
Control
and
Status
Register
CFE
CHARGE_EN
DFE
DISCHARGE_EN
If Current Protection is activated by the Battery Protection circuitry both the Charge-FET and
Discharge FET will be disabled by hardware. When the protection condition disappears the Current Protection Timer will ensure a hold-off time of 1 second before software can re-enable the
external FETs.
To turn on the Charge and Discharge FET a minimum VFET supply voltage is required. When
the C-FET/D-FET is off with a total cell voltage lower than 6V, SW should not turn on the CFET/D-FET unless a charger is connected. If the total cell voltage is higher than 6V, SW could
turn-on the C-FET or D-FET. Note however, if the FETs are already turned-on, the FET driver
can operate in the entire supply operating range of the device.
149
8042B–AVR–06/10
ATmega16HVB/32HVB
The C-FET/D-FETs is switched on by pumping the gate OC/OD above the source voltage
(PVT/BATT) of the external FET. When the gate-source voltage has reached a level higher than
typically 13V the pumping frequency is reduced and is regulated to maintain the high gatesource voltage. For low VFET voltages (< 8 Volts) this level is never reached, thus the pumping
frequency is not reduced. The gate-source voltage for low VFET voltages is close to 2VFET-2V.
To avoid over-heating the external FET's when turning them off OC/OD is pulled quickly low.
If the 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 should ensure that the D-FET is not disabled when a large charge current is flowing, and
that the C-FET is not disabled when a large discharge current is flowing.
25.3.2
DUVR – Deep Under Voltage Recovery Mode without Pre-charge FET
To allow charging of deeply discharged cells using chargers with pre-charge functionality, the
FET Driver can be configured to operate in Deep Under-Voltage Recovery (DUVR) mode.
DUVR mode allows charging of deeply discharged cells without using an additional pre-charge
FET. To enter Deep Under Voltage Recovery Mode, software should clear the DUVRD bit
(DUVRD=0) in the FET Control and Status Register (FCSR). DUVR mode cannot be used in 2cell applications, refer to ”Deep Under Voltage operation with Pre-charge FET” on page 152.
In DUVR mode the FET Driver regulates the voltage at VFET quickly to typically 4.5V by partly
opening the C-FET. At this voltage the chip is fully operational. With the C-FET partly open the
charger is allowed to charge the battery with a pre-charge current. As the cell voltage starts to
increase above 4.5V the VFET voltage follows the cell voltage. When the total cell voltage has
been charged to a voltage higher than 5V, it is safe to exit DUVR mode and to turn-on the C-FET
completely. Software should then set the DUVRD bit to exit DUVR and fully open the C-FET by
setting the CFET bit. Note that it is recommended that this is done in two steps.
1. Exit DUVR mode by setting the DUVRD bit.
2. Wait until register synchronization is complete (see guard time notice in ”Register
Description” on page 153), and enable the C-FET by setting the CFE bit.
To avoid potential heating of the C-FET and D-FET in DUVR mode, the charger should not be
allowed to enter quick-charge until the FET has been completely enabled and the FET driver
has exit DUVR mode. It is therefore recommended to use the CC-ADC to continuously monitor
the current flowing during DUVR mode charging, and to turn-off the FETs if an illegal charge current is measured. For fast tracking, it is recommended to use the CC-ADC Instantaneous
Current Output. For details on CC-ADC usage, see ”Coulomb Counter – Dedicated Fuel Gauging Sigma-delta ADC” on page 108.
Before entering DUVR-mode it is recommended to enable the D-FET. After enabling the D-FET
it is recommended that SW add a hold-off time of 10ms before DUVR mode is entered. This is to
make sure that the D-FET is completely enabled.
To avoid that the charger enters quick-charge before the battery has exit DUVR mode, it is recommended that either
1. The battery controls when the charger is allowed to enter quick-charge. This is done by
communicating to the charger over the SMBus line when the charger is allowed to enter
increase the charge current.
2. The charger itself controls when to enter quick-charge by sensing the voltage at the
Pack+ terminal. It is not recommended that the charger allows quick-charge until the
charger senses a Pack+ voltage higher than 7V. To avoid potential heating problem SW
150
8042B–AVR–06/10
ATmega16HVB/32HVB
need to ensure to exit DUVR mode and enable the C-FET before the charger sees this
limit.
When the battery is started from a power-off condition by connecting a legal charger, SW should
determine whether to allow charging or not before enabling the C-FET. Before allowing charging
it is recommended to use the V-ADC to measure the cell temperature and cell voltages. Depending on the total cell voltage, the device should either start up in DUVR mode or in normal
charging mode with the C-FET and D-FET enabled.
• If the total cell voltage is below 4.5V, the battery should enter DUVR charging mode. This
ensures safe operation voltage while allowing charging.
• If the total cell voltage is above 4.5V, the battery should enter normal charging mode with both
C-FET and D-FET enabled.
The ”DUVR mode charging in 3-cell mode configuration” on page 151 shows an example of
charging 3 deeply discharged Li-ion cells in series using DUVR mode.
Figure 25-3. DUVR mode charging in 3-cell mode configuration
14
Voltage
12
10
PVT
VFET
Pack+
8
6
4
2
0
RESET
DUVRD
CFE
DFE
12
3
4
5 6
7
1. A charger with 12.6V charge voltage is plugged to the Pack+ pin and the
ATmega16HVB/32HVB enters reset mode. Charger should be configured with a charge
current limit (pre-charge current).
2. The ATmega16HVB/32HVB exit reset and initializes modules. To determine if charging
should be allowed and if DUVR mode should be entered, cell temperature and cell voltages are measured by the V-ADC.
3. D-FET is enabled and the VFET voltage increase to the Pack+ level.
4. DUVR mode is entered by clearing the DUVRD bit in FCSR. The VFET voltage and the
Pack+ voltage will now be regulated to approximately 4.5V.
5. The total cell voltage has reached the regulated VFET limit and VFET follows the cell
voltage as the battery is charged.
151
8042B–AVR–06/10
ATmega16HVB/32HVB
6. The total cell voltage has reached 5V. DUVR mode is disabled and the C-FET can be
fully enabled. DUVR mode should be disabled before the C-CFET is enabled. VFET and
Pack+ will therefore rise to the charger voltage for a short period before the C-FET is
enabled.
7. Battery voltage reached charger voltage.
25.3.3
Deep Under Voltage operation with Pre-charge FET
If a charger without pre-charge functionality is used, the Pre-charge FET will provide the current
path and the pre-charge resistor will limit the charge current during charging of deeply over-discharged cells. After reaching sufficient battery voltage it is safe to turn on the Charge FET to
increase the charge current. Deep Under Voltage Operation with Pre-charge FET is supported
through PC5, which is a high voltage open drain pin. For configuration and usage of this pin, see
”High Voltage I/O Ports” on page 62.
25.3.4
Operation in Reset and Power off
In reset and power-off the C-FET and D-FET will be automatically turned off. Safety is remained
by active pulling OC/OD hard to ground.
152
8042B–AVR–06/10
ATmega16HVB/32HVB
25.4
25.4.1
Register Description
FCSR – FET Control and Status Register
Bit
7
6
5
4
3
2
1
0
(0xF0)
–
–
–
–
DUVRD
CPS
DFE
CFE
Read/Write
R
R
R
R
R/W
R
R/W
R/W
Initial Value
0
0
0
0
1
0
0
0
FCSR
• Bits 7:4 – Reserved
These bits are reserved in the ATmega16HVB/32HVB, and will always read as zero.
• Bit 3 – DUVRD: Deep Under-voltage Recovery Disabled
When the DUVRD is cleared (zero), the FET Driver will be forced to operate in Deep Under-voltage Recovery DUVR mode. See ”DUVR – Deep Under Voltage Recovery Mode without Precharge FET” on page 150 for details. To avoid that the FET driver tries to switch on the C-FET
during current protection or during internal reset, the DUVRD bit is overridden to one by hardware in these cases. When this bit is set (one), Deep Under-voltage Recovery mode of the FET
Driver will be disabled. DUVR mode should not be used in 2-cell applications.
• Bit 2 – CPS: Current Protection Status
The CPS bit shows the status of the Current Protection. This bit is set (one) when a Current Protection is active, and cleared (zero) otherwise.
• Bit 1 – 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 is enabled. This bit
will automatically be cleared by the CBP circuitry when Current Protection is activated. When
this bit is cleared, Short-circuit, Discharge High-current and Discharge Over-current are disabled
regardless of the settings in the BPCR Register.
• Bit 0 – 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 is enabled. This bit
will automatically be cleared by the CBP circuitry when Current Protection is activated. When
this bit is cleared and the DUVRD bit is set, Charge High-current Protection and Charge Overcurrent Protection are disabled regardless of the settings in the BPCR Register. When the
DUVRD bit is cleared, the charge FET will be enabled by DUVR mode regardless of the CFE
status.
Notes:
1. Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator
cycles + 3 CPU clock cycles is required between each time the FCSR register is written. Any
writing to the FCSR register during this period will be ignored.
2. The NFET drivers require a minimum total cell voltage of 6V or higher or a charger connected
to turn-on the FETs. Note that this limit only applies if the FET is disabled in advanced. If the
FET is already enabled, the FET will be fully operational in the entire voltage range of the
device (4-25V).
153
8042B–AVR–06/10
ATmega16HVB/32HVB
26. Cell Balancing
26.1
Overview
ATmega16HVB/32HVB 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 26-1. The figure shows a four-cell configuration. The cell balancing FETs are disabled in the Power-off mode.
For typical current through the Cell Balancing FETs, see ”Electrical Characteristics” on page
230.
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 26-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
NV
154
8042B–AVR–06/10
ATmega16HVB/32HVB
26.2
26.2.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 – Reserved
These bits are reserved in the ATmega16HVB/32HVB 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.
155
8042B–AVR–06/10
ATmega16HVB/32HVB
27. 2-wire Serial Interface
27.1
Features
•
•
•
•
•
•
•
•
•
•
27.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
Supports SM Bus transfer speeds from 10 to 100kHz
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.
When the TWI is not used, power consumption can be minimized by writing the PRTWI bit in
PRR0 to one. See ”PRR0 – Power Reduction Register 0” on page 40 for details on how to use
the PRTWI bit.
Figure 27-1. TWI Bus Interconnection
VBUS
Device 1
Device 2
Device 3
........
Device n
R1
R2
SDA
SCL
156
8042B–AVR–06/10
ATmega16HVB/32HVB
27.2.1
TWI Terminology
The following definitions are frequently encountered in this section.
Table 27-1.
27.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 27-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 237.
27.3
27.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 27-2. Data Validity
SDA
SCL
Data Stable
Data Stable
Data Change
157
8042B–AVR–06/10
ATmega16HVB/32HVB
27.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 27-3. START, REPEATED START, and STOP Conditions
SDA
SCL
START
27.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.
158
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-4. Address Packet Format
Addr MSB
Addr LSB
R/W
ACK
7
8
9
SDA
SCL
1
2
START
27.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 27-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
27.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 27-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.
159
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-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
27.4
2
SLA+R/W
2
7
STOP
Data Byte
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.
Figure 27-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
160
8042B–AVR–06/10
ATmega16HVB/32HVB
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 27-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.
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.
161
8042B–AVR–06/10
ATmega16HVB/32HVB
27.5
Overview of the TWI Module
The TWI module is comprised of several submodules, as shown in Figure 27-9. The shaded registers are accessible through the AVR data bus.
Figure 27-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
27.5.1
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.
162
8042B–AVR–06/10
ATmega16HVB/32HVB
27.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.
Note:
27.5.3
The TWI clock is synchronous to the CPU.
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.
27.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.
163
8042B–AVR–06/10
ATmega16HVB/32HVB
27.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.
164
8042B–AVR–06/10
ATmega16HVB/32HVB
27.6
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 27-10 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.
Application
Action
Figure 27-10. 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
165
8042B–AVR–06/10
ATmega16HVB/32HVB
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
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.
166
8042B–AVR–06/10
ATmega16HVB/32HVB
Assembly code example(1)
ldi r16,
(1<<TWINT)|(1<<TWSTA)|
1
in
r16,TWCR
3
andi r16, 0xF8
cpi
out
TWDR, r16
ldi r16, (1<<TWINT) |
(1<<TWEN)
out TWCR, r16
wait2:
in
r16,TWCR
;
if ((TWSR & 0xF8) != START)
ERROR();
andi r16, 0xF8
cpi
5
r16, MT_SLA_ACK
brne ERROR
ldi r16, DATA
out
TWDR, r16
ldi r16, (1<<TWINT) |
(1<<TWEN)
out TWCR, r16
wait3:
6
in
r16,TWCR
TWCR = (1<<TWINT) |
(1<<TWEN);
while (!(TWCR & (1<<TWINT)))
;
andi r16, 0xF8
cpi
7
r16, MT_DATA_ACK
brne ERROR
ldi r16,
(1<<TWINT)|(1<<TWEN)|
(1<<TWSTO)
out
Note:
if ((TWSR & 0xF8) !=
MT_SLA_ACK)
ERROR();
Check value of TWI Status
Register. Mask prescaler bits. If
status different from START go to
ERROR
Load SLA_W into TWDR
Register. Clear TWINT bit in
TWCR to start transmission of
address
Wait for TWINT flag set. This
indicates that the SLA+W has
been transmitted, and
ACK/NACK has been received.
Check value of TWI Status
Register. Mask prescaler bits. If
status different from
MT_SLA_ACK go to ERROR
TWDR = DATA;
TWCR = (1<<TWINT) |
(1<<TWEN);
Load DATA into TWDR Register.
Clear TWINT bit in TWCR to
start transmission of data
while (!(TWCR & (1<<TWINT)))
Wait for TWINT flag set. This
indicates that the DATA has been
transmitted, and ACK/NACK has
been received.
;
sbrs r16,TWINT
rjmp wait3
in
r16,TWSR
Wait for TWINT flag set. This
indicates that the START
condition has been transmitted
TWDR = SLA_W;
sbrs r16,TWINT
rjmp wait2
in
r16,TWSR
Send START condition
while (!(TWCR & (1<<TWINT)))
r16, START
brne ERROR
ldi r16, SLA_W
4
(1<<TWEN)
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) !=
MT_DATA_ACK)
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
1. See ”About Code Examples” on page 8.
167
8042B–AVR–06/10
ATmega16HVB/32HVB
27.7
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:
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 27-12 on page 171 to Figure 27-18 on page 180, 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 27-2 on page 170 to Table 27-5 on page 179. Note that the prescaler
bits are masked to zero in these tables.
27.7.1
Master Transmitter Mode
In the Master Transmitter mode, a number of data bytes are transmitted to a slave receiver (see
Figure 27-11 on page 169). 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.
168
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-11. Data Transfer in Master Transmitter Mode
VBUS
Device 1
Device 2
MASTER
TRANSMITTER
SLAVE
RECEIVER
........
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 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 27-2). 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 27-2.
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
169
8042B–AVR–06/10
ATmega16HVB/32HVB
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.
Table 27-2.
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
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
170
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-12. 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
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
171
8042B–AVR–06/10
ATmega16HVB/32HVB
27.7.2
Master Receiver Mode
In the Master Receiver mode, a number of data bytes are received from a slave transmitter (see
Figure 27-13). 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 27-13. 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 27-2 on page 170). 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 27-12 on page 171. 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:
172
8042B–AVR–06/10
ATmega16HVB/32HVB
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 over the bus.
Table 27-3.
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
0
1
0
0x50
Data byte has been received;
ACK has been returned
Read data byte or
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
173
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-14. 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
27.7.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 27-15). All the status codes mentioned in this section assume that the prescaler bits are
zero or are masked to zero.
Figure 27-15. 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:
174
8042B–AVR–06/10
ATmega16HVB/32HVB
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 27-4.
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.
175
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 27-4.
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
To/from TWDR
STA
STO
TWINT
TWEA
X
0
1
0
0x60
Own SLA+W has been received;
ACK has been returned
No TWDR action or
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
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
176
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-16. 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
177
8042B–AVR–06/10
ATmega16HVB/32HVB
27.7.4
Slave Transmitter Mode
In the Slave Transmitter mode, a number of data bytes are transmitted to a master receiver (see
Figure 27-17). All the status codes mentioned in this section assume that the prescaler bits are
zero or are masked to zero.
Figure 27-17. 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 27-5.
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).
178
8042B–AVR–06/10
ATmega16HVB/32HVB
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 27-5.
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
179
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-18. 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
27.7.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 27-6.
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.
180
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 27-6.
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
27.7.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 27-19. Combining Several TWI Modes to Access a Serial EEPROM
Master Transmitter
S
SLA+W
A
ADDRESS
S = START
Transmitted from master to slave
27.8
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.
181
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 27-20. 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 27-21. Possible status values are given in circles.
Figure 27-21. 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
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
182
8042B–AVR–06/10
ATmega16HVB/32HVB
27.9
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 27-22 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. Once the bus is disconnected, the TWBCIP bit should be cleared. This enables detection of when the bus is connected,
and prevents repetitive interrupts if the SCL and SDA lines remain low.
Figure 27-22. Overview of Bus Connect/Disconnect.
SCL
SDA
DELAY ELEMENT
START
OUTPUT
TWBCIP
TWBDT
DELAY
TWBCSR
SET TWBCIF
IRQ
8-BIT DATA BUS
183
8042B–AVR–06/10
ATmega16HVB/32HVB
27.10 Register Description
27.10.1
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 163 for calculating bit rates.
27.10.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-
184
8042B–AVR–06/10
ATmega16HVB/32HVB
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 – Reserved
This bit is a reserved 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.
27.10.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 27-2 on page 170 through Table 27-5 on page 179. 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 – Reserved
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.
185
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 27-7.
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 163. The value of TWPS1:0 is used
in the equation.
27.10.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.
27.10.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.
186
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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.
27.10.6
TWAMR – TWI (Slave) Address Mask Register
Bit
7
6
5
4
(0xBD)
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 27-23 shown the address match logic in
detail.
Figure 27-23. TWI Address Match Logic, Block Diagram
TWAR0
Address
Match
Address
Bit 0
TWAMR0
Address Bit Comparator 0
Address Bit Comparator 6..1
• Bit 0 – Reserved
This bit is an unused in the ATmega16HVB/32HVB, and will always read as zero.
27.10.7
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(1). 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
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.
Note:
1. The TWEN bit in the TWCR register must be set for the Bus Connect/Disconnect feature to be
enabled.
187
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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 – Reserved
These bits are reserved in the ATmega16HVB/32HVB 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 27-8.
Table 27-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.
188
8042B–AVR–06/10
ATmega16HVB/32HVB
28. debugWIRE On-chip Debug System
28.1
Features
•
•
•
•
•
•
•
•
•
•
28.2
Complete Program Flow Control
Emulates All On-chip Functions, Both Digital and Analog, except RESET Pin
Real-time Operation
Symbolic Debugging Support (Both at C and Assembler Source Level, or for Other HLLs)
Unlimited Number of Program Break Points (Using Software Break Points)
Non-intrusive Operation
Electrical Characteristics Identical to Real Device
Automatic Configuration System
High-Speed Operation
Programming of Non-volatile Memories
Overview
The debugWIRE On-chip debug system uses a One-wire, bi-directional interface to control the
program flow, execute AVR instructions in the CPU and to program the different non-volatile
memories.
28.3
Physical Interface
When the debugWIRE Enable (DWEN) Fuse is programmed and Lock bits are unprogrammed,
the debugWIRE system within the target device is activated. The RESET port pin is configured
as a wire-AND (open-drain) bi-directional I/O pin with pull-up enabled and becomes the communication gateway between target and emulator.
Figure 28-1. The debugWIRE Setup
3.0
1.8 - 5.5V
VCC
dW
dW(RESET)
GND
Figure 28-1 shows the schematic of a target MCU, with debugWIRE enabled, and the emulator
connector. The system clock is not affected by debugWIRE and will always be the clock source
selected by the OSCSEL Fuses.
189
8042B–AVR–06/10
ATmega16HVB/32HVB
When designing a system where debugWIRE will be used, the following observations must be
made for correct operation:
• Pull-up resistors on the dW/(RESET) line must not be smaller than 10kΩ. The pull-up resistor
is not required for debugWIRE functionality.
• Connecting the RESET pin directly to VCC will not work.
• Capacitors connected to the RESET pin must be disconnected when using debugWire.
• All external reset sources must be disconnected.
28.4
Software Break Points
debugWIRE supports Program memory Break Points by the AVR Break instruction. Setting a
Break Point in AVR Studio® will insert a BREAK instruction in the Program memory. The instruction replaced by the BREAK instruction will be stored. When program execution is continued, the
stored instruction will be executed before continuing from the Program memory. A break can be
inserted manually by putting the BREAK instruction in the program.
The Flash must be re-programmed each time a Break Point is changed. This is automatically
handled by AVR Studio through the debugWIRE interface. The use of Break Points will therefore
reduce the Flash Data retention. Devices used for debugging purposes should not be shipped to
end customers.
28.5
Limitations of debugWIRE
The debugWIRE communication pin (dW) is physically located on the same pin as External
Reset (RESET). An External Reset source is therefore not supported when the debugWIRE is
enabled.
A programmed DWEN Fuse enables some parts of the clock system to be running in all sleep
modes. This will increase the power consumption while in sleep. Thus, the DWEN Fuse should
be disabled when debugWire is not used.
When using debugWIRE to access the flash (reading/writing), one must make sure the
SPMCSR register is not locked from before. If SPMCSR is locked the result of the operation may
not be as expected.
28.6
Register Description
The following section describes the registers used with the debugWire.
28.6.1
DWDR – debugWire Data Register
Bit
7
6
5
0x31 (0x51)
4
3
2
1
0
DWDR[7:0]
DWDR
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 DWDR Register provides a communication channel from the running program in the MCU
to the debugger. This register is only accessible by the debugWIRE and can therefore not be
used as a general purpose register in the normal operations.
190
8042B–AVR–06/10
ATmega16HVB/32HVB
29. Boot Loader Support – Read-While-Write Self-Programming
29.1
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:
29.2
1. A page is a section in the Flash consisting of several bytes (see ”Page Size” on page 211)
used during programming. The page organization does not affect normal operation.
Overview
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.
29.3
Application and Boot Loader Flash Sections
The Flash memory is organized in two main sections, the Application section and the Boot
Loader section. The size of the different sections is configured by the BOOTSZ Fuses as shown
in Table 29-5 on page 204 and Figure 29-2. These two sections can have different level of protection since they have different sets of Lock bits.
29.3.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 30-2 on page 208. The Application section can never store any
Boot Loader code since the SPM instruction is disabled when executed from the Application
section.
29.3.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 30-2 on page 208.
191
8042B–AVR–06/10
ATmega16HVB/32HVB
29.4
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 296 on page 204 and Figure 29-2 on page 194. 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.
29.4.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 ”SPMCSR – Store Program Memory Control and Status Register” on page 206 for
details on how to clear RWWSB.
29.4.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 29-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
192
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 29-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
193
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 29-2. Memory Sections
Program Memory
BOOTSZ = '10'
Program Memory
BOOTSZ = '11'
0x0000
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
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'
0x0000
Note:
29.5
Read-While-Write Section
Application Flash Section
End RWW
Start NRWW
Application Flash Section
End Application
Start Boot Loader
Boot Loader Flash Section
Flashend
No Read-While-Write Section
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 29-5 on page 204.
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 30-2 on page 208 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.
194
8042B–AVR–06/10
ATmega16HVB/32HVB
29.6
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 29-2.
BOOTRST
Note:
Boot Reset Fuse(1)
Reset Address
1
Reset Vector = Application Reset (address 0x0000)
0
Reset Vector = Boot Loader Reset (see Table 29-5 on page 204)
1. “1” means unprogrammed, “0” means programmed
195
8042B–AVR–06/10
ATmega16HVB/32HVB
29.7
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 209), 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 29-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 29-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 29-3 are listed in Table 29-7 on page 204 and Table 2910 on page 205.
196
8042B–AVR–06/10
ATmega16HVB/32HVB
29.8
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 202 for an assembly
code example.
29.8.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.
29.8.2
Filling the Temporary Buffer (Page Loading)
To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write
“X0000001” 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.
197
8042B–AVR–06/10
ATmega16HVB/32HVB
29.8.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.
29.8.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 52.
29.8.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.
29.8.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 52, 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 202 for an example.
29.8.7
Setting the Lock Bits by SPM
To set the Lock bits, write the desired data to R0, write “X0001001” to SPMCSR and execute
SPM within four clock cycles after writing SPMCSR.
Bit
7
6
5
4
3
2
1
0
R0
1
1
BLB12
BLB11
BLB02
BLB01
LB2
LB1
See Table 30-2 on page 208 for how the different settings of the Lock bits affect the Flash
access.
If bits 5:0 in R0 are cleared (zero), the corresponding Lock bit will be programmed if an SPM
instruction is executed within four cycles after LBSET and SPMEN are set in SPMCSR. The Zpointer 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 is
also recommended to set bits 7 and 6 in R0 to “1” when writing the Lock bits. When programming the Lock bits the entire Flash can be read during the operation.
198
8042B–AVR–06/10
ATmega16HVB/32HVB
29.8.8
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 LBSET and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the LBSET and SPMEN bits are set in SPMCSR,
the value of the Lock bits will be loaded in the destination register. The LBSET and SPMEN bits
will auto-clear upon completion of reading the Lock bits. When LBSET 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 LBSET and
SPMEN bits in SPMCSR. When an LPM instruction is executed within three cycles after the
LBSET 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 30-4 on page 210 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 LBSET 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 30-3 on page 209 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.
29.8.9
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 29-3 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 6 cycles after writing to SPMCSR, which is locked for further writing during these
cycles. When SIGRD and SPMEN are cleared, LPM will work as described in the Instruction set
Manual.
Table 29-3.
Signature Row Addressing.
Signature Byte Description
Z-Pointer Address
Device ID 0, Manufacture ID
00H
Device ID 1, Flash Size
02H
Device ID 2, Device
04H
FOSCCAL
(1)
FOSC SEGMENT
01H
(2)
Reserved
05H
SLOW RC Period L
SLOW RC Period H
03H
06H
(3)
07H
199
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 29-3.
Signature Row Addressing. (Continued)
Signature Byte Description
Z-Pointer Address
SLOW RC Temp Prediction L
SLOW RC Temp Prediction H
08H
(4)
09H
(5)
ULP RC FRQ
0AH
SLOW RC FRQ(6)
0BH
ULP RC Temp Prediction Coefficient L
ULP RC Temp Prediction Coefficient H
OCH
(7)
ODH
ULP RC Period L
OEH
ULP RC Period H(8)
OFH
BGCRR Calibration Byte
10H
BGCCR Calibration Byte
11H
Reserved
12H:17H
VPTAT CAL L
VPTAT CAL H
18H
(9)
19H
V-ADC Cell1 Gain Calibration Word L
1AH
(10)
V-ADC Cell1 Gain Calibration Word H
1BH
V-ADC Cell2 Gain Calibration Word L
1CH
V-ADC Cell2 Gain Calibration Word H(10)
1DH
V-ADC Cell3 Gain Calibration Word L
1EH
(10)
V-ADC Cell3 Gain Calibration Word H
1FH
V-ADC Cell4 Gain Calibration Word L
20H
(10)
V-ADC Cell4 Gain Calibration Word H
21H
(11)
22H
(11)
V-ADC Cell2 Offset
23H
V-ADC Cell3 Offset(11)
24H
V-ADC Cell4 Offset(11)
25H
V-ADC Cell1 Offset
V-ADC0 Gain Calibration Word L
26H
(12)
V-ADC0 Gain Calibration Word H
27H
V-ADC1 Gain Calibration Word L
28H
V-ADC1 Gain Calibration Word H(13)
29H
V-ADC ADC0 Offset
(14)
2AH
V-ADC ADC1 Offset
(14)
2BH
Reserved
THOT
(15)
Notes:
2CH:2FH
30H
1. Default FOSCCAL value after reset.
2. FOSCCAL setting used to smooth the transition from one segment to the next when calibrating
the Fast RC oscillator.
3. 8 prescaled Slow RC periods in µs using the Oscillator Sampling Interface (@THOT°C).
200
8042B–AVR–06/10
ATmega16HVB/32HVB
4.
5.
6.
7.
8.
9.
Slow RC oscillator frequency temperature drift prediction value.
ULP RC oscillator frequency in kHz (@ THOT°C).
Slow RC oscillator frequency in kHz (@THOT°C).
ULP RC oscillator frequency temperature drift prediction value.
8 prescaled ULP RC periods in µs using the Oscillator Sampling Interface (@THOT°C).
Calibration word used to calculate the absolute temperature in Kelvin from a VTEMP
conversion.
10. Calibration word used to compensate for gain error in V-ADC Cells.
11. Calibration byte used to compensate for offset in V-ADC Cells.
12. Calibration word used to compensate for gain error in ADC0.
13. Calibration word used to compensate for gain error in ADC1.
14. Calibration byte used to compensate for offset in ADC0 and ADC1.
15. Hot temperature used for factory calibration in °C.
All other addresses are reserved for future use.
29.8.10
SPMCSR writing restrictions
Writing any other combination than “100001”, “010001”, “001001”, “000101”, “000011” or
“000001” in the lower six bits will have no effect.
SPMCSR is locked for writing under the following conditions:
• One or more of the bits 5:0 in SPMCSR is set to 1
• During EEPROM write (status bit EEWE in EECR is set)
SPMCSR will be cleared at the following events:
• on completion of successful execution the following instructions:
– LPM with LBSET and SPMEN set
– SPM with LBSET and SPMEN set
– SPM with PGERS and SPMEN set
– SPM with PGWRT and SPMEN set
– SPM with SPMEN set
• six cycles after writing SPMCSR if any other or no LPM/SPM is executed
29.8.11
Programming Time for Flash when Using SPM
The Fast RC Oscillator is used to time Flash accesses. Table 29-4 shows the typical programming time for Flash accesses from the CPU.
Table 29-4.
SPM Programming Time(1)
Symbol
Flash write (Page Erase, Page Write, and
write Lock bits by SPM)
Note:
Min Programming Time
Max Programming Time
3.7 ms
4.5 ms
1. Minimum and maximum programming time is per individual operation.
201
8042B–AVR–06/10
ATmega16HVB/32HVB
29.8.12
Simple Assembly Code Example for a Boot Loader
;-the routine writes one page of data from RAM to Flash
; the first data location in RAM is pointed to by the Y pointer
; the first data location in Flash is pointed to by the Z-pointer
;-error handling is not included
;-the routine must be placed inside the Boot space
; (at least the Do_spm sub routine). Only code inside NRWW section
; can be read during Self-Programming (Page Erase and Page Write).
;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24),
; loophi (r25), spmcrval (r20)
; storing and restoring of registers is not included in the routine
; register usage can be optimized at the expense of code size
;-It is assumed that either the interrupt table is moved to the
; Boot loader section or that the interrupts are disabled.
.equ PAGESIZEB = PAGESIZE*2
;PAGESIZEB is page size in BYTES, not words
.org SMALLBOOTSTART
Write_page:
; Page Erase
ldi spmcrval, (1<<PGERS) | (1<<SPMEN)
call Do_spm
; re-enable the RWW section
ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN)
call Do_spm
; transfer data from RAM to Flash page buffer
ldi looplo, low(PAGESIZEB)
;init loop variable
ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256
Wrloop:
ld
r0, Y+
ld
r1, Y+
ldi spmcrval, (1<<SPMEN)
call Do_spm
adiw ZH:ZL, 2
sbiw loophi:looplo, 2
;use subi for PAGESIZEB<=256
brne Wrloop
; execute Page Write
subi ZL, low(PAGESIZEB)
;restore pointer
sbci ZH, high(PAGESIZEB)
;not required for PAGESIZEB<=256
ldi spmcrval, (1<<PGWRT) | (1<<SPMEN)
call Do_spm
; re-enable the RWW section
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
202
8042B–AVR–06/10
ATmega16HVB/32HVB
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
203
8042B–AVR–06/10
ATmega16HVB/32HVB
ATmega16HVB Boot Loader Parameters
In Table 29-5 through Table 29-7, the parameters used in the description of the Self-Programming are given
Boot Reset
Address
(Start Boot
Loader Section)
End Application
Section
Boot Loader
Flash Section
BOOTSZ0
1
1
256 words
4
0x0000 - 0x1EFF
0x1F00 - 0x1FFF
0x1EFF
0x1F00
1
0
512 words
8
0x0000 - 0x1DFF
0x1E00 - 0x1FFF
0x1DFF
0x1E00
0
1
1024 words
16
0x0000 - 0x1BFF
0x1C00 - 0x1FFF
0x1BFF
0x1C00
0
0
2048 words
32
0x0000 - 0x17FF
0x1800 - 0x1FFF
0x17FF
0x1800
Note:
Boot Size
BOOTSZ1
Application
Flash Section
Boot Size Configuration(1)
Table 29-5.
Pages
29.8.13
1. The different BOOTSZ Fuse configurations are shown in Figure 29-2
Table 29-6.
Read-While-Write Limit(1)
Section
Pages
Address
Read-While-Write section (RWW)
96
0x0000 - 0x17FF
No Read-While-Write section (NRWW)
32
0x1800 - 0x1FFF
Note:
1. For details about these two section, see ”NRWW – No Read-While-Write Section” on page
192 and ”RWW – Read-While-Write Section” on page 192.
Table 29-7.
Explanation of different variables used in Figure 29-3 on page 196 and the mapping to the Z-pointer(1)
Corresponding
Z-value
Variable
Description
PCMSB
12
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
Z13
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[12:6]
Z12: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)
Note:
1. Z0: should be zero for all SPM commands, byte select for the LPM instruction.
See ”Addressing the Flash During Self-Programming” on page 196 for details about the use of
Z-pointer during Self-Programming.
204
8042B–AVR–06/10
ATmega16HVB/32HVB
ATmega32HVB Boot Loader Parameters
In Table 29-8 through Table 29-10, the parameters used in the description of the Self-Programming are given
Boot Reset
Address
(Start Boot
Loader Section)
End Application
Section
Boot Loader
Flash Section
BOOTSZ0
1
1
256 words
4
0x0000 - 0x3EFF
0x3F00 - 0x3FFF
0x3EFF
0x3F00
1
0
512 words
8
0x0000 - 0x3DFF
0x3E00 - 0x3FFF
0x3DFF
0x3E00
0
1
1024 words
16
0x0000 - 0x3BFF
0x3C00 - 0x3FFF
0x3BFF
0x3C00
0
0
2048 words
32
0x0000 - 0x37FF
0x3800 - 0x3FFF
0x37FF
0x3800
Note:
Boot Size
BOOTSZ1
Application
Flash Section
Boot Size Configuration(1)
Table 29-8.
Pages
29.8.14
1. The different BOOTSZ Fuse configurations are shown in Figure 29-2
Table 29-9.
Read-While-Write Limit(1)
Section
Pages
Address
Read-While-Write section (RWW)
224
0x0000 - 0x37FF
No Read-While-Write section (NRWW)
32
0x3800 - 0x3FFF
For details about these two section, see ”NRWW – No Read-While-Write Section” on page 192 and ”RWW
– Read-While-Write Section” on page 192.
Table 29-10. Explanation of different variables used in Figure 29-3 on page 196 and the mapping to the Z-pointer(1)
Corresponding
Z-value
Variable
Description
PCMSB
13
Most significant bit in the Program Counter. (The
Program Counter is 14 bits PC[13: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
Z14
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[13: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)
Note:
1. Z0: should be zero for all SPM commands, byte select for the LPM instruction.
See ”Addressing the Flash During Self-Programming” on page 196 for details about the use of
Z-pointer during Self-Programming.
205
8042B–AVR–06/10
ATmega16HVB/32HVB
29.9
29.9.1
Register Description
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
LBSET
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 199 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.
• 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 – LBSET: 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 Lock bits, according to the data in R0. The data in R1 and the address in the Zpointer are ignored. The LBSET bit will automatically be cleared upon completion of the Lock bit
set, or after six cycles if no SPM instruction is executed within four clock cycles.
An LPM instruction within three cycles after LBSET 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” on page 224 for details.
206
8042B–AVR–06/10
ATmega16HVB/32HVB
• 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 after six cycles 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 after six cycles 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, LBSET, 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 after six cycles 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.
207
8042B–AVR–06/10
ATmega16HVB/32HVB
30. Memory Programming
30.1
Program And Data Memory Lock Bits
The ATmega16HVB/32HVB provides six Lock bits which can be left unprogrammed (“1”) or can
be programmed (“0”) to obtain the additional features listed in Table 30-2. The Lock bits can only
be erased to “1” with the Chip Erase command.
Lock Bit Byte(1)
Table 30-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 30-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
208
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 30-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:
30.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 ATmega16HVB/32HVB has two Fuse bytes. Table 30-4 and Table 30-3 describe briefly the
functionality of all the fuses and how they are mapped into the Fuse byte. Note that the fuses are
read as logical zero, “0”, if they are programmed.
30.2.1
High Byte
Table 30-3.
Fuse High Byte
Bit No
Fuse High Byte
7:5
–
4
DUVRDINIT(1)
Reset Value of DUVRDRegister
3
DWEN
Enable debugWire
1 (unprogrammed)
2
BOOTSZ1
Select Boot Size
0 (programmed)(2)
1
BOOTSZ0
Select Boot Size
0 (programmed)(2)
0
BOOTRST
Select Reset Vector
1 (unprogrammed)
Notes:
Description
Default Value
0 (programmed)
1. The default DUVRDINIT should not be changed. DUVRDINIT= “1” is reserved for future use.
2. The default value of BOOTSZ1:0 results in maximum Boot Size.
209
8042B–AVR–06/10
ATmega16HVB/32HVB
30.2.2
Low Byte
Table 30-4.
Bit No
Fuse Low Byte
Fuse Low Byte
Description
Default Value
7
WDTON
Watchdog Timer always on
1 (unprogrammed)(1)
6
EESAVE
EEPROM memory is preserved
through the Chip Erase
1 (unprogrammed, EEPROM
not preserved)
5
SPIEN
Enable Serial Programmable Data
Downloading
0 (programmed, SPI
programming enabled)
4
SUT2
Select start-up time
1 (unprogrammed)(2)
3
SUT1
Select start-up time
1 (unprogrammed)(2)
2
SUT0
Select start-up time
1 (unprogrammed)(2)
1
OSCSEL1
Oscillator Select
0 (programmed)(3)
0
OSCSEL0
Oscillator Select
1 (unprogrammed)(3)
Notes:
1. The Watchdog is enabled/disabling by writing to the Watchdog Timer Control and Status Register (WDTCSR). But as a fail-safe, the WDTON fuse can be used to force the Watchdog to run
in System Reset mode.
2. The SUTx fuse bits are used to configure the startup time from sleep or reset. By default the
longest startup time is selected.
3. The default OSCSEL1:0 setting should not be changed. OSCSEL1:0="00" is reserved for test
purpose. Other values are reserved for future use.
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.
30.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.
30.3
Signature Bytes
All Atmel microcontrollers have a three-byte signature code which identifies the device. This
code can be read in both Programming mode, also when the device is locked. The three bytes
reside in a separate address space. The signature bytes of ATmega16HVB/32HVB is given in
Table 30-5.
Table 30-5.
Device ID
Signature Bytes Address
Part
0x000
0x001
0x002
ATmega16HVB
0x1E
0x94
0x0D
ATmega32HVB
0x1E
0x95
0x10
210
8042B–AVR–06/10
ATmega16HVB/32HVB
30.4
Calibration Bytes
The ATmega16HVB/32HVB has calibration bytes for the RC Oscillators, internal voltage reference, internal temperature reference and each differential cell voltage input. These bytes reside
in the signature address space. See ”Reading the Signature Row from Software” on page 199
for details.
30.5
Page Size
Table 30-6.
Flash Size
Page Size
PCWORD
No. of Pages
PCPAGE
PCMSB
8K words (16K bytes)
64 words
PC[5:0]
128
PC[12:6]
12
Table 30-7.
No. of Words in a Page and No. of Pages in the Flash, ATmega32HVB
Flash Size
Page Size
PCWORD
No. of Pages
PCPAGE
PCMSB
16K words (32K bytes)
64 words
PC[5:0]
256
PC[13:6]
13
Table 30-8.
No. of Words in a Page and No. of Pages in the EEPROM, ATmega16HVB
EEPROM Size
Page Size
PCWORD
No. of Pages
PCPAGE
EEAMSB
512 bytes
4 bytes
EEA[1:0]
128
EEA[8:2]
8
Table 30-9.
30.6
No. of Words in a Page and No. of Pages in the Flash, ATmega16HVB
No. of Words in a Page and No. of Pages in the EEPROM, ATmega32HVB
EEPROM Size
Page Size
PCWORD
No. of Pages
PCPAGE
EEAMSB
1K bytes
4 bytes
EEA[1:0]
256
EEA[9:2]
9
Serial Programming
Both the Flash and EEPROM memory arrays can be programmed using the serial SPI bus while
RESET is pulled to GND. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the Programming Enable instruction needs to be executed first
before program/erase operations can be executed. NOTE, in Table 30-10 on page 212, the pin
mapping for SPI programming is listed. Not all parts use the SPI pins dedicated for the internal
SPI interface.
211
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 30-1. Serial Programming and Verify.
+4.0 - 25.0V
VFET
MOSI
MISO
SCK
RESET
GND
Table 30-10. Pin Mapping Serial Programming
Symbol
Pins
I/O
Description
SCK
PB5
I
Serial Clock
MOSI
PB6
I
Serial Data in
MISO
PB7
O
Serial Data out
When programming the EEPROM, an auto-erase cycle is built into the self-timed programming
operation (in the Serial mode ONLY) and there is no need to first execute the Chip Erase
instruction. The Chip Erase operation turns the content of every memory location in both the
Program and EEPROM arrays into 0xFF.
Depending on OSCSEL Fuses, a valid clock must be present. The minimum low and high periods for the serial clock (SCK) input are defined as follows:
Low: > 2.2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
High: > 2.2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
30.6.1
Serial Programming Algorithm
When writing serial data to the ATmega16HVB/32HVB, data is clocked on the rising edge of
SCK.
When reading data from the ATmega16HVB/32HVB, data is clocked on the falling edge of SCK.
See ”Serial Programming Characteristics” on page 239 for timing details.
To program and verify the ATmega16HVB/32HVB in the Serial Programming mode, the following sequence is recommended (see four byte instruction formats in Table 30-12 on page 214):
1. Power-up sequence:
Make sure the chip is started as explained in Section 11.2.1 ”Power-on Reset and Charger Connect” on page 43 while RESET and SCK are set to “0”. In some systems, the
programmer can not guarantee that SCK is held low during power-up. In this case,
212
8042B–AVR–06/10
ATmega16HVB/32HVB
RESET must be given a positive pulse of at least two CPU clock cycles duration after
SCK has been set to “0”.
2. Wait for at least 20 ms and enable serial programming by sending the Programming
Enable serial instruction to pin MOSI.
3. The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte (0x53), will echo back when issuing the third
byte of the Programming Enable instruction. Whether the echo is correct or not, all four
bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a
positive pulse and issue a new Programming Enable command.
4. The Flash is programmed one page at a time. The memory page is loaded one byte at a
time by supplying the 5 LSB of the address and data together with the Load Program
memory Page instruction. To ensure correct loading of the page, the data low byte must
be loaded before data high byte is applied for a given address. The Program memory
Page is stored by loading the Write Program memory Page instruction with the 6 MSB of
the address. If polling (RDY/BSY) is not used, the user must wait at least tWD_FLASH before
issuing the next page. (See Table 30-11.) Accessing the serial programming interface
before the Flash write operation completes can result in incorrect programming.
5. A: The EEPROM array is programmed one byte at a time by supplying the address and
data together with the appropriate Write instruction. An EEPROM memory location is first
automatically erased before new data is written. If polling (RDY/BSY) is not used, the
user must wait at least tWD_EEPROM before issuing the next byte. (See Table 30-11.) In a
chip erased device, no 0xFFs in the data file(s) need to be programmed.
B: The EEPROM array is programmed one page at a time. The Memory page is loaded
one byte at a time by supplying the 2 LSB of the address and data together with the Load
EEPROM Memory Page instruction. The EEPROM Memory Page is stored by loading
the Write EEPROM Memory Page Instruction with the 6 MSB of the address. When using
EEPROM page access only byte locations loaded with the Load EEPROM Memory Page
instruction is altered. The remaining locations remain unchanged. If polling (RDY/BSY) is
not used, the used must wait at least tWD_EEPROM before issuing the next page (See Table
30-8 on page 211). In a chip erased device, no 0xFF in the data file(s) need to be
programmed.
6. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO.
7. At the end of the programming session, RESET can be set high to commence normal
operation.
8. Power-off sequence (if needed):
Set RESET to “1”.
Turn VCC power off.
Table 30-11. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol
Minimum Wait Delay
tWD_FLASH
4.5 ms
tWD_EEPROM
4.0 ms
tWD_ERASE
4.0 ms
tWD_FUSE
4.5 ms
213
8042B–AVR–06/10
ATmega16HVB/32HVB
30.6.2
Serial Programming Instruction set
Table 30-12 on page 214 and Figure 30-2 on page 215 describes the Instruction set.
Table 30-12. Serial Programming Instruction Set
Instruction Format
Instruction/Operation
Byte 1
Byte 2
Byte 3
Byte4
Programming Enable
$AC
$53
$00
$00
Chip Erase (Program Memory/EEPROM)
$AC
$80
$00
$00
Poll RDY/BSY
$F0
$00
$00
data byte out
Load Extended Address byte(1)
$4D
$00
Extended adr
$00
Load Program Memory Page, High byte
$48
adr MSB
adr LSB
high data byte in
Load Program Memory Page, Low byte
$40
adr MSB
adr LSB
low data byte in
Load EEPROM Memory Page (page access)
$C1
adr MSB
adr LSB
data byte in
Read Program Memory, High byte
$28
adr MSB
adr LSB
high data byte out
Read Program Memory, Low byte
$20
adr MSB
adr LSB
low data byte out
Read EEPROM Memory
$A0
adr MSB
adr LSB
data byte out
Read Lock bits
$58
$00
$00
data byte out
Read Signature Byte
$30
$00
adr LSB
data byte out
Read Fuse bits
$50
$00
$00
data byte out
Read Fuse High bits
$58
$08
$00
data byte out
Read Extended Fuse Bits
$50
$08
$00
data byte out
Read Calibration Byte
$38
$00
$00
data byte out
Write Program Memory Page
$4C
adr MSB
adr LSB
$00
Write EEPROM Memory
$C0
adr MSB
adr LSB
data byte in
Write EEPROM Memory Page (page access)
$C2
adr MSB
adr LSB
$00
Write Lock bits
$AC
$E0
$00
data byte in
Write Fuse bits
$AC
$A0
$00
data byte in
Write Fuse High bits
$AC
$A8
$00
data byte in
Write Extended Fuse Bits
$AC
$A4
$00
data byte in
Load Instructions
Read Instructions
Write Instructions(6)
Notes:
1.
2.
3.
4.
5.
6.
7.
Not all instructions are applicable for all parts.
a = address
Bits are programmed ‘0’, unprogrammed ‘1’.
To ensure future compatibility, unused Fuses and Lock bits should be unprogrammed (‘1’) .
Refer to the corresponding section for Fuse and Lock bits, Calibration and Signature bytes and Page size.
Instructions accessing program memory use word address. This address may be random within the page range.
See htt://www.atmel.com/avr for Application Notes regarding programming and programmers.
214
8042B–AVR–06/10
ATmega16HVB/32HVB
If the LSB in RDY/BSY data byte out is ‘1’, a programming operation is still pending. Wait until
this bit returns ‘0’ before the next instruction is carried out.
Within the same page, the low data byte must be loaded prior to the high data byte.
After data is loaded to the page buffer, program the EEPROM page, see Figure 30-2 on page
215.
Figure 30-2. Serial Programming Instruction example
Serial Programming Instruction
Load Program Memory Page (High/Low Byte)/
Load EEPROM Memory Page (page access)
Byte 1
Byte 2
Adr MSB
A
Bit 15 B
Byte 3
Write Program Memory Page/
Write EEPROM Memory Page
Byte 1
Byte 4
Byte 2
Adr LSB
Adr MSB
Bit 15 B
0
Byte 3
Byte 4
Adrr LSB
B
0
Page Buffer
Page Offset
Page 0
Page 1
Page 2
Page Number
Page N-1
Program Memory/
EEPROM Memory
215
8042B–AVR–06/10
ATmega16HVB/32HVB
30.7
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
ATmega16HVB/32HVB. Pulses are assumed to be at least 250 ns unless otherwise noted.
30.7.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.
30.7.2
Signal Names
In this section, some pins of the ATmega16HVB/32HVB are referenced by signal names
describing their functionality during parallel programming, see Figure 30-3 on page 216 and
Table 30-13 on page 217. 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 30-15 on page 217.
When pulsing WR or OE, the command loaded determines the action executed. The different
Commands are shown in Table 30-16 on page 218. Table 32-18 on page 241 shows the Parallel
programming characteristics.
Figure 30-3. Parallel Programming
+4.0 - 25.0V
+11.5 - 12.5V
RESET
VFET
PAGEL
BS2
RDY/BSY
BS1
X1
X0
DATA[7:0]
OE
XTAL1
WR
GND
216
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 30-13. Pin Name Mapping
Signal Name in
Programming Mode
Pin
Name
I/O
Function
RDY/BSY
PA0
O
0: Device is busy programming
1: Device is ready for new command.
BS1
PA1
I
Byte Select 1 (“0” selects low byte, “1” selects high byte).
BS2
PA2
I
Byte Select 2 (“0” selects low byte, “1” selects 2’nd high
byte).
PAGEL
PA3
I
Program Memory and EEPROM data Page Load.
RESET
RESET
I
DATA
PB[7:0]
I/O
WR
PC0
I
Write Pulse (Active low)
OE
PC1
I
Output Enable (Active low).
XTAL
PC2
I
XA0
PC3
I
XTAL Action Bit 0
XA1
PC4
I
XTAL Action Bit 1
Bi-directional Data bus (Output when OE is low).
Table 30-14. Pin Values Used to Enter Programming Mode
Pin
Symbol
Value
PB3
Prog_enable[3]
0
PB2
Prog_enable[2]
0
PB1
Prog_enable[1]
0
PB0
Prog_enable[0]
0
Table 30-15. 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
217
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 30-16. Command Byte Bit Coding
Command Byte
30.7.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 ”Power-on Reset and Charger Connect” on
page 43.
2. Set RESET to “0” and toggle XTAL1 at least six times.
3. Set the Prog_enable pins listed in Table 30-14 on page 217 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.
30.7.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.
218
8042B–AVR–06/10
ATmega16HVB/32HVB
30.7.5
Programming the Flash
The Flash is organized in pages, see Table 30-7 on page 211. 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 30-5 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 30-4 on page 220. 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.
219
8042B–AVR–06/10
ATmega16HVB/32HVB
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 30-5 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 30-4. 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 30-7 on page 211.
220
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 30-5. 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:
30.7.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 30-8 on page 211. 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 219 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 30-6 for
signal waveforms).
221
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 30-6. Programming the EEPROM Waveforms
K
DATA
A
G
0x11
ADDR. HIGH
B
ADDR. LOW
C
E
DATA
XX
B
ADDR. LOW
C
DATA
E
L
XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
30.7.7
Reading the Flash
The algorithm for reading the Flash memory is as follows (refer to ”Programming the Flash” on
page 219 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”.
30.7.8
Reading the EEPROM
The algorithm for reading the EEPROM memory is as follows (refer to ”Programming the Flash”
on page 219 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”.
222
8042B–AVR–06/10
ATmega16HVB/32HVB
30.7.9
Programming the Fuse Low Bits
The algorithm for programming the Fuse Low bits is as follows (refer to ”Programming the Flash”
on page 219 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.
30.7.10
Programming the Fuse High Bits
The algorithm for programming the Fuse High bits is as follows (refer to ”Programming the
Flash” on page 219 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 30-7. Programming the FUSES Waveforms
Write Fuse Low byte
DATA
A
C
0x40
DATA
XX
Write Fuse high byte
A
C
0x40
DATA
XX
Write Extended Fuse byte
A
C
0x40
DATA
XX
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
30.7.11
Programming the Lock Bits
The algorithm for programming the Lock bits is as follows (refer to ”Programming the Flash” on
page 219 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.
223
8042B–AVR–06/10
ATmega16HVB/32HVB
30.7.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 219 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 30-8. Mapping Between BS1, BS2 and the Fuse and Lock Bits During Read
Fuse Low Byte
0
Extended Fuse Byte
1
0
DATA
BS2
0
Lock Bits
1
Fuse High Byte
1
BS1
BS2
30.7.13
Reading the Signature Bytes
The algorithm for reading the Signature bytes is as follows (refer to ”Programming the Flash” on
page 219 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”.
30.7.14
Reading the Calibration Byte
The algorithm for reading the Calibration byte is as follows (refer to ”Programming the Flash” on
page 219 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”.
224
8042B–AVR–06/10
8042B–AVR–06/10
CELL1
CELL2
CELL3
CELL4
R1
R2
R3
R4
C1
C2
C3
C4
VSS
VC3
VC2
VC1
S-8244
SENSE
CO
ICT
VCC
C10
C11
R15
C12
R10
R16
D2
Q4
C17
F1
Optional secondary protection and fuse blow circuitry
R31
RT32
RT33
R14
R12
R11
R13
R5
R6
R7
R8
R9
C9
C5
C6
C7
C8
FUSE BLOW
D1
FUSE STATUS
R17
VCC
VFET
OD
VREF
C16
VREFGND
VCLMP10
C14
C13
VCC
RESET
C18
C15
PB7
PB6
PB5
PA0/ADC0/SGND
PA1/ADC1/SGND
PB4
PB2
PB1/CKOUT
PA2
PA3
PC5
PC4/SCL
PC3/SDA
PC1
PB3
VCC
BATT
PC0/EXT_PROT
R20
NI
VREG
ATmega16HVB/32HVB
OC
R19
Q2
NNI
PI
PPI
NV
PV1
PV2
PV3
PV4
PB0
PC2
PVT
R18
Q3
D10
D9
D8
D7
D6
D5
D4
R24
VCC
Q1
R28
R25
R27
R22
SW1
R30
D3
R23
R26
R29
VCC
R21
Pack+
-
Pack-
SMBCLK
SMBDATA
SYS PRESENT
+
ATmega16HVB/32HVB
31. Operating Circuit
Figure 31-1. Operating Circuit, 4-Cell
225
8042B–AVR–06/10
CELL1
CELL2
CELL3
R2
R3
R4
C2
C3
C4
VSS
VC3
VC2
VC1
S-8244
SENSE
CO
ICT
VCC
C10
C11
R15
C12
R10
R16
D2
Q4
C17
F1
Optional secondary protection and fuse blow circuitry
R31
R32
R33
R14
R12
R11
R13
R5
R6
R7
R8
R9
C9
C5
C6
C7
FUSE BLOW
D1
FUSE STATUS
R17
VCC
VFET
OD
VREF
C16
VREFGND
VCLMP10
RESET
C14
C13
VCC
C18
C15
PB7
PB6
PB5
PA0/ADC0/SGND
PA1/ADC1/SGND
PB4
PB2
PB1/CKOUT
PA2
PA3
PC5
PC4/SCL
PC3/SDA
PC1
PB3
VCC
BATT
PC0/EXT_PROT
R20
NNI
VREG
ATmega16HVB/32HVB
OC
R19
Q2
NI
PI
PPI
NV
PV1
PV2
PV3
PV4
PB0
PC2
PVT
R18
Q3
D10
D9
D8
D7
D6
D5
D4
R24
VCC
Q1
R28
R25
R27
R22
SW1
R30
D3
R23
R26
R29
VCC
R21
Pack+
-
Pack-
SMBCLK
SMBDATA
SYS PRESENT
+
ATmega16HVB/32HVB
Figure 31-2. Operating Circuit, 3-Cell
226
8042B–AVR–06/10
CELL1
CELL2
R3
R4
C3
C4
VSS
VC3
VC2
VC1
S-8244
SENSE
CO
ICT
VCC
C10
C11
R15
C12
R10
R16
D2
Q4
C17
F1
Optional secondary protection and fuse blow circuitry
R31
R32
R33
R14
R12
R11
R13
R5
R6
R7
R8
R9
C9
C5
C6
FUSE BLOW
D1
FUSE STATUS
R17
VCC
VFET
OD
VREF
C16
VREFGND
PA1/ADC1/SGND
VCLMP10
C14
C13
VCC
RESET
C18
C15
PB7
PB6
PB5
PA0/ADC0/SGND
PB2
PB1/CKOUT
PA2
PA3
PC4/SCL
PC3/SDA
PC1
PB4
VCC
BATT
PC0/EXT_PROT
R20
Q2
PB3
VREG
ATmega16HVB/32HVB
OC
Q3
NNI
PVT
R19
R34
NI
PI
PPI
NV
PV1
PV2
PV3
PV4
PB0
PC2
PC5
R18
R35
Q5
D10
D9
D8
D7
D6
D5
D4
R24
VCC
Q1
R28
R25
R27
R22
SW1
R30
D3
R23
R26
R29
VCC
R21
Pack+
-
Pack-
SMBCLK
SMBDATA
SYS PRESENT
+
ATmega16HVB/32HVB
Figure 31-3. Operating Circuit, 2-Cell
227
ATmega16HVB/32HVB
Table 31-1.
Bill of Materials
Symbol
Number
Description
C1-C4, C10, C11
6
Capacitor, ceramic, 0.1 - 1.0 µF, 50V, X7R
C5-C8
4
Capacitor, ceramic, 0.01 - 0.5 µF, 50V, X7R
C9, C12, C13, C15
4
Capacitor, ceramic, 0.1 µF, 50V, X7R
C14
1
Capacitor, ceramic, 2.2 - 4.7 µF, 10V, X7R
C16
1
Capacitor, ceramic, 1 - 22 µF, 10V, X7R
C17
1
Capacitor, ceramic, 0.47 µF, 10V, X7R
C18
1
Capacitor, ceramic, 22 nF, 50V, X7R
D1
1
Diode, signal
D2
1
Diode, double, Shottky
D4
1
Diode, signal
D3
1
Diode, Zener, value from design considerations
D4
1
Diode, Zener, 5V6
D5
1
Diode, double, Zener, 5V6
D6-D10
5
LEDs
F1
1
Chemical fuse
Q1
1
N-FET, 50V, 0.22A
Q2, Q3
2
N-FET, 30V, 10A
Q4
1
N-FET, 20V, 1.3A
Q5
1
P-FET, 30V, 10A
R1-R4
4
Resistor, chip, 1-10 kΩ, 1/16W, 5%
R5-R9
5
Resistor, chip, 10-1000Ω, 1/16W, 5%
R10
1
Sense resistor, 1-10 mΩ, 1W, 1%
R11, R12
2
Resistor, chip, 10-500Ω, 1/16W, 5%
R13, R14, R18, R19, R20, R21, R25
7
Resistor, chip 1 kΩ, 1/16W, 5%
R15
1
Resistor, chip, 100-1000Ω, 1/16W, 5%
R16, R17
2
Resistor, chip 200 kΩ, 1/16W, 5%
R22
1
Resistor, value from design considerations
R23
1
Resistor, value from design considerations
R24
1
Resistor, chip 1 kΩ, 1/16W, 5%
R26, R27
2
Resistor, chip 100 Ω, 1/16W, 5%
R28, R29
2
Resistor, chip 1 MΩ, 1/16W, 5%
R30
1
Resistor, chip 820 Ω, 1/16W, 5%
R31
1
Resistor, chip 10 kΩ, 1/16W, 5%
R32, R33
2
NTC thermistor, 10 kΩ, B = 3000 - 4000
R34
1
Resistor, value determined by battery pack and charger requirements
228
8042B–AVR–06/10
ATmega16HVB/32HVB
Symbol
Number
Description
R35
1
Resistor, chip 1 MΩ, 1/16W, 5%
SW
1
Switch, push button
U1
1
ATmega32HVB (Atmel)
U2
1
S-8244 secondary protection device (Seiko Instruments)
229
8042B–AVR–06/10
ATmega16HVB/32HVB
32. Electrical Characteristics
32.1
Absolute Maximum Ratings*
Operating Temperature.................................... -40°C to +85°C
Storage Temperature ..................................... -65°C to +150°C
Voltage on PA0 - PA3, PI, NI, PPI and NNI
with respect to Ground ............................. -0.5V to VREG +0.5V
Voltage on PB0 - PB7
with respect to Ground ............................. -0.5V to VCC +0.5V
*NOTICE:
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 PC0 - PC4,
PV1, and NV with respect to Ground................-0.5V to + 6.0V
Voltage on PC5, BATT, PVT, VFET, OC, OD, PV4, PV3,
and PV2 with respect to Ground........................-0.5V to + 35V
Voltage on VCLMP10 and RESET
with respect to Ground ......................................-0.5V to + 13V
Maximum Operating Voltage on VREG and VCC............. 4.5V
Maximum Operating Voltage on VFET .............................. 25V
32.2
Supply Current Characteristics
Table 32-1.
Symbol
TA= 25°C unless otherwise noted.
Parameter
Condition
Min
Typ
Max
Unit
VFET=16V, CPU clock=8MHz, All PRR bits set
3.75
5
mA
VFET=16V, CPU clock=1MHz, All PRR bits set
760
1000
Idle current
VFET=16V, CPU clock=1MHz, All PRR bits set
215
293
ADCNRM current
VFET=16V, CPU clock=1MHz, All PRR bits except
PRVADC are set, VADC enabled.
350
VFET=16V, Only WDT enabled, DUVR mode disabled.
28
46
TBD
TBD
<1
2
Active current
IVFET
µA
Power-save current
VFET=16V, WDT, CC-ADC, OC, OD and Battery
Protection enabled, DUVR mode disabled.
Power-off current
VFET=6V
230
8042B–AVR–06/10
ATmega16HVB/32HVB
32.3
NFET Driver Characteristics
Table 32-2.
TA= 25°C unless otherwise noted.
Symbol
Parameter
VOC,ON
OC pin on voltage relative to PVT
voltage
OD pin on voltage relative to BATT
voltage
VOD,ON
Condition
Min.
Typ.
OC enabled, VFET=16V
13
OC enabled, VFET=10V
13
OC enabled, VFET=4V
6
OD enabled, VFET=16V
13
OD enabled, VFET=10V
13
OD enabled, VFET=4V
6
OC pin off voltage realtive to GND
0.0
VOD,OFF
OD pin off voltage realtive to GND
0.0
Rise time on OC pin
Rise time on OD pin
tr,OD
V(OC-PVT)=0 to 2V, Ceq=4.7nF, VFET=16V
0.8
V(OC-PVT)=0 to 2V, Ceq=4.7nF, VFET=10V
1.1
V(OC-PVT)=0 to 2V, Ceq=4.7nF, VFET=6V
3
V(OC-PVT)=2 to 4V, Ceq=4.7nF, VFET=16V
1
V(OC-PVT)=2 to 4V, Ceq=4.7nF, VFET=10V
1.2
V(OC-PVT)=2 to 4V, Ceq=4.7nF, VFET=6V
1.3
V(OD-BATT)=0 to 2V, Ceq=4.7nF, VFET=16V
0.8
V(OD-BATT)=0 to 2V, Ceq=4.7nF, VFET=10V
1.1
V(OD-BATT)=0 to 2V, Ceq=4.7nF, VFET=6V
3
V(OD-BATT)=2 to 4V, Ceq=4.7nF, VFET=16V
1
V(OD-BATT)=2 to 4V, Ceq=4.7nF, VFET=10V
1.2
V(OD-BATT)=2 to 4V, Ceq=4.7nF, VFET=6V
1.3
ms
tf,OC
Fall time on OC pin
V(OD-PVT)=VOC,ON to 0V
50
tf,OD
Fall time on OD pin
V(OD-BATT)=VOD,ON to 0V
50
VVFET,DUVR
Regulated VFET voltage in DUVR
mode
DUVR enabled, VREF=1.1V
Note:
Units
V
VOC,OFF
tr,OC
Max.
ns
4.1
4.9
V
The NFET drivers require a minimum total cell voltage of 6V or higher or a charger connected to turn-on the FETs. Note that this
limit only applies if the FET is disabled in advanced. If the FET is already enabled, the FET will be fully operational in the entire
voltage range of the device (4-25V).
231
8042B–AVR–06/10
ATmega16HVB/32HVB
32.4
Reset Characteristics
Table 32-3.
Symbol
TA= -40 to 85°C unless otherwise noted.
Parameter
Condition
Min
(1)
VPOT
Typ
Max
Power-on Threshold Voltage (rising)
4.5
7
Power-on Threshold Voltage (falling)(1)(2)
4.5
6.3
tRST
Minimum pulse width on RESET Pin
VBOT
Brown-Out Detection (BOD) Trigger Level
VHYST
BOD Level Hysteresis
Units
V
900
ns
TA= 25°C
2.9
V
TA= 25°C
50
mV
Notes:
1. The voltage at the Pack + terminal will be slightly higher than VPOT when the chip is enabled. This is because of an internal
Pull-down current on the BATT pin in the range 50 - 150 uA and the RBATT resistor connected between the Pack + terminal
and the BATT pin. RBATT = 1k gives a voltage drop 0.05 - 0.15V.
2. The power-on reset will not work unless the voltage has been below VPOT (falling) after a power-off condition.
32.5
Voltage Regulator Characteristics
Table 32-4.
Symbol
VVREG
TA= -40 to 85°C unless otherwise noted.
Parameter
Regulator Output Voltage
VRSCL
Voltage Regulator Short- circuit Level at
VFET pin
VBLOD
Voltage Regulator Black-out Detection
Level at VREG pin
32.6
Condition
Min
VFET=16.8V, IOUT=20mA
3.1
VFET=6V, IOUT=20mA
3.1
VFET=4V, IOUT=7mA
3.1
Max
Unit
V
3.3
3.7
TA= 25°C
2.65
Voltage reference and Temperature Sensor Characteristics
Table 32-5.
TA= -40 to 85°C unless otherwise noted.
Parameter
Condition
Min
Reference Voltage
Ref. Voltage Accuracy(1)
Temperature Drift(1)(2)
VREF calibration
Hold Off Time
VPTAT, Voltage Proportional
to Absolute Temperature(2)
VPTAT Absolute Accuracy(3)
Notes:
Typ
Typ
Max
1.100
After factory calibration, TA= 25°C
Unit
V
± 0.1
± 0.2
TA = -40° - 85°C
60
90
TA = 0° - 60°C
25
50
%
ppm/K
CREG=2.2µF, BGCCR write
2
CREG=2.2µf, BGCRR write
5
µs
0.6
mV/K
±5
K
1. Calibration is done in Atmel factory test. Software should calibrate the VREF by writing the BGCRR and BGCCR registers
with the calibration values stored in the signature row.
2. This value is not tested in production.
232
8042B–AVR–06/10
ATmega16HVB/32HVB
3. The measured VPTAT voltage must be scaled with the calibration value stored in the VPTAT Calibration Register to get the
absolute temperature. The design target accuracy for this parameter assumes an exact calibration temperature. Actual
accuracy of this parameter after calibration in Atmel factory test remains to be determined.
32.7
ADC Characteristics
32.7.1
Voltage ADC Characteristics
Table 32-6.
TA= -40 to 85°C unless otherwise noted.
Parameter
Condition
Conversion Time
clkVADC = 1 MHz
Min
Typ
Max
Unit
519
μs
Resolution
12
Bits
Gain ADC0/1 (Un-scaled)
263
μV/LSB
Gain Cell Inputs (x0.2)
1.42
mV/LSB
INL(2)
ADC0, ADC1
±1
±3
CELL1, CELL2, CELL3
±1
±3
CELL4
±2
±5
Input Voltage range ADC0, ADC1, VTEMP
Input Voltage range CELL1
0
1
1.8
5
Input Voltage range CELL2
VPV1-GND>1.8V
0
5
Input Voltage range CELL3
VPV2-GND>1.8V
0
5
Input Voltage range CELL4
VPV3-GND>1.8V
0
5
Offset drift(1)(2)
Gain drift
Notes:
(1)(2)
ADC0, ADC1
1
CELL1, CELL2, CELL3
1
CELL4
5
ADC0, ADC1
6
CELL1, CELL2, CELL3
7
CELL4
15
LSB
V
LSB
LSB
1. Value is after Atmel factory offset and gain compensation in production (for details, see Table 29-3, “Signature Row
Addressing.,” on page 199) and it includes drift over the whole temperature range.
2. Value not tested in production but guarantied by design and characterization.
233
8042B–AVR–06/10
ATmega16HVB/32HVB
32.7.2
Coulomb Counter ADC Characteristics
Table 32-7.
TA= -40 to 85°C unless otherwise noted.
Parameter
Condition
Conversion Time
Min
Instantaneous conversion, clkCC-ADC=32kHz
Typ
Max
Unit
3.9
ms
Accumulated conversion CADAS=11, clkCC-ADC=32kHz
1
s
Instantaneous conversion
13
Accumulated conversion
18
Resolution
Bits
Accumulated conversion, CADVSE=0
1.67
Accumulated conversion, CADVSE=1
0.84
Instantaneous conversion, CADVSE=0
53.7
Instantaneous conversion, CADVSE=1
26.9
Gain
µV/LSB
CADVSE = 0
-200
200
CADVSE = 1
-100
100
mV
Input voltage Range
(1)
INL
TA= 0°- 60°C
Offset Error(2)
Accumulated conversion, TA= 25°C
-7
µV
Offset Error Drift(1)(2)
Accumulated conversion
30
nV/°C
± 0.005
(1)(3)
± 0.4
Gain Error
% FSR
±1
%
(1)
0.1
Gain Error Drift
Notes:
1. Values based on characterization data.
2. After software offset compensation, using the polarity switching (CADPOL) feature.
3. Value includes drift over the whole temperature range.
32.8
Clock Characteristics
Table 32-8.
± 0.003
TA= -40 to 85°C unless otherwise noted.
Parameter
Condition
Min
Typ
Max
Unit
Frequency
After factory calibration at
TA=25°C
7.92
8
8.08
MHz
Frequency drift(2)
With run-time calibration with
OSI interface and Slow RC
Oscillator as calibration clock
3
%
171
kHz
Calibrated Fast RC Oscillator
Frequency(3)
Slow RC Oscillator(1)
91
Frequency drift
131
1
%
Frequency prediction error
Ultra Low
Power RC Oscillator(1)
Notes:
Frequency(3)
Frequency drift(2)
0.5
89
128
6
167
kHz
%
1. The frequency is stored in the Value after factory calibration at 85ºC
2. Value not tested in production, but it is guarantied by design and characterization over the whole temperature range.
3. The actual oscillator frequency is measured in production and stored in the device signature row (for details, see ”Reading
the Signature Row from Software” on page 199).
234
8042B–AVR–06/10
ATmega16HVB/32HVB
32.9
Cell Balancing Characteristic
Table 32-9.
TA= 25°C unless otherwise noted.
Parameter
Condition
Min
Balancing Current
Battery cell Voltage VCELL =4.2V,
V-ADC filter resistance=470Ω
Typ
Max
Unit
4
mA
32.10 Battery Protection Characteristics
Table 32-10. TA= -40 to 85°C unless otherwise noted.
Symbol
Parameter
VSCD=VNNI-VPPI
Short Circuit Detection level
accuracy(1)(2)
VCOCD=VPPI-VNNI,
VDOCD=VNNI-VPPI
VCHCD=VPPI-VNNI,
VDHCD=VNNI-VPPI
Notes:
Charge/Discharge Over Current
Detection level accuracy(1)(2)
Charge/Discharge High Current
Detection Detection level
accuracy(1)(2)
Condition
Min
Typ
Max
VSCD=20mV (min level)
14
20
26
VSCD=150mV
130
150
170
VSCD=310mV(max)
280
310
340
VCOCD,DOCD=20mV (min level)
15
20
25
VCOCD,DOCD=150mV
130
150
170
VCOCD,DOCD=310mV(max)
280
310
340
VCHCD,DHCD=20mV (min level)
15
20
25
VCHCD,DHOCD=150mV
130
150
170
VCHCD,DHCD=310mV(max)
280
310
340
Unit
mV
1. Value includes drift in the internal Voltage Reference after VREF factory calibration.
2. Levels in charge and discharge direction can be configured independent of each other.
32.11 External Interrupt Characteristics
Table 32-11. Asynchronous External Interrupt Characteristics
Symbol
tINT
Parameter
Minimum pulse width for asynchronous external
interrupt
Condition
Min
Typ
50
Max
Units
ns
235
8042B–AVR–06/10
ATmega16HVB/32HVB
32.12 General I/O Lines Characteristics
32.12.1
Port A and B Characteristics
Table 32-12. TA = -40 to 85°C, VCC = 3.3V (unless otherwise noted)
Symbol
Parameter
Condition
Min.
Typ.
Max.
VIL
Input Low Voltage, Except
RESET pin
VIL1
Input Low Voltage,
RESET pin
VIH
Input High Voltage,
Except RESET pin
0.6VCC(2)
VCC + 0.5
VIH1
Input High Voltage,
RESET pin
0.9VCC(2)
VCC + 0.5
VOL
Output Low Voltage
IOL = 5mA
VOH
Output High Voltage
IOH = 2 mA
IIL
Input Leakage
Current I/O Pin
Pin low
(absolute value)
1
IIH
Input Leakage
Current I/O Pin
Pin high
(absolute value)
1
RRST
Reset Pull-up Resistor
30
60
RPU
I/O Pin Pull-up Resistor
20
50
Units
0.3VCC(1)
-0.5
0.3VCC(1)
V
0.5
2.3
µA
Notes:
kΩ
1. “Max” means the highest value where the pin is guaranteed to be read as low
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. 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.
4. 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.
This restriction is put because the device should be within spec throughout the whole operation range. The integrated voltage regulator could have problems providing this output when supplying high currents at low VFET voltages.
32.12.2
Port C Characteristics
Table 32-13. PC0-PC4 Characteristics
Symbol
Parameter
VIL
Min
Max
Input Low-voltage
-0.5
0.8
VIH
Input High-voltage
2.1
5.5
VOL(1)
Output Low-voltage
0
0.4
Note:
Condition
350 µA sink current
Units
V
1. This values is based on characterization and is not tested in production.
236
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 32-14. PC5 Characteristic
Symbol
Parameter
Condition
VOL
Output Low-voltage
500 µA sink current
Min
Max
Units
0
0.2
V
32.13 2-wire Serial Interface Characteristics
Table 32-15 on page 237 describes the requirements for devices connected to the Two-wire
Serial Bus. The ATmega16HVB/32HVB Two-wire Serial Interface meets or exceeds these
requirements under the noted conditions.
Timing symbols refer to Figure 32-1 on page 238.
Table 32-15. Two-wire Serial Bus Requirements
Symbol
Parameter
VIL
Min
Max
Input Low-voltage
-0.5
0.8
VIH
Input High-voltage
2.1
5.5
VOL(1)
Output Low-voltage
0
0.4
(1)
Condition
350 µA sink current
Rise Time for both SDA and SCL
tr
(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
Cb < 400 pF
250
50
-5
5
µA
–
10
pF
0
100
kHz
fSCL ≤ 100 kHz
V BUS – 0,4V
------------------------------350µA
V BUS – 0,4V
------------------------------100µA
Ω
0.1VBUS < Vi < 0.9VBUS
fCK(3)
ns
0
> max(16fSCL, 450 kHz)
(4)
SCL Clock Frequency
Rp
Value of Pull-up resistor
tHD;STA
Hold Time (repeated) START Condition
fSCL ≤ 100 kHz
4.0
–
tLOW
Low Period of the SCL Clock
fSCL ≤ 100 kHz
4.7
–
tHIGH
High period of the SCL clock
fSCL ≤ 100 kHz
4.0
–
tSU;STA
Set-up time for a repeated START condition
fSCL ≤ 100 kHz
4.7
–
tHD;DAT
Data hold time
fSCL ≤ 100 kHz
0.3
3.45
tSU;DAT
Data setup time
fSCL ≤ 100 kHz
250
–
tSU;STO
Setup time for STOP condition
fSCL ≤ 100 kHz
4.0
–
tBUF
Bus free time between a STOP and START
condition
fSCL ≤ 100 kHz
4.7
–
1.
2.
3.
4.
V
300
(2)
fSCL
Notes:
Units
µs
In ATmega16HVB/32HVB, this parameter is characterized and not tested.
Cb = capacitance of one bus line in pF.
fCK = CPU clock frequency
This requirement applies to all ATmega16HVB/32HVB Two-wire Serial Interface operation. Other devices connected to the
Two-wire Serial Bus need only obey the general fSCL requirement.
237
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 32-1. Two-wire Serial Bus Timing
tof
tHIGH
tr
tLOW
tLOW
SCL
tSU;STA
tHD;STA
tHD;DAT
tSU;DAT
tSU;STO
SDA
tBUF
32.14 SPI Timing Characteristics
See Figure 32-2 on page 239 and Figure on page 239 for details.
Table 32-16. SPI Timing Parameters
Description
Mode
1
SCK period
Master
See Figure
2
SCK high/low
Master
50% duty
3
Rise/Fall time
Master
3.6
4
Setup
Master
10
5
Hold
Master
10
6
Out to SCK
Master
0.5 • tsck
7
SCK to out
Master
10
8
SCK to out high
Master
10
9
SS low to out
Slave
15
10
SCK period
(1)
Min
Slave
4 • tck + 40 ns
Slave
2 • tck + 20 ns
11
SCK high/low
12
Rise/Fall time
Slave
13
Setup
Slave
10
tck
14
Hold
Slave
15
SCK to out
Slave
16
SCK to SS high
Slave
17
SS high to tri-state
Slave
18
SS low to SCK
Slave
Note:
Typ
1.6
15
Max
Units
ns
µs
ns
20
10
20
1. Refer to ”Serial Programming” on page 211 for serial programming requirements.
238
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 32-2. SPI Interface Timing Requirements (Master Mode)
SS
6
1
SCK
(CPOL = 0)
2
2
SCK
(CPOL = 1)
4
MISO
(Data Input)
5
3
MSB
...
LSB
7
MOSI
(Data Output)
8
MSB
...
LSB
SPI Interface Timing Requirements (Slave Mode)
SS
10
9
16
SCK
(CPOL = 0)
11
11
SCK
(CPOL = 1)
13
MOSI
(Data Input)
14
12
MSB
...
LSB
15
MISO
(Data Output)
17
MSB
...
LSB
X
32.15 Serial Programming Characteristics
Figure 32-3. Serial Programming Timing
MOSI
tSHOX
tOVSH
SCK
tSLSH
tSHSL
MISO
tSLIV
239
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 32-4. Serial Programming Waveforms
SERIAL DATA INPUT
(MOSI)
MSB
LSB
SERIAL DATA OUTPUT
(MISO)
MSB
LSB
SERIAL CLOCK INPUT
(SCK)
SAMPLE
Table 32-17. Serial Programming Characteristics, TA = -40°C to 85°C, VCC = 3.3V (Unless Otherwise Noted)
Symbol
Parameter
Min
1/tCLCL
Oscillator Frequency (ATmega16HVB/32HVB)
0
tCLCL
Oscillator Period (ATmega16HVB/32HVB)
tSHSL
SCK Pulse Width High
2.2 tCLCL(1)
tSLSH
SCK Pulse Width Low
2.2 tCLCL(1)
tOVSH
MOSI Setup to SCK High
tSHOX
MOSI Hold after SCK High
tSLIV
SCK Low to MISO Valid
Note:
Typ
Max
Units
8
MHz
125
ns
tCLCL
2 tCLCL
15
1. 2.2 tCLCL for fck < 12 MHz, 3 tCLCL for fck >= 12 MHz
32.16 Parallel Programming Characteristics
Figure 32-5. 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
240
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 32-6. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
LOAD ADDRESS
(LOW BYTE)
LOAD DATA LOAD DATA
(HIGH BYTE)
LOAD DATA
(LOW BYTE)
tXLPH
t XLXH
LOAD ADDRESS
(LOW BYTE)
tPLXH
XTAL1
BS1
PAGEL
DATA
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 32-5 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation.
Figure 32-7. 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)
ADDR1 (Low Byte)
DATA (High Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 32-5 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading operation.
Table 32-18. Parallel Programming Characteristics
Symbol
Parameter
Min
Typ
Max
Units
VPP
Programming Enable Voltage (RESET input)
11.5
12.5
V
IPP
Programming Enable Current
250
μA
tDVXH
Data and Control Valid before XTAL1 High
67
ns
tXLXH
XTAL1 Low to XTAL1 High
200
ns
tXHXL
XTAL1 Pulse Width High
150
ns
tXLDX
Data and Control Hold after XTAL1 Low
67
ns
241
8042B–AVR–06/10
ATmega16HVB/32HVB
Table 32-18. Parallel Programming Characteristics (Continued)
Symbol
Parameter
Min
tXLWL
XTAL1 Low to WR Low
0
tXLPH
XTAL1 Low to PAGEL high
0
tPLXH
PAGEL low to XTAL1 high
150
tBVPH
BS1 Valid before PAGEL High
67
tPHPL
PAGEL Pulse Width High
150
tPLBX
BS1 Hold after PAGEL Low
67
BS2/1 Hold after WR Low. (Fuse programming)
3200
BS2/1 Hold after WR Low. (All other operations)
67
tPLWL
PAGEL Low to WR Low
67
tBVWL
BS1 Valid to WR Low
67
tWLWH
WR Pulse Width Low
150
tWLRL
WR Low to RDY/BSY Low
tWLBX
tWLRH
tWLRH_EE
WR Low to RDY/BSY High
(1)
WR Low to RDY/BSY High
(2)
(3)
Typ
Max
ns
0
1
3.7
4.5
2.8
3.6
7.5
1
tWLRH_CE
WR Low to RDY/BSY High for Chip Erase
tXLOL
XTAL1 Low to OE Low
0
tBVDV
BS1 Valid to DATA valid
0
tOLDV
OE Low to DATA Valid
250
tOHDZ
OE High to DATA Tri-stated
250
Notes:
Units
μs
ms
250
ns
1. tWLRH is valid for the Write Flash, Write Fuse bits and Write Lock bits commands.
2. is valid for the Write EEPROM command
3. tWLRH_CE is valid for the Chip Erase command
242
8042B–AVR–06/10
ATmega16HVB/32HVB
33. Typical Characteristics
All Typical Characteristics contained in this data sheet are based on characterization of
ATmega16/32HVB.
33.1
33.1.1
Supply Current Characteristics
Active supply current characteristics
Active mode current measurements with all bits in the PRR registers set and all I/O modules
turned off.
Figure 33-1. Active Supply Current vs. VVFET, Internal RC Oscillator, 8 MHz.
4
3.95
I VFET [mA]
3.9
3.85
85 °C
3.8
3.75
25 °C
3.7
3.65
-40 °C
3.6
4
6
8
10
12
14
16
18
20
VVFET [V]
Figure 33-2. Active Supply Current vs. VVFET, Internal RC Oscillator, 4 MHz.
2.44
2.4
I VFET [mA]
2.36
85 °C
2.32
25 °C
2.28
2.24
-40 °C
2.2
4
6
8
10
12
14
16
18
20
VVFET [V]
243
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 33-3. Active Supply Current vs. VVFET, Internal RC Oscillator, 2 MHz.
1.33
1.31
85 °C
I VFET [mA]
1.29
1.27
25 °C
1.25
1.23
-40 °C
1.21
4
6
8
10
12
14
16
18
20
VVFET [V]
Figure 33-4. Active Supply Current vs. VVFET, Internal RC Oscillator, 1 MHz.
0.8
0.79
I VFET [mA]
0.78
85 °C
0.77
25 °C
0.76
0.75
0.74
-40 °C
0.73
0.72
4
6
8
10
12
14
16
18
20
VVFET [V]
244
8042B–AVR–06/10
ATmega16HVB/32HVB
33.1.2
Idle supply current characteristics
Idle current consumption measurements with all bits in the PRR registers set and all I/O modules
are turned off.
Figure 33-5. Idle Supply Current vs. VVFET, Internal RC Oscillator, 8 MHz.
0.815
0.795
85 °C
I VFET [mA]
0.775
0.755
25 °C
0.735
0.715
-40 °C
0.695
0.675
4
6
8
10
12
14
16
18
20
VVFET [V]
Figure 33-6. Idle Supply Current vs. VVFET, Internal RC Oscillator, 4 MHz.
0.48
85 °C
0.47
I VFET [mA]
0.46
25 °C
0.45
0.44
-40 °C
0.43
0.42
4
6
8
10
12
14
16
18
20
VVFET [V]
245
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 33-7. Idle Supply Current vs. VVFET, Internal RC Oscillator, 2 MHz.
0.308
85 °C
0.304
I VFET [mA]
0.3
0.296
25 °C
0.292
0.288
-40 °C
0.284
0.28
4
6
8
10
12
14
16
18
20
VVFET [V]
Figure 33-8. Idle Supply Current vs. VVFET, Internal RC Oscillator, 1 MHz.
0.225
85 °C
I VFET [mA]
0.221
25 °C
0.217
0.213
-40 °C
0.209
0.205
4
6
8
10
12
14
16
18
20
VVFET [V]
246
8042B–AVR–06/10
ATmega16HVB/32HVB
33.1.3
Power-save current characteristics
Power-save current consumption with External Interrupt and SMBus connect/disconnect functionality enabled. The Watchdog Timer, CC-ADC, Current Battery Protection (CBP), VREF, and
OC/OD are disabled.
Figure 33-9. Power-Save Supply Current vs. VVFET, External Interrupt and SMBus enabled, all
other modules disabled.
35
85 °C
33
31
25 °C
-40 °C
I VFET [uA]
29
27
25
23
21
19
17
4
6
8
10
12
14
16
18
20
VVFET [V]
Table 33-1 shows additional current consumption that needs to be added to the total power-budget when additional modules are enableds.
Table 33-1.
Typical additional I/O modules current consumption in Power-save
I/O modules enabled
WDT
VREF
CBP
(1)
Typical current consumption
(2)
CC/OD
CC-ADC
X
0.8 µA
X
X
X
X
X
X
X
X
X
X
Note:
(TA=25°C and VVFET=12V)
12 µA
41 µA
X
55 µA
1. Default I/O register configuration used. PPI and NNI connected to GND.
2. Measurements done with Fairchild FDS6690A N-Channel MOSFET.
247
8042B–AVR–06/10
ATmega16HVB/32HVB
33.1.4
Power-off current characteristics
Figure 33-10. Power-Off Supply Current vs. VVFET
1.8
85 °C
25 °C
1.6
-40 °C
I VFET [uA]
1.4
1.2
1
0.8
0.6
4
6
8
10
12
14
16
18
20
VVFET [V]
33.2
33.2.1
NFET Driver Characteristics
OC/OD Levels
Figure 33-11. OC/OD pin voltage vs. VVFET
35
-40 °C
25 °C
85 °C
Pin Voltage [V]
30
25
20
15
10
6
8
10
12
14
16
18
VVFET [V]
248
8042B–AVR–06/10
ATmega16HVB/32HVB
33.2.2
OC/OD rise time from 0V to 2V gate-source voltage with 4.7nF load
Figure 33-12. OC/OD Rise time, VGS = 0 to 2V vs. VVFET
5
4.5
4
Time [ms]
3.5
3
2.5
2
1.5
70 °C
25 °C
1
0.5
0
6
8
10
12
14
16
18
VVFET [V]
33.2.3
OC/OD rise time from 2V to 4V gate-source voltage with 4.7nF load
Figure 33-13. OC/OD Rise time, VGS = 2 to 4V vs. VVFET
3
2.5
Time [ms]
2
1.5
70 °C
1
25 °C
0.5
0
6
8
10
12
14
16
18
VVFET [V]
249
8042B–AVR–06/10
ATmega16HVB/32HVB
33.3
Battery Protection Characteristics
Figure 33-14. Battery Protection Level
Max
TYP(25 °C)
310
Detection Level [mV]
Min
260
210
160
110
60
10
F3 F4 F5 F6 F7 F8 F9 FA FB FC FD 77 78 79 7A 7B 7C 7D 37 38 39 3A 3B 3C 3D 17
Register Value
33.4
33.4.1
Clock Characteristics
Fast RC Oscillator characteristics
Figure 33-15. Fast RC Oscillator Frequency vs. Temperature (After factory calibration)
8.1
8.05
Frequency [MHz]
8
7.95
7.9
7.85
7.8
7.75
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
Temperature [°C]
250
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 33-16. Calibrated Fast RC Oscillator Frequency vs. OSCCAL value.
16
25 ˚C
14
F RC (M Hz)
12
10
8
6
4
0
16
32
48
64
80
96
112 128 144 160 176 192 208 224 240 256
OSCCAL VALUE
33.4.2
Ultra Low Power RC Oscillator characteristics
Figure 33-17. ULP RC Oscillator Frequency vs. Temperature
113
112
Frequency [kHz]
111
110
109
108
107
106
105
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
Temperature [°C]
251
8042B–AVR–06/10
ATmega16HVB/32HVB
33.4.3
Slow RC Oscillator characteristics
Figure 33-18. Slow RC Oscillator Frequency vs. Temperature
118.6
118.5
118.4
Frequency [kHz]
118.3
118.2
118.1
118
117.9
117.8
117.7
117.6
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
Temperature [°C]
33.5
Voltage Reference characteristics
Figure 33-19. Typical VREF curve with Atmel factory calibration at 25°C and 85°C.
1.101
1.100
1.099
VREF [V]
1.098
1.097
1.096
1.095
1.094
1.093
1.092
1.091
-40
-20
0
20
40
60
80
Temperature [°C]
252
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 33-20. Typical VREF deviation curve with Atmel factory calibration at 25°C and 85°C.
33.6
Voltage Regulator characteristics
Figure 33-21. Voltage Regulator vs. VVFET, ILOAD = 10 mA.
3.27
-40 °C
3.26
25 °C
85 °C
VREG [V]
3.25
3.24
3.23
3.22
3.21
4
6
8
10
12
14
16
18
20
22
24
26
VVFET [V]
253
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 33-22. Voltage Regulator vs. VVFET, ILOAD = 20 mA.
3.3
-40 °C
25 °C
85 °C
3.2
3.1
VREG [V]
3
2.9
2.8
2.7
2.6
2.5
2.4
4
6
8
10
12
14
16
18
20
22
24
26
VVFET [V]
Figure 33-23. Voltage Regulator Short-circuit Level at VVFET pin vs. Temperature.
3.75
Rising
3.7
VRSCL [V]
3.65
3.6
3.55
Falling
3.5
3.45
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
Temperature [°C]
254
8042B–AVR–06/10
ATmega16HVB/32HVB
Figure 33-24. BLOD Level.
2.661
2.659
2.657
2.655
VBLOD [V]
2.653
2.651
2.649
2.647
2.645
2.643
2.641
2.639
2.637
-40
-30
-20
-10
0
10
20
30
40
50
60
70
80
90
50
60
70
80
90
Temperature [°C]
33.7
BOD Threshold characteristics
Figure 33-25. BOD Level.
3
2.98
2.96
Rising
VCC [V]
2.94
2.92
2.9
Falling
2.88
2.86
2.84
2.82
-40
-30
-20
-10
0
10
20
30
40
Temperature [°C]
255
8042B–AVR–06/10
ATmega16HVB/32HVB
34. Register Summary
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
(0xFF)
Reserved
–
–
–
–
–
–
–
–
(0xFE)
BPPLR
–
–
–
–
–
–
BPPLE
BPPL
140
(0xFD)
BPCR
–
–
EPID
SCD
DOCD
COCD
DHCD
CHCD
141
(0xFC)
BPHCTR
–
–
HCPT[5:0]
143
(0xFB)
BPOCTR
–
–
OCPT[5:0]
142
(0xFA)
BPSCTR
–
(0xF9)
BPCHCD
SCPT[6:0]
Page
142
CHCDL[7:0]
145
(0xF8)
BPDHCD
DHCDL[7:0]
145
(0xF7)
BPCOCD
COCDL[7:0]
145
(0xF6)
BPDOCD
DOCDL[7:0]
144
(0xF5)
BPSCD
SCDL[7:0]
(0xF4)
Reserved
–
–
–
–
144
–
–
–
–
(0xF3)
BPIFR
–
–
–
SCIF
DOCIF
COCIF
DHCIF
CHCIF
147
(0xF2)
BPIMSK
–
–
–
SCIE
DOCIE
COCIE
DHCIE
CHCIE
146
(0xF1)
CBCR
–
–
–
–
CBE4
CBE3
CBE2
CBE1
155
(0xF0)
FCSR
–
–
–
–
DUVRD
CPS
DFE
CFE
153
(0xEF)
Reserved
–
–
–
–
–
–
–
–
(0xEE)
Reserved
–
–
–
–
–
–
–
–
(0xED)
Reserved
–
–
–
–
–
–
–
–
(0xEC)
Reserved
–
–
–
–
–
–
–
–
(0xEB)
Reserved
–
–
–
–
–
–
–
–
(0xEA)
CADRDC
CADRDC[7:0]
(0xE9)
CADRCC
CADRCC[7:0]
(0xE8)
CADCSRC
-
(0xE7)
CADCSRB
(0xE6)
CADCSRA
(0xE5)
CADICH
–
CADACIE
CADRCIE
CADEN
CADPOL
CADUB
CADICIE
115
115
–
-
-
CADVSE
114
CADACIF
CADRCIF
CADICIF
112
CADAS[1:0]
CADSI[1:0]
CADSE
111
CADIC[15:8]
114
(0xE4)
CADICL
CADIC[7:0]
114
(0xE3)
CADAC3
CADAC[31:24]
114
(0xE2)
CADAC2
CADAC[23:16]
114
(0xE1)
CADAC1
CADAC[15:8]
114
(0xE0)
CADAC0
(0xDF)
Reserved
–
–
–
–
CADAC[7:0]
–
–
–
–
114
(0xDE)
Reserved
–
–
–
–
–
–
–
–
(0xDD)
Reserved
–
–
–
–
–
–
–
–
(0xDC)
Reserved
–
–
–
–
–
–
–
–
(0xDB)
Reserved
–
–
–
–
–
–
–
–
(0xDA)
Reserved
–
–
–
–
–
–
–
–
(0xD9)
Reserved
–
–
–
–
–
–
–
–
(0xD8)
Reserved
–
–
–
–
–
–
–
–
(0xD7)
Reserved
–
–
–
–
–
–
–
–
(0xD6)
Reserved
–
–
–
–
–
–
–
–
(0xD5)
Reserved
–
–
–
–
–
–
–
–
(0xD4)
CHGDCSR
–
–
–
BATTPVL
CHGDISC1
CHGDISC1
CHGDIF
CHGDIE
(0xD3)
Reserved
–
–
–
–
–
–
–
–
(0xD2)
BGCSR
–
–
BGD
BGSCDE
–
–
BGSCDIF
BGSCDIE
(0xD1)
BGCRR
BGCR[7:0]
131
127
126
(0xD0)
BGCCR
–
–
(0xCF)
Reserved
–
–
–
–
–
BGCC[5:0]
–
–
–
256
(0xCE)
Reserved
–
–
–
–
–
–
–
–
(0xCD)
Reserved
–
–
–
–
–
–
–
–
(0xCC)
Reserved
–
–
–
–
–
–
–
–
(0xCB)
Reserved
–
–
–
–
–
–
–
–
(0xCA)
Reserved
–
–
–
–
–
–
–
–
(0xC9)
Reserved
–
–
–
–
–
–
–
–
(0xC8)
ROCR
ROCS
–
–
ROCD
–
–
ROCWIF
ROCWIE
(0xC7)
Reserved
–
–
–
–
–
–
–
–
(0xC6)
Reserved
–
–
–
–
–
–
–
–
(0xC5)
Reserved
–
–
–
–
–
–
–
–
(0xC4)
Reserved
–
–
–
–
–
–
–
–
(0xC3)
Reserved
(0xC2)
Reserved
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
(0xC1)
Reserved
–
–
–
–
–
–
–
–
(0xC0)
Reserved
–
–
–
–
–
–
–
–
134
256
8042B–AVR–06/10
ATmega16HVB/32HVB
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
(0xBF)
Reserved
–
–
–
–
–
–
–
–
(0xBE)
TWBCSR
TWBCIF
TWBCIE
–
–
–
TWBDT1
TWBDT0
TWBCIP
187
(0xBD)
TWAMR
–
187
TWIE
184
(0xBC)
TWCR
(0xBB)
TWDR
(0xBA)
TWAR
(0xB9)
TWSR
TWAM[6:0]
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
–
2–wire Serial Interface Data Register
186
TWA[6:0]
TWS[7:3]
(0xB8)
TWBR
(0xB7)
Reserved
–
(0xB6)
Reserved
–
(0xB5)
Reserved
–
(0xB4)
Reserved
(0xB3)
Page
TWGCE
186
185
–
TWPS1
TWPS0
2–wire Serial Interface Bit Rate Register
184
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
–
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)
OCR1B
Timer/Counter1 – Output Compare Register B
(0x88)
OCR1A
Timer/Counter1 – Output Compare Register A
(0x87)
Reserved
–
–
–
(0x86)
Reserved
–
–
–
(0x85)
TCNT1H
Timer/Counter1 (8 Bit) High Byte
(0x84)
TCNT1L
Timer/Counter1 (8 Bit) Low Byte
(0x83)
Reserved
–
–
–
–
–
(0x82)
Reserved
–
–
–
–
–
–
–
–
(0x81)
TCCR1B
–
–
–
–
–
CS12
CS11
CS10
81
(0x80)
TCCR1A
TCW1
ICEN1
ICNC1
ICES1
ICS1
–
–
WGM10
94
(0x7F)
Reserved
–
–
–
–
–
–
–
–
(0x7E)
DIDR0
–
–
–
–
–
–
PA1DID
PA0DID
95
95
–
–
–
–
–
–
–
–
–
–
95
95
–
–
–
122
257
8042B–AVR–06/10
ATmega16HVB/32HVB
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
(0x7D)
Reserved
–
–
–
–
–
–
–
–
(0x7C)
VADMUX
–
–
–
–
(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
–
–
–
–
ICIE1
OCIE1B
OCIE1A
TOIE1
96
(0x6E)
TIMSK0
–
–
–
–
ICIE0
OCIE0B
OCIE0A
TOIE0
96
(0x6D)
Reserved
–
–
–
–
–
–
–
–
(0x6C)
PCMSK1
(0x6B)
PCMSK0
–
–
–
–
(0x6A)
Reserved
–
–
–
–
–
–
(0x69)
EICRA
ISC31
ISC30
ISC21
ISC20
ISC11
ISC10
ISC01
ISC00
58
(0x68)
PCICR
–
–
–
–
–
–
PCIE1
PCIE0
60
(0x67)
Reserved
–
–
–
–
–
–
–
–
(0x66)
FOSCCAL
(0x65)
Reserved
–
–
–
–
–
–
–
–
VADMUX[3:0]
Page
120
VADC Data Register High byte
120
121
VADC Data Register Low byte
121
PCINT[15:8]
60
PCINT[3:0]
61
–
–
Fast Oscillator Calibration Register
32
(0x64)
PRR0
–
PRTWI
PRVRM
–
PRSPI
PRTIM1
PRTIM0
PRVADC
(0x63)
Reserved
–
–
–
–
–
–
–
–
40
(0x62)
Reserved
–
–
–
–
–
–
–
–
(0x61)
CLKPR
CLKPCE
–
–
–
–
–
CLKPS1
CLKPS0
32
(0x60)
WDTCSR
WDIF
WDIE
WDP3
WDCE
WDE
WDP2
WDP1
WDP0
49
0x3F (0x5F)
SREG
I
T
H
S
V
N
Z
C
10
0x3E (0x5E)
SPH
SP15
SP14
SP13
SP12
SP11
SP10
SP9
SP8
13
0x3D (0x5D)
SPL
SP7
SP6
SP5
SP4
SP3
SP2
SP1
SP0
13
0x3C (0x5C)
Reserved
–
–
–
–
–
–
–
–
0x3B (0x5B)
Reserved
–
–
–
–
–
–
–
–
0x3A (0x5A)
Reserved
–
–
–
–
–
–
–
–
0x39 (0x59)
Reserved
–
–
–
–
–
–
–
–
0x38 (0x58)
Reserved
–
–
–
–
–
–
–
–
0x37 (0x57)
SPMCSR
SPMIE
RWWSB
SIGRD
CTPB
RFLB
PGWRT
PGERS
SPMEN
0x36 (0x56)
Reserved
–
–
–
–
–
–
–
–
206
0x35 (0x55)
MCUCR
–
–
CKOE
PUD
–
–
IVSEL
IVCE
78/32
0x34 (0x54)
MCUSR
–
–
–
OCDRF
WDRF
BODRF
EXTRF
PORF
49
0x33 (0x53)
SMCR
–
–
–
–
SE
39
0x32 (0x52)
Reserved
–
–
–
–
SM[2:0]
–
–
–
–
0x31 (0x51)
DWDR
0x30 (0x50)
Reserved
–
–
–
debugWIRE Data Register
–
–
–
–
–
190
–
–
–
–
–
–
–
–
0x2F (0x4F)
Reserved
0x2E (0x4E)
SPDR
0x2D (0x4D)
SPSR
SPIF
WCOL
–
0x2C (0x4C)
SPCR
SPIE
SPE
DORD
0x2B (0x4B)
GPIOR2
General Purpose I/O Register 2
0x2A (0x4A)
GPIOR1
General Purpose I/O Register 1
24
0x29 (0x49)
OCR0B
Timer/Counter0 Output Compare Register B
95
0x28 (0x48)
OCR0A
Timer/Counter0 Output Compare Register A
95
0x27 (0x47)
TCNT0H
Timer/Counter0 (8 Bit) High Byte
95
0x26 (0x46)
TCNT0L
Timer/Counter0 (8 Bit) Low Byte
0x25 (0x45)
TCCR0B
–
–
–
–
–
CS02
CS01
SPI Data Register
107
–
–
–
–
SPI2X
106
MSTR
CPOL
CPHA
SPR1
SPR0
105
24
95
CS00
81
94
0x24 (0x44)
TCCR0A
TCW0
ICEN0
ICNC0
ICES0
ICS0
–
–
WGM00
0x23 (0x43)
GTCCR
TSM
–
–
–
–
–
–
PSRSYNC
0x22 (0x42)
EEARH
–
–
–
–
–
–
EEPROM High byte
0x21 (0x41)
EEARL
EEPROM Address Register Low Byte
20
0x20 (0x40)
EEDR
EEPROM Data Register
20
–
–
EEPM1
EEPM0
EERIE
EEMPE
EEPE
EERE
20
0x1F (0x3F)
EECR
0x1E (0x3E)
GPIOR0
0x1D (0x3D)
EIMSK
–
–
–
–
INT3
INT2
INT1
INT0
59
0x1C (0x3C)
EIFR
–
–
–
–
INTF3
INTF2
INTF1
INTF0
59
General Purpose I/O Register 0
21
24
258
8042B–AVR–06/10
ATmega16HVB/32HVB
Address
Name
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Page
0x1B (0x3B)
PCIFR
–
–
–
–
–
–
PCIF1
PCIF0
60
0x1A (0x3A)
Reserved
–
–
–
–
–
–
–
–
0x19 (0x39)
Reserved
–
–
–
–
–
–
–
–
0x18 (0x38)
Reserved
–
–
–
–
–
–
–
–
0x17 (0x37)
OSICSR
–
–
–
OSISEL0
–
–
OSIST
OSIEN
33
0x16 (0x36)
TIFR1
–
–
–
–
ICF1
OCF1B
OCF1A
TOV1
96
0x15 (0x35)
TIFR0
–
–
–
–
ICF0
OCF0B
OCF0A
TOV0
96
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)
Reserved
–
–
–
–
–
–
–
–
0x0A (0x2A)
Reserved
–
–
–
–
–
–
–
–
0x09 (0x29)
Reserved
–
–
–
–
–
–
–
–
0x08 (0x28)
PORTC
–
–
PORTC5
PORTC4
PORTC3
PORTC2
PORTC1
PORTC0
0x07 (0x27)
Reserved
–
–
–
–
–
–
–
–
66
0x06 (0x26)
PINC
–
–
–
PINC4
PINC3
PINC2
PINC1
PINC0
66
0x05 (0x25)
PORTB
PORTB7
PORTB6
PORTB5
PORTB4
PORTB3
PORTB2
PORTB1
PORTB0
78
0x04 (0x24)
DDRB
DDB7
DDB6
DDB5
DDB4
DDB3
DDB2
DDB1
DDB0
78
0x03 (0x23)
PINB
PINB7
PINB6
PINB5
PINB4
PINB3
PINB2
PINB1
PINB0
78
0x02 (0x22)
PORTA
–
–
–
–
PORTA3
PORTA2
PORTA1
PORTA0
78
0x01 (0x21)
DDRA
–
–
–
–
DDA3
DDA2
DDA1
DDA0
78
0x00 (0x20)
PINA
–
–
–
–
PINA3
PINA2
PINA1
PINA0
78
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 ATmega16HVB/32HVB 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.
259
8042B–AVR–06/10
ATmega16HVB/32HVB
35. 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
SBCI
Rd, K
Subtract with Carry Constant from Reg.
Rd ← Rd - K - C
Z,C,N,V,H
1
SBIW
Rdl,K
Subtract Immediate from Word
Rdh:Rdl ← Rdh:Rdl - K
Z,C,N,V,S
2
AND
Rd, Rr
Logical AND Registers
Rd ← Rd • Rr
Z,N,V
1
ANDI
Rd, K
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
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) <<
1
R1:R0 ← (Rd x Rr) << 1
R1:R0 ← (Rd x Rr) << 1
Z,C
2
Z,C
2
Z,C
2
2
FMULS
Rd, Rr
Fractional Multiply Signed
FMULSU
Rd, Rr
Fractional Multiply Signed with Unsigned
BRANCH INSTRUCTIONS
RJMP
k
IJMP
Relative Jump
PC ← PC + k + 1
None
Indirect Jump to (Z)
PC ← Z
None
2
JMP
k
Direct Jump
PC ← k
None
3
RCALL
k
Relative Subroutine Call
PC ← PC + k + 1
None
3
Indirect Call to (Z)
PC ← Z
None
3
Direct Subroutine Call
PC ← k
None
4
RET
Subroutine Return
PC ← STACK
None
4
RETI
Interrupt Return
PC ← STACK
I
4
ICALL
CALL
k
CPSE
Rd,Rr
Compare, Skip if Equal
if (Rd = Rr) PC ← PC + 2 or 3
None
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/2/3
1/2/3
1
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
260
8042B–AVR–06/10
ATmega16HVB/32HVB
35. 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
SEC
Set Carry
C←1
C
1
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
SES
Set Signed Test Flag
S←1
S
1
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
Set Half Carry Flag in SREG
H←1
H
1
CLH
Clear Half Carry Flag in SREG
H←0
H
1
Rd ← Rr
Rd+1:Rd ← Rr+1:Rr
None
1
None
1
1
DATA TRANSFER INSTRUCTIONS
MOV
Rd, Rr
Move Between Registers
MOVW
Rd, Rr
Copy Register Word
LDI
Rd, K
Load Immediate
Rd ← K
None
LD
Rd, X
Load Indirect
Rd ← (X)
None
2
LD
Rd, X+
Load Indirect and Post-Inc.
Rd ← (X), X ← X + 1
None
2
2
LD
Rd, - X
Load Indirect and Pre-Dec.
X ← X - 1, Rd ← (X)
None
LD
Rd, Y
Load Indirect
Rd ← (Y)
None
2
LD
Rd, Y+
Load Indirect and Post-Inc.
Rd ← (Y), Y ← Y + 1
None
2
LD
Rd, - Y
Load Indirect and Pre-Dec.
Y ← Y - 1, Rd ← (Y)
None
2
LDD
Rd,Y+q
Load Indirect with Displacement
Rd ← (Y + q)
None
2
LD
Rd, Z
Load Indirect
Rd ← (Z)
None
2
LD
Rd, Z+
Load Indirect and Post-Inc.
Rd ← (Z), Z ← Z+1
None
2
LD
Rd, -Z
Load Indirect and Pre-Dec.
Z ← Z - 1, Rd ← (Z)
None
2
LDD
Rd, Z+q
Load Indirect with Displacement
Rd ← (Z + q)
None
2
LDS
Rd, k
Load Direct from SRAM
Rd ← (k)
None
2
ST
X, Rr
Store Indirect
(X) ← Rr
None
2
ST
X+, Rr
Store Indirect and Post-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
-
Rd, P
In Port
Rd ← P
None
1
SPM
IN
261
8042B–AVR–06/10
ATmega16HVB/32HVB
35. 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
Watchdog Reset
(see specific descr. for WDR/timer)
None
1
BREAK
Break
For On-chip Debug Only
None
N/A
262
8042B–AVR–06/10
ATmega16HVB/32HVB
36. Ordering Information
36.1
ATmega16HVB
Speed (MHz)
Power Supply
Ordering Code
Package
Operation Range
1 - 8 MHz
4 - 25V
ATMEGA16HVB-8X3
44X1
-40°C to 85°C
Package Type
44X1
44-lead, 4.4 mm Body Width, Plastic Thin Shrink Small Outline Package (TSSOP)
263
8042B–AVR–06/10
ATmega16HVB/32HVB
36.2
ATmega32HVB
Speed (MHz)
Power Supply
Ordering Code
Package
Operation Range
1 - 8 MHz
4 - 25V
ATMEGA32HVB-8X3
44X1
-40°C to 85°C
Package Type
44X1
44-lead, 4.4 mm Body Width, Plastic Thin Shrink Small Outline Package (TSSOP)
264
8042B–AVR–06/10
ATmega16HVB/32HVB
37. Packaging Information
37.1
44X1
3 2
3 2
C
C
1
1
E1
E1
E
E
End View
End View
L
L
44
44
Ø
Ø
Top View
Top View
b
b
SYMBOL
COMMON DIMENSIONS
(Unit of Measure
= mm)
COMMON
DIMENSIONS
(Unit of Measure = mm)
MIN
MAX
NOM
NOTE
SYMBOL
A
MIN
–
NOTE
A
A
e
e
D
D
Side View
Side View
A1
A1
NOM
–
MAX
1.20
A
A1
–
0.05
–
1.20
0.15
A1
b
0.05
0.17
–
0.15
0.27
b
C
0.17
0.09
–
0.27
0.20
C
D
0.09
10.90
–
11.00
0.20
11.10
D
E1
10.90
4.30
11.00
4.40
11.10
4.50
E1
E
4.30
6.20
4.40
6.40
4.50
6.60
E
e
6.20
6.40
0.50
TYP
6.60
e
L
0.50
0.50
TYP
0.60
0.70
L
Ø
0.50
0o
0.60
–
0.70
8o
Ø
0o
–
8o
Note: These drawings are for general information only. Refer to JEDEC Drawing MO-153BE.
Note: These drawings are for general information only. Refer to JEDEC Drawing MO-153BE.
R
R
2325 Orchard Parkway
San Jose,
CA Parkway
95131
2325
Orchard
San Jose, CA 95131
TITLE
44X1,
TITLE 44-lead, 4.4 mm Body Width, Plastic Thin Shrink
Small Outline
44X1,
44-lead,Package
4.4 mm (TSSOP)
Body Width, Plastic Thin Shrink
Small Outline Package (TSSOP)
5/16/07
5/16/07
DRAWING NO. REV.
DRAWING
44X1 NO. REV.
A
44X1
A
265
8042B–AVR–06/10
ATmega16HVB/32HVB
38. Errata
38.1
38.1.1
ATmega16HVB
Rev. B
Stack Pointer initial value
The stack pointer in ATmega16HVB is incorrectly initialized to 0x08ff instead of 0x04ff.
Problem Fix/Workaround
Initialize the stack pointer in software before the stack is used. Most C-compilers does initialize the stack pointer without manual intervention.
Assembly Code Example:
ldi r16,high(RAMEND) ; Main program start out SPH,r16 ; Set Stack Pointer to top of RAM
ldi r16,low(RAMEND) out SPL,r16 C Code Example (if required): SP = RAMEND;
TWI bus can get stuck if TWI STOP condition bit is set in slave mode
If the TWSTO bit in TWCR is set while the TWI starts to receive data in slave mode, it can result
in pulling the SCL pin low and then the TWI bus will get stuck. To release the SCL pin and get
out of this situation the TWI module needs to be disabled and then re-enabled.
Problem Fix/Workaround
While in slave mode the TWSTO bit should be written only to recover from an error condition
and then cleared before a data transfer starts.
38.1.2
Rev. A
Not sampled.
38.2
38.2.1
ATmega32HVB
Rev. B
No known errata.
38.2.2
Rev. A
Not sampled.
266
8042B–AVR–06/10
ATmega16HVB/32HVB
39. Datasheet Revision History
Please note that the referring page numbers in this section are referring to this document. The
referring revision in this section are referring to the document revision.
39.1
Rev. 8042B-06/10
1.
Removed direction arrow in Figure 17-1 on page 82.
Updated ”Configuring PA1 and PA0 for V-ADC operation” on page 118.
Updated ”Operating Circuit” on page 225, with correct naming convention for thermistors RT32
and RT33.
39.2
Rev. 8042A-08/09
1.
Initial revision
267
8042B–AVR–06/10
ATmega16HVB/32HVB
Table of Contents
Features ..................................................................................................... 1
1
Pin Configurations ................................................................................... 2
1.1TSSOP ......................................................................................................................2
1.2Pin Descriptions ........................................................................................................2
2
Overview ................................................................................................... 5
2.1Comparison Between ATmega16HVB and ATmega32HVB .....................................7
3
Disclaimer ................................................................................................. 8
4
Resources ................................................................................................. 8
5
About Code Examples ............................................................................. 8
6
Data Retention .......................................................................................... 8
7
AVR CPU Core .......................................................................................... 9
7.1Overview ...................................................................................................................9
7.2ALU – Arithmetic Logic Unit ....................................................................................10
7.3Status Register ........................................................................................................10
7.4General Purpose Register File ................................................................................12
7.5Stack Pointer ...........................................................................................................13
7.6Instruction Execution Timing ...................................................................................14
7.7Reset and Interrupt Handling ..................................................................................14
8
AVR Memories ........................................................................................ 17
8.1Overview .................................................................................................................17
8.2In-System Reprogrammable Flash Program Memory .............................................17
8.3SRAM Data Memory ...............................................................................................17
8.4EEPROM Data Memory ..........................................................................................19
8.5I/O Memory ..............................................................................................................19
8.6Register Description ................................................................................................20
9
System Clock and Clock Options ......................................................... 25
9.1Clock Systems and their Distribution .......................................................................25
9.2Clock Sources .........................................................................................................26
9.3Clock Startup Sequence ..........................................................................................28
9.4Clock Output ............................................................................................................28
9.5System Clock Prescaler ..........................................................................................28
i
8042B–AVR–06/10
9.6VADC Clock Prescaler ............................................................................................29
9.7OSI – Oscillator Sampling Interface ........................................................................29
9.8Register Description ................................................................................................32
10 Power Management and Sleep Modes ................................................. 35
10.1Sleep Modes .........................................................................................................35
10.2Idle Mode ...............................................................................................................37
10.3ADC Noise Reduction ...........................................................................................37
10.4Power-save Mode .................................................................................................37
10.5Power-off Mode .....................................................................................................38
10.6Power Reduction Register .....................................................................................38
10.7Minimizing Power Consumption ............................................................................38
10.8Register Description ..............................................................................................39
11 System Control and Reset .................................................................... 42
11.1Resetting the AVR .................................................................................................42
11.2Reset Sources .......................................................................................................42
11.3Reset and the Voltage Reference .........................................................................45
11.4Watchdog Timer ....................................................................................................46
11.5Register Description ..............................................................................................49
12 Interrupts ................................................................................................ 52
12.1Overview ...............................................................................................................52
12.2Interrupt Vectors in ATmega16HVB/32HVB ..........................................................52
12.3Moving Interrupts Between Application and Boot Space ......................................56
12.4Register Description ..............................................................................................56
13 External Interrupts ................................................................................. 58
13.1Overview ...............................................................................................................58
13.2Register Description ..............................................................................................58
14 High Voltage I/O Ports ........................................................................... 62
14.1Overview ...............................................................................................................62
14.2High Voltage Ports as General Digital I/O .............................................................63
14.3Overview ...............................................................................................................64
14.4Alternate Port Functions ........................................................................................64
14.5Register Description ..............................................................................................66
15 Low Voltage I/O-Ports ............................................................................ 67
15.1Overview ...............................................................................................................67
ii
ATmega16HVB/32HVB
8042B–AVR–06/10
ATmega16HVB/32HVB
15.2Low Voltage Ports as General Digital I/O ..............................................................68
15.3Alternate Port Functions ........................................................................................72
15.4Register Description ..............................................................................................78
16 Timer/Counter0 and Timer/Counter1 Prescalers ................................ 79
16.1Overview ...............................................................................................................79
16.2External Clock Source ...........................................................................................80
16.3Register Description ..............................................................................................81
17 Timer/Counter (T/C0,T/C1) .................................................................... 82
17.1Features ................................................................................................................82
17.2Overview ...............................................................................................................82
17.3Timer/Counter Clock Sources ...............................................................................83
17.4Counter Unit ..........................................................................................................83
17.5Modes of Operation ...............................................................................................84
17.6Input Capture Unit .................................................................................................86
17.7Output Compare Unit ............................................................................................88
17.8Timer/Counter Timing Diagrams ...........................................................................89
17.9Accessing Registers in 16-bit Mode ......................................................................90
17.10Register Description ............................................................................................94
18 SPI – Serial Peripheral Interface ........................................................... 98
18.1Features ................................................................................................................98
18.2Overview ...............................................................................................................98
18.3SS Pin Functionality ............................................................................................103
18.4Data Modes .........................................................................................................103
18.5Register Description ............................................................................................105
19 Coulomb Counter – Dedicated Fuel Gauging Sigma-delta ADC .... 108
19.1Features ..............................................................................................................108
19.2Overview .............................................................................................................108
19.3Normal Operation ................................................................................................109
19.4Regular Current Detection Operation ..................................................................110
19.5Offset Canceling by Polarity Switching ................................................................110
19.6Configuration and Usage .....................................................................................111
19.7Register Description ............................................................................................111
20 Voltage ADC – 7-channel General Purpose 12-bit Sigma-Delta ADC ....
117
20.1Features ..............................................................................................................117
iii
8042B–AVR–06/10
20.2Overview .............................................................................................................117
20.3Operation .............................................................................................................117
20.4Register Description ............................................................................................120
21 Voltage Reference and Temperature Sensor .................................... 123
21.1Features ..............................................................................................................123
21.2Overview .............................................................................................................123
21.3Operation .............................................................................................................124
21.4Bandgap Calibration ............................................................................................124
21.5Bandgap Buffer Settling Time .............................................................................124
21.6Register Description ............................................................................................126
22 Charger Detect ..................................................................................... 129
22.1Features ..............................................................................................................129
22.2Overview .............................................................................................................129
22.3Operation .............................................................................................................130
22.4Register Description ............................................................................................131
23 Voltage Regulator ................................................................................ 132
23.1Features ..............................................................................................................132
23.2Overview .............................................................................................................132
23.3Regulator Start-up ...............................................................................................133
23.4Battery Pack Short Detection ..............................................................................133
23.5Black-Out Detection ............................................................................................133
23.6Register Description ............................................................................................134
24 Battery Protection ................................................................................ 135
24.1Features ..............................................................................................................135
24.2Overview .............................................................................................................135
24.3Operation .............................................................................................................136
24.4External Protection Input .....................................................................................137
24.5Optimizing Usage for Low Power Consumption ..................................................139
24.6Battery Protection CPU Interface ........................................................................140
24.7Register Description ............................................................................................140
25 FET Driver ............................................................................................. 148
25.1Features ..............................................................................................................148
25.2Overview .............................................................................................................148
25.3Operation and Usage ..........................................................................................149
iv
ATmega16HVB/32HVB
8042B–AVR–06/10
ATmega16HVB/32HVB
25.4Register Description ............................................................................................153
26 Cell Balancing ...................................................................................... 154
26.1Overview .............................................................................................................154
26.2Register Description ............................................................................................155
27 2-wire Serial Interface .......................................................................... 156
27.1Features ..............................................................................................................156
27.2Two-wire Serial Interface Bus Definition ..............................................................156
27.3Data Transfer and Frame Format ........................................................................157
27.4Multi-master Bus Systems, Arbitration and Synchronization ...............................160
27.5Overview of the TWI Module ...............................................................................162
27.6Using the TWI ......................................................................................................165
27.7Transmission Modes ...........................................................................................168
27.8Multi-master Systems and Arbitration ..................................................................181
27.9Bus Connect/Disconnect for Two-wire Serial Interface .......................................183
27.10Register Description ..........................................................................................184
28 debugWIRE On-chip Debug System .................................................. 189
28.1Features ..............................................................................................................189
28.2Overview .............................................................................................................189
28.3Physical Interface ................................................................................................189
28.4Software Break Points .........................................................................................190
28.5Limitations of debugWIRE ...................................................................................190
28.6Register Description ............................................................................................190
29 Boot Loader Support – Read-While-Write Self-Programming ......... 191
29.1Features ..............................................................................................................191
29.2Overview .............................................................................................................191
29.3Application and Boot Loader Flash Sections .......................................................191
29.4Read-While-Write and No Read-While-Write Flash Sections ..............................192
29.5Boot Loader Lock Bits .........................................................................................194
29.6Entering the Boot Loader Program ......................................................................195
29.7Addressing the Flash During Self-Programming .................................................196
29.8Self-Programming the Flash ................................................................................197
29.9Register Description ............................................................................................206
30 Memory Programming ......................................................................... 208
30.1Program And Data Memory Lock Bits .................................................................208
v
8042B–AVR–06/10
30.2Fuse Bits .............................................................................................................209
30.3Signature Bytes ...................................................................................................210
30.4Calibration Bytes .................................................................................................211
30.5Page Size ............................................................................................................211
30.6Serial Programming .............................................................................................211
30.7Parallel Programming ..........................................................................................216
31 Operating Circuit .................................................................................. 225
32 Electrical Characteristics .................................................................... 230
32.1Absolute Maximum Ratings* ...............................................................................230
32.2Supply Current Characteristics ............................................................................230
32.3NFET Driver Characteristics ................................................................................231
32.4Reset Characteristics ..........................................................................................232
32.5Voltage Regulator Characteristics .......................................................................232
32.6Voltage reference and Temperature Sensor Characteristics ..............................232
32.7ADC Characteristics ............................................................................................233
32.8Clock Characteristics ...........................................................................................234
32.9Cell Balancing Characteristic ..............................................................................235
32.10Battery Protection Characteristics .....................................................................235
32.11External Interrupt Characteristics ......................................................................235
32.12General I/O Lines Characteristics .....................................................................236
32.132-wire Serial Interface Characteristics ...............................................................237
32.14SPI Timing Characteristics ................................................................................238
32.15Serial Programming Characteristics ..................................................................239
32.16Parallel Programming Characteristics ...............................................................240
33 Typical Characteristics ........................................................................ 243
33.1Supply Current Characteristics ............................................................................243
33.2NFET Driver Characteristics ................................................................................248
33.3Battery Protection Characteristics .......................................................................250
33.4Clock Characteristics ...........................................................................................250
33.5Voltage Reference characteristics .......................................................................252
33.6Voltage Regulator characteristics ........................................................................253
33.7BOD Threshold characteristics ............................................................................255
34 Register Summary ............................................................................... 256
35 Instruction Set Summary .................................................................... 260
vi
ATmega16HVB/32HVB
8042B–AVR–06/10
ATmega16HVB/32HVB
36 Ordering Information ........................................................................... 263
36.1ATmega16HVB ...................................................................................................263
36.2ATmega32HVB ...................................................................................................264
37 Packaging Information ........................................................................ 265
37.144X1 ....................................................................................................................265
38 Errata ..................................................................................................... 266
38.1ATmega16HVB ...................................................................................................266
38.2ATmega32HVB ...................................................................................................266
39 Datasheet Revision History ................................................................ 267
39.1Rev. 8042B-06/10 ...............................................................................................267
39.2Rev. 8042A-08/09 ...............................................................................................267
Table of Contents....................................................................................... i
vii
8042B–AVR–06/10
Headquarters
International
Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131
USA
Tel: 1(408) 441-0311
Fax: 1(408) 487-2600
Atmel Asia
Unit 1-5 & 16, 19/F
BEA Tower, Millennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
Hong Kong
Tel: (852) 2245-6100
Fax: (852) 2722-1369
Atmel Europe
Le Krebs
8, Rue Jean-Pierre Timbaud
BP 309
78054 Saint-Quentin-enYvelines Cedex
France
Tel: (33) 1-30-60-70-00
Fax: (33) 1-30-60-71-11
Atmel Japan
9F, Tonetsu Shinkawa Bldg.
1-24-8 Shinkawa
Chuo-ku, Tokyo 104-0033
Japan
Tel: (81) 3-3523-3551
Fax: (81) 3-3523-7581
Technical Support
avr@atmel.com
Sales Contact
www.atmel.com/contacts
Product Contact
Web Site
www.atmel.com
Literature Requests
www.atmel.com/literature
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 ATMEL’S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL’S WEB SITE, 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 OF 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 product 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’s products are not intended, authorized, or warranted for use
as components in applications intended to support or sustain life.
© 2010 Atmel Corporation. All rights reserved. Atmel ®, Atmel logo and combinations thereof, AVR®, AVR® logo and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
8042B–AVR–06/10