ATmega 8 U2
ATmega 8 U2
ATmega 8 U2
7799C–AVR–12/09
ATmega8U2/16U2/32U2
1. Pin Configurations
Figure 1-1. Pinout
UCAP
AVCC
D+
D-
32 31 30 29 28 27 26 25
XTAL1 1 24 Reset (PC1 / dW)
(PC0) XTAL2 2 23 PC6 (OC.1A / PCINT8)
GND 3 22 PC7 (INT4 / ICP1 / CLKO)
VCC 4 21 PB7 (PCINT7 / OC.0A / OC.1C)
(PCINT11 / AIN2 ) PC2 5 QFN32 20 PB6 (PCINT6)
PC4 (PCINT10)
(RXD1 / AIN1 / INT2) PD2 8 17 PB3 (PDO / MISO / PCINT3)
9 10 11 12 13 14 15 16
UGND
UVCC
AVCC
UCAP
(TXD1 / INT3) PD3
(INT5/ AIN3) PD4
(XCK / AIN4 / PCINT12) PD5
D+
D-
32 31 30 29 28 27 26 25
XTAL1 1 24 Reset (PC1 / dW)
(PC0) XTAL2 2 23 PC6 (OC.1A / PCINT8)
GND 3 22 PC7 (INT4 / ICP1 / CLKO)
VCC 4 21 PB7 (PCINT7 / OC.0A / OC.1C)
(PCINT11 /AIN2 ) PC2 5 VQFP32 20 PB6 (PCINT6)
(OC.0B / INT0) PD0 6 19 PB5 (PCINT5)
(AIN0 / INT1) PD1 7 18 PB4 (T1 / PCINT4)
(RXD1 / AIN1 / INT2) PD2 8 17 PB3 (PDO / MISO / PCINT3)
9 10 11 12 13 14 15 16
(XCK AIN4 / PCINT12) PD5
(TXD1 / INT3) PD3
Note: The large center pad underneath the VQFP and QFN package should be soldered to ground on
the board to ensure good mechanical stability.
1.1 Disclaimer
Typical values contained in this datasheet are based on simulations and characterization of
other AVR microcontrollers manufactured on the same process technology. Min and Max values
will be available after the device is characterized.
2
7799C–AVR–12/09
ATmega8U2/16U2/32U2
2. Overview
The ATmega8U2/16U2/32U2 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture.
By executing powerful instructions in a single clock cycle, the ATmega8U2/16U2/32U2 achieves throughputs approaching
1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed.
RESET
XTAL2
XTAL1
PD7 - PD0 PC7 - PC0 PB7 - PB0
DATA REGISTER DATA DIR. DATA REGISTER DATA DIR. DATA REGISTER DATA DIR.
PORTD REG. PORTD PORTC REG. PORTC PORTB REG. PORTB
8-BIT DA TA BUS
VCC
POR - BOD
RESET
INTERNAL
GND CALIB. OSC
OSCILLATOR
OSCILLATOR
WATCHDOG
PROGRAM STACK TIMER
Debug-Wire
COUNTER POINTER
CONTROL 1uF
LINES ALU EEPROM
PLL
STATUS
REGISTER
D+/SCK
USB
D-/SDATA
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
3
7799C–AVR–12/09
ATmega8U2/16U2/32U2
architecture is more code efficient while achieving throughputs up to ten times faster than con-
ventional CISC microcontrollers.
The ATmega8U2/16U2/32U2 provides the following features: 8K/16K/32K Bytes of In-System
Programmable Flash with Read-While-Write capabilities, 512/512/1024 Bytes EEPROM,
512/512/1024 SRAM, 22 general purpose I/O lines, 32 general purpose working registers, two
flexible Timer/Counters with compare modes and PWM, one USART, a programmable Watch-
dog Timer with Internal Oscillator, an SPI serial port, debugWIRE interface, also used for
accessing the On-chip Debug system and programming and five software selectable power sav-
ing modes. The Idle mode stops the CPU while allowing the SRAM, Timer/Counters, SPI port,
and interrupt system to continue functioning. The Power-down mode saves the register contents
but freezes the Oscillator, disabling all other chip functions until the next interrupt or Hardware
Reset. In Standby mode, the Crystal/Resonator Oscillator is running while the rest of the device
is sleeping. This allows very fast start-up combined with low power consumption. In Extended
Standby mode, the main Oscillator continues to run.
The device is manufactured using Atmel’s high-density nonvolatile memory technology. The on-
chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI serial
interface, by a conventional nonvolatile memory programmer, or by an on-chip Boot program
running on the AVR core. The boot program can use any interface to download the application
program in the application Flash memory. Software in the Boot Flash section will continue to run
while the Application Flash section is updated, providing true Read-While-Write operation. By
combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip,
the Atmel ATmega8U2/16U2/32U2 is a powerful microcontroller that provides a highly flexible
and cost effective solution to many embedded control applications.
The ATmega8U2/16U2/32U2 are supported with a full suite of program and system develop-
ment tools including: C compilers, macro assemblers, program debugger/simulators, in-circuit
emulators, and evaluation kits.
2.2.1 VCC
Digital supply voltage.
2.2.2 GND
Ground.
2.2.3 AVCC
AVCC is the supply voltage pin (input) for all analog features (Analog Comparator, PLL). It
should be externally connected to VCC through a low-pass filter.
4
7799C–AVR–12/09
ATmega8U2/16U2/32U2
2.2.7 D-
USB Full Speed Negative Data Upstream Port
2.2.8 D+
USB Full Speed Positive Data Upstream Port
2.2.9 UGND
USB Ground.
2.2.10 UVCC
USB Pads Internal Regulator Input supply voltage.
2.2.11 UCAP
USB Pads Internal Regulator Output supply voltage. Should be connected to an external capac-
itor (1µF).
2.2.12 RESET/PC1/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 “System Control and
Reset” on page 47. Shorter pulses are not guaranteed to generate a reset. This pin alternatively
serves as debugWire channel or as generic I/O. The configuration depends on the fuses RST-
DISBL and DWEN.
2.2.13 XTAL1
Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.
2.2.14 XTAL2/PC0
Output from the inverting Oscillator amplifier if enabled by Fuse. Also serves as a generic I/O.
5
7799C–AVR–12/09
ATmega8U2/16U2/32U2
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr.
4. Code Examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. 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 documen-
tation for more details.
These code examples assume that the part specific header file is included before compilation.
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".
5. 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.
6
7799C–AVR–12/09
ATmega8U2/16U2/32U2
6.1 Introduction
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
Program Status
Flash
Counter and Control
Program
Memory
Interrupt
32 x 8 Unit
Instruction General
Register Purpose SPI
Registrers Unit
Instruction Watchdog
Decoder Timer
Indirect Addressing
Direct Addressing
ALU Analog
Control Lines Comparator
I/O Module1
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 instruc-
tion is pre-fetched from the program memory. This concept enables instructions to be executed
in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
7
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typ-
ical ALU operation, two operands are output from the 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 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 opera-
tion, 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 for-
mat. Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and the
Application Program section. Both sections have dedicated Lock bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot Program section.
During interrupts and subroutine 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 posi-
tion. The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Regis-
ters, SPI, and other I/O 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
ATmega8U2/16U2/32U2 has Extended I/O space from 0x60 - 0xFF in SRAM where only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
8
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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.
Bit 7 6 5 4 3 2 1 0
0x3F (0x5F) I T H S V N Z C SREG
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
9
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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 6-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 imple-
mented 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.
10
7799C–AVR–12/09
ATmega8U2/16U2/32U2
15 XH XL 0
X-register 7 0 7 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 0 7 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 7 0 7 0
R31 (0x1F) R30 (0x1E)
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementa-
tions of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
11
7799C–AVR–12/09
ATmega8U2/16U2/32U2
6.6.1 SPH and SPL – Stack Pointer High and Low Register
Bit 15 14 13 12 11 10 9 8
0x3E (0x5E) SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
7 6 5 4 3 2 1 0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 1 0 0 0 0 0
1 1 1 1 1 1 1 1
clkCPU
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
Figure 6-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 destina-
tion register.
clkCPU
Total Execution Time
12
7799C–AVR–12/09
ATmega8U2/16U2/32U2
13
7799C–AVR–12/09
ATmega8U2/16U2/32U2
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence..
When using the SEI instruction to enable interrupts, the instruction following SEI will be exe-
cuted before any pending interrupts, as shown in this example.
14
7799C–AVR–12/09
ATmega8U2/16U2/32U2
15
7799C–AVR–12/09
ATmega8U2/16U2/32U2
7. AVR Memories
This section describes the different memories in the ATmega8U2/16U2/32U2. The AVR archi-
tecture has two main memory spaces, the Data Memory and the Program Memory space. In
addition, the ATmega8U2/16U2/32U2 features an EEPROM Memory for data storage. All three
memory spaces are linear and regular.
16
7799C–AVR–12/09
ATmega8U2/16U2/32U2
0x00000
17
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The 32 general purpose working registers, 64 I/O registers, and the 512/512/1024bytes of inter-
nal data SRAM in the ATmega8U2/16U2/32U2 are all accessible through all these addressing
modes. The Register File is described in “General Purpose Register File” on page 10.
Data Memory
32 Registers $0000 - $001F
64 I/O Registers $0020 - $005F
160 Ext I/O Reg. $0060 - $00FF
$0100
Internal SRAM
(512/512/1024 x 8)
$2FF/$2FF/$4FF (8U2/16U2/32U2)
clkCPU
Address Compute Address Address valid
Data
Write
WR
Data
Read
RD
18
7799C–AVR–12/09
ATmega8U2/16U2/32U2
For a detailed description of SPI, debugWIRE and Parallel data downloading to the EEPROM,
see page 259, page 244, and page 250 respectively.
19
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Extended I/O space from 0x60 - 0x1FF in SRAM, only the ST/STS/STD and LD/LDS/LDD
instructions can be used.
For compatibility with future devices, reserved bits should be written to zero if accessed.
Reserved I/O memory addresses should never be written.
Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most
other AVRs, the CBI and SBI instructions will only operate on the specified bit, and can therefore
be used on registers containing such Status Flags. The CBI and SBI instructions work with reg-
isters 0x00 to 0x1F only.
The I/O and peripherals control registers are explained in later sections.
20
7799C–AVR–12/09
ATmega8U2/16U2/32U2
21
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The following code examples show one assembly and one C function for writing to the
EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts glob-
ally) so that no interrupts will occur during 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
7799C–AVR–12/09
ATmega8U2/16U2/32U2
23
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The next code examples show assembly and C functions for reading the EEPROM. The exam-
ples assume that interrupts are controlled so that no interrupts will occur during execution of
these functions.
24
7799C–AVR–12/09
ATmega8U2/16U2/32U2
25
7799C–AVR–12/09
ATmega8U2/16U2/32U2
PLL Clock
Prescaler Source clock Watchdog clock
Clock
Multiplexer
26
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 8-2. Example of clock switching with wake-up from USB Host
resume
1 Resume from Host
External
Oscillator
RC oscillator
3ms
Watchdog wake-up
from power-down
27
7799C–AVR–12/09
ATmega8U2/16U2/32U2
upstream-resume
External
Oscillator
RC oscillator
3ms
Watchdog wake-up
from power-down
28
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. For all fuses “1” means unprogrammed while “0” means programmed.
Main purpose of the delay is to keep the AVR in reset until it is supplied with minimum Vcc. The
delay will not monitor the actual voltage and it will be required to select a delay longer than the
Vcc rise time. If this is not possible, an internal or external Brown-Out Detection circuit should be
used. A BOD circuit will ensure sufficient Vcc before it releases the reset, and the time-out delay
can be disabled. Disabling the time-out delay without utilizing a Brown-Out Detection circuit is
not recommended.
29
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The oscillator is required to oscillate for a minimum number of cycles before the clock is consid-
ered stable. An internal ripple counter monitors the oscillator output clock, and keeps the internal
reset active for a given number of clock cycles. The reset is then released and the device will
start to execute. The recommended oscillator start-up time is dependent on the clock type, and
varies from 6 cycles for an externally applied clock to 32K cycles for a low frequency crystal.
The start-up sequence for the clock includes both the time-out delay and the start-up time when
the device starts up from reset. When starting up from Power-save or Power-down mode, Vcc is
assumed to be at a sufficient level and only the start-up time is included.
C2
XTAL2
C1
XTAL1
GND
The Low Power Oscillator can operate in three different modes, each optimized for a specific fre-
quency range. The operating mode is selected by the fuses CKSEL3..1 as shown in Table 8-3.
Notes: 1. The frequency ranges are preliminary values. Actual values are TBD.
2. This option should not be used with crystals, only with ceramic resonators.
30
7799C–AVR–12/09
ATmega8U2/16U2/32U2
3. If 8 MHz frequency exceeds the specification of the device (depends on VCC), the CKDIV8
Fuse can be programmed in order to divide the internal frequency by 8. It must be ensured
that the resulting divided clock meets the frequency specification of the device.
The CKSEL0 Fuse together with the SUT1..0 Fuses select the start-up times as shown in Table
8-4.
Table 8-4. Start-up Times for the Low Power Crystal Oscillator Clock Selection
Start-up Time from Additional Delay
Oscillator Source / Power-down and from Reset
Power Conditions Power-save (VCC = 5.0V) CKSEL0 SUT1..0
Ceramic resonator, fast
258 CK 14CK + 4.1 ms(1) 0 00
rising power
Ceramic resonator, slowly
258 CK 14CK + 65 ms(1) 0 01
rising power
Ceramic resonator, BOD
1K CK 14CK(2) 0 10
enabled
Ceramic resonator, fast
1K CK 14CK + 4.1 ms(2) 0 11
rising power
Ceramic resonator, slowly
1K CK 14CK + 65 ms(2) 1 00
rising power
Crystal Oscillator, BOD
16K CK 14CK 1 01
enabled
Crystal Oscillator, fast
16K CK 14CK + 4.1 ms 1 10
rising power
Crystal Oscillator, slowly
16K CK 14CK + 65 ms 1 11
rising power
Notes: 1. These options should only be used when not operating close to the maximum frequency of the
device, and only if frequency stability at start-up is not important for the application. These
options are not suitable for crystals.
2. These options are intended for use with ceramic resonators and will ensure frequency stability
at start-up. They can also be used with crystals when not operating close to the maximum fre-
quency of the device, and if frequency stability at start-up is not important for the application.
Table 8-5. Start-up times for the internal calibrated RC Oscillator clock selection
Start-up Time from Power- Additional Delay from
Power Conditions down and Power-save Reset (VCC = 5.0V) SUT1..0
BOD enabled 6 CK 14CK 00
Fast rising power 6 CK 14CK + 4.1 ms 01
(1)
Slowly rising power 6 CK 14CK + 65 ms 10
Reserved 11
Note: 1. The device is shipped with this option selected.
31
7799C–AVR–12/09
ATmega8U2/16U2/32U2
32
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 1. Start-up Times for the Full Swing Crystal Oscillator Clock Selection
Start-up Time from Additional Delay
Oscillator Source / Power-down and from Reset
Power Conditions Power-save (VCC = 5.0V) CKSEL0 SUT1..0
(1)
Ceramic resonator, fast 258 CK 14CK + 4.1 ms 0 00
rising power
Ceramic resonator, 258 CK 14CK + 65 ms(1) 0 01
slowly rising power
Ceramic resonator, 1K CK 14CK(2) 0 10
BOD enabled
Ceramic resonator, fast 1K CK 14CK + 4.1 ms(2) 0 11
rising power
Ceramic resonator, 1K CK 14CK + 65 ms(2) 1 00
slowly rising power
Crystal Oscillator, BOD 16K CK 14CK 01
1
enabled
Crystal Oscillator, fast 16K CK 14CK + 4.1 ms 10
1
rising power
Crystal Oscillator, 16K CK 14CK + 65 ms 11
1
slowly rising power
Notes: 1. These options should only be used when not operating close to the maximum frequency of the
device, and only if frequency stability at start-up is not important for the application. These
options are not suitable for crystals.
They can also be used with crystals when not operating close to the maximum frequency of the device, and
if frequency stability at start-up is not important for the application.
33
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 8-7. Start-up times for the internal calibrated RC Oscillator clock selection
Start-up Time from Power- Additional Delay from
Power Conditions down and Power-save Reset (VCC = 5.0V) SUT1..0
BOD enabled 6 CK 14 CK 00
Fast rising power 6 CK 14 CK + 4.1 ms 01
(1)
Slowly rising power 6 CK 14 CK + 65 ms 10
Reserved 11
34
7799C–AVR–12/09
ATmega8U2/16U2/32U2
NC XTAL2
EXTERNAL
CLOCK XTAL1
SIGNAL
GND
When this clock source is selected, start-up times are determined by the SUT Fuses as shown in
Table 8-8.
35
7799C–AVR–12/09
ATmega8U2/16U2/32U2
decrease the system clock frequency and the power consumption when the requirement for pro-
cessing power is low. This can be used with all clock source options, and it 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 8-9 on page 40.
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
neither the clock frequency corresponding to the previous setting, nor the clock frequency corre-
sponding to the new setting.
The ripple counter that implements the prescaler runs at the frequency of the undivided clock,
which may be faster than the CPU's clock frequency. Hence, it is not possible to determine the
state of the prescaler - even if it were readable, 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 writ-
ten, it takes between T1 + T2 and T1 + 2 * T2 before the new clock frequency is active. In this
interval, 2 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.
8.10 PLL
The PLL is used to generate internal high frequency (48 MHz) clock for USB interface, the PLL
input is generated from an external low-frequency (the crystal oscillator or external clock input
pin from XTAL1).
36
7799C–AVR–12/09
ATmega8U2/16U2/32U2
/48 1
Lock
TclkTimer1
Detector T1 0
XTAL1 XTAL
XTAL2 OSCILLATOR
PLL clock PLL
Prescaler
/2 1
clk clk USB
RC OSCILLATOR 8MHz
8 MHz 0
To System
Clock Prescaler PDIV3..0
PLLUSB
• Bit 5:4 – EXSUT[1:0]: SUT for External Oscillator / Low Power Oscillator
These 2 bits are the SUT value for the External Oscillator / Low Power Oscillator. If the External
oscillator / Low Power Oscillator is selected by fuse bits, the SUT fuse are copyed into these
bits. The firmware can modify these bits by writing a new value. This value will be used at the
next start of the External Oscillator / Low Power Oscillator.
37
7799C–AVR–12/09
ATmega8U2/16U2/32U2
lator is selected by the fuse bits configuration. The firmware has to check if the clock is correctly
started before selected it.
• Bit 3:0 – EXCKSEL[3:0]: CKSEL for External oscillator / Low Power Oscillator
Clock configuration for the External Oscillator / Low Power Oscillator. After a reset, if the Exter-
nal oscillator / Low Power Oscillator is selected by fuse bits, this part of the register is loaded
with the fuse configuration. Firmware can modify it to change the start-up time after the clock
switch.
38
7799C–AVR–12/09
ATmega8U2/16U2/32U2
the oscillator frequency. The oscillator can be calibrated to frequencies as specified in Table 26-
1 on page 266. 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.8 MHz. Otherwise, the EEPROM or Flash write may fail.
The CAL7 bit determines the range of operation for the oscillator. Setting this bit to 0 gives the
lowest frequency range, setting this bit to 1 gives the highest frequency range. The two fre-
quency ranges are overlapping, in other words a setting of OSCCAL = 0x7F gives a higher
frequency than OSCCAL = 0x80.
The CAL[6:0] bits are used to tune the frequency within the selected range. A setting of 0x00
gives the lowest frequency in that range, and a setting of 0x7F gives the highest frequency in the
range.
39
7799C–AVR–12/09
ATmega8U2/16U2/32U2
40
7799C–AVR–12/09
ATmega8U2/16U2/32U2
41
7799C–AVR–12/09
ATmega8U2/16U2/32U2
9.1 Overview
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 consump-
tion to the application’s requirements.
Table 9-1. Active Clock Domains and Wake-up Sources in the Different Sleep Modes.
Active Clock
Domains Oscillators Wake-up Sources
USB Asynchonous
USB Synchronous
EEPROM Ready
WDT Interrupt
INT[7:0] and
Interrupts(3)
Main Clock
PCINT12-0
Interrupts
Other I/O
Enabled
clkFLASH
Source
clkCPU
SPM/
clkIO
Sleep Mode
Idle X X X X X X X X
(2)
Power-down X X X
(2)
Power-save X X X
(1) (2)
Standby X X X X
Extended
X X(2) X X
Standby
Notes: 1. Only recommended with external crystal or resonator selected as clock source.
2. For INT[7:4], only level interrupt.
3. Asynchronous USB interrupt is WAKEUPI only.
To enter any of the five sleep modes, the SE bit in SMCR must be written to logic one and a
SLEEP instruction must be executed. The SM2, SM1, and SM0 bits in the SMCR Register select
which sleep mode (Idle, Power-down, Power-save, Standby or Extended standby) will be acti-
vated by the SLEEP instruction. See Table 9-2 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 sleep. If a reset occurs during sleep mode,
the MCU wakes up and executes from the Reset Vector.
42
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Watchdog, and the interrupt system 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, USART Transmit Complete or some USB interrupts (like SOFI,
WAKEUPI...). If wake-up from the Analog Comparator interrupt is not required, the Analog Com-
parator can be powered down by setting the ACD bit in the Analog Comparator Control and
Status Register – ACSR. This will reduce power consumption in Idle mode.
43
7799C–AVR–12/09
ATmega8U2/16U2/32U2
when stopping the clock will remain occupied, hence the peripheral should in most cases be dis-
abled 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.
44
7799C–AVR–12/09
ATmega8U2/16U2/32U2
enabled and the input signal is left floating or have an analog signal level close to VCC/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 VCC/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 Registers (DIDR1). Refer to
“DIDR1 – Digital Input Disable Register 1” on page 225 for details.
Note: 1. Standby modes are only recommended for use with external crystals or resonators.
45
7799C–AVR–12/09
ATmega8U2/16U2/32U2
46
7799C–AVR–12/09
ATmega8U2/16U2/32U2
47
7799C–AVR–12/09
ATmega8U2/16U2/32U2
MCU Status
Register (MCUSR)
PORF
BORF
EXTRF
WDRF
USBRF
Power-on Reset
Circuit
Brown-out
BODLEVEL [2..0] Reset Circuit
Pull-up Resistor
SPIKE
FILTER
USB Device
Reset Detection
Watchdog
Oscillator
CKSEL[3:0]
SUT[1:0]
VRST
RESET
tTOUT
TIME-OUT
INTERNAL
RESET
48
7799C–AVR–12/09
ATmega8U2/16U2/32U2
VRST
RESET
tTOUT
TIME-OUT
INTERNAL
RESET
49
7799C–AVR–12/09
ATmega8U2/16U2/32U2
VCC VBOT+
VBOT-
RESET
TIME-OUT tTOUT
INTERNAL
RESET
CK
50
7799C–AVR–12/09
ATmega8U2/16U2/32U2
that remains enabled. This allows the device to stay attached to the bus during and after the
reset, while enhancing firmware reliability.
10.4.1 Features
• Clocked from separate On-chip Oscillator
• 3 Operating modes
– Interrupt
– System Reset
– Interrupt and System ResetSelectable Time-out period from 16ms to 8s
• Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode
• Early warning after one Time-Out period reached, programmable Reset (see operating modes)
after 2 Time-Out periods reached.
10.4.2 Overview
ATmega8U2/16U2/32U2 has an Enhanced Watchdog Timer (WDT). The WDT is a timer count-
ing cycles of a separate on-chip 128 kHz oscillator. The WDT gives a early warning interrupt
51
7799C–AVR–12/09
ATmega8U2/16U2/32U2
when the counter reaches a given time-out value. The WDT gives an interrupt or a system reset
when the counter reaches two times the given time-out value. In normal operation mode, it is
required that the system uses the WDR - Watchdog Timer Reset - instruction to restart the coun-
ter before the time-out value is reached. If the system doesn't restart the counter, an interrupt or
system reset will be issued.
WCLKD1
WCLKD0
128kHz
OSCILLATOR
OSC/1
OSC/3
CLOCK
DIVIDER OSC/5
OSC/7
OSC/2K
OSC/4K
OSC/8K
OSC/16K
OSC/32K
OSC/64K
OSC/128K
OSC/256K
OSC/512K
OSC/1024K
WDP0
WATCHDOG
WDP1
WDP2
RESET WDP3
WDE
MCU RESET
WDIF
INTERRUPT
WDIE
EARLY WARNING
WDEWIE INTERRUPT
In Interrupt mode, the WDT gives an interrupt when the timer expires two times. 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 two times. 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.
In addition to these modes, the early warning interrupt can be enabled in order to generate an
interrupt when the WDT counter expires the first time.
The Watchdog always on (WDTON) fuse, if programmed, will force the Watchdog Timer to Sys-
tem 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, altera-
tions to the Watchdog set-up must follow timed sequences. The sequence for clearing WDE or
changing time-out configuration is as follows:
1. In the same operation, write a logic one to the Watchdog change enable bits WDCE
and WDE. A logic one must be written to WDE regardless of the previous value of the
WDE bit and even if it will be cleared after the operation.
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.
52
7799C–AVR–12/09
ATmega8U2/16U2/32U2
While the WDT prescaler allows only even division factors (2, 4, 8...), the WDT peripheral also
includes a clock divider that directly acts on the clock source. This divider handles odd division
factors (3, 5, 7). In combination with the prescaler, a large number of time-out values can be
obtained.
The divider factor change is also ruled by the secure timed sequence : first the WDE and WDCE
bits must be set, and then four cycles are available to load the new divider value into the
WDTCKD register. Be aware that after this operation WDE will still be set. So keep in mind the
importance of order of operations. When setting up the WDT in Interrupt mode with specific val-
ues of prescaler and divider, the divider register must be loaded before the prescaler register :
1. Set WDCE and WDE
2. Load the divider factor into WDTCKD
3. Wait WDCE being automatically cleared (just wait 2 more cycles)
4. Set again WDCE and WDE
5. Clear WDE, set WDIE and load the prescaler factor into WDTCSR in a same operation
6. Now the system is properly configured for Interrupt only mode. Inverting the two opera-
tions would have been resulted into “Reset and Interrupt mode” and needed a third
operation to clear WDE.
The following code example shows one assembly and one C function for turning off the Watch-
dog Timer. The example assumes that interrupts are controlled (e.g. by disabling interrupts
globally) so that no interrupts will occur during the execution of these functions.
53
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. The example code assumes that the part specific header file is included.
Note: If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out
condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not
set up to handle the Watchdog, this might lead to an eternal loop of time-out resets. To avoid this
situation, the application software should always clear the Watchdog System Reset Flag
(WDRF) and the WDE control bit in the initialisation routine, even if the Watchdog is not in use.
The following code example shows one assembly and one C function for changing the time-out
value of the Watchdog Timer.
54
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. The example code assumes that the part specific header file is included.
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.
55
7799C–AVR–12/09
ATmega8U2/16U2/32U2
56
7799C–AVR–12/09
ATmega8U2/16U2/32U2
function of the Watchdog System Reset mode. If the interrupt is not executed before the next
time-out, a System Reset will be applied.
57
7799C–AVR–12/09
ATmega8U2/16U2/32U2
58
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 10-3. Watchdog Timer Prescale Select, DIV = 0 (CLKwdt = CLK128 / 1) (Continued)
Watchdog
Number of WDT Oscillator Early warning Typical Reset/Interrupt Typical
Cycles before 1st time-out Time-out at Time-out at
WDP3 WDP2 WDP1 WDP0 (Early warning) VCC = 5.0V VCC = 5.0V
1 0 1 0
1 0 1 1
1 1 0 0
Reserved
1 1 0 1
1 1 1 0
1 1 1 1
59
7799C–AVR–12/09
ATmega8U2/16U2/32U2
60
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 10-6. Watchdog Timer Prescale Select, DIV = 3 (CLKwdt = CLK128 / 7) (Continued)
Watchdog
Number of WDT Oscillator Early warning Typical Reset/Interrupt Typical
Cycles before 1st time-out Time-out at Time-out at
WDP3 WDP2 WDP1 WDP0 (Early warning) VCC = 5.0V VCC = 5.0V
1 0 1 0
1 0 1 1
1 1 0 0
Reserved
1 1 0 1
1 1 1 0
1 1 1 1
61
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 10-8. Watchdog Timer Prescale Select, DIV = 5 (CLKwdt = CLK128 / 11)
Watchdog
Number of WDT Oscillator Early warning Typical Reset/Interrupt Typical
Cycles before 1st time-out Time-out at Time-out at
WDP3 WDP2 WDP1 WDP0 (Early warning) VCC = 5.0V VCC = 5.0V
0 0 0 0 2K (2048) cycles 88 ms 176 ms
0 0 0 1 4K (4096) cycles 176 ms 352 ms
0 0 1 0 8K (8192) cycles 352 ms 704 ms
0 0 1 1 16K (16384) cycles 704 ms 1.4 s
0 1 0 0 32K (32768) cycles 1.4 s 2.8 s
0 1 0 1 64K (65536) cycles 2.8 s 5.6 s
0 1 1 0 128K (131072) cycles 5.6 s 11.2 s
0 1 1 1 256K (262144) cycles 11.2 s 22.5 s
1 0 0 0 512K (524288) cycles 22.5 s 45 s
1 0 0 1 1024K (1048576) cycles 45s 90 s
1 0 1 0
1 0 1 1
1 1 0 0
Reserved
1 1 0 1
1 1 1 0
1 1 1 1
Table 10-9. Watchdog Timer Prescale Select, DIV = 6(CLKwdt = CLK128 / 13)
Watchdog
Number of WDT Oscillator Early warning Typical Reset/Interrupt Typical
Cycles before 1st time-out Time-out at Time-out at
WDP3 WDP2 WDP1 WDP0 (Early warning) VCC = 5.0V VCC = 5.0V
0 0 0 0 2K (2048) cycles 104 ms 208 ms
0 0 0 1 4K (4096) cycles 208 ms 416 ms
0 0 1 0 8K (8192) cycles 416 ms 832 ms
0 0 1 1 16K (16384) cycles 832 ms 1.64 s
0 1 0 0 32K (32768) cycles 1.6 s 3.3 s
0 1 0 1 64K (65536) cycles 3.3 s 6.6 s
0 1 1 0 128K (131072) cycles 6.6 s 13.3 s
0 1 1 1 256K (262144) cycles 13.3 s 26.6 s
1 0 0 0 512K (524288) cycles 26.6 s 53.2 s
1 0 0 1 1024K (1048576) cycles 53.2 s 106.4 s
62
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 10-9. Watchdog Timer Prescale Select, DIV = 6(CLKwdt = CLK128 / 13) (Continued)
Watchdog
Number of WDT Oscillator Early warning Typical Reset/Interrupt Typical
Cycles before 1st time-out Time-out at Time-out at
WDP3 WDP2 WDP1 WDP0 (Early warning) VCC = 5.0V VCC = 5.0V
1 0 1 0
1 0 1 1
1 1 0 0
Reserved
1 1 0 1
1 1 1 0
1 1 1 1
Table 10-10. Watchdog Timer Prescale Select, DIV = 7 (CLKwdt = CLK128 / 15)
Watchdog
Number of WDT Oscillator Early warning Typical Reset/Interrupt Typical
Cycles before 1st time-out Time-out at Time-out at
WDP3 WDP2 WDP1 WDP0 (Early warning) VCC = 5.0V VCC = 5.0V
0 0 0 0 2K (2048) cycles 120 ms 240 ms
0 0 0 1 4K (4096) cycles 240 ms 480 ms
0 0 1 0 8K (8192) cycles 480 ms 960 ms
0 0 1 1 16K (16384) cycles 0.960 s 1.9 s
0 1 0 0 32K (32768) cycles 1.92 s 3.8 s
0 1 0 1 64K (65536) cycles 3.8 s 7.6 s
0 1 1 0 128K (131072) cycles 7.6 s 15.3 s
0 1 1 1 256K (262144) cycles 15.3 s 30.7 s
1 0 0 0 512K (524288) cycles 30.7 s 61.4 s
1 0 0 1 1024K (1048576) cycles 61.4 s 122 s
1 0 1 0
1 0 1 1
1 1 0 0
Reserved
1 1 0 1
1 1 1 0
1 1 1 1
63
7799C–AVR–12/09
ATmega8U2/16U2/32U2
11. Interrupts
11.1 Overview
This section describes the specifics of the interrupt handling as performed in
ATmega8U2/16U2/32U2. For a general explanation of the AVR interrupt handling, refer to
“Reset and Interrupt Handling” on page 13.
64
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. The Boot Reset Address is shown in Table 23-8 on page 239. For the BOOTRST Fuse “1”
means unprogrammed while “0” means programmed.
65
7799C–AVR–12/09
ATmega8U2/16U2/32U2
66
7799C–AVR–12/09
ATmega8U2/16U2/32U2
12. I/O-Ports
12.1 Overview
All 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 chang-
ing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as
input). Each output buffer has symmetrical drive characteristics with both high sink and source
capability. The pin driver is strong enough to drive LED displays directly. All port pins have indi-
vidually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have
protection diodes to both VCC and Ground as indicated in Figure 12-1. Refer to “Electrical Char-
acteristics” on page 264 for a complete list of parameters.
Rpu
Pxn Logic
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” repre-
sents 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 Regis-
ters and bit locations are listed in “Register Description for I/O-Ports” on page 82.
Three I/O memory address locations are allocated for each 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 correspond-
ing bit in the Data Register. In addition, the Pull-up Disable – PUD bit in MCUCR disables the
pull-up function for all pins in all ports when set.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on page
68. Most 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 alter-
nate functions.
67
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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.
PUD
Q D
DDxn
Q CLR
WDx
RESET
RDx
DATA BUS
1
Pxn Q D
PORTxn 0
Q CLR
RESET
WRx WPx
SLEEP RRx
SYNCHRONIZER
RPx
D Q D Q
PINxn
L Q Q
clk I/O
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.
68
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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).
69
7799C–AVR–12/09
ATmega8U2/16U2/32U2
SYSTEM CLK
SYNC LATCH
PINxn
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 indi-
cated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed
between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indi-
cated in Figure 12-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.
SYSTEM CLK
r16 0xFF
SYNC LATCH
PINxn
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
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. For the assembly program, two temporary registers are used to minimize the time from pull-
ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3
as low and redefining bits 0 and 1 as strong high drivers.
71
7799C–AVR–12/09
ATmega8U2/16U2/32U2
PUOVxn
1
0
PUD
DDOExn
DDOVxn
1
0 Q D
DDxn
Q CLR
WDx
PVOExn RESET
RDx
PVOVxn
DATA BUS
1 1
Pxn
0 Q D 0
PORTxn
PTOExn
Q CLR
DIEOExn
WPx
DIEOVxn RESET
1 WRx
RRx
0 SLEEP
SYNCHRONIZER
RPx
SET
D Q D Q
PINxn
L CLR Q CLR Q
clk I/O
DIxn
AIOxn
72
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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 12-2 summarizes the function of the overriding signals. The pin and port indexes from Fig-
ure 12-5 are not shown in the succeeding tables. The overriding signals are generated internally
in the modules having the alternate function.
The following subsections shortly describe the alternate functions for each port, and relate the
overriding signals to the alternate function. Refer to the alternate function description for further
details.
73
7799C–AVR–12/09
ATmega8U2/16U2/32U2
• OC0A/OC1C/PCINT7, Bit 7
OC0A, Output Compare Match A output: The PB7 pin can serve as an external output for the
Timer/Counter0 Output Compare. The pin has to be configured as an output (DDB7 set “one”) to
serve this function. The OC0A pin is also the output pin for the PWM mode timer function.
OC1C, Output Compare Match C output: The PB7 pin can serve as an external output for the
Timer/Counter1 Output Compare C. The pin has to be configured as an output (DDB7 set “one”)
to serve this function. The OC1C pin is also the output pin for the PWM mode timer function.
PCINT7, Pin Change Interrupt source 7: The PB7 pin can serve as an external interrupt source.
• PCINT6, Bit 6
PCINT6, Pin Change Interrupt source 6: The PB6 pin can serve as an external interrupt source.
• PCINT5, Bit 5
PCINT5, Pin Change Interrupt source 5: The PB5 pin can serve as an external interrupt source.
• T1/PCINT4, Bit 4
T1, Timer/Counter1 counter source.
PCINT4, Pin Change Interrupt source 4: The PB4 pin can serve as an external interrupt source.
74
7799C–AVR–12/09
ATmega8U2/16U2/32U2
75
7799C–AVR–12/09
ATmega8U2/16U2/32U2
.Table 12-4 and Table 12-5 relate the alternate functions of Port B to the overriding signals
shown in Figure 12-5 on page 72. SPI MSTR INPUT and SPI SLAVE OUTPUT constitute the
MISO signal, while MOSI is divided into SPI MSTR OUTPUT and SPI SLAVE INPUT..
76
7799C–AVR–12/09
ATmega8U2/16U2/32U2
• ICP1/INT4/CLK0, Bit 7
ICP1, Input Capture pin 1 :The PC7 pin can act as an input capture for Timer/Counter1.
INT4, External Interrupt source 4 : The PC7 pin can serve as an external interrupt source to the
MCU.
CLK0, Clock Output : The PC7 pin can serve as oscillator clock ouput if the feature is enabled by
fuse.
• PCINT8/OC1A, Bit 6
PCINT8, Pin Change Interrupt source 8 : The PC6 pin can serve as an external interrupt source.
OC1A, Output Compare Match A output: The PC6 pin can serve as an external output for the
Timer/Counter1 Output Compare. The pin has to be configured as an output (DDC6 set “one”) to
serve this function. The OC1A pin is also the output pin for the PWM mode timer function.
• PCINT9/OC1B, Bit 5
PCINT9, Pin Change Interrupt source 9: The PC5 pin can serve as an external interrupt source.
OC1B, Output Compare Match B output: The PC5 pin can serve as an external output for the
Timer/Counter1 Output Compare. The pin has to be configured as an output (DDC5 set “one”) to
serve this function. The OC1B pin is also the output pin for the PWM mode timer function.
• PCINT10, Bit 4
PCINT10, Pin Change Interrupt source 10 : The PC4 pin can serve as an external interrupt
source.
• PCINT11, Bit 2
PCINT11, Pin Change Interrupt source 11 : The PC2 pin can serve as an external interrupt
source.
• Reset/dW, Bit 1
77
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Reset, Reset input. External Reset input is active low and enabled by unprogramming ("1") the
RSTDISBL Fuse. Pullup is activated and output driver and digital input are deactivated when the
pin is used as the RESET pin.
dW, debugWire channel. 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 wired -AND (open-drain) bi-directional I/O pin with pull-up
enabled and becomes the communication gateway between the target and the emulator.
• XTAL2, Bit 0
XTAL2, Oscillator. The PC0 pin can serve as Inverting Output for internal Oscillator amplifier.
Table 12-7 and Table 12-8 relate the alternate functions of Port C to the overriding signals
shown in Figure 12-5 on page 72.
78
7799C–AVR–12/09
ATmega8U2/16U2/32U2
• HWB/TO/INT7/CTS, Bit 7
HWB, Hardware Boot : The PD7 pin can serve as
TO, Timer/Counter0 counter source.
INT7, External Interrupt source 7: The PD7 pin can serve as an external interrupt source to the
MCU.
CTS, USART1 Transmitter Flow Control. This pin can control the transmitter in function of its
state.
• INT6/RTS,Bit 6
INT6, External Interrupt source 6: The PD6 pin can serve as an external interrupt source to the
MCU.
RTS, USART1 Receiver Flow Control. This pin can control the receiver in function of its state.
• XCK1/PCINT12, Bit 5
XCK1, USART1 External Clock : The data direction register DDRD5 controls whether the clock
is output (DDRD5 set) or input (DDRD5 cleared). The XCK1 pin is active only when the USART1
operates in Synchronous Mode.
PCINT12, Pin Change Interrupt source 12: The PD5 pin can serve as an external interrupt
source.
• INT5, Bit 4
INT5, External Interrupt source 5: The PD4 pin can serve as an external interrupt source to the
MCU.
• INT3/TXD1, Bit 3
INT3, External Interrupt source 3: The PD3 pin can serve as an external interrupt source to the
MCU.
79
7799C–AVR–12/09
ATmega8U2/16U2/32U2
TXD1, USART1 Transmit Data : When the USART1 Transmitter is enabled, this pin is config-
ured as an ouput regardless of DDRD3.
• INT2/AIN1/RXD1, Bit 2
INT2, External Interrupt source 2: The PD2 pin can serve as an external interrupt source to the
MCU.
AIN1, Analog Comparator Negative input. This pin is directly connected to the negative input of
the Analog Comparator.
RXD1, USART1 Receive Data : When the USART1 Receiver is enabled, this pin is configured
as an input regardless of DDRD2. When the USART forces this pin to be an input, the pull-up
can still be controlled by the PORTD2 bit.
• INT1/AIN0, Bit 1
INT1, External Interrupt source 1: The PD1 pin can serve as an external interrupt source to the
MCU.
AIN0, Analog Comparator Positive input. This pin is directly connected to the positive input of
the Analog Comparator.
• INT0/OC0B, Bit 0
INT0, External Interrupt source 0: The PD0 pin can serve as an external interrupt source to the
MCU.
OC0B, Output Compare Match B output: The PD0 pin can serve as an external output for the
Timer/Counter0 Output Compare. The pin has to be configured as an output (DDD0 set “one”) to
serve this function. The OC0B pin is also the output pin for the PWM mode timer function.
Table 12-10 and Table 12-11 relates the alternate functions of Port D to the overriding signals
shown in Figure 12-5 on page 72.
80
7799C–AVR–12/09
ATmega8U2/16U2/32U2
81
7799C–AVR–12/09
ATmega8U2/16U2/32U2
82
7799C–AVR–12/09
ATmega8U2/16U2/32U2
83
7799C–AVR–12/09
ATmega8U2/16U2/32U2
13.1 Overview
The External Interrupts are triggered by the INT[7:0] pin or any of the PCINT[12:0] pins. Observe
that, if enabled, the interrupts will trigger even if the INT[7:0] or PCINT[12:0] pins are configured
as outputs. This feature provides a way of generating a software interrupt.
The Pin change interrupt PCI0 will trigger if any enabled PCINT[7:0] pin toggles. PCMSK0 Reg-
ister control which pins contribute to the pin change interrupts. The Pin change interrupt PCI1
will trigger if any enabled PCINT[12:8] pin toggles. PCMSK1 Register control which pins contrib-
ute to the pin change interrupts. Pin change interrupts on PCINT[12:0] are detected
asynchronously. This implies that these interrupts can be used for waking the part also from
sleep modes other than Idle mode.
The External Interrupts can be triggered by a falling or rising edge or a low level. This is set up
as indicated in the specification for the External Interrupt Control Registers – EICRA (INT[3:0])
and EICRB (INT[7:4]). When the external interrupt is enabled and is configured as level trig-
gered, the interrupt will trigger as long as the pin is held low. Note that recognition of falling or
rising edge interrupts on INT[7:4] requires the presence of an I/O clock, described in “System
Clock and Clock Options” on page 26. Low level interrupts and the edge interrupt on INT[3:0] are
detected asynchronously. This implies that these interrupts can be used for waking the part also
from sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle
mode.
Note that if a level triggered interrupt is used for wake-up from Power-down, 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 inter-
rupt will be generated. The start-up time is defined by the SUT and CKSEL Fuses as described
in “System Clock and Clock Options” on page 26.
• Bits 7:0 – ISC31, ISC30 – ISC00, ISC00: External Interrupt 3:0 Sense Control Bits
The External Interrupts 3:0 are activated by the external pins INT[3: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. Edges on INT[3:0] are registered asynchro-
nously. Pulses on INT[3:0] pins wider than the minimum pulse width given in “External Interrupts
Characteristics” on page 268 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 com-
pletion 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
84
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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.
• Bits 7:0 – ISC71, ISC70 - ISC41, ISC40: External Interrupt 7:4 Sense Control Bits
The External Interrupts [7:4] are activated by the external pins INT[7:4] 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-2. The value on the INT[7:4] pins are sampled
before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one
clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an inter-
rupt. Observe that CPU clock frequency can be lower than the XTAL frequency if the XTAL
divider is enabled. If low level interrupt is selected, the low level must be held until the comple-
tion 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.
Note: 1. n = 7, 6, 5 or 4.
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.
85
7799C–AVR–12/09
ATmega8U2/16U2/32U2
86
7799C–AVR–12/09
ATmega8U2/16U2/32U2
87
7799C–AVR–12/09
ATmega8U2/16U2/32U2
14.1 Overview
Timer/Counter0 and 1 share the same prescaler module, but the Timer/Counters can have dif-
ferent prescaler settings. The description below applies to all Timer/Counters. Tn is used as a
general name, n = 0 or 1.
Tn D Q D Q D Q Tn_sync
(To Clock
Select Logic)
LE
clk I/O
88
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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 sys-
tem 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 fre-
quency (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.
PSR10
Tn
Synchronization
Tn
Synchronization
CSn0 CSn0
CSn1 CSn1
CSn2 CSn2
89
7799C–AVR–12/09
ATmega8U2/16U2/32U2
90
7799C–AVR–12/09
ATmega8U2/16U2/32U2
15.1 Features
• Two Independent Output Compare Units
• Double Buffered Output Compare Registers
• Clear Timer on Compare Match (Auto Reload)
• Glitch Free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B)
15.2 Overview
Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output
Compare Units, and with PWM support. It allows accurate program execution timing (event man-
agement) and wave generation.
A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 15-1. For the actual
placement of I/O pins, refer to “Pinout” on page 2. CPU accessible I/O Registers, including I/O
bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed
in the “Register Description” on page 102.
Edge
Tn
Detector
TOP BOTTOM
( From Prescaler )
Timer/Counter
TCNTn
= =0
OCnA
(Int.Req.)
Waveform
= Generation
OCnA
OCRnA
Fixed
OCnB
TOP
(Int.Req.)
Value
DATA BUS
Waveform
= Generation
OCnB
OCRnB
TCCRnA TCCRnB
15.2.1 Registers
The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit
registers. Interrupt request (abbreviated to Int.Req. in the figure) signals are all visible in the
Timer Interrupt Flag Register (TIFR0). All interrupts are individually masked with the Timer Inter-
rupt Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter
91
7799C–AVR–12/09
ATmega8U2/16U2/32U2
uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the Clock Select logic is referred to as the timer clock (clkT0).
The double buffered Output Compare Registers (OCR0A and OCR0B) are compared with the
Timer/Counter value at all times. The result of the compare can be used by the Waveform Gen-
erator to generate a PWM or variable frequency output on the Output Compare pins (OC0A and
OC0B). See “Output Compare Unit” on page 93. for details. The Compare Match event will also
set the Compare Flag (OCF0A or OCF0B) which can be used to generate an Output Compare
interrupt request.
15.2.2 Definitions
Many register and bit references in this section are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Com-
pare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or
bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing
Timer/Counter0 counter value and so on.
The definitions in Table 15-1 are also used extensively throughout the document.
Table 15-1. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes 0x00.
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR0A Register. The assignment is depen-
dent on the mode of operation.
Clock Select
count Edge
Tn
clear clkTn Detector
TCNTn Control Logic
direction
( From Prescaler )
bottom top
92
7799C–AVR–12/09
ATmega8U2/16U2/32U2
93
7799C–AVR–12/09
ATmega8U2/16U2/32U2
OCRnx TCNTn
= (8-bit Comparator )
OCFnx (Int.Req.)
top
bottom
Waveform Generator OCnx
FOCn
WGMn1:0 COMnX1:0
The OCR0x Registers are double buffered when using any of the Pulse Width Modulation
(PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the dou-
ble buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare
Registers to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR0x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is dis-
abled the CPU will access the OCR0x directly.
94
7799C–AVR–12/09
ATmega8U2/16U2/32U2
generation. Similarly, do not write the TCNT0 value equal to BOTTOM when the counter is
down-counting.
The setup of the OC0x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC0x value is to use the Force Output Com-
pare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even when
changing between Waveform Generation modes.
Be aware that the COM0x[1:0] bits are not double buffered together with the compare value.
Changing the COM0x[1:0] bits will take effect immediately.
COMnx1
COMnx0 Waveform
D Q
FOCn Generator
1
OCnx
OCnx Pin
0
D Q
DATA BUS
PORT
D Q
DDR
clk I/O
The general I/O port function is overridden by the Output Compare (OC0x) from the Waveform
Generator if either of the COM0x1:0 bits are set. However, the OC0x pin direction (input or out-
put) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC0x pin (DDR_OC0x) must be set as output before the OC0x value is visi-
ble on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin logic allows initialization of the OC0x state before the out-
put is enabled. Note that some COM0x1:0 bit settings are reserved for certain modes of
operation. See “Register Description” on page 102.
95
7799C–AVR–12/09
ATmega8U2/16U2/32U2
96
7799C–AVR–12/09
ATmega8U2/16U2/32U2
TCNTn
OCn
(COMnx1:0 = 1)
(Toggle)
Period 1 2 3 4
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing TOP to a value close to BOTTOM when the counter is run-
ning with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR0A is lower than the current
value of TCNT0, the counter will miss the Compare Match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can
occur.
For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical
level on each Compare Match by setting the Compare Output mode bits to toggle mode
(COM0A[1:0] = 1). The OC0A value will not be visible on the port pin unless the data direction
for the pin is set to output. The waveform generated will have a maximum frequency of fOC0 =
fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following
equation:
f clk_I/O
f OCnx = -------------------------------------------------
-
2 ⋅ N ⋅ ( 1 + OCRnx )
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
97
7799C–AVR–12/09
ATmega8U2/16U2/32U2
PWM mode is shown in Figure 15-6. The TCNT0 value is in the timing diagram shown as a his-
togram for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Com-
pare Matches between OCR0x and TCNT0.
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
Period 1 2 3 4 5 6 7
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches TOP. If the inter-
rupt is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins.
Setting the COM0x[1:0] bits to two will produce a non-inverted PWM and an inverted PWM out-
put can be generated by setting the COM0x[1:0] to three: Setting the COM0A[1:0] bits to one
allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not
available for the OC0B pin (See Table 15-3 on page 102). The actual OC0x value will only be
visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is
generated by setting (or clearing) the OC0x Register at the Compare Match between OCR0x
and TCNT0, and clearing (or setting) the OC0x Register at the timer clock cycle the counter is
cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
f clk_I/O
f OCnxPWM = -----------------
-
N ⋅ 256
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR0A is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0A equal to MAX will result
in a constantly high or low output (depending on the polarity of the output set by the COM0A1:0
bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by set-
ting OC0x to toggle its logical level on each Compare Match (COM0x[1:0] = 1). The waveform
generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This
98
7799C–AVR–12/09
ATmega8U2/16U2/32U2
feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Out-
put Compare unit is enabled in the fast PWM mode.
OCRnx Update
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
Period 1 2 3
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted
PWM output can be generated by setting the COM0x[1:0] to three: Setting the COM0A0 bit to
99
7799C–AVR–12/09
ATmega8U2/16U2/32U2
one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is
not available for the OC0B pin (See Table 15-4 on page 103). The actual OC0x value will only
be visible on the port pin if the data direction for the port pin is set as output. The PWM wave-
form is generated by clearing (or setting) the OC0x Register at the Compare Match between
OCR0x and TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at
Compare Match between OCR0x and TCNT0 when the counter decrements. The PWM fre-
quency for the output when using phase correct PWM can be calculated by the following
equation:
f clk_I/O
f OCnxPCPWM = -----------------
-
N ⋅ 510
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR0A is set equal to BOTTOM, the
output will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 15-7 OCnx has a transition from high to low even though
there is no Compare Match. The point of this transition is to guarantee symmetry around BOT-
TOM. There are two cases that give a transition without Compare Match.
• OCR0A changes its value from MAX, like in Figure 15-7. When the OCR0A value is MAX the
OCn pin value is the same as the result of a down-counting Compare Match. To ensure
symmetry around BOTTOM the OCn value at MAX must correspond to the result of an up-
counting Compare Match.
• The timer starts counting from a value higher than the one in OCR0A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the
way up.
clkI/O
clkTn
(clkI/O /1)
TOVn
Figure 15-9 shows the same timing data, but with the prescaler enabled.
100
7799C–AVR–12/09
ATmega8U2/16U2/32U2
clkI/O
clkTn
(clkI/O /8)
TOVn
Figure 15-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC
mode and PWM mode, where OCR0A is TOP.
Figure 15-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O /8)
OCFnx
Figure 15-11 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode and fast
PWM mode where OCR0A is TOP.
Figure 15-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Pres-
caler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O /8)
TCNTn
TOP - 1 TOP BOTTOM BOTTOM + 1
(CTC)
OCRnx TOP
OCFnx
101
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 15-3 shows the COM0A[1:0] bit functionality when the WGM0[1:0] bits are set to fast
PWM mode.
Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See “Fast PWM Mode” on page 97
for more details.
102
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 15-4 shows the COM0A1:0 bit functionality when the WGM0[2:0] bits are set to phase cor-
rect PWM mode.
Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See “Phase Correct PWM Mode” on
page 99 for more details.
Table 15-3 shows the COM0B[1:0] bit functionality when the WGM0[2:0] bits are set to fast
PWM mode.
Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See “Fast PWM Mode” on page 97
for more details.
103
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 15-4 shows the COM0B[1:0] bit functionality when the WGM0[2:0] bits are set to phase
correct PWM mode.
Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Com-
pare Match is ignored, but the set or clear is done at TOP. See “Phase Correct PWM Mode” on
page 99 for more details.
104
7799C–AVR–12/09
ATmega8U2/16U2/32U2
105
7799C–AVR–12/09
ATmega8U2/16U2/32U2
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare
Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running,
introduces a risk of missing a Compare Match between TCNT0 and the OCR0x Registers.
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC0A pin.
The Output Compare Register B contains an 8-bit value that is continuously compared with the
counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC0B pin.
106
7799C–AVR–12/09
ATmega8U2/16U2/32U2
107
7799C–AVR–12/09
ATmega8U2/16U2/32U2
16.1 Features
• True 16-bit Design (i.e., Allows 16-bit PWM)
• Three independent Output Compare Units
• Double Buffered Output Compare Registers
• One Input Capture Unit
• Input Capture Noise Canceler
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• External Event Counter
• Five independent interrupt sources (TOV1, OCF1A, OCF1B, OCF1C, ICF1)
16.2 Overview
The 16-bit Timer/Counter 1 unit allows accurate program execution timing (event management),
wave generation, and signal timing measurement. Most register and bit references in this sec-
tion are written in general form. A lower case “n” replaces the Timer/Counter number (for this
product, only n=1 is available), and a lower case “x” replaces the Output Compare unit channel.
However, when using the register or bit defines in a program, the precise form must be used,
i.e., TCNT1 for accessing Timer/Counter1 counter value and so on.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 16-1. For the actual
placement of I/O pins, see “Pinout” on page 2. CPU accessible I/O Registers, including I/O bits
and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in
the “16-bit Timer/Counter 1 with PWM” on page 108.
The Power Reduction Timer/Counter1 bit, PRTIM1, in “PRR0 – Power Reduction Register 0” on
page 46 must be written to zero to enable Timer/Counter1 module.
108
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Edge
Tn
Detector
TOP BOTTOM
( From Prescaler )
Timer/Counter
TCNTn
= =0
OCFnA
(Int.Req.)
Waveform
= OCnA
Generation
OCRnA
Fixed OCFnB
TOP (Int.Req.)
Values
Waveform
= OCnB
Generation
DATABUS
OCRnB
OCFnC
(Int.Req.)
Waveform
= OCnC
Generation
OCRnC
( From Analog
Comparator Ouput )
ICFn (Int.Req.)
Edge Noise
ICRn
Detector Canceler
ICPn
Note: 1. Refer to Figure 1-1 on page 2, Table 12-3 on page 74, and Table 12-6 on page 77 for
Timer/Counter1 pin placement and description.
16.2.1 Registers
The Timer/Counter (TCNTn), Output Compare Registers (OCRnA/B/C), and Input Capture Reg-
ister (ICRn) are all 16-bit registers. Special procedures must be followed when accessing the 16-
bit registers. These procedures are described in the section “Accessing 16-bit Registers” on
page 110. The Timer/Counter Control Registers (TCCRnA/B/C) are 8-bit registers and have no
CPU access restrictions. Interrupt requests (shorten as Int.Req.) signals are all visible in the
Timer Interrupt Flag Register (TIFRn). All interrupts are individually masked with the Timer Inter-
rupt Mask Register (TIMSKn). TIFRn and TIMSKn are not shown in the figure since these
registers are shared by other timer units.
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 (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the clock select logic is referred to as the timer clock (clkTn).
The double buffered Output Compare Registers (OCRnA/B/C) are compared with the
Timer/Counter value at all time. The result of the compare can be used by the Waveform Gener-
ator to generate a PWM or variable frequency output on the Output Compare pin (OCnA/B/C).
109
7799C–AVR–12/09
ATmega8U2/16U2/32U2
See “Output Compare Units” on page 117.. The compare match event will also set the Compare
Match Flag (OCFnA/B/C) which can be used to generate an Output Compare interrupt request.
The Input Capture Register can capture the Timer/Counter value at a given external (edge trig-
gered) event on either the Input Capture pin (ICPn) or on the Analog Comparator pins (See
“Analog Comparator” on page 223.) The Input Capture unit includes a digital filtering unit (Noise
Canceler) for reducing the chance of capturing noise spikes.
The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined
by either the OCRnA Register, the ICRn Register, or by a set of fixed values. When using
OCRnA as TOP value in a PWM mode, the OCRnA Register can not be used for generating a
PWM output. However, the TOP value will in this case be double buffered allowing the TOP
value to be changed in run time. If a fixed TOP value is required, the ICRn Register can be used
as an alternative, freeing the OCRnA to be used as PWM output.
16.2.2 Definitions
The following definitions are used extensively throughout the document:
MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535).
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 one of the fixed values: 0x00FF,
TOP
0x01FF, or 0x03FF, or to the value stored in the OCRnA or ICRn Register. The
assignment is dependent of the mode of operation.
110
7799C–AVR–12/09
ATmega8U2/16U2/32U2
111
7799C–AVR–12/09
ATmega8U2/16U2/32U2
112
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The following code examples show how to do an atomic write of the TCNTn Register contents.
Writing any of the OCRnA/B/C or ICRn Registers can be done by using the same principle.
113
7799C–AVR–12/09
ATmega8U2/16U2/32U2
TEMP (8-bit)
Clock Select
Count Edge
Tn
TCNTnH (8-bit) TCNTnL (8-bit) Clear clkTn Detector
Control Logic
Direction
TCNTn (16-bit Counter)
( From Prescaler )
TOP BOTTOM
114
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The Timer/Counter Overflow Flag (TOVn) is set according to the mode of operation selected by
the WGMn3:0 bits. TOVn can be used for generating a CPU interrupt.
TEMP (8-bit)
Analog
Comparator Noise Edge
ICFn (Int.Req.)
Canceler Detector
ICPn
Note: The Analog Comparator Output (ACO) can only trigger the Timer/Counter1 ICP – not
Timer/Counter3, 4 or 5.
When a change of the logic level (an event) occurs on the Input Capture Pin (ICPn), alternatively
on the analog Comparator output (ACO), and this change confirms to the setting of the edge
detector, a capture will be triggered. When a capture is triggered, the 16-bit 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 ICRn 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.
115
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Reading the 16-bit value in the Input Capture Register (ICRn) is done by first reading the low
byte (ICRnL) and then the high byte (ICRnH). When the low byte is read the high byte is copied
into the high byte Temporary Register (TEMP). When the CPU reads the ICRnH I/O location it
will access the TEMP Register.
The ICRn Register can only be written when using a Waveform Generation mode that utilizes
the ICRn Register for defining the counter’s TOP value. In these cases the Waveform Genera-
tion mode (WGMn3:0) bits must be set before the TOP value can be written to the ICRn
Register. When writing the ICRn Register the high byte must be written to the ICRnH I/O location
before the low byte is written to ICRnL.
For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 110.
116
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Using the Input Capture unit in any mode of operation when the TOP value (resolution) is
actively changed during operation, is not recommended.
Measurement of an external signal’s 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
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the clearing of the ICFn Flag is not required (if an interrupt handler is used).
TEMP (8-bit)
OCRnxH Buf. (8-bit) OCRnxL Buf. (8-bit) TCNTnH (8-bit) TCNTnL (8-bit)
= (16-bit Comparator )
OCFnx (Int.Req.)
TOP
Waveform Generator OCnx
BOTTOM
WGMn3:0 COMnx1:0
117
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The OCRnx Register is double buffered when using any of the twelve Pulse Width Modulation
(PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the
double buffering is disabled. The double buffering synchronizes the update of the OCRnx Com-
pare Register to either TOP or BOTTOM of the counting sequence. The synchronization
prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the out-
put glitch-free.
The OCRnx Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCRnx Buffer Register, and if double buffering is dis-
abled the CPU will access the OCRnx directly. The content of the OCR1x (Buffer or Compare)
Register is only changed by a write operation (the Timer/Counter does not update this register
automatically as the TCNT1 and ICR1 Register). Therefore OCR1x is not read via the high byte
temporary register (TEMP). However, it is a good practice to read the low byte first as when
accessing other 16-bit registers. Writing the OCRnx Registers must be done via the TEMP Reg-
ister since the compare of all 16 bits is done continuously. The high byte (OCRnxH) has to be
written first. When the high byte I/O location is written by the CPU, the TEMP Register will be
updated by the value written. Then when the low byte (OCRnxL) is written to the lower eight bits,
the high byte will be copied into the upper 8-bits of either the OCRnx buffer or OCRnx Compare
Register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 110.
118
7799C–AVR–12/09
ATmega8U2/16U2/32U2
COMnx1
COMnx0 Waveform
D Q
FOCnx Generator
1
OCnx
OCnx Pin
0
D Q
DATA BUS
PORT
D Q
DDR
clk I/O
The general I/O port function is overridden by the Output Compare (OCnx) from the Waveform
Generator if either of the COMnx1:0 bits are set. However, the OCnx pin direction (input or out-
put) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OCnx pin (DDR_OCnx) must be set as output before the OCnx value is visi-
ble on the pin. The port override function is generally independent of the Waveform Generation
mode, but there are some exceptions. Refer to Table 16-1, Table 16-2 and Table 16-3 for
details.
The design of the Output Compare pin logic allows initialization of the OCnx state before the out-
put is enabled. Note that some COMnx1:0 bit settings are reserved for certain modes of
operation. See “16-bit Timer/Counter 1 with PWM” on page 108.
The COMnx1:0 bits have no effect on the Input Capture unit.
119
7799C–AVR–12/09
ATmega8U2/16U2/32U2
non-PWM modes refer to Table 16-1 on page 130. For fast PWM mode refer to Table 16-2 on
page 130, and for phase correct and phase and frequency correct PWM refer to Table 16-3 on
page 131.
A change of the COMnx1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOCnx strobe bits.
120
7799C–AVR–12/09
ATmega8U2/16U2/32U2
TCNTn
OCnA
(COMnA1:0 = 1)
(Toggle)
Period 1 2 3 4
An interrupt can be generated at each time the counter value reaches the TOP value by either
using the OCFnA or ICFn Flag according to the register used to define the TOP value. If the
interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. How-
ever, changing the 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 buff-
ering feature. If the new value written to OCRnA or ICRn is lower than the current value of
TCNTn, the counter will miss the compare match. The counter will then have to count to its max-
imum value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur.
In many cases this feature is not desirable. An alternative will then be to use the fast PWM mode
using OCRnA for defining TOP (WGMn3:0 = 15) since the OCRnA then will be double buffered.
For generating a waveform output in CTC mode, the OCnA output can be set to toggle its logical
level on each compare match by setting the Compare Output mode bits to toggle mode
(COMnA1:0 = 1). The OCnA value will not be visible on the port pin unless the data direction for
the pin is set to output (DDR_OCnA = 1). The waveform generated will have a maximum fre-
quency of fOCnA = fclk_I/O/2 when OCRnA is set to zero (0x0000). The waveform frequency is
defined by the following equation:
f clk_I/O
f OCnA = --------------------------------------------------
-
2 ⋅ N ⋅ ( 1 + OCRnA )
The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).
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 0x0000.
121
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICRn or
OCRnA. The minimum resolution allowed is 2-bit (ICRn or OCRnA set to 0x0003), and the max-
imum resolution is 16-bit (ICRn or OCRnA set to MAX). The PWM resolution in bits can be
calculated by using the following equation:
log ( TOP + 1 )
R FPWM = -----------------------------------
log ( 2 )
In fast PWM mode the counter is incremented until the counter value matches either one of the
fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn[3:0] = 5, 6, or 7), the value in ICRn
(WGMn[3:0] = 14), or the value in OCRnA (WGMn[3:0] = 15). The counter is then cleared at the
following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 16-7.
The figure shows fast PWM mode when OCRnA or ICRn is used to define TOP. The TCNTn
value is in the timing diagram shown as a histogram for illustrating the single-slope operation.
The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks
on the TCNTn slopes represent compare matches between OCRnx and TCNTn. The OCnx
Interrupt Flag will be set when a compare match occurs.
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
Period 1 2 3 4 5 6 7 8
The Timer/Counter Overflow Flag (TOVn) is set each time the counter reaches TOP. In addition
the OCnA or ICFn Flag is set at the same timer clock cycle as TOVn is set when either OCRnA
or ICRn is used for defining the TOP value. If one of the interrupts are enabled, the interrupt han-
dler routine can be used for updating the TOP and compare values.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNTn and the OCRnx.
Note that when using fixed TOP values the unused bits are masked to zero when any of the
OCRnx Registers are written.
The procedure for updating ICRn differs from updating OCRnA when used for defining the TOP
value. The ICRn Register is not double buffered. This means that if ICRn is changed to a low
value when the counter is running with none or a low prescaler value, there is a risk that the new
ICRn value written is lower than the current value of TCNTn. The result will then be that the
counter will miss the compare match at the TOP value. The counter will then have to count to the
MAX value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur.
The OCRnA Register however, is double buffered. This feature allows the OCRnA I/O location
122
7799C–AVR–12/09
ATmega8U2/16U2/32U2
to be written anytime. When the OCRnA I/O location is written the value written will be put into
the OCRnA Buffer Register. The OCRnA Compare Register will then be updated with the value
in the Buffer Register at the next timer clock cycle the TCNTn matches TOP. The update is done
at the same timer clock cycle as the TCNTn is cleared and the TOVn Flag is set.
Using the ICRn Register for defining TOP works well when using fixed TOP values. By using
ICRn, the OCRnA Register is free to be used for generating a PWM output on OCnA. However,
if the base PWM frequency is actively changed (by changing the TOP value), using the OCRnA
as TOP is clearly a better choice due to its double buffer feature.
In fast PWM mode, the compare units allow generation of PWM waveforms on the OCnx pins.
Setting the COMnx1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COMnx1:0 to three (see Table on page 130). The actual OCnx
value will only be visible on the port pin if the data direction for the port pin is set as output
(DDR_OCnx). The PWM waveform is generated by setting (or clearing) the OCnx Register at
the compare match between OCRnx and TCNTn, and clearing (or setting) the OCnx Register at
the timer clock cycle the counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
f clk_I/O
f OCnxPWM = ----------------------------------
-
N ⋅ ( 1 + TOP )
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCRnx Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCRnx is set equal to BOTTOM (0x0000) the out-
put will be a narrow spike for each TOP+1 timer clock cycle. Setting the OCRnx equal to TOP
will result in a constant high or low output (depending on the polarity of the output set by the
COMnx1:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by set-
ting OCnA to toggle its logical level on each compare match (COMnA1:0 = 1). This applies only
if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have
a maximum frequency of fOCnA = fclk_I/O/2 when OCRnA is set to zero (0x0000). This feature is
similar to the OCnA toggle in CTC mode, except the double buffer feature of the Output Com-
pare unit is enabled in the fast PWM mode.
123
7799C–AVR–12/09
ATmega8U2/16U2/32U2
0x0003), and the maximum resolution is 16-bit (ICRn or OCRnA set to MAX). The PWM resolu-
tion in bits can be calculated by using the following equation:
In phase correct PWM mode the counter is incremented until the counter value matches either
one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn[3:0] = 1, 2, or 3), the value in ICRn
(WGMn[3:0] = 10), or the value in OCRnA (WGMn3:0 = 11). The counter has then reached the
TOP and changes the count direction. The TCNTn value will be equal to TOP for one timer clock
cycle. The timing diagram for the phase correct PWM mode is shown on Figure 16-8. The figure
shows phase correct PWM mode when OCRnA or ICRn is used to define TOP. The TCNTn
value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The
diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on
the TCNTn slopes represent compare matches between OCRnx and TCNTn. The OCnx Inter-
rupt Flag will be set when a compare match occurs.
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
Period 1 2 3 4
The Timer/Counter Overflow Flag (TOVn) is set each time the counter reaches BOTTOM. When
either OCRnA or ICRn is used for defining the TOP value, the OCnA or ICFn Flag is set accord-
ingly at the same timer clock cycle as the OCRnx Registers are updated with the double buffer
value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the counter
reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNTn and the OCRnx.
Note that when using fixed TOP values, the unused bits are masked to zero when any of the
OCRnx Registers are written. As the third period shown in Figure 16-8 illustrates, changing the
TOP actively while the Timer/Counter is running in the phase correct mode can result in an
unsymmetrical output. The reason for this can be found in the time of update of the OCRnx Reg-
124
7799C–AVR–12/09
ATmega8U2/16U2/32U2
ister. Since the OCRnx update occurs at TOP, the PWM period starts and ends at TOP. This
implies that the length of the falling slope is determined by the previous TOP value, while the
length of the rising slope is determined by the new TOP value. When these two values differ the
two slopes of the period will differ in length. The difference in length gives the unsymmetrical
result on the output.
It is recommended to use the phase and frequency correct mode instead of the phase correct
mode when changing the TOP value while the Timer/Counter is running. When using a static
TOP value there are practically no differences between the two modes of operation.
In phase correct PWM mode, the compare units allow generation of PWM waveforms on the
OCnx pins. Setting the COMnx[1:0] bits to two will produce a non-inverted PWM and an inverted
PWM output can be generated by setting the COMnx[1:0] to three (See Table 16-3 on page
131). The actual OCnx value will only be visible on the port pin if the data direction for the port
pin is set as output (DDR_OCnx). The PWM waveform is generated by setting (or clearing) the
OCnx Register at the compare match between OCRnx and TCNTn when the counter incre-
ments, and clearing (or setting) the OCnx Register at compare match between OCRnx and
TCNTn when the counter decrements. The PWM frequency for the output when using phase
correct PWM can be calculated by the following equation:
f clk_I/O
f OCnxPCPWM = ---------------------------
-
2 ⋅ N ⋅ TOP
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCRnx Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCRnx is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. If
OCR1A is used to define the TOP value (WGM13:0 = 11) and COM1A[1:0] = 1, the OC1A out-
put will toggle with a 50% duty cycle.
125
7799C–AVR–12/09
ATmega8U2/16U2/32U2
the maximum resolution is 16-bit (ICRn or OCRnA set to MAX). The PWM resolution in bits can
be calculated using the following equation:
log ( TOP + 1 )
R PFCPWM = -----------------------------------
log ( 2 )
In phase and frequency correct PWM mode the counter is incremented until the counter value
matches either the value in ICRn (WGMn[3:0] = 8), or the value in OCRnA (WGMn[3:0] = 9). The
counter has then reached the TOP and changes the count direction. The TCNTn value will be
equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency
correct PWM mode is shown on Figure 16-9. The figure shows phase and frequency correct
PWM mode when OCRnA or ICRn is used to define TOP. The TCNTn value is in the timing dia-
gram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-
inverted and inverted PWM outputs. The small horizontal line marks on the TCNTn slopes repre-
sent compare matches between OCRnx and TCNTn. The OCnx Interrupt Flag will be set when a
compare match occurs.
Figure 16-9. Phase and Frequency Correct PWM Mode, Timing Diagram
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
OCRnx/TOP Updateand
TOVn Interrupt Flag Set
(Interrupt on Bottom)
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
Period 1 2 3 4
The Timer/Counter Overflow Flag (TOVn) is set at the same timer clock cycle as the OCRnx
Registers are updated with the double buffer value (at BOTTOM). When either OCRnA or ICRn
is used for defining the TOP value, the OCnA or ICFn Flag set when TCNTn has reached TOP.
The Interrupt Flags can then be used to generate an interrupt each time the counter reaches the
TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNTn and the OCRnx.
As Figure 16-9 shows the output generated is, in contrast to the phase correct mode, symmetri-
cal in all periods. Since the OCRnx Registers are updated at BOTTOM, the length of the rising
and the falling slopes will always be equal. This gives symmetrical output pulses and is therefore
frequency correct.
126
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Using the ICRn Register for defining TOP works well when using fixed TOP values. By using
ICRn, the OCRnA Register is free to be used for generating a PWM output on OCnA. However,
if the base PWM frequency is actively changed by changing the TOP value, using the OCRnA as
TOP is clearly a better choice due to its double buffer feature.
In phase and frequency correct PWM mode, the compare units allow generation of PWM wave-
forms on the OCnx pins. Setting the COMnx[1:0] bits to two will produce a non-inverted PWM
and an inverted PWM output can be generated by setting the COMnx1:0 to three (See Table 16-
3 on page 131). The actual OCnx value will only be visible on the port pin if the data direction for
the port pin is set as output (DDR_OCnx). The PWM waveform is generated by setting (or clear-
ing) the OCnx Register at the compare match between OCRnx and TCNTn when the counter
increments, and clearing (or setting) the OCnx Register at compare match between OCRnx and
TCNTn when the counter decrements. The PWM frequency for the output when using phase
and frequency correct PWM can be calculated by the following equation:
f clk_I/O
f OCnxPFCPWM = ---------------------------
-
2 ⋅ N ⋅ TOP
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCRnx Register represents special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCRnx is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be set to high for non-
inverted PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A
is used to define the TOP value (WGM1[3:0] = 9) and COM1A[1:0] = 1, the OC1A output will tog-
gle with a 50% duty cycle.
clkI/O
clkTn
(clkI/O /1)
OCFnx
Figure 16-11 shows the same timing data, but with the prescaler enabled.
127
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 16-11. Timer/Counter Timing Diagram, Setting of OCFnx, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O /8)
OCFnx
Figure 16-12 shows the count sequence close to TOP in various modes. When using phase and
frequency correct PWM mode the OCRnx Register is updated at BOTTOM. The timing diagrams
will be the same, but TOP should be replaced by BOTTOM, TOP-1 by BOTTOM+1 and so on.
The same renaming applies for modes that set the TOVn Flag at BOTTOM.
clkI/O
clkTn
(clkI/O /1)
TCNTn
TOP - 1 TOP BOTTOM BOTTOM + 1
(CTC and FPWM)
TCNTn
TOP - 1 TOP TOP - 1 TOP - 2
(PC and PFC PWM)
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
Old OCRnx Value New OCRnx Value
(Update at TOP)
Figure 16-13 shows the same timing data, but with the prescaler enabled.
128
7799C–AVR–12/09
ATmega8U2/16U2/32U2
clkI/O
clkTn
(clkI/O/8)
TCNTn
TOP - 1 TOP BOTTOM BOTTOM + 1
(CTC and FPWM)
TOVn (FPWM)
and ICF n (if used
as TOP)
OCRnx
Old OCRnx Value New OCRnx Value
(Update at TOP)
Bit 7 6 5 4 3 2 1 0
(0x80) COM1A1 COM1A0 COM1B1 COM1B0 COM1C1 COM1C0 WGM11 WGM10 TCCR1A
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
129
7799C–AVR–12/09
ATmega8U2/16U2/32U2
.
Table 16-2 shows the COMnx[1:0] bit functionality when the WGMn[3:0] bits are set to the fast
PWM mode.
130
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 16-3. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM
COMnA1/COMnB/ COMnA0/COMnB0/
COMnC1 COMnC0 Description
Normal port operation, OCnA/OCnB/OCnC
0 0
disconnected.
WGM1[3:0] = 8, 9 10 or 11: Toggle OC1A on
Compare Match, OC1B and OC1C disconnected
0 1 (normal port operation). For all other WGM1
settings, normal port operation,
OC1A/OC1B/OC1C disconnected.
Clear OCnA/OCnB/OCnC on compare match
1 0 when up-counting. Set OCnA/OCnB/OCnC on
compare match when downcounting.
Set OCnA/OCnB/OCnC on compare match when
1 1 up-counting. Clear OCnA/OCnB/OCnC on
compare match when downcounting.
Note: A special case occurs when OCRnA/OCRnB/OCRnC equals TOP and
COMnA1/COMnB1//COMnC1 is set. See “Phase Correct PWM Mode” on page 99. for more
details.
131
7799C–AVR–12/09
ATmega8U2/16U2/32U2
132
7799C–AVR–12/09
ATmega8U2/16U2/32U2
133
7799C–AVR–12/09
ATmega8U2/16U2/32U2
If external pin modes are used for the Timer/Countern, 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.
The two Timer/Counter I/O locations (TCNTnH and TCNTnL, combined TCNTn) give direct
access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To
ensure that both the high and low bytes are read and written simultaneously when the CPU
accesses these registers, the access is performed using an 8-bit temporary High Byte Register
(TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit
Registers” on page 110.
Modifying the counter (TCNTn) while the counter is running introduces a risk of missing a com-
pare match between TCNTn and one of the OCRnx Registers.
Writing to the TCNTn Register blocks (removes) the compare match on the following timer clock
for all compare units.
134
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The Output Compare Registers contain a 16-bit value that is continuously compared with the
counter value (TCNTn). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OCnx pin.
The Output Compare Registers are 16-bit in size. To ensure that both the high and low bytes are
written simultaneously when the CPU writes to these registers, the access is performed using an
8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other
16-bit registers. See “Accessing 16-bit Registers” on page 110.
IThe Input Capture is updated with the counter (TCNTn) value each time an event occurs on the
ICPn pin (or optionally on the Analog Comparator output for Timer/Counter1). The Input Capture
can be used for defining the counter TOP value.
The Input Capture Register is 16-bit in size. To ensure that both the high and low bytes are read
simultaneously when the CPU accesses these registers, the access is performed using an 8-bit
temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit
registers. See “Accessing 16-bit Registers” on page 110.
135
7799C–AVR–12/09
ATmega8U2/16U2/32U2
136
7799C–AVR–12/09
ATmega8U2/16U2/32U2
137
7799C–AVR–12/09
ATmega8U2/16U2/32U2
17.1 Features
• 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 Flag Protection
• Wake-up from Idle Mode
• Double Speed (CK/2) Master SPI Mode
17.2 Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
ATmega8U2/16U2/32U2 and peripheral devices or between several AVR devices.
USART can also be used in Master SPI mode, see “USART in SPI Mode” on page 176.
The Power Reduction SPI bit, PRSPI, in “Minimizing Power Consumption” on page 44 on page
50 must be written to zero to enable SPI module.
DIVIDER
/2/4/8/16/32/64/128
SPI2X
SPI2X
Note: 1. Refer to Figure 1-1 on page 2, and Table 12-6 on page 77 for SPI pin placement.
138
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The interconnection between Master and Slave CPUs with SPI is shown in Figure 17-2. The sys-
tem 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 Mas-
ter 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.
SHIFT
ENABLE
The system is single buffered in the transmit direction and double buffered in the receive direc-
tion. 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. Oth-
erwise, 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.
139
7799C–AVR–12/09
ATmega8U2/16U2/32U2
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden
according to Table 17-1. For more details on automatic port overrides, refer to “Alternate Port
Functions” on page 72.
Note: 1. See “Alternate Functions of Port B” on page 74 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.
140
7799C–AVR–12/09
ATmega8U2/16U2/32U2
SPI_MasterTransmit:
; Start transmission of data (r16)
out SPDR,r16
Wait_Transmit:
; Wait for transmission complete
sbis SPSR,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);
}
141
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The following code examples show how to initialize the SPI as a Slave and how to perform a
simple reception.
SPI_SlaveReceive:
; Wait for reception complete
sbis SPSR,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;
}
142
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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.
143
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 LSB
LSB first (DORD = 1) LSB Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 MSB
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) MSB Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 LSB
LSB first (DORD = 1) LSB Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 MSB
144
7799C–AVR–12/09
ATmega8U2/16U2/32U2
145
7799C–AVR–12/09
ATmega8U2/16U2/32U2
146
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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 regis-
ter causes the Shift Register Receive buffer to be read.
147
7799C–AVR–12/09
ATmega8U2/16U2/32U2
18. USART
18.1 Features
• Full Duplex Operation (Independent Serial Receive and Transmit Registers)
• Asynchronous or Synchronous Operation
• Flow control CTS/RTS signals hardware management
• Master or Slave Clocked Synchronous Operation
• High Resolution Baud Rate Generator
• Supports Serial Frames with 5, 6, 7, 8, or 9 Data Bits and 1 or 2 Stop Bits
• Odd or Even Parity Generation and Parity Check Supported by Hardware
• Data OverRun Detection
• Framing Error Detection
• Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter
• Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete
• Multi-processor Communication Mode
• Double Speed Asynchronous Communication Mode
18.2 Overview
The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a
highly flexible serial communication device.
A simplified block diagram of the USART Transmitter is shown in Figure 18-1 on page 149. CPU
accessible I/O Registers and I/O pins are shown in bold.
148
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Clock Generator
UBRR[H:L]
OSC
Transmitter
TX
UDR (Transmit)
CONTROL
PARITY
GENERATOR
DATA BUS
PIN
TRANSMIT SHIFT REGISTER TxD
CONTROL
Receiver
CLOCK RX
RECOVERY CONTROL
DATA PIN
RECEIVE SHIFT REGISTER RxD
RECOVERY CONTROL
PARITY
UDR (Receive)
CHECKER
Note: 1. See Figure 1-1 on page 2, Table 12-9 on page 79 and for USART pin placement.
The dashed boxes in the block diagram separate the three main parts of the USART (listed from
the top): Clock Generator, Transmitter and Receiver. Control Registers are shared by all units.
The Clock Generation logic consists of synchronization logic for external clock input used by
synchronous slave operation, and the baud rate generator. The XCKn (Transfer Clock) pin is
only used by synchronous transfer mode. The Transmitter consists of a single write buffer, a
serial Shift Register, Parity Generator and Control logic for handling different serial frame for-
mats. The write buffer allows a continuous transfer of data without any delay between frames.
The Receiver is the most complex part of the USART module due to its clock and data recovery
units. The recovery units are used for asynchronous data reception. In addition to the recovery
units, the Receiver includes a Parity Checker, Control logic, a Shift Register and a two level
receive buffer (UDRn). The Receiver supports the same frame formats as the Transmitter, and
can detect Frame Error, Data OverRun and Parity Errors.
149
7799C–AVR–12/09
ATmega8U2/16U2/32U2
for the XCKn pin (DDR_XCKn) controls whether the clock source is internal (Master mode) or
external (Slave mode). The XCKn pin is only active when using synchronous mode.
Figure 18-2 shows a block diagram of the clock generation logic.
Prescaling UBRR+1
/2 /4 /2
Down-Counter 0
1
0
OSC txclk
1
DDR_XCK
Sync Edge
xcki Register Detector 0
XCK UMSEL
xcko 1
Pin
DDR_XCK UCPOL 1
rxclk
0
Signal description:
150
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 18-1 contains equations for calculating the baud rate (in bits per second) and for calculat-
ing the UBRRn value for each mode of operation using an internally generated clock source.
f OSC
-–1
UBRRn = -------------------
8BAUD
f OSC
-–1
UBRRn = -------------------
2BAUD
f OSC
Synchronous Master mode BAUD = --------------------------------------
-
2 ( UBRRn + 1 )
Note: 1. The baud rate is defined to be the transfer rate in bit per second (bps)
BAUD Baud rate (in bits per second, bps)
fOSC System Oscillator clock frequency
UBRRn Contents of the UBRRHn and UBRRLn Registers, (0-4095)
Some examples of UBRRn values for some system clock frequencies are found in Table 18-9 on
page 172.
151
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note that fosc depends on the stability of the system clock source. It is therefore recommended to
add some margin to avoid possible loss of data due to frequency variations.
UCPOL = 1 XCK
RxD / TxD
Sample
UCPOL = 0 XCK
RxD / TxD
Sample
The UCPOLn bit UCRSC selects which XCKn clock edge is used for data sampling and which is
used for data change. As Figure 18-3 shows, when UCPOLn is zero the data will be changed at
rising XCKn edge and sampled at falling XCKn edge. If UCPOLn is set, the data will be changed
at falling XCKn edge and sampled at rising XCKn edge.
152
7799C–AVR–12/09
ATmega8U2/16U2/32U2
A frame starts with the start bit followed by the least significant data bit. Then the next data bits,
up to a total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit
is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can
be directly followed by a new frame, or the communication line can be set to an idle (high) state.
Figure 18-4 illustrates the possible combinations of the frame formats. Bits inside brackets are
optional.
(IDLE) St 0 1 2 3 4 [5] [6] [7] [8] [P] Sp1 [Sp2] (St / IDLE)
P even = d n – 1 ⊕ … ⊕ d 3 ⊕ d 2 ⊕ d 1 ⊕ d 0 ⊕ 0
P odd = d n – 1 ⊕ … ⊕ d 3 ⊕ d 2 ⊕ d 1 ⊕ d 0 ⊕ 1
153
7799C–AVR–12/09
ATmega8U2/16U2/32U2
154
7799C–AVR–12/09
ATmega8U2/16U2/32U2
155
7799C–AVR–12/09
ATmega8U2/16U2/32U2
show a transmit function that handles 9-bit characters. For the assembly code, the data to be
sent is assumed to be stored in registers R17:R16.
Notes: 1. These transmit functions are written to be general functions. They can be optimized if the con-
tents of the UCSRnB is static. For example, only the TXB8 bit of the UCSRnB Register is used
after initialization.
2. See “Code Examples” on page 6.
The ninth bit can be used for indicating an address frame when using multi processor communi-
cation mode or for other protocol handling as for example synchronization.
156
7799C–AVR–12/09
ATmega8U2/16U2/32U2
UDRn in order to clear UDREn or disable the Data Register Empty interrupt, otherwise a new
interrupt will occur once the interrupt routine terminates.
The Transmit Complete (TXCn) Flag bit is set one when the entire frame in the Transmit Shift
Register has been shifted out and there are no new data currently present in the transmit buffer.
The TXCn Flag bit is automatically cleared when a transmit complete interrupt is executed, or it
can be cleared by writing a one to its bit location. The TXCn Flag is useful in half-duplex commu-
nication interfaces (like the RS-485 standard), where a transmitting application must enter
receive mode and free the communication bus immediately after completing the transmission.
When the Transmit Compete Interrupt Enable (TXCIEn) bit in UCSRnB is set, the USART
Transmit Complete Interrupt will be executed when the TXCn Flag becomes set (provided that
global interrupts are enabled). When the transmit complete interrupt is used, the interrupt han-
dling routine does not have to clear the TXCn Flag, this is done automatically when the interrupt
is executed.
157
7799C–AVR–12/09
ATmega8U2/16U2/32U2
bits of the data read from the UDRn will be masked to zero. The USART has to be initialized
before the function can be used.
158
7799C–AVR–12/09
ATmega8U2/16U2/32U2
159
7799C–AVR–12/09
ATmega8U2/16U2/32U2
160
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The UPEn bit is set if the next character that can be read from the receive buffer had a Parity
Error when received and the Parity Checking was enabled at that point (UPMn1 = 1). This bit is
valid until the receive buffer (UDRn) is read.
161
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Sample
(U2X = 0) 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3
Sample
(U2X = 1) 0 1 2 3 4 5 6 7 8 1 2
When the clock recovery logic detects a high (idle) to low (start) transition on the RxDn line, the
start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in
the figure. The clock recovery logic then uses samples 8, 9, and 10 for Normal mode, and sam-
ples 4, 5, and 6 for Double Speed mode (indicated with sample numbers inside boxes on the
figure), to decide if a valid start bit is received. If two or more of these three samples have logical
high levels (the majority wins), the start bit is rejected as a noise spike and the Receiver starts
looking for the next high to low-transition. If however, a valid start bit is detected, the clock recov-
ery logic is synchronized and the data recovery can begin. The synchronization process is
repeated for each start bit.
RxD BIT n
Sample
(U2X = 0) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1
Sample
(U2X = 1) 1 2 3 4 5 6 7 8 1
The decision of the logic level of the received bit is taken by doing a majority voting of the logic
value to the three samples in the center of the received bit. The center samples are emphasized
on the figure by having the sample number inside boxes. The majority voting process is done as
follows: If two or all three samples have high levels, the received bit is registered to be a logic 1.
If two or all three samples have low levels, the received bit is registered to be a logic 0. This
majority voting process acts as a low pass filter for the incoming signal on the RxDn pin. The
recovery process is then repeated until a complete frame is received. Including the first stop bit.
Note that the Receiver only uses the first stop bit of a frame.
Figure 18-7 shows the sampling of the stop bit and the earliest possible beginning of the start bit
of the next frame.
162
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 18-7. Stop Bit Sampling and Next Start Bit Sampling
Sample
(U2X = 0) 1 2 3 4 5 6 7 8 9 10 0/1 0/1 0/1
Sample
(U2X = 1) 1 2 3 4 5 6 0/1
The same majority voting is done to the stop bit as done for the other bits in the frame. If the stop
bit is registered to have a logic 0 value, the Frame Error (FEn) Flag will be set.
A new high to low transition indicating the start bit of a new frame can come right after the last of
the bits used for majority voting. For Normal Speed mode, the first low level sample can be at
point marked (A) in Figure 18-7. For Double Speed mode the first low level must be delayed to
(B). (C) marks a stop bit of full length. The early start bit detection influences the operational
range of the Receiver.
( D + 1 )S
R slow = ------------------------------------------ ( D + 2 )S
R fast = -----------------------------------
-
S – 1 + D ⋅ S + SF ( D + 1 )S + S M
163
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 18-2. Recommended Maximum Receiver Baud Rate Error for Normal Speed Mode (U2Xn = 0)
D Recommended Max Receiver
# (Data+Parity Bit) Rslow (%) Rfast (%) Max Total Error (%) Error (%)
5 93.20 106.67 +6.67/-6.8 ± 3.0
6 94.12 105.79 +5.79/-5.88 ± 2.5
7 94.81 105.11 +5.11/-5.19 ± 2.0
8 95.36 104.58 +4.58/-4.54 ± 2.0
9 95.81 104.14 +4.14/-4.19 ± 1.5
10 96.17 103.78 +3.78/-3.83 ± 1.5
Table 18-3. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode (U2Xn = 1)
D Recommended Max Receiver
# (Data+Parity Bit) Rslow (%) Rfast (%) Max Total Error (%) Error (%)
5 94.12 105.66 +5.66/-5.88 ± 2.5
6 94.92 104.92 +4.92/-5.08 ± 2.0
7 95.52 104,35 +4.35/-4.48 ± 1.5
8 96.00 103.90 +3.90/-4.00 ± 1.5
9 96.39 103.53 +3.53/-3.61 ± 1.5
10 96.70 103.23 +3.23/-3.30 ± 1.0
The recommendations of the maximum receiver baud rate error was made under the assump-
tion that the Receiver and Transmitter equally divides the maximum total error.
There are two possible sources for the receivers baud rate error. The Receiver’s system clock
(XTAL) will always have some minor instability over the supply voltage range and the tempera-
ture range. When using a crystal to generate the system clock, this is rarely a problem, but for a
resonator the system clock may differ more than 2% depending of the resonators tolerance. The
second source for the error is more controllable. The baud rate generator can not always do an
exact division of the system frequency to get the baud rate wanted. In this case an UBRR value
that gives an acceptable low error can be used if possible.
164
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The Multi-processor Communication mode enables several slave MCUs to receive data from a
master MCU. This is done by first decoding an address frame to find out which MCU has been
addressed. If a particular slave MCU has been addressed, it will receive the following data
frames as normal, while the other slave MCUs will ignore the received frames until another
address frame is received.
165
7799C–AVR–12/09
ATmega8U2/16U2/32U2
stop sending characters. RTS usage and so associated flow control is enabled using RTSEN bit
in UCSRnD.
Figure 18-8. shows a reception example.
CPU Read
RXD C1 C2 C3
RTS
RTS
RTS will rise at 2/3 of the last received stop bit if the receive fifo is full.
To ensure reliable transmissions, even after a RTS rise, an extra-data can still be received and
stored in the Receive Shift Register.
CTS
166
7799C–AVR–12/09
ATmega8U2/16U2/32U2
The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the
same I/O address referred to as USART Data Register or UDRn. The Transmit Data Buffer Reg-
ister (TXB) will be the destination for data written to the UDRn Register location. Reading the
UDRn Register location will return the contents of the Receive Data Buffer Register (RXB).
For 5-, 6-, or 7-bit characters the upper unused bits will be ignored by the Transmitter and set to
zero by the Receiver.
The transmit buffer can only be written when the UDREn Flag in the UCSRnA Register is set.
Data written to UDRn when the UDREn Flag is not set, will be ignored by the USART Transmit-
ter. When data is written to the transmit buffer, and the Transmitter is enabled, the Transmitter
will load the data into the Transmit Shift Register when the Shift Register is empty. Then the
data will be serially transmitted on the TxDn pin.
The receive buffer consists of a two level FIFO. The FIFO will change its state whenever the
receive buffer is accessed. Due to this behavior of the receive buffer, do not use Read-Modify-
Write instructions (SBI and CBI) on this location. Be careful when using bit test instructions
(SBIC and SBIS), since these also will change the state of the FIFO.
167
7799C–AVR–12/09
ATmega8U2/16U2/32U2
168
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. See “USART in SPI Mode” on page 176 for full description of the Master SPI Mode (MSPIM)
operation
169
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Receiver will generate a parity value for the incoming data and compare it to the UPMn setting.
If a mismatch is detected, the UPEn Flag in UCSRnA will be set.
170
7799C–AVR–12/09
ATmega8U2/16U2/32U2
171
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 18-9. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies
fosc = 1.0000 MHz fosc = 1.8432 MHz fosc = 2.0000 MHz
Baud
U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1
Rate
(bps) UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error
2400 25 0.2% 51 0.2% 47 0.0% 95 0.0% 51 0.2% 103 0.2%
4800 12 0.2% 25 0.2% 23 0.0% 47 0.0% 25 0.2% 51 0.2%
9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2%
14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1%
19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2%
28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5%
38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0%
57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5%
76.8k – – 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5%
115.2k – – 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5%
230.4k – – – – – – 0 0.0% – – – –
250k – – – – – – – – – – 0 0.0%
(1)
Max. 62.5 kbps 125 kbps 115.2 kbps 230.4 kbps 125 kbps 250 kbps
1. UBRR = 0, Error = 0.0%
172
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 18-10. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued)
fosc = 3.6864 MHz fosc = 4.0000 MHz fosc = 7.3728 MHz
Baud
U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1
Rate
(bps) UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error
2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0%
4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0%
9600 23 0.0% 47 0.0% 25 0.2% 51 0.2% 47 0.0% 95 0.0%
14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0%
19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.0% 47 0.0%
28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0%
38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0%
57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0%
76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0%
115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0%
230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0%
250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8%
0.5M – – 0 -7.8% – – 0 0.0% 0 -7.8% 1 -7.8%
1M – – – – – – – – – – 0 -7.8%
(1)
Max. 230.4 kbps 460.8 kbps 250 kbps 0.5 Mbps 460.8 kbps 921.6 kbps
1. UBRR = 0, Error = 0.0%
173
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 18-11. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued)
fosc = 8.0000 MHz fosc = 11.0592 MHz fosc = 14.7456 MHz
Baud
U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1
Rate
(bps) UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error
2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0%
4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0%
9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0%
14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0%
19.2k 25 0.2% 51 0.2% 35 0.0% 71 0.0% 47 0.0% 95 0.0%
28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0%
38.4k 12 0.2% 25 0.2% 17 0.0% 35 0.0% 23 0.0% 47 0.0%
57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0%
76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0%
115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0%
230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0%
250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3%
0.5M 0 0.0% 1 0.0% – – 2 -7.8% 1 -7.8% 3 -7.8%
1M – – 0 0.0% – – – – 0 -7.8% 1 -7.8%
(1)
Max. 0.5 Mbps 1 Mbps 691.2 kbps 1.3824 Mbps 921.6 kbps 1.8432 Mbps
1. UBRR = 0, Error = 0.0%
174
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 18-12. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued)
fosc = 16.0000 MHz fosc = 18.4320 MHz fosc = 20.0000 MHz
Baud
U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1
Rate
(bps) UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error
2400 416 -0.1% 832 0.0% 479 0.0% 959 0.0% 520 0.0% 1041 0.0%
4800 207 0.2% 416 -0.1% 239 0.0% 479 0.0% 259 0.2% 520 0.0%
9600 103 0.2% 207 0.2% 119 0.0% 239 0.0% 129 0.2% 259 0.2%
14.4k 68 0.6% 138 -0.1% 79 0.0% 159 0.0% 86 -0.2% 173 -0.2%
19.2k 51 0.2% 103 0.2% 59 0.0% 119 0.0% 64 0.2% 129 0.2%
28.8k 34 -0.8% 68 0.6% 39 0.0% 79 0.0% 42 0.9% 86 -0.2%
38.4k 25 0.2% 51 0.2% 29 0.0% 59 0.0% 32 -1.4% 64 0.2%
57.6k 16 2.1% 34 -0.8% 19 0.0% 39 0.0% 21 -1.4% 42 0.9%
76.8k 12 0.2% 25 0.2% 14 0.0% 29 0.0% 15 1.7% 32 -1.4%
115.2k 8 -3.5% 16 2.1% 9 0.0% 19 0.0% 10 -1.4% 21 -1.4%
230.4k 3 8.5% 8 -3.5% 4 0.0% 9 0.0% 4 8.5% 10 -1.4%
250k 3 0.0% 7 0.0% 4 -7.8% 8 2.4% 4 0.0% 9 0.0%
0.5M 1 0.0% 3 0.0% – – 4 -7.8% – – 4 0.0%
1M 0 0.0% 1 0.0% – – – – – – – –
(1)
Max. 1 Mbps 2 Mbps 1.152 Mbps 2.304 Mbps 1.25 Mbps 2.5 Mbps
1. UBRR = 0, Error = 0.0%
175
7799C–AVR–12/09
ATmega8U2/16U2/32U2
19.1 Features
• Full Duplex, Three-wire Synchronous Data Transfer
• Master Operation
• Supports all four SPI Modes of Operation (Mode 0, 1, 2, and 3)
• LSB First or MSB First Data Transfer (Configurable Data Order)
• Queued Operation (Double Buffered)
• High Resolution Baud Rate Generator
• High Speed Operation (fXCKmax = fCK/2)
• Flexible Interrupt Generation
19.2 Overview
The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) can be
set to a master SPI compliant mode of operation. Setting both UMSELn1:0 bits to one enables
the USART in MSPIM logic. In this mode of operation the SPI master control logic takes direct
control over the USART resources. These resources include the transmitter and receiver shift
register and buffers, and the baud rate generator. The parity generator and checker, the data
and clock recovery logic, and the RX and TX control logic is disabled. The USART RX and TX
control logic is replaced by a common SPI transfer control logic. However, the pin control logic
and interrupt generation logic is identical in both modes of operation.
The I/O register locations are the same in both modes. However, some of the functionality of the
control registers changes when using MSPIM.
176
7799C–AVR–12/09
ATmega8U2/16U2/32U2
f OSC f OSC
Synchronous Master mode BAUD = --------------------------------------
- -–1
UBRRn = -------------------
2 ( UBRRn + 1 ) 2BAUD
Note: 1. The baud rate is defined to be the transfer rate in bit per second (bps)
BAUD Baud rate (in bits per second, bps)
fOSC System Oscillator clock frequency
UBRRn Contents of the UBRRnH and UBRRnL Registers, (0-4095)
XCK XCK
XCK XCK
177
7799C–AVR–12/09
ATmega8U2/16U2/32U2
178
7799C–AVR–12/09
ATmega8U2/16U2/32U2
179
7799C–AVR–12/09
ATmega8U2/16U2/32U2
transmitter controls the transfer clock. The data written to UDRn is moved from the transmit buf-
fer to the shift register when the shift register is ready to send a new frame.
Note: To keep the input buffer in sync with the number of data bytes transmitted, the UDRn register must
be read once for each byte transmitted. The input buffer operation is identical to normal USART
mode, i.e. if an overflow occurs the character last received will be lost, not the first data in the buf-
fer. This means that if four bytes are transferred, byte 1 first, then byte 2, 3, and 4, and the UDRn
is not read before all transfers are completed, then byte 3 to be received will be lost, and not byte
1.
The following code examples show a simple USART in MSPIM mode transfer function based on
polling of the Data Register Empty (UDREn) Flag and the Receive Complete (RXCn) Flag. The
USART has to be initialized before the function can be used. For the assembly code, the data to
be sent is assumed to be stored in Register R16 and the data received will be available in the
same register (R16) after the function returns.
The function simply waits for the transmit buffer to be empty by checking the UDREn Flag,
before loading it with new data to be transmitted. The function then waits for data to be present
in the receive buffer by checking the RXCn Flag, before reading the buffer and returning the
value..
180
7799C–AVR–12/09
ATmega8U2/16U2/32U2
•
Bit 7 6 5 4 3 2 1 0
RXCn TXCn UDREn - - - - - UCSRnA
Read/Write R/W R/W R/W R R R R R
Initial Value 0 0 0 0 0 1 1 0
181
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
RXCIEn TXCIEn UDRIE RXENn TXENn – – – UCSRnB
Read/Write R/W R/W R/W R/W R/W R R R
Initial Value 0 0 0 0 0 1 1 0
182
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
UMSELn1 UMSELn0 – – – UDORDn UCPHAn UCPOLn UCSRnC
Read/Write R/W R/W R R R R/W R/W R/W
Initial Value 0 0 0 0 0 1 1 0
183
7799C–AVR–12/09
ATmega8U2/16U2/32U2
However, since the USART in MSPIM mode reuses the USART resources, the use of the
USART in MSPIM mode is somewhat different compared to the SPI. In addition to differences of
the control register bits, and that only master operation is supported by the USART in MSPIM
mode, the following features differ between the two modules:
• The USART in MSPIM mode includes (double) buffering of the transmitter. The SPI has no
buffer.
• The USART in MSPIM mode receiver includes an additional buffer level.
• The SPI WCOL (Write Collision) bit is not included in USART in MSPIM mode.
• The SPI double speed mode (SPI2X) bit is not included. However, the same effect is
achieved by setting UBRRn accordingly.
• Interrupt timing is not compatible.
• Pin control differs due to the master only operation of the USART in MSPIM mode.
A comparison of the USART in MSPIM mode and the SPI pins is shown in Table 19-4 on page
184.
184
7799C–AVR–12/09
ATmega8U2/16U2/32U2
20.1 Features
• USB 2.0 Full-speed device
• Ping-pong mode (dual bank), with transparent switch
• 176 bytes of DPRAM
– 1 endpoint of 64 bytes max (default control endpoint)
– 2 endpoints of 64 bytes max (one bank)
– 2 endpoints of 64 bytes max (one or two banks)
20.2 Overview
The USB controller provides the hardware to implement a USB2.0 compliant Full-Speed USB
device in the ATmega8U2/16U2/32U2. A simplified block diagram of the USB controller is shown
in Figure 20-1 on page 185.
The USB controller requires a 48 MHz ±0.25% reference clock for USB Full-Speed compliance.
This clock is generated by an internal PLL. The reference clock to the PLL must be provided
from an external crystal or an external clock input. Only these two clock options will be able to
provide a reference clock within the accuracy and jitter requirements of the USB specification.
See section “System Clock and Clock Options” on page 26 for details on the
ATmega8U2/16U2/32U2 system clock and clock options.
To comply to the USB specifications electrical characteristics, the USB Pads (D+ or D-) must be
powered at 3.0V to 3.6V. As the ATmega8U2/16U2/32U2 can be powered up to 5.5V, an inter-
nal regulator is provided to correctly power the USB pads. See “USB Module Powering Options”
on page 186 for details on the powering options available for the USB controller
Regulator
clk
PLL 8MHz PLL clock
UCAP 6x Prescaler
clk
48MHz
D- CPU
DPLL
Clock
Recovery
D+
USB
Interface
On-Chip
USB DPRAM
185
7799C–AVR–12/09
ATmega8U2/16U2/32U2
5.5
16 MHz
USB compliant,
4.5 with internal regulator
4.0
3.6
8 MHz
USB compliant,
without internal regulator
3.0
2.7
USB not operational
2 MHz
VCC min
VCC AVCC
UCAP
1µF
VBUS UVCC
UDM D+
UDP D-
UVSS UVSS
VSS
XTAL1 XTAL2
186
7799C–AVR–12/09
ATmega8U2/16U2/32U2
VCC AVCC
UCAP
1µF
VBUS UVCC
UDM D+
UDP D-
UVSS UVSS
VSS
XTAL1 XTAL2
Figure 20-5. Typical Self powered application with 4.0V to 5.5V I/O(1)
UCAP
1µF
VBUS VBUS
UDP D+
Rs=22
UDM D-
Rs=22
UVSS UGND
UID UID
Note: 1. The internal 3.3V regulator is bypassed. Disable the regulator to avoid additional power con-
sumption. See the “REGCR – Regulator Control Register” on page 196 for details.
187
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 20-6. Typical Self powered application with 3.0V to 3.6 I/O
UCAP
1µF
VBUS VBUS
UDP D+
Rs=22
UDM D-
Rs=22
UVSS UGND
UID UID
188
7799C–AVR–12/09
ATmega8U2/16U2/32U2
20.4.1 Introduction
The USB controller is disabled and reset after a hardware reset generated by:
– Power on reset
– External reset
– Watchdog reset
– Brown out reset
– debugWIRE reset
– USB End Of Reset
In the case of USB End Of Reset (EOR), the USB controller is reset, but not disabled. Therefore
the device remains attached.
Reset
USBE = 1 HW RESET
(except from EOR)
USBE = 0
Device USBE = 0
HW RESET
(from EOR)
189
7799C–AVR–12/09
ATmega8U2/16U2/32U2
20.4.3 Interrupts
Two interrupts vectors are assigned to the USB controller.
USB Endpoint/Pipe
Interrupt Vector
Endpoint
Interrupt
The USB module distinguishes between USB General events and USB Endpoints events.
UPRSMI
UDINT.6
UPRSME
UDIEN.6
EORSMI
UDINT.5
EORSME
UDIEN.5
WAKEUPI
UDINT.4
WAKEUPE USB General
UDIEN.4 Interrupt Vector
EORSTI
UDINT.3
EORSTE
UDIEN.3
SOFI
UDINT.2
SOFE
UDIEN.2
SUSPI
UDINT.0 Asynchronous Interrupt source
SUSPE (allows the CPU to wake up from power down mode)
UDIEN.0
The WAKEUP interrupt allows device wake-up from power-down mode, and is an asynchronous
interrupt, triggering each time a state change is detected on the data lines. The other interrupts
are synchronous and will be detected only if the USB clock is enabled (FRZCLK bit set).
190
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Endpoint 4
Endpoint 3
Endpoint 2
Endpoint 1
Endpoint 0
OVERFI
UESTAX.6
UNDERFI
FLERRE
UESTAX.5
UEIENX.7
NAKINI
UEINTX.6
NAKINE
UEIENX.6
NAKOUTI
UEINTX.4
TXSTPE
UEIENX.4 USB Endpoi
Interrupt Vec
RXSTPI EPINT
UEINTX.3 UEINT.X
TXOUTE
UEIENX.3
RXOUTI
UEINTX.2
RXOUTE
UEIENX.2
STALLEDI
UEINTX.1
STALLEDE
UEIENX.1
TXINI
UEINTX.0
TXINE
UEIENX.0
Each endpoint has 8 interrupts sources associated with flags, and each source can be enabled
to trigger the corresponding endpoint interrupt.
If, for an endpoint, at least one of the sources is enabled to trigger interrupt, the corresponding
event(s) will make the program branch to the USB Endpoint Interrupt vector. The user may
determine the source (endpoint) of the interrupt by reading the “UDINT – USB Device Interrupt
Register” on page 210.
20.5.2 Power-down
In Power-down mode, the oscillator is stopped and halts all the clocks (CPU and peripherals).
The USB controller wakes up when:
• the WAKEUPI interrupt is triggered (single asynchronous interrupt)
191
7799C–AVR–12/09
ATmega8U2/16U2/32U2
4 4 4 4
Conflict
Lost memory 3
3 3
2
EPEN=0 3 2 (bigger size)
(ALLOC=1)
1 1 1 1
0 0 0 0
EPEN=1
ALLOC=1
192
7799C–AVR–12/09
ATmega8U2/16U2/32U2
• Endpoints activation:
Endpoint 0 to Endpoint 4 are configured, in the growing order. The memory of each is
reserved in the DPRAM.
• Endpoint disable:
The Endpoint 2 is disabled (EPEN=0), but its memory reservation is internally kept by the
controller.
• Free its memory:
The ALLOC bit is cleared: the Endpoint 3 slides down, but the Endpoint 4 does not slide.
• Endpoint activation:
The firmware chooses to reconfigure the Endpoint 2, but with a bigger size. The controller
reserved the memory after the endpoint 1 memory and automatically slide the Endpoint 3.
The Endpoint 4 does not move and a memory conflict appear, in that both Endpoint 3 and 4
use a common area. The data of those endpoints are potentially lost.
Note that:
• The data of Endpoint 0 is never lost at activation or deactivation of a higher Endpoint. The
data is lost only if the Endpoint 0 is deactivated.
• Deactivate and reactivate the same Endpoint with the same parameters does not lead to a
slide of the higher endpoints. For those endpoints, the data are preserved.
• CFGOK is set by hardware even in the case that there is a “conflict” in the memory allocation.
USBE=1
& DETACH=0
Idle mode & suspend
The SUSPI flag indicated that a suspend state has been detected on the USB bus. This flag
automatically put the USB pad in Idle. The detection of a non-idle event sets the WAKEUPI flag
and wakes-up the USB pad.
193
7799C–AVR–12/09
ATmega8U2/16U2/32U2
PAD status
Active Power Down Active
Moreover, the pad can also be put in the Idle mode if the DETACH bit is set. It come back in the
Active mode when the DETACH bit is cleared.
194
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xD8) USBE - FRZLK - - - - - USBCON
Read/Write R/W R R/W R R R R R
Initial Value 0 0 1 0 0 0 0 0
195
7799C–AVR–12/09
ATmega8U2/16U2/32U2
buffers.
196
7799C–AVR–12/09
ATmega8U2/16U2/32U2
21.1 Overview
The USB device controller supports full speed data transfers. In addition to the default control
endpoint, it provides four other endpoints, which can be configured in control, bulk, interrupt or
isochronous modes:
The controller starts in the “idle” mode. In this mode, the pad consumption is reduced to the
minimum.
<any
other
USBE=0 state>
USBE=0 Idle
Reset USBE=1
UID=1
HW
RESET
197
7799B–AVR–07/09
ATmega8U2/16U2/32U2
• the Rx and Tx banks are cleared and their internal pointers are restored,
• the UEINTX, UESTA0X and UESTA1X are restored to their reset value.
The data toggle field remains unchanged.
The other registers remain unchanged.
The endpoint configuration remains active and the endpoint is still enabled.
The endpoint reset may be associated with a clear of the data toggle command (RSTDT bit) as
an answer to the CLEAR_FEATURE USB command.
198
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Endpoint
Activation
UECFG0X Configure:
EPDIR - the endpoint direction
EPTYPE - the endpoint type
... - the Not Yet Disable feature
Configure:
UECFG1X - the endpoint size
ALLOC - the bank parametrization
EPSIZE Allocation and reorganization of
EPBK the memory is made on-the-fly
As long as the endpoint is not correctly configured (CFGOK cleared), the hardware does not
acknowledge the packets sent by the host.
CFGOK will not be set if the Endpoint size parameter is bigger than the DPRAM size.
A clear of EPEN acts as an endpoint reset (see “Endpoint reset” on page 197 for more details).
It also performs the next operation:
• The configuration of the endpoint is kept (EPSIZE, EPBK, ALLOC kept)
• It resets the data toggle field.
• The DPRAM memory associated to the endpoint is still reserved.
See “Memory management” on page 192 for more details about the memory
allocation/reorganization.
199
7799B–AVR–07/09
ATmega8U2/16U2/32U2
UADD contains the default address 00h after a power-up or an USB reset.
ADDEN is cleared by hardware:
• after a power-up reset,
• when an USB reset is received,
• or when the macro is disabled (USBE cleared)
When this bit is cleared, the default device address 00h is used.
21.9 Detach
The reset value of the DETACH bit is 1.
It is possible to re-enumerate a device, simply by setting and clearing the DETACH bit (the line
discharge time must be taken in account).
• When the USB device controller is in full-speed mode, setting DETACH will disconnect the
pull-up on the D+. Then, clearing DETACH will connect the pull-up on the D+.
D+ D+
D- D-
Detach, then
EN=1 Attach EN=1
200
7799B–AVR–07/09
ATmega8U2/16U2/32U2
201
7799B–AVR–07/09
ATmega8U2/16U2/32U2
RXOUTI HW SW HW SW
TXINI SW
202
7799B–AVR–07/09
ATmega8U2/16U2/32U2
RXOUTI HW SW
TXINI SW HW SW
Wr Enable
HOST
Wr Enable
CPU
Once the OUT status stage has been received, the USB controller waits for a SETUP request.
The SETUP request have priority over any other request and has to be ACK’ed. This means that
any other flag should be cleared and the fifo reset when a SETUP is received.
WARNING: the byte counter is reset when a OUT Zero Length Packet is received. The firmware
has to take care of this.
21.13.1 Overview
The Endpoint must be configured first.
203
7799B–AVR–07/09
ATmega8U2/16U2/32U2
HW HW
RXOUTI SW SW
DATA DATA
OUT ACK OUT ACK
(to bank 0) (to bank 1)
HW
HW
RXOUTI SW SW
204
7799B–AVR–07/09
ATmega8U2/16U2/32U2
• The CPU can free the bank by clearing FIFOCON when all the data is read, that is:
• after “N” read of UEDATX,
• as soon as RWAL is cleared by hardware.
If the endpoint uses 2 banks, the second one can be filled by the HOST while the current one is
being read by the CPU. Then, when the CPU clear FIFOCON, the next bank may be already
ready and RXOUTI is set immediately.
205
7799B–AVR–07/09
ATmega8U2/16U2/32U2
The RWAL bit always reflects the state of the current bank. This bit is set if the firmware can
write data to the bank, and cleared by hardware when the bank is full.
NAK IN
DATA
ACK IN
(bank 0)
HW
TXINI SW SW
DATA DATA
IN ACK IN ACK
(bank 0) (bank 1)
HW
TXINI SW SW SW
FIFOCON write data from CPU SW write data from CPU SW write data from CPU
BANK 0 BANK 1 BANK0
21.14.1.1 Abort
An “abort” stage can be produced by the host in some situations:
206
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Endpoint
Abort
No
Abort done
21.15.1 Underflow
An underflow can occur during IN stage if the host attempts to read a bank which is empty. In
this situation, the UNDERFI interrupt is triggered.
An underflow can also occur during OUT stage if the host send a packet while the banks are
already full. Typically, he CPU is not fast enough. The packet is lost.
It is not possible to have underflow error during OUT stage, in the CPU side, since the CPU
should read only if the bank is ready to give data (RXOUTI=1 or RWAL=1)
21.16 Overflow
In Control, Isochronous, Bulk or Interrupt Endpoint, an overflow can occur during OUT stage, if
the host attempts to write in a bank that is too small for the packet. In this situation, the OVERFI
interrupt is triggered (if enabled). The packet is acknowledged and the RXOUTI interrupt is also
triggered (if enabled). The bank is filled with the first bytes of the packet.
207
7799B–AVR–07/09
ATmega8U2/16U2/32U2
It is not possible to have overflow error during IN stage, in the CPU side, since the CPU should
write only if the bank is ready to access data (TXINI=1 or RWAL=1).
21.17 Interrupts
The next figure shows all the interrupts sources:
There are 2 kind of interrupts: processing (i.e. their generation are part of the normal processing)
and exception (errors).
Processing interrupts are generated when:
• Upstream resume(UPRSMI)
• End of resume(EORSMI)
• Wake up(WAKEUPI)
• End of reset (Speed Initialization)(EORSTI)
• Start of frame(SOFI, if FNCERR=0)
• Suspend detected after 3 ms of inactivity(SUSPI)
Exception Interrupts are generated when:
• CRC error in frame number of SOF(SOFI, FNCERR=1)
208
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Endpoint 3
Endpoint 2
Endpoint 1
Endpoint 0
OVERFI
UESTAX.6
UNDERFI
FLERRE
UESTAX.5
UEIENX.7
NAKINI
UEINTX.6
NAKINE
UEIENX.6
NAKOUTI
UEINTX.4
TXSTPE
Endpoint Interrupt
UEIENX.4
RXSTPI EPINT
UEINTX.3 UEINT.X
TXOUTE
UEIENX.3
RXOUTI
UEINTX.2
RXOUTE
UEIENX.2
STALLEDI
UEINTX.1
STALLEDE
UEIENX.1
TXINI
UEINTX.0
TXINE
UEIENX.0
Bit 7 6 5 4 3 2 1 0
(0xE0) - - - - - RSTCPU RMWKUP DETACH UDCON
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 1
209
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xE1) - UPRSMI EORSMI WAKEUPI EORSTI SOFI - SUSPI UDINT
Read/Write R R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
210
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xE2) - UPRSME EORSME WAKEUPE EORSTE SOFE - SUSPE UDIEN
Read/Write R R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
211
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xE3) ADDEN UADD[6:0] UDADDR
Read/Write R/W R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
212
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xE5) - - - - - FNUM[10:8] UDFNUMH
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0xE4) FNUM[7:0] UDFNUML
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0xE6) - - - FNCERR - - - - UDMFN
Read/Write R R R R/W R R R R
Initial Value 0 0 0 0 0 0 0 0
213
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xE9) - - - - - EPNUM[2:0] UENUM
Read/Write R R R R R 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
(0xEA) - - - EPRST D4 EPRST D3 EPRST D2 EPRST D1 EPRST D0 UERST
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
Bit 7 6 5 4 3 2 1 0
(0xEB) - - STALLRQ STALLRQC RSTDT - - EPEN UECONX
Read/Write R R R/W R/W R/W R R R/W
Initial Value 0 0 0 0 0 0 0 0
214
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xEC) EPTYPE1:0 - - - - - EPDIR UECFG0X
Read/Write R/W R/W R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
215
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xED) - EPSIZE[2:0] EPBK1:0 ALLOC - UECFG1X
Read/Write R R/W R/W R/W R/W R/W R/W R
Initial Value 0 0 0 0 0 0 0 0
216
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xEE) CFGOK OVERFI UNDERFI - DTSEQ1:0 NBUSYBK1:0 UESTA0X
Read/Write R R/W R/W R R R R R
Initial Value 0 0 0 0 0 0 0 0
217
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xEF) - - - - - CTRLDIR CURRBK[1:0] UESTA1X
Read/Write R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
218
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xE8) FIFOCON NAKINI RWAL NAKOUTI RXSTPI RXOUTI STALLEDI TXINI UEINTX
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
219
7799B–AVR–07/09
ATmega8U2/16U2/32U2
This flag is set by the USB controller when the current bank contains a new packet. This
RXOUTI flag can generate a “USB endpoint interrupt” if RXOUTE bit is set. Writing this bit to
zero acknowledges the interrupt source (USB clocks must be enabled before). Writing this bit to
one has no effect for an OUT endpoint.
• Endpoint IN direction (KILLBK bit)
Writing this bit to one kills the last loaded bank. This sequence can be used to cancelled a previ-
ously loaded endpoint. Clearing by software has no effect. See page 206 for more details on the
Abort.
Bit 7 6 5 4 3 2 1 0
(0xF0) FLERRE NAKINE - NAKOUTE RXSTPE RXOUTE STALLEDE TXINE UEIENX
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
220
7799B–AVR–07/09
ATmega8U2/16U2/32U2
Bit 7 6 5 4 3 2 1 0
(0xF1) DAT D7 DAT D6 DAT D5 DAT D4 DAT D3 DAT D2 DAT D1 DAT D0 UEDATX
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0xF2) BYCT D7 BYCT D6 BYCT D5 BYCT D4 BYCT D3 BYCT D2 BYCT D1 BYCT D0 UEBCLX
Read/Write R R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
221
7799B–AVR–07/09
ATmega8U2/16U2/32U2
This register contains the number of received byte into the current bank of the selected end-
point. The content of this register is decremented after each write access to the endpoint data
register.
Bit 7 6 5 4 3 2 1 0
(0xF4) - - - EPINT4:0 UEINT
Read/Write R R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
222
7799B–AVR–07/09
ATmega8U2/16U2/32U2
22.1 Overview
The Analog Comparator compares the input values on the positive pin AIN0 and negative pin
AIN1. When the voltage on the positive pin AIN0 is higher than the voltage on the negative pin
AIN1, the Analog Comparator output, ACO, is set. The comparator’s output can be set to trigger
the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate
interrupt, exclusive to the Analog Comparator. The user can select Interrupt triggering on com-
parator output rise, fall or toggle. A block diagram of the comparator and its surrounding logic is
shown in Figure 22-1. User can also replace by software the AIN0 input by the internal Bandgap
reference.
ACBG
AIN0
ACMUX
AIN2
AIN3
AIN4
AIN5
AIN6
Notes: 1. Refer to Figure 1-1 on page 2 and Table 12-9 on page 79 for Analog Comparator pin
placement.
223
7799C–AVR–12/09
ATmega8U2/16U2/32U2
224
7799C–AVR–12/09
ATmega8U2/16U2/32U2
When changing the ACIS1/ACIS0 bits, the Analog Comparator Interrupt must be disabled by
clearing its Interrupt Enable bit in the ACSR Register. Otherwise an interrupt can occur when the
bits are changed.
225
7799C–AVR–12/09
ATmega8U2/16U2/32U2
23.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: 1. A page is a section in the Flash consisting of several bytes (see Table 25-7 on page 249) used
during programming. The page organization does not affect normal operation.
23.2 Overivew
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 applica-
tion software updates controlled by the MCU using a Flash-resident Boot Loader program. The
Boot Loader program can use any available data interface and associated protocol to read code
and write (program) that code into the Flash memory, or read the code from the program mem-
ory. The program code within the Boot Loader section has the capability to write into the entire
Flash, including the Boot Loader memory. The Boot Loader can thus even modify itself, and it
can also erase itself from the code if the feature is not needed anymore. The size of the Boot
Loader memory is configurable with fuses and the Boot Loader has two separate sets of Boot
Lock bits which can be set independently. This gives the user a unique flexibility to select differ-
ent levels of protection.
226
7799C–AVR–12/09
ATmega8U2/16U2/32U2
227
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Read-While-Write
(RWW) Section
Z-pointer
Addresses NRWW
Z-pointer Section
Addresses RWW No Read-While-Write
Section (NRWW) Section
CPU is Halted
During the Operation
Code Located in
NRWW Section
Can be Read During
the Operation
228
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Read-While-Write Section
Read-While-Write Section
Application Flash Section Application Flash Section
No Read-While-Write Section
No Read-While-Write Section
End RWW End RWW
Start NRWW Start NRWW
End Application
End Application Start Boot Loader
Start Boot Loader Boot Loader Flash Section
Boot Loader Flash Section
Flashend Flashend
Read-While-Write Section
Application Flash Section Application Flash Section
No Read-While-Write Section
End RWW
Start NRWW Start NRWW, Start Boot Loader
Application Flash Section
End Application
Boot Loader Flash Section
Start Boot Loader
Boot Loader Flash Section
Flashend Flashend
Note: 1. The parameters in the figure above are given in Table 23-8 on page 239.
229
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 23-3. Boot Lock Bit1 Protection Modes (Boot Loader Section)(1)
BLB1 Mode BLB12 BLB11 Protection
No restrictions for SPM or (E)LPM accessing the Boot Loader
1 1 1
section.
2 1 0 SPM is not allowed to write to the Boot Loader section.
SPM is not allowed to write to the Boot Loader section, and
(E)LPM executing from the Application section is not allowed to
3 0 0 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.
(E)LPM executing from the Application section is not allowed to
read from the Boot Loader section. If Interrupt Vectors are
4 0 1
placed in the Application section, interrupts are disabled while
executing from the Boot Loader section.
Note: 1. “1” means unprogrammed, “0” means programmed
230
7799C–AVR–12/09
ATmega8U2/16U2/32U2
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.
231
7799C–AVR–12/09
ATmega8U2/16U2/32U2
RESET
tSHRH tHHRH
PD7/HWB
HWBE ?
Ext. Hardware
Conditions ?
BOOTRST ?
232
7799C–AVR–12/09
ATmega8U2/16U2/32U2
PCMSB PAGEMSB
PROGRAM
PCPAGE PCWORD
COUNTER
01
02
PAGEEND
Note: 1. The different variables used in Figure 23-4 are listed in Table 23-10 on page 239.
233
7799C–AVR–12/09
ATmega8U2/16U2/32U2
234
7799C–AVR–12/09
ATmega8U2/16U2/32U2
RWWSB by writing the RWWSRE. See “Simple Assembly Code Example for a Boot Loader” on
page 237 for an example.
See Table 23-2 and Table 23-3 for how the different settings of the Boot Loader bits affect the
Flash access.
If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock bit will be programmed if an
SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCSR.
The Z-pointer is don’t care during this operation, but for future compatibility it is recommended to
load the Z-pointer with 0x0001 (same as used for reading the lOck bits). For future compatibility it
is also recommended to set bits 7, 6, 1, and 0 in R0 to “1” when writing the Lock bits. When pro-
gramming the Lock bits the entire Flash can be read during the operation.
The algorithm for reading the Fuse Low byte is similar to the one described above for reading
the Lock bits. To read the Fuse Low byte, load the Z-pointer with 0x0000 and set the BLBSET
and SPMEN bits in SPMCSR. When an (E)LPM instruction is executed within three cycles after
the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low byte (FLB) will
be loaded in the destination register as shown below. Refer to Table 25-5 on page 248 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 (E)LPM
instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the
SPMCSR, the value of the Fuse High byte (FHB) will be loaded in the destination register as
235
7799C–AVR–12/09
ATmega8U2/16U2/32U2
shown below. Refer to Table 25-4 on page 248 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
When reading the Extended Fuse byte, load 0x0002 in the Z-pointer. When an (E)LPM instruc-
tion is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR,
the value of the Extended Fuse byte (EFB) will be loaded in the destination register as shown
below. Refer to Table 25-3 on page 247 for detailed description and mapping of the Extended
Fuse byte.
Bit 7 6 5 4 3 2 1 0
Rd – – – – – EFB2 EFB1 EFB0
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are
unprogrammed, will be read as one.
236
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Flash corruption can easily be avoided by following these design recommendations (one is
sufficient):
1. If there is no need for a Boot Loader update in the system, program the Boot Loader
Lock bits to prevent any Boot Loader software updates.
2. Keep the AVR RESET active (low) during periods of insufficient power supply voltage.
This can be done by enabling the internal Brown-out Detector (BOD) if the operating
voltage matches the detection level. If not, an external low VCC reset protection circuit
can be used. If a reset occurs while a write operation is in progress, the write operation
will be completed provided that the power supply voltage is sufficient.
3. Keep the AVR core in Power-down sleep mode during periods of low VCC. This will pre-
vent the CPU from attempting to decode and execute instructions, effectively protecting
the SPMCSR Register and thus the Flash from unintentional writes.
237
7799C–AVR–12/09
ATmega8U2/16U2/32U2
call Do_spm
adiw ZH:ZL, 2
sbiw loophi:looplo, 2 ;use subi for PAGESIZEB<=256
brne Wrloop
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, EEPE
rjmp Wait_ee
; SPM timed sequence
out SPMCSR, spmcrval
spm
; restore SREG (to enable interrupts if originally enabled)
out SREG, temp2
ret
238
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Reset Address
Flash Section
Flash Section
Loader Section)
BOOTSZ1
BOOTSZ0
Boot Size
Boot Loader
Application
Application
(Start Boot
Section
Pages
Boot
End
1 1 256 words 4 0x0000 - 0xEFF 0xF00 - 0xFFF 0xEFF 0xF00
1 0 512 words 8 0x0000 - 0xDFF 0xE00 - 0xFFF 0xDFF 0xE00
0 1 1024 words 16 0x0000 - 0xBFF 0xC00 - 0xFFF 0xBFF 0xC00
0 0 2048 words 32 0x0000 - 0x7FF 0x800 - 0xFFF 0x7FF 0x800
Table 23-10. Explanation of different variables used in Figure 23-4 and the mapping to the Z-pointer
Corresponding
Variable Z-value Description(1)
Most significant bit in the Program Counter. (The Program
PCMSB 12
Counter is 13 bits PC[12:0])
Most significant bit which is used to address the words within
PAGEMSB 5
one page (64 words in a page requires six bits PC [5:0]).
Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not
ZPCMSB Z13
used, the ZPCMSB equals PCMSB + 1.
Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not
ZPAGEMSB Z6
used, the ZPAGEMSB equals PAGEMSB + 1.
Program Counter page address: Page select, for Page Erase
PCPAGE PC[12:6] Z13:Z7
and Page Write
Program Counter word address: Word select, for filling
PCWORD PC[5:0] Z6:Z1
temporary buffer (must be zero during Page Write operation)
Note: 1. Z0: should be zero for all SPM commands, byte select for the (E)LPM instruction.
See “Addressing the Flash During Self-Programming” on page 232 for details about the use of Z-pointer during Self-
Programming.
239
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Reset Address
Flash Section
Flash Section
Loader Section)
BOOTSZ1
BOOTSZ0
Boot Size
Boot Loader
Application
Application
(Start Boot
Section
Pages
Boot
End
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
Table 23-13. Explanation of different variables used in Figure 23-4 and the mapping to the Z-pointer
Corresponding
Variable Z-value Description(1)
Most significant bit in the Program Counter. (The Program
PCMSB 12
Counter is 13 bits PC[12:0])
Most significant bit which is used to address the words within
PAGEMSB 5
one page (64 words in a page requires six bits PC [5:0]).
Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not
ZPCMSB Z13
used, the ZPCMSB equals PCMSB + 1.
Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not
ZPAGEMSB Z6
used, the ZPAGEMSB equals PAGEMSB + 1.
Program Counter page address: Page select, for Page Erase
PCPAGE PC[12:6] Z13:Z7
and Page Write
Program Counter word address: Word select, for filling
PCWORD PC[5:0] Z6:Z1
temporary buffer (must be zero during Page Write operation)
Note: 1. Z0: should be zero for all SPM commands, byte select for the (E)LPM instruction.
See “Addressing the Flash During Self-Programming” on page 232 for details about the use of Z-pointer during Self-
Programming.
240
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Reset Address
Flash Section
Flash Section
Loader Section)
BOOTSZ1
BOOTSZ0
Boot Size
Boot Loader
Application
Application
(Start Boot
Section
Pages
Boot
End
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
Table 23-16. Explanation of different variables used in Figure 23-4 and the mapping to the Z-pointer
Corresponding
Variable Z-value Description(1)
Most significant bit in the Program Counter. (The Program
PCMSB 12
Counter is 13 bits PC[12:0])
Most significant bit which is used to address the words within
PAGEMSB 5
one page (64 words in a page requires six bits PC [5:0]).
Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not
ZPCMSB Z13
used, the ZPCMSB equals PCMSB + 1.
Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not
ZPAGEMSB Z6
used, the ZPAGEMSB equals PAGEMSB + 1.
Program Counter page address: Page select, for Page Erase
PCPAGE PC[12:6] Z13:Z7
and Page Write
Program Counter word address: Word select, for filling
PCWORD PC[5:0] Z6:Z1
temporary buffer (must be zero during Page Write operation)
Note: 1. Z0: should be zero for all SPM commands, byte select for the (E)LPM instruction.
See “Addressing the Flash During Self-Programming” on page 232 for details about the use of Z-pointer during Self-
Programming.
241
7799C–AVR–12/09
ATmega8U2/16U2/32U2
242
7799C–AVR–12/09
ATmega8U2/16U2/32U2
243
7799C–AVR–12/09
ATmega8U2/16U2/32U2
24.1 Features
• 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
24.2 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.
2.7 - 5.5
VCC
(See Note)
dW dW(RESET)
GND
Figure 24-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 CKSEL Fuses.
244
7799C–AVR–12/09
ATmega8U2/16U2/32U2
When designing a system where debugWIRE will be used, the following observations must be
made for correct operation:
• Connecting the RESET pin directly to VCC will not work.
• Any capacitors (or additionnal circuitry) connected to the RESET pin must be disconnected
when using debugWire.
• All external reset sources must be disconnected.
Note: some releases of JTAG Ice mkII firmware may require a pull-up resistor with a value between 8
and 14 kOhms when operating at 5V.
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.
245
7799C–AVR–12/09
ATmega8U2/16U2/32U2
246
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. See “System and Reset Characteristics” on page 267 for BODLEVEL Fuse decoding.
247
7799C–AVR–12/09
ATmega8U2/16U2/32U2
248
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 25-7. No. of Words in a Page and No. of Pages in the Flash
No. of
Device Flash Size Page Size PCWORD Pages PCPAGE PCMSB
ATmega8U2 4K words (8Kbytes) 32 words PC[4:0] 128 PC[11:6] 11
ATmega16U2 8K words (16Kbytes) 64 words PC[5:0] 128 PC[12:6] 12
ATmega32U2 16K words (32Kbytes) 64 words PC[5:0] 256 PC[13:6] 13
Table 25-8. No. of Bytes in a Page and No. of Pages in the EEPROM
No. of
Device EEPROM Size Page Size PCWORD Pages PCPAGE EEAMSB
ATmega8U2 256 bytes 4 bytes EEA[1:0] 128 EEA[8:2] 8
ATmega16U2 512 bytes 4 bytes EEA[1:0] 128 EEA[8:2] 8
ATmega32U2 1K bytes 4 bytes EEA[1:0] 256 EEA[9:2] 9
249
7799C–AVR–12/09
ATmega8U2/16U2/32U2
XA1 PD6
PAGEL PD7
+12 V RESET
BS2 PC6
XTAL1
GND
250
7799C–AVR–12/09
ATmega8U2/16U2/32U2
251
7799C–AVR–12/09
ATmega8U2/16U2/32U2
252
7799C–AVR–12/09
ATmega8U2/16U2/32U2
253
7799C–AVR–12/09
ATmega8U2/16U2/32U2
01
02
PAGEEND
Note: 1. PCPAGE and PCWORD are listed in Table 25-7 on page 249.
254
7799C–AVR–12/09
ATmega8U2/16U2/32U2
A B C D E B C D E G H I
0x10 ADDR. LOW DATA LOW DATA HIGH XX ADDR. LOW DATA LOW DATA HIGH XX ADDR. HIGH ADDR. EXT.H XX
DATA
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
Note: 1. “XX” is don’t care. The letters refer to the programming description above.
255
7799C–AVR–12/09
ATmega8U2/16U2/32U2
A G B C E B C E L
0x11 ADDR. HIGH ADDR. LOW DATA XX ADDR. LOW DATA XX
DATA
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
256
7799C–AVR–12/09
ATmega8U2/16U2/32U2
A C A C A C
0x40 DATA XX 0x40 DATA XX 0x40 DATA XX
DATA
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
257
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 25-6. Mapping Between BS1, BS2 and the Fuse and Lock Bits During Read
0
Extended Fuse Byte 1
DATA
BS2
Lock Bits 0
1
BS1
Fuse High Byte 1
BS2
258
7799C–AVR–12/09
ATmega8U2/16U2/32U2
+1.8 - 5.5V
VCC
+1.8 - 5.5V(2)
PDI
AVCC
PDO
SCK
XTAL1
RESET
GND
Notes: 1. If the device is clocked by the internal Oscillator, it is no need to connect a clock source to the
XTAL1 pin.
2. VCC - 0.3V < AVCC < VCC + 0.3V, however, AVCC should always be within 1.8 - 5.5V
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 CKSEL 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 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
High: > 2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
259
7799C–AVR–12/09
ATmega8U2/16U2/32U2
260
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table 25-15. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FLASH 4.5 ms
tWD_EEPROM 9.0 ms
tWD_ERASE 9.0 ms
SAMPLE
261
7799C–AVR–12/09
ATmega8U2/16U2/32U2
262
7799C–AVR–12/09
ATmega8U2/16U2/32U2
263
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Operating Temperature.................................. -55°C to +125°C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent dam-
Storage Temperature ..................................... -65°C to +150°C age to the device. This is a stress rating only and
functional operation of the device at these or
Voltage on any Pin except RESET & UVcc other conditions beyond those indicated in the
with respect to Ground(7) .............................-0.5V to VCC+0.5V operational sections of this specification is not
implied. Exposure to absolute maximum rating
Voltage on RESET with respect to Ground......-0.5V to +13.0V conditions for extended periods may affect
device reliability.
Voltage on UVcc with respect to Ground ...........-0.5V to +6.0V
26.2 DC Characteristics
TA = -40°C to 85°C, VCC = 2.7V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min.(5) Typ. Max.(5) Units
Input Low Voltage,
VIL VCC = 2.7V - 5.5V -0.5 0.8 V
Standard IOs(8)
Input Low Voltage,
VIL1 VCC = 2.7V - 5.5V -0.5 0.1VCC(1) V
XTAL1 pin
Input Low Voltage,
VIL2 VCC = 2.7V - 5.5V -0.5 0.1VCC(1) V
RESET pin
Input High Voltage,
VIH VCC = 2.7V - 5.5V 2 VCC + 0.5 V
Standard IOs(8)
Input High Voltage,
VIH1 VCC = 2.7V - 5.5V 0.7VCC(2) VCC + 0.5 V
XTAL1 pin
Input High Voltage,
VIH2 VCC = 2.7V - 5.5V 0.9VCC(2) VCC + 0.5 V
RESET pin
Output Low Voltage(3),
IOL = 10mA, VCC = 5V 0.7
VOL Standard IOs(8), V
IOL = 5mA, VCC = 3V 0.5
MOSI/MISO pins
Output High Voltage(4),
IOH = -10mA, VCC = 5V 4.2
VOH Standard IOs(8), V
IOH = -5mA, VCC = 3V 2.3
MOSI/MISO pins
Input Leakage VCC = 5.5V, pin low
IIL 1 µA
Current I/O Pin (absolute value)
Input Leakage VCC = 5.5V, pin high
IIH 1 µA
Current I/O Pin (absolute value)
RRST Reset Pull-up Resistor 30 60 kΩ
RPU I/O Pin Pull-up Resistor 20 50 kΩ
264
7799C–AVR–12/09
ATmega8U2/16U2/32U2
265
7799C–AVR–12/09
ATmega8U2/16U2/32U2
7. As specified in the USB Electrical chapter, the D+/D- pads can withstand voltages down to -1V applied through a 39Ω resis-
tor (in series with the external 39Ω resistor).
8. All IOs Except XTAL1 and Reset pins
16 MHz
8 MHz
Safe Operating Area
V IH1
V IL1
266
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: All DC Characteristics contained in this datasheet are based on simulation and characterization of
other AVR microcontrollers manufactured in the same process technology. These values are pre-
liminary values representing design targets, and will be updated after characterization of actual
silicon.
267
7799C–AVR–12/09
ATmega8U2/16U2/32U2
268
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Note: 1. In SPI Programming mode the minimum SCK high/low period is:
- 2 tCLCL for fCK < 12 MHz
- 3 tCLCL for fCK > 12 MHz
SCK
(CPOL = 0)
2 2
SCK
(CPOL = 1)
4 5 3
MISO
MSB ... LSB
(Data Input)
7 8
MOSI
MSB ... LSB
(Data Output)
269
7799C–AVR–12/09
ATmega8U2/16U2/32U2
SS
10 16
9
SCK
(CPOL = 0)
11 11
SCK
(CPOL = 1)
13 14 12
MOSI
MSB ... LSB
(Data Input)
15 17
MISO
MSB ... LSB X
(Data Output)
RESET
tSHRH tHHRH
ALE/HWB
StartUpTime(SUT) +
tHHRH HWB low Hold after Reset High
Time Out Delay(TOUT)
Figure 26-5. Parallel Programming Timing, Including some General Timing Requirements
tXLWL
tXHXL
XTAL1
tDVXH tXLDX
Data & Contol
(DATA, XA0/1, BS1, BS2)
tBVPH tPLBX t BVWL
tWLBX
PAGEL tPHPL
tWLWH
WR tPLWL
WLRL
RDY/BSY
tWLRH
270
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 26-6. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
LOAD ADDRESS LOAD DATA LOAD DATA LOAD DATA LOAD ADDRESS
(LOW BYTE) (LOW BYTE) (HIGH BYTE) (LOW BYTE)
t XLXH tXLPH
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 26-5 (i.e., tDVXH, tXHXL, and tXLDX) also apply to load-
ing operation.
Figure 26-7. Parallel Programming Timing, Reading Sequence (within the Same Page) with
Timing Requirements(1)
LOAD ADDRESS READ DATA READ DATA LOAD ADDRESS
(LOW BYTE) (LOW BYTE) (HIGH BYTE) (LOW BYTE)
tXLOL
XTAL1
tBVDV
BS1
tOLDV
OE
tOHDZ
DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
XA0
XA1
Note: 1. The timing requirements shown in Figure 26-5 (i.e., tDVXH, tXHXL, and tXLDX) also apply to read-
ing operation.
271
7799C–AVR–12/09
ATmega8U2/16U2/32U2
272
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-1. Active Supply Current vs. Frequency (Regulator Enabled T = 85°C)
18
16
5.5 V
14 5.0 V
12 4.5 V
ICC (mA)
10
4.0 V
8
3.6 V
6
2.7 V
4
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Frequency (MHz)
273
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-2. Active Supply Current vs. Frequency (Regulator Disabled T = 85°C)
8
3.6 V
7
3.3 V
6
3.0 V
5
2.7 V
ICC (mA)
4
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Frequency (MHz)
Figure 27-3. Idle Supply Current vs. Frequency (Regulator Enabled T = 85°C)
4
5.5 V
3.5
5.0 V
3
4.5 V
2.5
ICC (mA)
4.0 V
2
3.6 V
1.5
0.5
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Frequency (MHz)
274
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-4. Idle Supply Current vs. Frequency (Regulator Disabled T = 85°C
2.1
3.6 V
1.8 3.3 V
2.7 V
1.5
1.2
ICC (mA)
0.9
0.6
0.3
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Frequency (MHz)
Figure 27-5. Power-Down Supply Current vs. VCC (Watchdog Timer Disabled)
6.8
85 °C
6.5
6.2
25 °C
5.9
ICC (uA)
5.6
5.3
4.7
4.4
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
275
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-6. Power-Down Supply Current vs. VCC (Watchdog Timer Enabled)
16
85 °C
15 25 °C
14
13
ICC (uA)
12
11
10
8
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Figure 27-7. Power-Down Supply Current vs. VCC (WDT Enabled BODEN)
43
85 °C
41 25 °C
39
ICC (uA)
37
35
33
31
3.5 3.7 3.9 4.1 4.3 4.5 4.7 4.9 5.1 5.3 5.5
VCC (V)
276
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-8. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5 V)
150
125
100
IOP (uA)
75
50
25 -40 °C
25 °C
0
85 °C
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VOP (V)
Figure 27-9. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5 V)
120
100
80
IRESET (uA)
60
40
20 25 °C
-40 °C
85 °C
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VRESET (V)
277
7799C–AVR–12/09
ATmega8U2/16U2/32U2
3.5 85 °C
2.5
VOL (V)
1.5
25 °C
1
-40 °C
0.5
0
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
0.9
0.8 85 °C
0.7 25 °C
0.6
-40 °C
VOL (V)
0.5
0.4
0.3
0.2
0.1
0
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
278
7799C–AVR–12/09
ATmega8U2/16U2/32U2
3.5
2.5
VOH (V)
-40 °C
1.5
25 °C
1
0.5
85 °C
0
0 2 4 6 8 10 12 14 16 18 20
IOH (mA)
4.9
4.8
4.7
4.6
VOH (V)
4.5
4.4
-40 °C
4.3
4.2 25 °C
4.1 85 °C
4
0 2 4 6 8 10 12 14 16 18 20
IOH (mA)
279
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-14. USB DP HI Pull-Up Resistor Current vs. USB Pin Voltage
1600
1400
1200
1000
600
400 25 °C
200
-40 °C
85 °C
0
0 0.5 1 1.5 2 2.5 3 3.5
VUSB (V)
Figure 27-15. I/O Pin Input Threshold Voltage vs. VCC (VIH, I/O Pin read as ‘1’)
1.7
-40 °C
25 °C
85 °C
1.5
Threshold (V)
1.3
1.1
0.9
0.7
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
280
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Figure 27-16. I/O Pin Input Threshold Voltage vs. VCC (VIL, I/O Pin read as ‘0’)
1.8
-40 °C
1.6 25 °C
85 °C
1.4
Threshold (V)
1.2
0.8
0.6
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
2.81
Rising Vcc
2.8
2.79
2.78
Threshold (V)
2.77
2.76
2.75
Falling Vcc
2.74
2.73
2.72
2.71
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature (°C)
281
7799C–AVR–12/09
ATmega8U2/16U2/32U2
3.58
3.56
Falling Vcc
Threshold (V)
3.55
3.54
3.53
3.52
3.51
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature (°C)
4.37
Falling Vcc
Threshold (V)
4.36
4.35
4.34
4.33
4.32
4.31
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature (°C)
282
7799C–AVR–12/09
ATmega8U2/16U2/32U2
1.105
25 °C
1.101
1.099
1.097
1.095
-40 °C
2.5 3 3.5 4 4.5 5 5.5
Vcc (V)
118
117
116
FRC (kHz)
115
114
1.9 V
113
2.7 V
112
3.6 V
111
5.5 V
110
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature (°C)
283
7799C–AVR–12/09
ATmega8U2/16U2/32U2
119
118
117
-40 °C
116
115
112
111
110 85 °C
109
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
8.3
85 °C
8.2
8.1
FRC (MHz)
8 25 °C
7.9
7.8 -40 °C
7.7
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
284
7799C–AVR–12/09
ATmega8U2/16U2/32U2
8.3 5.5 V
4.5 V
8.2 3.3 V
2.7 V
8.1
FRC (MHz)
8
7.9
7.8
7.7
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature (°C)
10
FRC (MHz)
0
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
285
7799C–AVR–12/09
ATmega8U2/16U2/32U2
440 -40 °C
85 °C
390
25 °C
340
290
ICC (mA)
240
190
140
90
40
2.5 3 3.5 4 4.5 5 5.5
Voltage (V)
3.4
25 °C
85 °C
3.3 -40 °C
Output Voltage (V)
3.2
3.1
2.9
2.8
3 3.5 4 4.5 5 5.5
Input Voltage (V)
286
7799C–AVR–12/09
ATmega8U2/16U2/32U2
85 °C
3.2 25 °C
-40 °C
3
Current (V)
2.8
2.6
2.4
2.2
2.5 3 3.5 4 4.5 5 5.5
Voltage (V)
Figure 27-29. Reset Supply Current vs. Frequency (Excluding Current Through the Reset
Pullup)
4.5
5.5 V
4
5.0 V
3.5
3
4.5 V
ICC (mA)
2.5
2
3.6 V
1.5
0.5
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Frequency (MHz)
287
7799C–AVR–12/09
ATmega8U2/16U2/32U2
288
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
(0xBE) Reserved - - - - - - - -
(0xBD) Reserved - - - - - - - -
(0xBC) Reserved - - - - - - - -
(0xBB) Reserved - - - - - - - -
(0xBA) Reserved - - - - - - - -
(0xB9) Reserved - - - - - - - -
(0xB8) Reserved - - - - - - - -
(0xB7) Reserved - - - - - - - -
(0xB6) Reserved - - - - - - - -
(0xB5) Reserved - - - - - - - -
(0xB4) Reserved - - - - - - - -
(0xB3) Reserved - - - - - - - -
(0xB2) Reserved - - - - - - - -
(0xB1) Reserved - - - - - - - -
(0xB0) Reserved - - - - - - - -
(0xAF) Reserved - - - - - - - -
(0xAE) Reserved - - - - - - - -
(0xAD) Reserved - - - - - - - -
(0xAC) Reserved - - - - - - - -
(0xAB) Reserved - - - - - - - -
(0xAA) Reserved - - - - - - - -
(0xA9) Reserved - - - - - - - -
(0xA8) Reserved - - - - - - - -
(0xA7) Reserved - - - - - - - -
(0xA6) Reserved - - - - - - - -
(0xA5) Reserved - - - - - - - -
(0xA4) Reserved - - - - - - - -
(0xA3) Reserved - - - - - - - -
(0xA2) Reserved - - - - - - - -
(0xA1) Reserved - - - - - - - -
(0xA0) Reserved - - - - - - - -
(0x9F) Reserved - - - - - - - -
(0x9E) Reserved - - - - - - - -
(0x9D) Reserved - - - - - - - -
(0x9C) Reserved - - - - - - - -
(0x9B) Reserved - - - - - - - -
(0x9A) Reserved - - - - - - - -
(0x99) Reserved - - - - - - - -
(0x98) Reserved - - - - - - - -
(0x97) Reserved - - - - - - - -
(0x96) Reserved - - - - - - - -
(0x95) Reserved - - - - - - - -
(0x94) Reserved - - - - - - - -
(0x93) Reserved - - - - - - - -
(0x92) Reserved - - - - - - - -
(0x91) Reserved - - - - - - - -
(0x90) Reserved - - - - - - - -
(0x8F) Reserved - - - - - - - -
(0x8E) Reserved - - - - - - - -
(0x8D) OCR1CH Timer/Counter1 - Output Compare Register C High Byte page 135
(0x8C) OCR1CL Timer/Counter1 - Output Compare Register C Low Byte page 135
(0x8B) OCR1BH Timer/Counter1 - Output Compare Register B High Byte page 135
(0x8A) OCR1BL Timer/Counter1 - Output Compare Register B Low Byte page 135
(0x89) OCR1AH Timer/Counter1 - Output Compare Register A High Byte page 135
(0x88) OCR1AL Timer/Counter1 - Output Compare Register A Low Byte page 135
(0x87) ICR1H Timer/Counter1 - Input Capture Register High Byte page 135
(0x86) ICR1L Timer/Counter1 - Input Capture Register Low Byte page 135
(0x85) TCNT1H Timer/Counter1 - Counter Register High Byte page 134
(0x84) TCNT1L Timer/Counter1 - Counter Register Low Byte page 134
(0x83) Reserved - - - - - - - -
(0x82) TCCR1C FOC1A FOC1B FOC1C - - - - - page 134
(0x81) TCCR1B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10 page 133
(0x80) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 COM1C1 COM1C0 WGM11 WGM10 page 129
(0x7F) Reserved - - - - - - - -
(0x7E) Reserved - - - - - - - -
(0x7D) ACMUX - - - - - CMUX2 CMUX1 CMUX0 page 225
289
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
(0x7C) Reserved - - - - - - - -
(0x7B) Reserved - - - - - - - -
(0x7A) Reserved - - - - - - - -
(0x79) Reserved - - - - - - - -
(0x78) Reserved - - - - - - - -
(0x77) Reserved - - - - - - - -
(0x76) Reserved - - - - - - - -
(0x75) Reserved - - - - - - - -
(0x74) Reserved - - - - - - - -
(0x73) Reserved - - - - - - - -
(0x72) Reserved - - - - - - - -
(0x71) Reserved - - - - - - - -
(0x70) Reserved - - - - - - - -
(0x6F) TIMSK1 - - ICIE1 - OCIE1C OCIE1B OCIE1A TOIE1 page 135
(0x6E) TIMSK0 - - - - - OCIE0B OCIE0A TOIE0 page 106
(0x6D) Reserved - - - - - - - -
(0x6C) PCMSK1 - - - PCINT12 PCINT11 PCINT10 PCINT9 PCINT8 page 87
(0x6B) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 page 87
(0x6A) EICRB ISC71 ISC70 ISC61 ISC60 ISC51 ISC50 ISC41 ISC40 page 85
(0x69) EICRA ISC31 ISC30 ISC21 ISC20 ISC11 ISC10 ISC01 ISC00 page 84
(0x68) PCICR - - - - - - PCIE1 PCIE0 page 86
(0x67) Reserved - - - - - - - -
(0x66) OSCCAL Oscillator Calibration Register page 38
(0x65) PRR1 PRUSB - - - - - - PRUSART1 page 46
(0x64) PRR0 - - PRTIM0 - PRTIM1 PRSPI - - page 46
(0x63) REGCR - - - - - - - REGDIS page 196
(0x62) WDTCKD - - WDEWIFCM WCLKD2 WDEWIF WDEWIE WCLKD1 WCLKD0 page 57
(0x61) CLKPR CLKPCE - - - CLKPS3 CLKPS2 CLKPS1 CLKPS0 page 39
(0x60) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 page 56
0x3F (0x5F) SREG I T H S V N Z C page 9
0x3E (0x5E) SPH SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 page 12
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 page 12
0x3C (0x5C) Reserved - - - - - - - -
0x3B (0x5B) Reserved - - - - - - - -
0x3A (0x5A) Reserved - - - - - - - -
0x39 (0x59) Reserved - - - - - - - -
0x38 (0x58) Reserved - - - - - - - -
0x37 (0x57) SPMCSR SPMIE RWWSB SIGRD RWWSRE BLBSET PGWRT PGERS SPMEN page 242
0x36 (0x56) Reserved - - - - - - - -
0x35 (0x55) MCUCR - - - - - - IVSEL IVCE page 65, 82
0x34 (0x54) MCUSR - - USBRF - WDRF BORF EXTRF PORF page 55
0x33 (0x53) SMCR - - - - SM2 SM1 SM0 SE page 45
0x32 (0x52) Reserved - - - - - - - -
0x31 (0x51) DWDR debugWIRE Data Register page 245
0x30 (0x50) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 page 224
0x2F (0x4F) Reserved - - - - - - - -
0x2E (0x4E) SPDR SPI Data Register page 147
0x2D (0x4D) SPSR SPIF WCOL - - - - - SPI2X page 146
0x2C (0x4C) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 page 145
0x2B (0x4B) GPIOR2 General Purpose I/O Register 2 page 24
0x2A (0x4A) GPIOR1 General Purpose I/O Register 1 page 24
0x29 (0x49) PLLCSR - - - PLLP2 PLLP1 PLLP0 PLLE PLOCK page 40
0x28 (0x48) OCR0B Timer/Counter0 Output Compare Register B page 106
0x27 (0x47) OCR0A Timer/Counter0 Output Compare Register A page 106
0x26 (0x46) TCNT0 Timer/Counter0 (8 Bit) page 106
0x25 (0x45) TCCR0B FOC0A FOC0B - - WGM02 CS02 CS01 CS00 page 105
0x24 (0x44) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 - - WGM01 WGM00 page 105
0x23 (0x43) GTCCR TSM - - - - - PSRASY PSRSYNC page 89
0x22 (0x42) EEARH - - - - EEPROM Address Register High Byte page 20
0x21 (0x41) EEARL EEPROM Address Register Low Byte page 20
0x20 (0x40) EEDR EEPROM Data Register page 20
0x1F (0x3F) EECR - - EEPM1 EEPM0 EERIE EEMPE EEPE EERE page 21
0x1E (0x3E) GPIOR0 General Purpose I/O Register 0 page 25
0x1D (0x3D) EIMSK INT7 INT6 INT5 INT4 INT3 INT2 INT1 INT0 page 86
0x1C (0x3C) EIFR INTF7 INTF6 INTF5 INTF4 INTF3 INTF2 INTF1 INTF0 page 86
0x1B (0x3B) PCIFR - - - - - - PCIF1 PCIF0 page 86
290
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x1A (0x3A) Reserved - - - - - - - -
0x19 (0x39) Reserved - - - - - - - -
0x18 (0x38) Reserved - - - - - - - -
0x17 (0x37) Reserved - - - - - - - -
0x16 (0x36) TIFR1 - - ICF1 - OCF1C OCF1B OCF1A TOV1 page 136
0x15 (0x35) TIFR0 - - - - - OCF0B OCF0A TOV0 page 107
0x14 (0x34) Reserved - - - - - - - -
0x13 (0x33) Reserved - - - - - - - -
0x12 (0x32) Reserved - - - - - - - -
0x11 (0x31) Reserved - - - - - - - -
0x10 (0x30) Reserved - - - - - - - -
0x0F (0x2F) Reserved - - - - - - - -
0x0E (0x2E) Reserved - - - - - - - -
0x0D (0x2D) Reserved - - - - - - - -
0x0C (0x2C) Reserved - - - - - - - -
0x0B (0x2B) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 page 83
0x0A (0x2A) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 page 83
0x09 (0x29) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 page 83
0x08 (0x28) PORTC PORTC7 PORTC6 PORTC5 PORTC4 - PORTC2 PORTC1 PORTC0 page 82
0x07 (0x27) DDRC DDC7 DDC6 DDC5 DDC4 - DDC2 DDC1 DDC0 page 82
0x06 (0x26) PINC PINC7 PINC6 PINC5 PINC4 - PINC2 PINC1 PINC0 page 82
0x05 (0x25) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 page 82
0x04 (0x24) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 page 82
0x03 (0x23) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 page 82
0x02 (0x22) Reserved - - - - - - - -
0x01 (0x21) Reserved - - - - - - - -
0x00 (0x20) Reserved - - - - - - - -
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Moreover reserved bits are not
guaranteed to be read as “0”. 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 reg-
isters, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on
all bits in the I/O register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions
work with registers 0x00 to 0x1F only.
4. When using the I/O specific commands IN and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O reg-
isters as data space using LD and ST instructions, $20 must be added to these addresses. The ATmega8U2/16U2/32U2 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 - $1FF in SRAM, only the ST/STS/STD and LD/LDS/LDD
instructions can be used.
291
7799C–AVR–12/09
ATmega8U2/16U2/32U2
292
7799C–AVR–12/09
ATmega8U2/16U2/32U2
293
7799C–AVR–12/09
ATmega8U2/16U2/32U2
30.1 ATmega8U2
Package Type
32A 32-lead, 7 x7 x 1.2 mm, lead pitch 0.8 mm Thin Quad Flat Package
32M1 32-pad, 5 x 5 x 1 mm body, pad pitch 0.50 mm Quad Flat No lead (QFN)
294
7799C–AVR–12/09
ATmega8U2/16U2/32U2
30.2 ATmega16U2
Speed Power Supply Ordering Code Package Operational Range
ATmega16U2-AU 32A
16 MHz 2.7 - 5.5V -40°C to +85°C
ATmega16U2-MU 32M1-A
Package Type
32A 32-lead, 7 x7 x 1.2 mm, lead pitch 0.8 mm Thin Quad Flat Package
32M1 32-pad, 5 x 5 x 1 mm body, pad pitch 0.50 mm Quad Flat No lead (QFN)
295
7799C–AVR–12/09
ATmega8U2/16U2/32U2
30.3 ATmega32U2
Speed Power Supply Ordering Code Package Operational Range
ATmega32U2-AU 32A
16 MHz 2.7 - 5.5V -40°C to +85°C
ATmega32U2-MU 32M1-A
Package Type
32A 32-lead, 7 x7 x 1.2 mm, lead pitch 0.8 mm Thin Quad Flat Package
32M1 32-pad, 5 x 5 x 1 mm body, pad pitch 0.50 mm Quad Flat No lead (QFN)
296
7799C–AVR–12/09
ATmega8U2/16U2/32U2
31.1 QFN32
297
7799C–AVR–12/09
ATmega8U2/16U2/32U2
31.2 TQFP32
298
7799C–AVR–12/09
ATmega8U2/16U2/32U2
32. Errata
32.3.1 rev. C
No Known Errata
299
7799C–AVR–12/09
ATmega8U2/16U2/32U2
300
7799C–AVR–12/09
ATmega8U2/16U2/32U2
1. Initial revision.
301
7799C–AVR–12/09
ATmega8U2/16U2/32U2
Table of Contents
Features ..................................................................................................... 1
2 Overview ................................................................................................... 3
2.1Block Diagram ...........................................................................................................3
2.2Pin Descriptions ........................................................................................................4
3 Resources ................................................................................................. 6
i
7799C–AVR–12/09
ATmega8U2/16U2/32U2
11 Interrupts ................................................................................................ 64
11.1Overview ...............................................................................................................64
11.2Interrupt Vectors in ATmega8U2/16U2/32U2 ........................................................64
11.3Register Description ..............................................................................................65
12 I/O-Ports .................................................................................................. 67
12.1Overview ...............................................................................................................67
12.2Ports as General Digital I/O ...................................................................................68
12.3Alternate Port Functions ........................................................................................72
12.4Register Description for I/O-Ports ..........................................................................82
ii
7799C–AVR–12/09
ATmega8U2/16U2/32U2
14.1Overview ...............................................................................................................88
14.2Internal Clock Source ............................................................................................88
14.3Prescaler Reset .....................................................................................................88
14.4External Clock Source ...........................................................................................88
14.5Register Description ..............................................................................................89
iii
7799C–AVR–12/09
ATmega8U2/16U2/32U2
18.2Overview .............................................................................................................148
18.3Clock Generation .................................................................................................149
18.4Frame Formats ....................................................................................................152
18.5USART Initialization ............................................................................................154
18.6Data Transmission – The USART Transmitter ....................................................155
18.7Data Reception – The USART Receiver .............................................................157
18.8Asynchronous Data Reception ............................................................................161
18.9Multi-processor Communication Mode ................................................................164
18.10Hardware Flow Control ......................................................................................165
18.11Register Description ..........................................................................................167
18.12Examples of Baud Rate Setting ........................................................................171
iv
7799C–AVR–12/09
ATmega8U2/16U2/32U2
v
7799C–AVR–12/09
ATmega8U2/16U2/32U2
vi
7799C–AVR–12/09
ATmega8U2/16U2/32U2
30.1ATmega8U2 ........................................................................................................294
30.2ATmega16U2 ......................................................................................................295
30.3ATmega32U2 ......................................................................................................296
Table of Contents....................................................................................... i
vii
7799C–AVR–12/09
Headquarters International
Product Contact
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 CONDI-
TIONS 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 INCIDEN-
TAL 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.
© 2009 Atmel Corporation. All rights reserved. Atmel ®, Atmel logo and combinations thereof AVR ®, and others are registered trademarks or
trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
7799C–AVR–12/09