Atmel 7810 Automotive Microcontrollers ATmega328P - Datasheet PDF
Atmel 7810 Automotive Microcontrollers ATmega328P - Datasheet PDF
Atmel 7810 Automotive Microcontrollers ATmega328P - Datasheet PDF
DATASHEET
Features
7810D-AVR-01/15
I/O and packages
23 programmable I/O lines
32-lead TQFP, and 32-pad QFN/MLF
Operating voltage:
2.7V to 5.5V for ATmega328P
Temperature range:
Automotive temperature range: 40C to +125C
Speed grade:
0 to 8MHz at 2.7 to 5.5V (automotive temperature range: 40C to +125C)
0 to 16MHz at 4.5 to 5.5V (automotive temperature range: 40C to +125C)
Low power consumption
Active mode: 1.5mA at 3V - 4MHz
Power-down mode: 1A at 3V
2 ATmega328P [DATASHEET]
7810DAVR01/15
1. Pin Configurations
PC4 (ADC4/SDA/PCINT12)
PC5 (ADC5/SCL/PCINT13)
PC6 (RESET/PCINT14)
PC2 (ADC2/PCINT10)
PC3 (ADC3/PCINT11)
PD2 (INT0/PCINT18)
PD0 (RXD/PCINT16)
PD1 (TXD/PCINT17)
32 31 30 29 28 27 26 25
9 10 11 12 13 14 15 16
(PCINT21/OC0B/T1) PD5
(PCINT22/OC0A/AIN0) PD6
(PCINT23/AIN1) PD7
(PCINT0/CLKO/ICP1) PB0
(PCINT1/OC1A) PB1
(PCINT2/SS/OC1B) PB2
(PCINT3/OC2A/MOSI) PB3
(PCINT4/MISO) PB4
PC4 (ADC4/SDA/PCINT12)
PC5 (ADC5/SCL/PCINT13)
PC6 (RESET/PCINT14)
PC2 (ADC2/PCINT10)
PC3 (ADC3/PCINT11)
PD2 (INT0/PCINT18)
PD0 (RXD/PCINT16)
PD1 (TXD/PCINT17)
32 31 30 29 28 27 26 25
9 10 11 12 13 14 15 16
(PCINT21/OC0B/T1) PD5
(PCINT22/OC0A/AIN0) PD6
(PCINT23/AIN1) PD7
(PCINT0/CLKO/ICP1) PB0
(PCINT1/OC1A) PB1
(PCINT2/SS/OC1B) PB2
(PCINT3/OC2A/MOSI) PB3
(PCINT4/MISO) PB4
ATmega328P [DATASHEET] 3
7810DAVR01/15
1.1 Pin Descriptions
1.1.1 VCC
Digital supply voltage.
1.1.2 GND
Ground.
1.1.5 PC6/RESET
If the RSTDISBL fuse is programmed, PC6 is used as an input pin. If the RSTDISBL fuse is unprogrammed, PC6 is used as
a reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not
running. The minimum pulse length is given in Table 28-4 on page 261. Shorter pulses are not guaranteed to generate a
reset.
The various special features of port C are elaborated in Section 13.3.2 Alternate Functions of Port C on page 68.
1.1.7 AVCC
AVCC is the supply voltage pin for the A/D converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if
the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6..4 use digital
supply voltage, VCC.
1.1.8 AREF
AREF is the analog reference pin for the A/D converter.
4 ATmega328P [DATASHEET]
7810DAVR01/15
1.1.9 ADC7:6 (TQFP and QFN/MLF Package Only)
In the TQFP and QFN/MLF package, ADC7:6 serve as analog inputs to the A/D converter. These pins are powered from the
analog supply and serve as 10-bit ADC channels.
1.2 Disclaimer
Typical values contained in this datasheet are based on simulations and characterization of actual ATmega328P AVR
microcontrollers manufactured on the typical process technology. automotive min and max values are based on
characterization of actual ATmega328P AVR microcontrollers manufactured on the whole process excursion (corner run).
ATmega328P [DATASHEET] 5
7810DAVR01/15
2. Overview
The Atmel ATmega328P 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 ATmega328P achieves throughputs approaching 1MIPS per MHz
allowing the system designer to optimize power consumption versus processing speed.
Watchdog
Power debugWIRE
Timer
Supervision
POR/ BOD
and
Watchdog RESET Program
Oscillator Logic
Oscillator
Circuits/ Flash SRAM
Clock
Generation
AVR CPU
EEPROM
AVCC
AREF
GND
2
8-bit T/C 0 16-bit T/C 1 A/D Conv.
DATA BUS
Analog Internal 6
8-bit T/C 2 Comp. Bandgap
RESET
XTAL[1..2]
6 ATmega328P [DATASHEET]
7810DAVR01/15
The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly
connected to the arithmetic logic unit (ALU), allowing two independent registers to be accessed in one single instruction
executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times
faster than conventional CISC microcontrollers.
The Atmel ATmega328P provides the following features: 32K bytes of in-system programmable flash with read-while-write
capabilities, 1K bytes EEPROM, 2K bytes SRAM, 23 general purpose I/O lines, 32 general purpose working registers, three
flexible Timer/Counters with compare modes, internal and external interrupts, a serial programmable USART, a byte-
oriented 2-wire serial interface, an SPI serial port, a 6-channel 10-bit ADC (8 channels in TQFP and QFN/MLF packages), a
programmable watchdog timer with internal oscillator, and five software selectable power saving modes. The idle mode
stops the CPU while allowing the SRAM, Timer/Counters, USART, 2-wire serial interface, 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 power-save mode, the asynchronous timer continues to run, allowing
the user to maintain a timer base while the rest of the device is sleeping. The ADC noise reduction mode stops the CPU and
all I/O modules except asynchronous timer and ADC, to minimize switching noise during ADC conversions. 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.
The device is manufactured using Atmel high density non-volatile memory technology. The on-chip ISP flash allows the
program memory to be reprogrammed in-system through an SPI serial interface, by a conventional non-volatile memory
programmer, or by an 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 ATmega328P is a powerful microcontroller that provides
a highly flexible and cost effective solution to many embedded control applications.
The ATmega328P AVR is supported with a full suite of program and system development tools including: C compilers,
macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits.
ATmega328P [DATASHEET] 7
7810DAVR01/15
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for download on
http://www.atmel.com/avr.
4. Data Retention
Reliability qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at
85C or 100 years at 25C.
8 ATmega328P [DATASHEET]
7810DAVR01/15
6. AVR CPU Core
6.1 Overview
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct
program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and
handle interrupts.
Interrupt
32 x 8
Unit
General
Instruction
Purpose
Register
Registers SPI
Indirect Addressing Unit
Instruction
Direct Addressing
Decoder Watchdog
ALU Timer
I/O Module 1
Data
SRAM
I/O Module 2
I/O Module n
EEPROM
I/O Lines
In order to maximize performance and parallelism, the AVR uses a harvard architecture with separate memories and
buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one
instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions
to be executed in every clock cycle. The program memory is in-system reprogrammable flash memory.
ATmega328P [DATASHEET] 9
7810DAVR01/15
The fast-access register file contains 32 8-bit general purpose working registers with a single clock cycle access time. This
allows single-cycle arithmetic logic unit (ALU) operation. In a typical ALU operation, two operands are output from the
register file, the operation is executed, and the result is stored back in the register file in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing enabling
efficient address calculations. One of the these address pointers can also be used as an address pointer for look up tables in
flash program memory. These added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register
operations can also be executed in the ALU. After an arithmetic operation, the status register is updated to reflect
information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole
address space. Most AVR instructions have a single 16-bit word format. Every program memory address contains a 16- or
32-bit instruction.
Program flash memory space is divided in two sections, the boot program section and the application program section. Both
sections have dedicated lock bits for write and read/write protection. The SPM instruction that writes into the application flash
memory section must reside in the boot program section.
During interrupts and subroutine calls, the return address program counter (PC) is stored on the stack. The stack is
effectively allocated in the general data SRAM, and consequently the stack size is only limited by the total SRAM size and
the usage of the SRAM. All user programs must initialize the SP in the reset routine (before subroutines or interrupts are
executed). The stack pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed through
the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional global interrupt enable bit in the status
register. All interrupts have a separate interrupt vector in the interrupt vector table. The interrupts have priority in accordance
with their interrupt vector position. The lower the interrupt vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as control registers, SPI, and other I/O functions.
The I/O memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5F. In
addition, the ATmega328P has extended I/O space from 0x60 - 0xFF in SRAM where only the ST/STS/STD and
LD/LDS/LDD instructions can be used.
10 ATmega328P [DATASHEET]
7810DAVR01/15
6.3.1 SREG AVR Status Register
The AVR status register SREG is defined as:
Bit 7 6 5 4 3 2 1 0
0x3F (0x5F) I T H S V N Z C 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
ATmega328P [DATASHEET] 11
7810DAVR01/15
6.4 General Purpose Register File
The register file is optimized for the AVR enhanced RISC instruction set. In order to achieve the required performance and
flexibility, the following input/output schemes are supported by the register file:
One 8-bit output operand and one 8-bit result input
Two 8-bit output operands and one 8-bit result input
Two 8-bit output operands and one 16-bit result input
One 16-bit output operand and one 16-bit result input
Figure 6-2 shows the structure of the 32 general purpose working registers in the CPU.
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 implemented as SRAM locations, this memory organization
provides great flexibility in access of the registers, as the X-, Y- and Z-pointer registers can be set to index any register in the
file.
12 ATmega328P [DATASHEET]
7810DAVR01/15
6.4.1 The X-register, Y-register, and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit address
pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as described
in Figure 6-3.
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 implementations of the AVR architecture is so small that only
SPL is needed. In this case, the SPH register will not be present.
ATmega328P [DATASHEET] 13
7810DAVR01/15
6.5.1 SPH and SPL Stack Pointer High and Stack Pointer 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 RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND
RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND
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 destination register.
clkCPU
14 ATmega328P [DATASHEET]
7810DAVR01/15
6.7 Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate reset vector each have a separate
program vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic
one together with the global interrupt enable bit in the status register in order to enable the interrupt. Depending on the
program counter value, interrupts may be automatically disabled when boot lock bits BLB02 or BLB12 are programmed. This
feature improves software security. See the Section 27. Memory Programming on page 241 for details.
The lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. The complete
list of vectors is shown in Section 11. Interrupts on page 49. The list also determines the priority levels of the different
interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next is INT0 the
external interrupt request 0. The interrupt vectors can be moved to the start of the boot flash section by setting the IVSEL bit
in the MCU control register (MCUCR). Refer to Section 11. Interrupts on page 49 for more information. The reset vector can
also be moved to the start of the boot flash section by programming the BOOTRST fuse, see Section 26. Boot Loader
Support Read-While-Write Self-Programming on page 229.
When an interrupt occurs, the global interrupt enable I-bit is cleared and all interrupts are disabled. The user software can
write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine.
The I-bit is automatically set when a return from interrupt instruction RETI is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the interrupt flag. For these
interrupts, the program counter is vectored to the actual interrupt vector in order to execute the interrupt handling routine,
and hardware clears the corresponding interrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit
position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt
flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more
interrupt conditions occur while the global interrupt enable bit is cleared, the corresponding interrupt flag(s) will be set and
remembered until the global interrupt enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily
have interrupt flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any
pending interrupt is served.
Note that the status register is not automatically stored when entering an interrupt routine, nor restored when returning from
an interrupt routine. This must be handled by software.
ATmega328P [DATASHEET] 15
7810DAVR01/15
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed
after the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example shows how this can
be used to avoid interrupts during the timed EEPROM write sequence.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE ; start EEPROM write
sbi EECR, EEPE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1<<EEMPE); /* start EEPROM write */
EECR |= (1<<EEPE);
SREG = cSREG; /* restore SREG value (I-bit) */
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending
interrupts, as shown in this example.
16 ATmega328P [DATASHEET]
7810DAVR01/15
7. AVR Memories
7.1 Overview
This section describes the different memories in the ATmega328P. The AVR architecture has two main memory spaces,
the data memory and the program memory space. In addition, the ATmega328P features an EEPROM memory for data
storage. All three memory spaces are linear and regular.
ATmega328P [DATASHEET] 17
7810DAVR01/15
7.3 SRAM Data Memory
Figure 7-2 shows how the ATmega328P SRAM memory is organized.
The ATmega328P is a complex microcontroller with more peripheral units than can be supported within the 64 locations
reserved in the opcode for the IN and OUT instructions. For the extended I/O space from 0x60 - 0xFF in SRAM, only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
The lower 2303 data memory locations address both the register file, the I/O memory, extended I/O memory, and the
internal data SRAM. The first 32 locations address the register file, the next 64 location the standard I/O memory, then 160
locations of extended I/O memory, and the next 2048 locations address the internal data SRAM.
The five different addressing modes for the data memory cover: Direct, indirect with displacement, indirect, indirect with
pre-decrement, and indirect with post-increment. In the register file, registers R26 to R31 feature the indirect addressing
pointer registers.
The direct addressing reaches the entire data space.
The indirect with displacement mode reaches 63 address locations from the base address given by the Y- or Z-register.
When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X,
Y, and Z are decremented or incremented.
The 32 general purpose working registers, 64 I/O registers, 160 extended I/O registers, and the 2048 bytes of internal data
SRAM in the ATmega328P are all accessible through all these addressing modes. The register file is described in
Section 6.4 General Purpose Register File on page 12.
Data Memory
0x08FF
clkCPU
Data
Write
WR
Data
Read
RD
18 ATmega328P [DATASHEET]
7810DAVR01/15
7.4 EEPROM Data Memory
The Atmel ATmega328P contains 1Kbyte of data EEPROM memory. It is organized as a separate data space, in which
single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access
between the EEPROM and the CPU is described in the following, specifying the EEPROM address registers, the EEPROM
data register, and the EEPROM control register.
Section 27. Memory Programming on page 241 contains a detailed description on EEPROM programming in SPI or
parallel programming mode.
ATmega328P [DATASHEET] 19
7810DAVR01/15
7.5.1 General Purpose I/O Registers
The Atmel ATmega328P contains three general purpose I/O registers. These registers can be used for storing any
information, and they are particularly useful for storing global variables and status flags. General purpose I/O registers within
the address range 0x00 - 0x1F are directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
20 ATmega328P [DATASHEET]
7810DAVR01/15
Table 7-1. EEPROM Mode Bits
When the write access time has elapsed, the EEPE bit is cleared by hardware. The user software can poll this bit and wait
for a zero before writing the next byte. When EEPE has been set, the CPU is halted for two cycles before the next instruction
is executed.
ATmega328P [DATASHEET] 21
7810DAVR01/15
The calibrated oscillator is used to time the EEPROM accesses. Table 7-2 lists the typical programming time for EEPROM
access from the CPU.
The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume
that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during execution of these
functions. The examples also assume that no flash boot loader is present in the software. If such code is present, the
EEPROM write function must also wait for any ongoing SPM command to finish.
Assembly Code Example
EEPROM_write:
; Wait for completion of previous write
sbic EECR,EEPE
rjmp EEPROM_write
; Set up address (r18:r17) in address register
out EEARH, r18
out EEARL, r17
; Write data (r16) to Data Register
out EEDR,r16
; Write logical one to EEMPE
sbi EECR,EEMPE
; Start eeprom write by setting EEPE
sbi EECR,EEPE
ret
C Code Example
void EEPROM_write(unsigned int uiAddress, unsigned char ucData)
{
/* Wait for completion of previous write */
while(EECR & (1<<EEPE))
;
/* Set up address and Data Registers */
EEAR = uiAddress;
EEDR = ucData;
/* Write logical one to EEMPE */
EECR |= (1<<EEMPE);
/* Start eeprom write by setting EEPE */
EECR |= (1<<EEPE);
}
22 ATmega328P [DATASHEET]
7810DAVR01/15
The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts
are controlled so that no interrupts will occur during execution of these functions.
Assembly Code Example
EEPROM_read:
; Wait for completion of previous write
sbic EECR,EEPE
rjmp EEPROM_read
; Set up address (r18:r17) in address register
out EEARH, r18
out EEARL, r17
; Start eeprom read by writing EERE
sbi EECR,EERE
; Read data from Data Register
in r16,EEDR
ret
C Code Example
unsigned char EEPROM_read(unsigned int uiAddress)
{
/* Wait for completion of previous write */
while(EECR & (1<<EEPE))
;
/* Set up address register */
EEAR = uiAddress;
/* Start eeprom read by writing EERE */
EECR |= (1<<EERE);
/* Return data from Data Register */
return EEDR;
}
ATmega328P [DATASHEET] 23
7810DAVR01/15
8. System Clock and Clock Options
clkADC
clkI/O clkCPU
AVR Clock
Control Unit
clkASY clkFLASH
System Clock
Reset Logic Watchdog Timer
Prescaler
Clock Watchdog
Multiplexer Oscillator
24 ATmega328P [DATASHEET]
7810DAVR01/15
8.1.4 Asynchronous Timer Clock clkASY
The asynchronous timer clock allows the asynchronous Timer/Counter to be clocked directly from an external clock or an
external 32kHz clock crystal. The dedicated clock domain allows using this Timer/Counter as a real-time counter even when
the device is in sleep mode.
Typ Time-out (VCC = 5.0V) Typ Time-out (VCC = 3.0V) Number of Cycles
0ms 0ms 0
4.1ms 4.3ms 512
65ms 69ms 8K (8,192)
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.
ATmega328P [DATASHEET] 25
7810DAVR01/15
The oscillator is required to oscillate for a minimum number of cycles before the clock is considered 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.
C1
XTAL1 (TOSC1)
GND
The low power oscillator can operate in three different modes, each optimized for a specific frequency range. The operating
mode is selected by the fuses CKSEL3..1 as shown in Table 8-3.
26 ATmega328P [DATASHEET]
7810DAVR01/15
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
Oscillator Source / Power Start-up Time from Power- Additional Delay from
Conditions down and Power-save Reset (VCC = 5.0V) CKSEL0 SUT1..0
Ceramic resonator, fast rising
258CK 14CK + 4.1ms(1) 0 00
power
Ceramic resonator, slowly rising
258CK 14CK + 65ms(1) 0 01
power
Ceramic resonator, BOD
1KCK 14CK(2) 0 10
enabled
Ceramic resonator, fast rising
1KCK 14CK + 4.1ms(2) 0 11
power
Ceramic resonator, slowly rising
1KCK 14CK + 65ms(2) 1 00
power
Crystal oscillator, BOD enabled 16KCK 14CK 1 01
Crystal oscillator, fast rising
16KCK 14CK + 4.1ms 1 10
power
Crystal oscillator, slowly rising
16KCK 14CK + 65ms 1 11
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 frequency of the device, and if
frequency stability at start-up is not important for the application.
ATmega328P [DATASHEET] 27
7810DAVR01/15
Figure 8-3. Crystal Oscillator Connections
C2
XTAL2 (TOSC2)
C1
XTAL1 (TOSC1)
GND
Table 8-6. Start-up Times for the Full Swing Crystal Oscillator Clock Selection
Oscillator Source / Start-up Time from Power- Additional Delay from
Power Conditions down and Power-save Reset (VCC = 5.0V) CKSEL0 SUT1..0
Ceramic resonator, fast rising
258CK 14CK + 4.1ms(1) 0 00
power
Ceramic resonator, slowly rising
258CK 14CK + 65ms(1) 0 01
power
Ceramic resonator, BOD
1KCK 14CK(2) 0 10
enabled
Ceramic resonator, fast rising
1KCK 14CK + 4.1ms(2) 0 11
power
Ceramic resonator, slowly rising
1KCK 14CK + 65ms(2) 1 00
power
Crystal oscillator, BOD enabled 16KCK 14CK 1 01
Crystal oscillator, fast rising
16KCK 14CK + 4.1ms 1 10
power
Crystal oscillator, slowly rising
16KCK 14CK + 65ms 1 11
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 frequency of the device, and if
frequency stability at start-up is not important for the application.
28 ATmega328P [DATASHEET]
7810DAVR01/15
8.5 Low Frequency Crystal Oscillator
The low-frequency crystal oscillator is optimized for use with a 32.768kHz watch crystal. When selecting crystals, load
capacitance and crystals equivalent series resistance, ESR must be taken into consideration. Both values are specified by
the crystal vendor. ATmega328P oscillator is optimized for very low power consumption, and thus when selecting crystals,
see Table 8-7 for maximum ESR recommendations on 6.5pF, 9.0pF and 12.5pF crystals
The low-frequency crystal oscillator provides an internal load capacitance of typical 6pF at each TOSC pin. The external
capacitance (C) needed at each TOSC pin can be calculated by using:
C = 2 CL C S
where CL is the load capacitance for a 32.768kHz crystal specified by the crystal vendor and CS is the total stray
capacitance for one TOSC pin.
Crystals specifying load capacitance (CL) higher than 6pF, require external capacitors applied as described in
Figure 8-2 on page 26.
The low-frequency crystal oscillator must be selected by setting the CKSEL fuses to 0110 or 0111, as shown in Table 8-9.
Start-up times are determined by the SUT fuses as shown in Table 8-8.
Table 8-8. Start-up Times for the Low-frequency Crystal Oscillator Clock Selection
SUT1..0 Additional Delay from Reset (VCC = 5.0V) Recommended Usage
00 4CK Fast rising power or BOD enabled
01 4CK + 4.1ms Slowly rising power
10 4CK + 65ms Stable frequency at start-up
11 Reserved
Table 8-9. Start-up Times for the Low-frequency Crystal Oscillator Clock Selection
ATmega328P [DATASHEET] 29
7810DAVR01/15
By changing the OSCCAL register from SW, see Section 8.12.1 OSCCAL Oscillator Calibration Register on page 32, it is
possible to get a higher calibration accuracy than by using the factory calibration. The accuracy of this calibration is shown
as User calibration in Table 28-1 on page 260.
When this oscillator is used as the chip clock, the watchdog oscillator will still be used for the watchdog timer and for the
reset time-out. For more information on the pre-programmed calibration value, see Section 27.4 Calibration Byte on page
244.
When this oscillator is selected, start-up times are determined by the SUT fuses as shown in Table 8-11.
Table 8-11. Start-up Times for the Internal calibrated RC Oscillator Clock Selection
Start-up Time from Power-down and Additional Delay from Reset
Power Conditions Power-save (VCC = 5.0V) SUT1..0
(1)
BOD enabled 6CK 14CK 00
Fast rising power 6CK 14CK + 4.1ms 01
Slowly rising power 6CK 14CK + 65ms(2) 10
Reserved 11
Notes: 1. If the RSTDISBL fuse is programmed, this start-up time will be increased to
14CK + 4.1ms to ensure programming mode can be entered.
2. The device is shipped with this option selected.
When this clock source is selected, start-up times are determined by the SUT fuses as shown in Table 8-13.
Table 8-13. Start-up Times for the 128 kHz Internal Oscillator
Start-up Time from Power-down and
Power Conditions Power-save Additional Delay from Reset SUT1..0
(1)
BOD enabled 6CK 14CK 00
Fast rising power 6CK 14CK + 4ms 01
Slowly rising power 6CK 14CK + 64ms 10
Reserved 11
Note: 1. If the RSTDISBL fuse is programmed, this start-up time will be increased to
14CK + 4.1ms to ensure programming mode can be entered.
30 ATmega328P [DATASHEET]
7810DAVR01/15
8.8 External Clock
To drive the device from an external clock source, XTAL1 should be driven as shown in Figure 8-4. To run the device on an
external clock, the CKSEL fuses must be programmed to 0000 (see Table 8-14).
Frequency CKSEL3..0
0 to 16MHz 0000
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-15.
When applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable
operation of the MCU. A variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable
behavior. If changes of more than 2% is required, ensure that the MCU is kept in reset during the changes.
Note that the system clock prescaler can be used to implement run-time changes of the internal clock frequency while still
ensuring stable operation. Refer to Section 8.11 System Clock Prescaler on page 32 for details.
ATmega328P [DATASHEET] 31
7810DAVR01/15
8.10 Timer/Counter Oscillator
Atmel ATmega328P uses the same crystal oscillator for low-frequency oscillator and Timer/Counter oscillator. See Section
8.5 Low Frequency Crystal Oscillator on page 29 for details on the oscillator and crystal requirements.
Atmel ATmega328P share the Timer/Counter oscillator pins (TOSC1 and TOSC2) with XTAL1 and XTAL2. When using the
Timer/Counter oscillator, the system clock needs to be four times the oscillator frequency. Due to this and the pin sharing,
the Timer/Counter oscillator can only be used when the calibrated internal RC oscillator is selected as system clock source.
Applying an external clock source to TOSC1 can be done if EXTCLK in the ASSR register is written to logic one. See Section
17.9 Asynchronous Operation of Timer/Counter2 on page 126 for further description on selecting external clock as input
instead of a 32.768kHz watch crystal.
32 ATmega328P [DATASHEET]
7810DAVR01/15
8.12.2 CLKPR Clock Prescale Register
Bit 7 6 5 4 3 2 1 0
(0x61) CLKPCE CLKPS3 CLKPS2 CLKPS1 CLKPS0 CLKPR
Read/Write R/W R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 See Bit Description
ATmega328P [DATASHEET] 33
7810DAVR01/15
9. Power Management and Sleep Modes
Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides
various sleep modes allowing the user to tailor the power consumption to the applications requirements.
When enabled, the brown-out detector (BOD) actively monitors the power supply voltage during the sleep periods. To further
save power, it is possible to disable the BOD in some sleep modes. See Section 9.2 BOD Disable on page 35 for more
details.
Table 9-1. Active Clock Domains and Wake-up Sources in the Different Sleep Modes.
Timer Oscillator
Source Enabled
SPM/EEPROM
TWI Address
BOD Disable
Pin Change
Main Clock
Software
Enabled
clkFLASH
Other/O
Timer2
Ready
clkADC
Match
clkCPU
clkASY
WDT
ADC
clkIO
Sleep Mode
Idle X X X X X(2) X X X X X X X
ADC noise
X X X X(2) X(3) X X(2) X X X
Reduction
Power-down X(3) X X X
(2) (3)
Power-save X X X X X X X
Standby(1) X X(3) X X X
Extended
X(2) X X(2) X(3) X X X X
Standby
Notes: 1. Only recommended with external crystal or resonator selected as clock source.
2. If Timer/Counter2 is running in asynchronous mode.
3. For INT1 and INT0, only level interrupt.
To enter any of the six 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, ADC noise reduction, power-
down, power-save, standby, or extended standby) will be activated by the SLEEP instruction. See Table 9-2 on page 38 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.
34 ATmega328P [DATASHEET]
7810DAVR01/15
9.2 BOD Disable
When the brown-out detector (BOD) is enabled by BODLEVEL fuses, Table 27-7 on page 244, the BOD is actively
monitoring the power supply voltage during a sleep period. To save power, it is possible to disable the BOD by software for
some of the sleep modes, see Table 9-1 on page 34. The sleep mode power consumption will then be at the same level as
when BOD is globally disabled by fuses. If BOD is disabled in software, the BOD function is turned off immediately after
entering the sleep mode. Upon wake-up from sleep, BOD is automatically enabled again. This ensures safe operation in
case the VCC level has dropped during the sleep period.
When the BOD has been disabled, the wake-up time from sleep mode will be approximately 60s to ensure that the BOD is
working correctly before the MCU continues executing code.
BOD disable is controlled by bit 6, BODS (BOD Sleep) in the control register MCUCR, see Section 9.11.2 MCUCR MCU
Control Register on page 38. Writing this bit to one turns off the BOD in relevant sleep modes, while a zero in this bit keeps
BOD active. Default setting keeps BOD active, i.e. BODS set to zero.
Writing to the BODS bit is controlled by a timed sequence and an enable bit, see Section 9.11.2 MCUCR MCU Control
Register on page 38.
ATmega328P [DATASHEET] 35
7810DAVR01/15
9.6 Power-save Mode
When the SM2..0 bits are written to 011, the SLEEP instruction makes the MCU enter power-save mode. This mode is
identical to power-down, with one exception:
If Timer/Counter2 is enabled, it will keep running during sleep. The device can wake up from either timer overflow or output
compare event from Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in TIMSK2, and the
global interrupt enable bit in SREG is set.
If Timer/Counter2 is not running, power-down mode is recommended instead of power-save mode.
The Timer/Counter2 can be clocked both synchronously and asynchronously in power-save mode. If Timer/Counter2 is not
using the asynchronous clock, the Timer/Counter oscillator is stopped during sleep. If Timer/Counter2 is not using the
synchronous clock, the clock source is stopped during sleep. Note that even if the synchronous clock is running in
power-save, this clock is only available for Timer/Counter2.
36 ATmega328P [DATASHEET]
7810DAVR01/15
9.10.3 Brown-out Detector
If the brown-out detector is not needed by the application, this module should be turned off. If the brown-out detector is
enabled by the BODLEVEL fuses, it will be enabled in all sleep modes, and hence, always consume power. In the deeper
sleep modes, this will contribute significantly to the total current consumption. Refer to Section 10.5 Brown-out Detection
on page 42 for details on how to configure the brown-out detector.
Bit 7 6 5 4 3 2 1 0
0x33 (0x53) SM2 SM1 SM0 SE SMCR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
ATmega328P [DATASHEET] 37
7810DAVR01/15
Bits 3..1 SM2..0: Sleep Mode Select Bits 2, 1, and 0
These bits select between the five available sleep modes as shown in Table 9-2 on page 38.
38 ATmega328P [DATASHEET]
7810DAVR01/15
Bit 6 - PRTIM2: Power Reduction Timer/Counter2
Writing a logic one to this bit shuts down the Timer/Counter2 module in synchronous mode (AS2 is 0). When the
Timer/Counter2 is enabled, operation will continue like before the shutdown.
ATmega328P [DATASHEET] 39
7810DAVR01/15
10. System Control and Reset
MCU Status
Register (MCUSR)
PORF
BORF
EXTRF
WDRF
Power-on Reset
VCC
Circuit
Brown-out
BODLEVEL [2..0] Reset Circuit
INTERNAL RESET
Pull-up Resistor
Q
Reset Circuit S
R
COUNTER RESET
SPIKE Watchdog
RESET
FILTER Timer
RSTDISBL
Watchdog
Oscillator
CK Delay Counters
Clock
TIMEOUT
Generator
CKSEL[3:0]
SUT[1:0]
40 ATmega328P [DATASHEET]
7810DAVR01/15
10.3 Power-on Reset
A power-on reset (POR) pulse is generated by an on-chip detection circuit. The detection level is defined in Section 28.6
System and Reset Characteristics on page 261. The POR is activated whenever VCC is below the detection level. The POR
circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage.
A power-on reset (POR) circuit ensures that the device is reset from power-on. Reaching the power-on reset threshold
voltage invokes the delay counter, which determines how long the device is kept in RESET after VCC rise. The RESET signal
is activated again, without any delay, when VCC decreases below the detection level.
VCC VPOT
RESET VRST
tTOUT
Time-out
Internal
Reset
VCC V POT
RESET V RST
tTOUT
Time-out
Internal
Reset
ATmega328P [DATASHEET] 41
7810DAVR01/15
10.4 External Reset
An external reset is generated by a low level on the RESET pin. Reset pulses longer than the minimum pulse width (see
Section 28.6 System and Reset Characteristics on page 261) will generate a reset, even if the clock is not running. Shorter
pulses are not guaranteed to generate a reset. When the applied signal reaches the reset threshold voltage VRST on its
positive edge, the delay counter starts the MCU after the time-out period tTOUT has expired. The external reset can be
disabled by the RSTDISBL fuse, see Table 27-7 on page 244.
RESET V RST
tTOUT
TIME-OUT
INTERNAL
RESET
RESET
tTOUT
TIME-OUT
INTERNAL
RESET
42 ATmega328P [DATASHEET]
7810DAVR01/15
10.6 Watchdog System Reset
When the watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse,
the delay timer starts counting the time-out period tTOUT. Refer to Section 10.8 Watchdog Timer on page 43 for details on
operation of the watchdog timer.
RESET
1 CK Cycle
WDT
TIME-OUT
tTOUT
RESET
Time-OUT
INTERNAL
RESET
10.8.1 Features
Clocked from separate on-chip oscillator
3 operating modes
Interrupt
System reset
Interrupt and system reset
Selectable time-out period from 16ms to 8s
Possible hardware fuse watchdog always on (WDTON) for fail-safe mode
ATmega328P [DATASHEET] 43
7810DAVR01/15
10.8.2 Overview
Atmel ATmega328P has an enhanced watchdog timer (WDT). The WDT is a timer counting cycles of a separate on-chip
128kHz oscillator. The WDT gives an interrupt or a system reset when the counter reaches a given time-out value. In normal
operation mode, it is required that the system uses the WDR - watchdog timer reset - instruction to restart the counter before
the time-out value is reached. If the system doesn't restart the counter, an interrupt or system reset will be issued.
128kHz Watchdog
Oscillator Prescaler
OSC/2K
OSC/4K
OSC/8K
OSC/16K
OSC/32K
OSC/64K
OSC/128K
OSC/256K
OSC/512K
OSC/1024K
WDP0
WDP1
WATCHDOG WDP2
RESET WDP3
WDE
MCU RESET
WDIF
INTERRUPT
WDIE
In interrupt mode, the WDT gives an interrupt when the timer expires. This interrupt can be used to wake the device from
sleep-modes, and also as a general system timer. One example is to limit the maximum time allowed for certain operations,
giving an interrupt when the operation has run longer than expected. In system reset mode, the WDT gives a reset when the
timer expires. This is typically used to prevent system hang-up in case of runaway code. The third mode, Interrupt and
system reset mode, combines the other two modes by first giving an interrupt and then switch to system reset mode. This
mode will for instance allow a safe shutdown by saving critical parameters before a system reset.
The watchdog always on (WDTON) fuse, if programmed, will force the watchdog timer to system reset mode. With the fuse
programmed the system reset mode bit (WDE) and interrupt mode bit (WDIE) are locked to 1 and 0 respectively. To further
ensure program security, alterations to the watchdog set-up must follow timed sequences.
The sequence for clearing WDE and changing time-out configuration is as follows:
1. In the same operation, write a logic one to the watchdog change enable bit (WDCE) and WDE. A logic one must
be written to WDE regardless of the previous value of the WDE bit.
2. Within the next four clock cycles, write the WDE and watchdog prescaler bits (WDP) as desired, but with the
WDCE bit cleared. This must be done in one operation.
44 ATmega328P [DATASHEET]
7810DAVR01/15
The following code example shows one assembly and one C function for turning off the watchdog timer. The example
assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the
execution of these functions.
ATmega328P [DATASHEET] 45
7810DAVR01/15
The following code example shows one assembly and one C function for changing the time-out value of the watchdog timer.
Assembly Code Example(1)
WDT_Prescaler_Change:
; Turn off global interrupt
cli
; Reset Watchdog Timer
wdr
; Start timed sequence
lds r16, WDTCSR
ori r16, (1<<WDCE) | (1<<WDE)
sts WDTCSR, r16
; -- Got four cycles to set the new values from here -
; Set new prescaler(time-out) value = 64K cycles (~0.5 s)
ldi r16, (1<<WDE) | (1<<WDP2) | (1<<WDP0)
sts WDTCSR, r16
; -- Finished setting new values, used 2 cycles -
; Turn on global interrupt
sei
ret
C Code Example(1)
void WDT_Prescaler_Change(void)
{
__disable_interrupt();
__watchdog_reset();
/* Start timed equence */
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* Set new prescaler(time-out) value = 64K cycles (~0.5 s) */
WDTCSR = (1<<WDE) | (1<<WDP2) | (1<<WDP0);
__enable_interrupt();
}
Note: 1. See Section 5. About Code Examples on page 8.
2. 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.
46 ATmega328P [DATASHEET]
7810DAVR01/15
Bit 1 EXTRF: External Reset Flag
This bit is set if an external reset occurs. The bit is reset by a power-on reset, or by writing a logic zero to the flag.
ATmega328P [DATASHEET] 47
7810DAVR01/15
Bit 3 - WDE: Watchdog System Reset Enable
WDE is overridden by WDRF in MCUSR. This means that WDE is always set when WDRF is set. To clear WDE, WDRF
must be cleared first. This feature ensures multiple resets during conditions causing failure, and a safe start-up after the
failure.
WDP3 WDP2 WDP1 WDP0 Number of WDT Oscillator Cycles Typical Time-out at VCC = 5.0V
0 0 0 0 2K (2048) cycles 16ms
0 0 0 1 4K (4096) cycles 32ms
0 0 1 0 8K (8192) cycles 64ms
0 0 1 1 16K (16384) cycles 0.125s
0 1 0 0 32K (32768) cycles 0.25s
0 1 0 1 64K (65536) cycles 0.5s
0 1 1 0 128K (131072) cycles 1.0s
0 1 1 1 256K (262144) cycles 2.0s
1 0 0 0 512K (524288) cycles 4.0s
1 0 0 1 1024K (1048576) cycles 8.0s
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
48 ATmega328P [DATASHEET]
7810DAVR01/15
11. Interrupts
This section describes the specifics of the interrupt handling as performed in Atmel ATmega328P. For a general
explanation of the AVR interrupt handling, refer to Section 6.7 Reset and Interrupt Handling on page 15.
Each interrupt vector occupies two instruction words in Atmel ATmega328P.
In Atmel ATmega328P, the reset vector is affected by the BOOTRST fuse, and the interrupt vector start address is
affected by the IVSEL bit in MCUCR.
ATmega328P [DATASHEET] 49
7810DAVR01/15
Table 11-2 shows reset and interrupt vectors placement for the various combinations of BOOTRST and IVSEL settings. If the
program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at
these locations. This is also the case if the reset vector is in the application section while the interrupt vectors are in the boot
section or vice versa.
The most typical and general program setup for the reset and interrupt vector addresses in Atmel ATmega328P is:
Address Labels Code Comments
0x0000 jmp RESET ; Reset Handler
0x0002 jmp EXT_INT0 ; IRQ0 Handler
0x0004 jmp EXT_INT1 ; IRQ1 Handler
0x0006 jmp PCINT0 ; PCINT0 Handler
0x0008 jmp PCINT1 ; PCINT1 Handler
0x000A jmp PCINT2 ; PCINT2 Handler
0x000C jmp WDT ; Watchdog Timer Handler
0x000E jmp TIM2_COMPA ; Timer2 Compare A Handler
0x0010 jmp TIM2_COMPB ; Timer2 Compare B Handler
0x0012 jmp TIM2_OVF ; Timer2 Overflow Handler
0x0014 jmp TIM1_CAPT ; Timer1 Capture Handler
0x0016 jmp TIM1_COMPA ; Timer1 Compare A Handler
0x0018 jmp TIM1_COMPB ; Timer1 Compare B Handler
0x001A jmp TIM1_OVF ; Timer1 Overflow Handler
0x001C jmp TIM0_COMPA ; Timer0 Compare A Handler
0x001E jmp TIM0_COMPB ; Timer0 Compare B Handler
0x0020 jmp TIM0_OVF ; Timer0 Overflow Handler
0x0022 jmp SPI_STC ; SPI Transfer Complete Handler
0x0024 jmp USART_RXC ; USART, RX Complete Handler
0x0026 jmp USART_UDRE ; USART, UDR Empty Handler
0x0028 jmp USART_TXC ; USART, TX Complete Handler
0x002A jmp ADC ; ADC Conversion Complete Handler
0x002C jmp EE_RDY ; EEPROM Ready Handler
0x002E jmp ANA_COMP ; Analog Comparator Handler
0x0030 jmp TWI ; 2-wire Serial Interface Handler
0x0032 jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x0033 RESET: ldi r16, high(RAMEND); Main program start
0x0034 out SPH,r16 ; Set Stack Pointer to top of RAM
0x0035 ldi r16, low(RAMEND)
0x0036 out SPL,r16
0x0037 sei ; Enable interrupts
0x0038 <instr> xxx
... ... ... ...
50 ATmega328P [DATASHEET]
7810DAVR01/15
When the BOOTRST fuse is unprogrammed, the boot section size set to 2Kbytes and the IVSEL bit in the MCUCR register
is set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector
addresses in Atmel ATmega328P is:
Address Labels Code Comments
0x0000 RESET: ldi r16,high(RAMEND); Main program start
0x0001 out SPH,r16 ; Set Stack Pointer to top of RAM
0x0002 ldi r16,low(RAMEND)
0x0003 out SPL,r16
0x0004 sei ; Enable interrupts
0x0005 <instr> xxx
;
.org 0x3C02
0x3C02 jmp EXT_INT0 ; IRQ0 Handler
0x3C04 jmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x3C32 jmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST fuse is programmed and the boot section size set to 2Kbytes, the most typical and general program
setup for the reset and interrupt vector addresses in Atmel ATmega328P is:
Address Labels Code Comments
.org 0x0002
0x0002 jmp EXT_INT0 ; IRQ0 Handler
0x0004 jmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x0032 jmp SPM_RDY ; Store Program Memory Ready Handler
;
.org 0x3C00
0x3C00 RESET: ldi r16,high(RAMEND); Main program start
0x3C01 out SPH,r16 ; Set Stack Pointer to top of RAM
0x3C02 ldi r16,low(RAMEND)
0x3C03 out SPL,r16
0x3C04 sei ; Enable interrupts
0x3C05 <instr> xxx
When the BOOTRST fuse is programmed, the boot section size set to 2Kbytes and the IVSEL bit in the MCUCR register is
set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector
addresses in Atmel ATmega328P is:
Address Labels Code Comments
;
.org 0x3C00
0x3C00 jmp RESET ; Reset handler
0x3C02 jmp EXT_INT0 ; IRQ0 Handler
0x3C04 jmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x3C32 jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x3C33 RESET: ldi r16,high(RAMEND); Main program start
0x3C34 out SPH,r16 ; Set Stack Pointer to top of RAM
0x3C35 ldi r16,low(RAMEND)
0x3C36 out SPL,r16
0x3C37 sei ; Enable interrupts
0x3C38 <instr> xxx
ATmega328P [DATASHEET] 51
7810DAVR01/15
11.2 Register Description
52 ATmega328P [DATASHEET]
7810DAVR01/15
12. External Interrupts
The external interrupts are triggered by the INT0 and INT1 pins or any of the PCINT23..0 pins. Observe that, if enabled, the
interrupts will trigger even if the INT0 and INT1 or PCINT23..0 pins are configured as outputs. This feature provides a way of
generating a software interrupt. The pin change interrupt PCI2 will trigger if any enabled PCINT23..16 pin toggles. The pin
change interrupt PCI1 will trigger if any enabled PCINT14..8 pin toggles. The pin change interrupt PCI0 will trigger if any
enabled PCINT7..0 pin toggles. The PCMSK2, PCMSK1 and PCMSK0 registers control which pins contribute to the pin
change interrupts. Pin change interrupts on PCINT23..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 INT0 and INT1 interrupts can be triggered by a falling or rising edge or a low level. This is set up as indicated in the
specification for the external interrupt control register A EICRA. When the INT0 or INT1 interrupts are enabled and are
configured as level triggered, the interrupts will trigger as long as the pin is held low. Note that recognition of falling or rising
edge interrupts on INT0 or INT1 requires the presence of an I/O clock, described in Section 8.1 Clock Systems and their
Distribution on page 24. Low level interrupt on INT0 and INT1 is detected asynchronously. This implies that this interrupt
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 interrupt will be generated. The start-up time is defined by the SUT and CKSEL fuses as
described in Section 8. System Clock and Clock Options on page 24.
clk
PCINT(0)
pin_lat
pin_sync
pcint_in_(0)
pcint_syn
pcint_setflag
PCIF
ATmega328P [DATASHEET] 53
7810DAVR01/15
12.2 Register Description
54 ATmega328P [DATASHEET]
7810DAVR01/15
12.2.2 EIMSK External Interrupt Mask Register
Bit 7 6 5 4 3 2 1 0
0x1D (0x3D) INT1 INT0 EIMSK
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
ATmega328P [DATASHEET] 55
7810DAVR01/15
12.2.4 PCICR Pin Change Interrupt Control Register
Bit 7 6 5 4 3 2 1 0
(0x68) PCIE2 PCIE1 PCIE0 PCICR
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
56 ATmega328P [DATASHEET]
7810DAVR01/15
12.2.6 PCMSK2 Pin Change Mask Register 2
Bit 7 6 5 4 3 2 1 0
(0x6D) PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 PCMSK2
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
ATmega328P [DATASHEET] 57
7810DAVR01/15
13. I/O-Ports
13.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 changing 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 individually 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 13-1. Refer to Section 28. Electrical Characteristics on page 258 for a complete list of parameters.
Rpu
Pxn
Logic
See Figure
Cpin General Digital I/O
for Details
All registers and bit references in this section are written in general form. A lower case x represents the numbering letter for
the port, and a lower case n represents the bit number. However, when using the register or bit defines in a program, the
precise form must be used. For example, PORTB3 for bit no. 3 in port B, here documented generally as PORTxn. The
physical I/O registers and bit locations are listed in Section 13.4 Register Description on page 72.
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
corresponding 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 Section 13.2 Ports as General Digital I/O on page 59. 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 Section 13.3 Alternate Port Functions on page 63. Refer to the individual module sections for a
full description of the alternate functions. Note that enabling the alternate function of some of the port pins does not affect the
use of the other pins in the port as general digital I/O.
58 ATmega328P [DATASHEET]
7810DAVR01/15
13.2 Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 13-2 shows a functional description of one
I/O-port pin, here generically called Pxn.
PUD
Q D
DDxn
Q
CLR
WDx
RESET
RDx
DATA BUS
Pxn Q D
0
PORTxn
Q
CLR
RESET WPx
SLEEP WRx
RRx
Synchronizer
RPx
D Q D Q
PINxn
L Q Q
CLKI/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.
ATmega328P [DATASHEET] 59
7810DAVR01/15
13.2.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction
can be used to toggle one single bit in a port.
SYSTEM CLK
SYNC LATCH
PINxn
tpd, max
tpd, min
Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is
low, and goes transparent when the clock is high, as indicated by the shaded region of the SYNC LATCH signal. The signal
value is latched when the system clock goes low. It is clocked into the PINxn register at the succeeding positive clock edge.
As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between and 1
system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 13-4 on page 61.
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.
60 ATmega328P [DATASHEET]
7810DAVR01/15
Figure 13-4. Synchronization when Reading a Software Assigned Pin Value
SYSTEM CLK
r16 0xFF
SYNC LATCH
PINxn
tpd
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.
Assembly Code Example(1)
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi r16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0)
ldi r17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0)
out PORTB,r16
out DDRB,r17
; Insert nop for synchronization
nop
; Read port pins
in r16,PINB
...
C Code Example
unsigned char i;
...
/* Define pull-ups and set outputs high */
/* Define directions for port pins */
PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0);
DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0);
/* Insert nop for synchronization*/
__no_operation();
/* Read port pins */
i = PINB;
...
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.
ATmega328P [DATASHEET] 61
7810DAVR01/15
13.2.5 Digital Input Enable and Sleep Modes
As shown in Figure 13-2, the digital input signal can be clamped to ground at the input of the Schmitt trigger. The signal
denoted SLEEP in the figure, is set by the MCU sleep controller in power-down mode, power-save mode, and standby mode
to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2.
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled, SLEEP
is active also for these pins. SLEEP is also overridden by various other alternate functions as described in Section 13.3
Alternate Port Functions on page 63.
If a logic high level (one) is present on an asynchronous external interrupt pin configured as interrupt on rising edge, falling
edge, or any logic change on pin while the external interrupt is not enabled, the corresponding external interrupt flag will be
set when resuming from the above mentioned sleep mode, as the clamping in these sleep mode produces the requested
logic change.
62 ATmega328P [DATASHEET]
7810DAVR01/15
13.3 Alternate Port Functions
Most port pins have alternate functions in addition to being general digital I/Os. Figure 13-5 shows how the port pin control
signals from the simplified Figure 13-2 on page 59 can be overridden by alternate functions. The overriding signals may not
be present in all port pins, but the figure serves as a generic description applicable to all port pins in the AVR
microcontroller family.
1 PUOVxn
PUD
0
DDOExn
1 DDOVxn
0 Q D
DDxn
Q
CLR
WDx
RESET
RDx
PVOExn
1 PVOVxn
Pxn 1
DATA BUS
0 Q D
0
PORTxn
DIEOExn Q PTOExn
CLR
1 DIEOVxn RESET
WRx WPx
0 SLEEP RRx
Synchronizer
RPx
D SET Q D Q
PINxn
L Q Q
CLR CLR
CLKI/O
DIxn
AIOxn
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.
ATmega328P [DATASHEET] 63
7810DAVR01/15
Table 13-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 13-5 on page 63 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.
64 ATmega328P [DATASHEET]
7810DAVR01/15
13.3.1 Alternate Functions of Port B
The port B pins with alternate functions are shown in Table 13-3.
ATmega328P [DATASHEET] 65
7810DAVR01/15
SCK/PCINT5 Port B, Bit 5
SCK: Master clock output, slave clock input pin for SPI channel. When the SPI is enabled as a slave, this pin is configured as
an input regardless of the setting of DDB5. When the SPI is enabled as a master, the data direction of this pin is controlled
by DDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.
PCINT5: Pin change interrupt source 5. The PB5 pin can serve as an external interrupt source.
66 ATmega328P [DATASHEET]
7810DAVR01/15
Table 13-4. Overriding Signals for Alternate Functions in PB7..PB4
ATmega328P [DATASHEET] 67
7810DAVR01/15
13.3.2 Alternate Functions of Port C
The port C pins with alternate functions are shown in Table 13-6.
68 ATmega328P [DATASHEET]
7810DAVR01/15
ADC2/PCINT10 Port C, Bit 2
PC2 can also be used as ADC input channel 2. Note that ADC input channel 2 uses analog power.
PCINT10: Pin change interrupt source 10. The PC2 pin can serve as an external interrupt source.
ATmega328P [DATASHEET] 69
7810DAVR01/15
13.3.3 Alternate Functions of Port D
The port D pins with alternate functions are shown in Table 13-9.
70 ATmega328P [DATASHEET]
7810DAVR01/15
INT1/OC2B/PCINT19 Port D, Bit 3
INT1, external interrupt source 1: The PD3 pin can serve as an external interrupt source.
OC2B, output compare match output: The PD3 pin can serve as an external output for the Timer/Counter0 compare match
B. The PD3 pin has to be configured as an output (DDD3 set (one)) to serve this function. The OC2B pin is also the output
pin for the PWM mode timer function.
PCINT19: Pin change interrupt source 19. The PD3 pin can serve as an external interrupt source.
ATmega328P [DATASHEET] 71
7810DAVR01/15
Table 13-11. Overriding Signals for Alternate Functions in PD3..PD0
72 ATmega328P [DATASHEET]
7810DAVR01/15
13.4.5 PORTC The Port C Data Register
Bit 7 6 5 4 3 2 1 0
0x08 (0x28) PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 PORTC
Read/Write R R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
ATmega328P [DATASHEET] 73
7810DAVR01/15
14. 8-bit Timer/Counter0 with PWM
14.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)
14.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 management) and wave generation.
A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 14-1. For the actual placement of I/O pins, refer to
Section 1-1 Pinout on page 3. 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 Section 14.9 Register Description on page 84.
The PRTIM0 bit in Section 9.10 Minimizing Power Consumption on page 36 must be written to zero to enable
Timer/Counter0 module.
(from Prescaler)
TOP BOTTOM
Timer/Counter
TCNTn
= = 0
Waveform
= Generation
OCnA
OCRnA
Fixed
TOP
DATA BUS
Waveform
= Generation
OCnB
OCRnB
TCCRnA TCCRnB
74 ATmega328P [DATASHEET]
7810DAVR01/15
14.2.1 Definitions
Many register and bit references in this section are written in general form. A lower case n replaces the Timer/Counter
number, in this case 0. A lower case x replaces the output compare unit, in this case compare unit A or compare unit B.
However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing
Timer/Counter0 counter value and so on.
The definitions in Table 14-1 are also used extensively throughout the document.
Parameter Definition
BOTTOM The counter reaches the BOTTOM when it becomes 0x00.
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The
TOP TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0A register.
The assignment is dependent on the mode of operation.
14.2.2 Registers
The Timer/Counter (TCNT0) and output compare registers (OCR0A and OCR0B) are 8-bit registers. interrupt request
(abbreviated to Int.Req. in the figure) signals are all visible in the timer interrupt flag register (TIFR0). All interrupts are
individually masked with the timer interrupt mask register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T0 pin. The clock select
logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The
Timer/Counter is inactive when no clock source is selected. The output from the clock select logic is referred to as the timer
clock (clkT0).
The double buffered output compare registers (OCR0A and OCR0B) are compared with the Timer/Counter value at all
times. The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on
the output compare pins (OC0A and OC0B). See Section 15.7.3 Using the Output Compare Unit on page 99 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.
Clock Select
count Edge
Tn
clear clkTn Detector
TCNTn Control Logic
direction
(from Prescaler)
bottom top
ATmega328P [DATASHEET] 75
7810DAVR01/15
Signal description (internal signals):
count Increment or decrement TCNT0 by 1.
direction Select between increment and decrement.
clear Clear TCNT0 (set all bits to zero).
clkTn Timer/Counter clock, referred to as clkT0 in the following.
top Signalize that TCNT0 has reached maximum value.
bottom Signalize that TCNT0 has reached minimum value (zero).
Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0).
clkT0 can be generated from an external or internal clock source, selected by the clock select bits (CS02:0). When no clock
source is selected (CS02:0 = 0) the timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of
whether clkT0 is present or not. A CPU write overrides (has priority over) all counter clear or count operations.
The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the Timer/Counter control
register (TCCR0A) and the WGM02 bit located in the Timer/Counter control register B (TCCR0B). There are close
connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs
OC0A and OC0B. For more details about advanced counting sequences and waveform generation, see Section 14.7
Modes of Operation on page 78.
The Timer/Counter overflow flag (TOV0) is set according to the mode of operation selected by the WGM02:0 bits. TOV0 can
be used for generating a CPU interrupt.
OCRnx TCNTn
= (8-bit Comparator)
top
FOCn
WGMn1:0 COMnx1:0
76 ATmega328P [DATASHEET]
7810DAVR01/15
The OCR0x registers are double buffered when using any of the pulse width modulation (PWM) modes. For the normal and
clear timer on compare (CTC) modes of operation, the double buffering is disabled. The double buffering synchronizes the
update of the OCR0x compare registers to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR0x register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has
access to the OCR0x buffer register, and if double buffering is disabled the CPU will access the OCR0x directly.
ATmega328P [DATASHEET] 77
7810DAVR01/15
Figure 14-4. Compare Match Output Unit, Schematic
COMnx1
COMnx0 Waveform
Generator D Q
FOCnx
1
OCnx
OCnx Pin
0
D Q
D Q
DDR
clkI/O
The general I/O port function is overridden by the output compare (OC0x) from the waveform generator if either of the
COM0x1:0 bits are set. However, the OC0x pin direction (input or output) is still controlled by the data direction register
(DDR) for the port pin. The data direction register bit for the OC0x pin (DDR_OC0x) must be set as output before the OC0x
value is visible on the pin. The port override function is independent of the waveform generation mode.
The design of the output compare pin logic allows initialization of the OC0x state before the output is enabled. Note that
some COM0x1:0 bit settings are reserved for certain modes of operation. See Section 14.9 Register Description on page
84
78 ATmega328P [DATASHEET]
7810DAVR01/15
14.7.1 Normal Mode
The simplest mode of operation is the normal mode (WGM02:0 = 0). In this mode the counting direction is always up
(incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value
(TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter overflow flag (TOV0) will be
set in the same timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth bit, except
that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 flag,
the timer resolution can be increased by software. There are no special cases to consider in the normal mode, a new counter
value can be written anytime.
The output compare unit can be used to generate interrupts at some given time. Using the output compare to generate
waveforms in normal mode is not recommended, since this will occupy too much of the CPU time.
TCNTn
OCn (COMnA1:0 = 1)
(Toggle)
1 2 3 4
Period
An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A flag. If the interrupt
is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to
BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does
not have the double buffering feature. If the new value written to OCR0A is lower than the current value of TCNT0, the
counter will miss the compare match. The counter will then have to count to its maximum value (0xFF) and wrap around
starting at 0x00 before the compare match can occur.
For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical level on each compare
match by setting the compare output mode bits to toggle mode (COM0A1:0 = 1). The OC0A value will not be visible on the
port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of
fOC0 = fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following equation:
f clk_I/O
f OCnx = ----------------------------------------------------
2 N 1 + OCRnx
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
As for the normal mode of operation, the TOV0 flag is set in the same timer clock cycle that the counter counts from MAX to
0x00.
ATmega328P [DATASHEET] 79
7810DAVR01/15
14.7.3 Fast PWM Mode
The fast pulse width modulation or fast PWM mode (WGM02:0 = 3 or 7) provides a high frequency PWM waveform
generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from
BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7.
In non-inverting compare output mode, the output compare (OC0x) is cleared on the compare match between TCNT0 and
OCR0x, and set at BOTTOM. In inverting compare output mode, the output is set on compare match and cleared at
BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the
phase correct PWM mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited for
power regulation, rectification, and DAC applications. High frequency allows physically small sized external components
(coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at
the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 14-6. The TCNT0 value is in
the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0x
and TCNT0.
OCRnx Interrupt
Flag Set
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3 4 5 6 7
Period
The Timer/Counter overflow flag (TOV0) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt
handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to
two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM0x1:0 to three:
Setting the COM0A1:0 bits to one allows the OC0A pin to toggle on compare matches if the WGM02 bit is set. This option is
not available for the OC0B pin (see Table 14-6 on page 85). 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).
80 ATmega328P [DATASHEET]
7810DAVR01/15
The extreme values for the OCR0A register represents special cases when generating a PWM waveform output in the fast
PWM mode. If the OCR0A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle.
Setting the OCR0A equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by
the COM0A1:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0x to toggle its logical
level on each compare match (COM0x1:0 = 1). The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2
when OCR0A is set to zero. This feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the
output compare unit is enabled in the fast PWM mode.
OCnx Interrupt
Flag Set
OCRnx Update
TOVn Interrupt
Flag Set
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3
Period
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.
ATmega328P [DATASHEET] 81
7810DAVR01/15
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the
COM0x1:0 bits to two will produce a non-inverted PWM. An inverted PWM output can be generated by setting the
COM0x1:0 to three: Setting the COM0A0 bits to 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 14-7 on page 85). The actual OC0x value will only be visible on
the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the
OC0x register at the compare match between OCR0x and TCNT0 when the counter increments, and setting (or clearing) the
OC0x register at compare match between OCR0x and TCNT0 when the counter decrements. The PWM frequency for the
output when using phase correct PWM can be calculated by the following equation:
f clk_I/O
f OCnxPCPWM = -------------------
N 510
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A register represent special cases when generating a PWM waveform output in the phase
correct PWM mode. If the OCR0A is set equal to BOTTOM, the output will be continuously low and if set equal to MAX the
output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic
values.
At the very start of period 2 in Figure 14-7 on page 81 OCnx has a transition from high to low even though there is no
compare match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a
transition without compare match.
OCRnx changes its value from MAX, like in Figure 14-7 on page 81. When the OCR0A value is MAX the OCn pin
value is the same as the result of a down-counting compare match. To ensure symmetry around BOTTOM the OCnx
value at MAX must correspond to the result of an up-counting compare match.
The timer starts counting from a value higher than the one in OCRnx, and for that reason misses the compare match
and hence the OCnx change that would have happened on the way up.
clkI/O
clkTn
(clkI/O/1)
TOVn
82 ATmega328P [DATASHEET]
7810DAVR01/15
Figure 14-9 shows the same timing data, but with the prescaler enabled.
clkI/O
clkTn
(clkI/O/8)
TOVn
Figure 14-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 14-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O/8)
OCFnx
Figure 14-11 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode and fast PWM mode where OCR0A is
TOP.
Figure 14-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O/8)
TCNTn
(CTC) TOP - 1 TOP BOTTOM BOTTOM + 1
OCRnx TOP
OCFnx
ATmega328P [DATASHEET] 83
7810DAVR01/15
14.9 Register Description
Table 14-3 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM mode.
Table 14-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode.
84 ATmega328P [DATASHEET]
7810DAVR01/15
Bits 5:4 COM0B1:0: Compare Match Output B Mode
These bits control the output compare pin (OC0B) behavior. If one or both of the COM0B1:0 bits are set, the OC0B output
overrides the normal port functionality of the I/O pin it is connected to. However, note that the data direction register (DDR)
bit corresponding to the OC0B pin must be set in order to enable the output driver.
When OC0B is connected to the pin, the function of the COM0B1:0 bits depends on the WGM02:0 bit setting. Table 14-5
shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to a normal or CTC mode (non-PWM).
Table 14-6 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM mode.
Table 14-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode.
ATmega328P [DATASHEET] 85
7810DAVR01/15
Bits 1:0 WGM01:0: Waveform Generation Mode
Combined with the WGM02 bit found in the TCCR0B register, these bits control the counting sequence of the counter, the
source for maximum (TOP) counter value, and what type of waveform generation to be used, see Table 14-8. Modes of
operation supported by the Timer/Counter unit are: Normal mode (counter), clear timer on compare match (CTC) mode, and
two types of pulse width modulation (PWM) modes (see Section 14.7 Modes of Operation on page 78).
86 ATmega328P [DATASHEET]
7810DAVR01/15
Bit 3 WGM02: Waveform Generation Mode
See the description in the Section 14.9.1 TCCR0A Timer/Counter Control Register A on page 84.
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.
ATmega328P [DATASHEET] 87
7810DAVR01/15
14.9.6 TIMSK0 Timer/Counter Interrupt Mask Register
Bit 7 6 5 4 3 2 1 0
(0x6E) OCIE0B OCIE0A TOIE0 TIMSK0
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
88 ATmega328P [DATASHEET]
7810DAVR01/15
15. 16-bit Timer/Counter1 with PWM
15.1 Features
True 16-bit design (i.e., allows 16-bit PWM)
Two 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
Four independent interrupt sources (TOV1, OCF1A, OCF1B, and ICF1)
15.2 Overview
The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal
timing measurement.
Most register and bit references in this section are written in general form. A lower case n replaces the Timer/Counter
number, and a lower case x replaces the output compare unit channel. However, when using the register or bit defines in a
program, the precise form must be used, i.e., TCNT1 for accessing Timer/Counter1 counter value and so on.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 15-1 on page 90. For the actual placement of I/O
pins, refer to Section 1-1 Pinout on page 3. 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 Section 15.11 Register Description on page 108.
The PRTIM1 bit in Section 9.11.3 PRR Power Reduction Register on page 38 must be written to zero to enable
Timer/Counter1 module.
ATmega328P [DATASHEET] 89
7810DAVR01/15
Figure 15-1. 16-bit Timer/Counter Block Diagram(1)
TOVn (Int. Req.)
Count
Clear Clock Select
Control Logic
Direction Edge
clkTn
Tn
Detector
(from Prescaler)
TOP BOTTOM
Timer/Counter
TCNTn
= = 0
Waveform
= Generation
OCnA
OCRnA
Fixed
DATA BUS
Edge Noise
ICRn
Detector Canceler
ICPn
TCCRnA TCCRnB
Note: 1. Refer to Figure 1-1 on page 3, Table 13-3 on page 65 and Table 13-9 on page 70 for Timer/Counter1 pin
placement and description.
15.2.1 Registers
The Timer/Counter (TCNT1), output compare registers (OCR1A/B), and input capture register (ICR1) are all 16-bit registers.
Special procedures must be followed when accessing the 16-bit registers. These procedures are described in the Section
15.3 Accessing 16-bit Registers on page 91. The Timer/Counter control registers (TCCR1A/B) are 8-bit registers and have
no CPU access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are all visible in the timer
interrupt flag register (TIFR1). All interrupts are individually masked with the timer interrupt mask register (TIMSK1). TIFR1
and TIMSK1 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T1 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 (clkT1).
90 ATmega328P [DATASHEET]
7810DAVR01/15
The double buffered output compare registers (OCR1A/B) are compared with the Timer/Counter value at all time. The result
of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the output
compare pin (OC1A/B). See Section 15.7 Output Compare Units on page 97. The compare match event will also set the
compare match flag (OCF1A/B) 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 triggered) event on either the input
capture pin (ICP1) or on the analog comparator pins (see Section 22. Analog Comparator on page 202). 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 OCR1A
register, the ICR1 register, or by a set of fixed values. When using OCR1A as TOP value in a PWM mode, the OCR1A
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 ICR1 register can be used as an alternative,
freeing the OCR1A to be used as PWM output.
15.2.2 Definitions
The following definitions are used extensively throughout the section:
Parameter Definition
BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.
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
TOP value can be assigned to be one of the fixed values: 0x00FF, 0x01FF, or 0x03FF, or to the value stored in
the OCR1A or ICR1 register. The assignment is dependent of the mode of operation.
ATmega328P [DATASHEET] 91
7810DAVR01/15
The following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the
temporary register. The same principle can be used directly for accessing the OCR1A/B and ICR1 registers. Note that when
using C, the compiler handles the 16-bit access.
Assembly Code Examples(1)
...
; Set TCNT1 to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNT1H,r17
out TCNT1L,r16
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
...
C Code Examples(1)
unsigned int i;
...
/* Set TCNT1 to 0x01FF */
TCNT1 = 0x1FF;
/* Read TCNT1 into i */
i = TCNT1;
...
Note: 1. See Section 5. About Code Examples on page 8
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.
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two
instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or
any other of the 16-bit timer registers, then the result of the access outside the interrupt will be corrupted. Therefore, when
both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during
the 16-bit access.
92 ATmega328P [DATASHEET]
7810DAVR01/15
The following code examples show how to do an atomic read of the TCNT1 register contents. Reading any of the OCR1A/B
or ICR1 registers can be done by using the same principle.
Assembly Code Example(1)
TIM16_ReadTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
; Restore global interrupt flag
out SREG,r18
ret
C Code Example(1)
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNT1 into i */
i = TCNT1;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}
Note: 1. See Section 5. About Code Examples on page 8.
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.
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
ATmega328P [DATASHEET] 93
7810DAVR01/15
The following code examples show how to do an atomic write of the TCNT1 register contents. Writing any of the OCR1A/B
or ICR1 registers can be done by using the same principle.
Assembly Code Example(1)
TIM16_WriteTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT1 to r17:r16
out TCNT1H,r17
out TCNT1L,r16
; Restore global interrupt flag
out SREG,r18
ret
C Code Example(1)
void TIM16_WriteTCNT1(unsigned int i)
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNT1 to i */
TCNT1 = i;
/* Restore global interrupt flag */
SREG = sreg;
}
Note: 1. See Section 5. About Code Examples on page 8.
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.
The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNT1.
94 ATmega328P [DATASHEET]
7810DAVR01/15
15.5 Counter Unit
The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 15-2 shows a block
diagram of the counter and its surroundings.
TOVn
(Int. Req.)
TEMP (8-bit)
Clock Select
Count Edge
TCNTnH (8-bit) TCNTnL (8-bit) Tn
Clear clkTn Detector
Control Logic
Direction
TCNTnH (16-bit Counter) (from Prescaler)
TOP BOTTOM
ATmega328P [DATASHEET] 95
7810DAVR01/15
Figure 15-3. Input Capture Unit Block Diagram
DATA BUS (8-bit)
TEMP (8-bit)
- Analog
Comparator
Noise Edge
ICFn (Int. Req.)
Canceler Detector
ICPn
When a change of the logic level (an event) occurs on the input capture pin (ICP1), 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 (TCNT1) is written to the input capture register (ICR1). The input capture flag (ICF1)
is set at the same system clock as the TCNT1 value is copied into ICR1 register. If enabled (ICIE1 = 1), the input capture flag
generates an input capture interrupt. The ICF1 flag is automatically cleared when the interrupt is executed. Alternatively the
ICF1 flag can be cleared by software by writing a logical one to its I/O bit location.
Reading the 16-bit value in the input capture register (ICR1) is done by first reading the low byte (ICR1L) and then the high
byte (ICR1H). When the low byte is read the high byte is copied into the high byte temporary register (TEMP). When the
CPU reads the ICR1H I/O location it will access the TEMP register.
The ICR1 register can only be written when using a waveform generation mode that utilizes the ICR1 register for defining the
counters TOP value. In these cases the waveform generation mode (WGM13:0) bits must be set before the TOP value can
be written to the ICR1 register. When writing the ICR1 register the high byte must be written to the ICR1H I/O location before
the low byte is written to ICR1L.
For more information on how to access the 16-bit registers refer to Section 15.3 Accessing 16-bit Registers on page 91.
96 ATmega328P [DATASHEET]
7810DAVR01/15
15.6.2 Noise Canceler
The noise canceler improves noise immunity by using a simple digital filtering scheme. The noise canceler input is monitored
over four samples, and all four must be equal for changing the output that in turn is used by the edge detector.
The noise canceler is enabled by setting the input capture noise canceler (ICNC1) bit in Timer/Counter control register B
(TCCR1B). When enabled the noise canceler introduces additional four system clock cycles of delay from a change applied
to the input, to the update of the ICR1 register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.
ATmega328P [DATASHEET] 97
7810DAVR01/15
Figure 15-4. Output Compare Unit, Block Diagram
DATA BUS (8-bit)
TEMP (8-bit)
OCRnxH Buf. (8-bit) OCRnxL Buf. (8-bit) TCNTnH (8-bit) TCNTnL (8-bit)
= (16-bitComparator)
TOP
Waveform Generator OCnx
BOTTOM
WGMn3:0 COMnx1:0
The OCR1x 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 OCR1x compare 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 output glitch-free.
The OCR1x register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has
access to the OCR1x buffer register, and if double buffering is disabled the CPU will access the OCR1x 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 OCR1x
registers must be done via the TEMP register since the compare of all 16 bits is done continuously. The high byte (OCR1xH)
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 (OCR1xL) is written to the lower eight bits, the high byte will be copied into the upper 8-bits
of either the OCR1x buffer or OCR1x compare register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to Section 15.3 Accessing 16-bit Registers on page 91.
98 ATmega328P [DATASHEET]
7810DAVR01/15
15.7.3 Using the Output Compare Unit
Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock cycle, there are risks
involved when changing TCNT1 when using any of the output compare channels, independent of whether the Timer/Counter
is running or not. If the value written to TCNT1 equals the OCR1x value, the compare match will be missed, resulting in
incorrect waveform generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP values. The
compare match for the TOP will be ignored and the counter will continue to 0xFFFF. Similarly, do not write the TCNT1 value
equal to BOTTOM when the counter is downcounting.
The setup of the OC1x should be performed before setting the data direction register for the port pin to output. The easiest
way of setting the OC1x value is to use the force output compare (FOC1x) strobe bits in normal mode. The OC1x register
keeps its value even when changing between waveform generation modes.
Be aware that the COM1x1:0 bits are not double buffered together with the compare value. Changing the COM1x1:0 bits will
take effect immediately.
COMnx1
COMnx0 Waveform
Generator D Q
FOCn
1
OCnx
OCnx Pin
0
D Q
DATA BUS
PORT
D Q
DDR
clkI/O
The general I/O port function is overridden by the output compare (OC1x) from the waveform generator if either of the
COM1x1:0 bits are set. However, the OC1x pin direction (input or output) is still controlled by the data direction register
(DDR) for the port pin. The data direction register bit for the OC1x pin (DDR_OC1x) must be set as output before the OC1x
value is visible on the pin. The port override function is generally independent of the waveform generation mode, but there
are some exceptions. Refer to Table 15-2 on page 108, Table 15-3 on page 108 and Table 15-4 on page 109 for details.
The design of the output compare pin logic allows initialization of the OC1x state before the output is enabled. Note that
some COM1x1:0 bit settings are reserved for certain modes of operation. See Section 15.11 Register Description on page
108. The COM1x1:0 bits have no effect on the input capture unit.
ATmega328P [DATASHEET] 99
7810DAVR01/15
15.8.1 Compare Output Mode and Waveform Generation
The waveform generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the
COM1x1:0 = 0 tells the waveform generator that no action on the OC1x register is to be performed on the next compare
match. For compare output actions in the non-PWM modes refer to Table 15-2 on page 108. For fast PWM mode refer to
Table 15-3 on page 108, and for phase correct and phase and frequency correct PWM refer to Table 15-4 on page 109.
A change of the COM1x1: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 FOC1x strobe bits.
TCNTn
OCnA (COMnA1:0 = 1)
(Toggle)
1 2 3 4
Period
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 TOV1 flag is set in the same timer clock cycle that the counter counts from MAX to
0x0000.
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 (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 = 14), or the value in OCR1A (WGM13: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 15-7 on page 102. The figure shows fast PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 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 TCNT1 slopes represent compare matches between
OCR1x and TCNT1. The OC1x interrupt flag will be set when a compare match occurs.
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3 4 5 6 7 8
Period
The Timer/Counter overflow flag (TOV1) is set each time the counter reaches TOP. In addition the OC1A or ICF1 flag is set
at the same timer clock cycle as TOV1 is set when either OCR1A or ICR1 is used for defining the TOP value. If one of the
interrupts are enabled, the interrupt handler 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 TCNT1 and the OCR1x. Note that when using fixed TOP values the unused bits are masked to zero when any of the
OCR1x registers are written.
The procedure for updating ICR1 differs from updating OCR1A when used for defining the TOP value. The ICR1 register is
not double buffered. This means that if ICR1 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 ICR1 value written is lower than the current value of TCNT1. 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 OCR1A register however, is double
buffered. This feature allows the OCR1A I/O location to be written anytime. When the OCR1A I/O location is written the
value written will be put into the OCR1A buffer register. The OCR1A compare register will then be updated with the value in
the buffer register at the next timer clock cycle the TCNT1 matches TOP. The update is done at the same timer clock cycle
as the TCNT1 is cleared and the TOV1 flag is set.
Using the ICR1 register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A register is
free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively changed (by
changing the TOP value), using the OCR1A 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 OC1x pins. Setting the COM1x1:0 bits to
two will produce a inverted PWM and an non-inverted PWM output can be generated by setting the COM1x1:0 to three (see
Table on page 108). The actual OC1x value will only be visible on the port pin if the data direction for the port pin is set as
output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x register at the compare match
between OCR1x and TCNT1, and clearing (or setting) the OC1x 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 OCR1x register represents special cases when generating a PWM waveform output in the fast
PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the output will be a narrow spike for each TOP+1 timer clock
cycle. Setting the OCR1x equal to TOP will result in a constant high or low output (depending on the polarity of the output set
by the COM1x1:0 bits.)
log TOP + 1
R PCPWM = ---------------------------------
log 2
In phase correct PWM mode the counter is incremented until the counter value matches either one of the fixed values
0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1 (WGM13:0 = 10), or the value in OCR1A
(WGM13:0 = 11). The counter has then reached the TOP and changes the count direction. The TCNT1 value will be equal to
TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 15-8. The figure
shows phase correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 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 TCNT1 slopes represent compare matches between OCR1x and TCNT1.
The OC1x interrupt flag will be set when a compare match occurs.
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3 4
Period
The Timer/Counter overflow flag (TOV1) is set each time the counter reaches BOTTOM. When either OCR1A or ICR1 is
used for defining the TOP value, the OC1A or ICF1 flag is set accordingly at the same timer clock cycle as the OCR1x
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.
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 OCR1x register represent special cases when generating a PWM waveform output in the phase
correct PWM mode. If the OCR1x 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 COM1A1:0 = 1, the OC1A output will toggle with a
50% duty cycle.
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
ICR1 (WGM13:0 = 8), or the value in OCR1A (WGM13:0 = 9). The counter has then reached the TOP and changes the
count direction. The TCNT1 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 15-9 on page 105. The figure shows phase and frequency correct
PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 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 TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x interrupt flag will be
set when a compare match occurs.
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3 4
Period
The Timer/Counter overflow flag (TOV1) is set at the same timer clock cycle as the OCR1x registers are updated with the
double buffer value (at BOTTOM). When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 flag
set when TCNT1 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 TCNT1 and the OCR1x.
As Figure 15-9 shows the output generated is, in contrast to the phase correct mode, symmetrical in all periods. Since the
OCR1x 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.
Using the ICR1 register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A register is
free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively changed by
changing the TOP value, using the OCR1A 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 waveforms on the OC1x pins.
Setting the COM1x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting
the COM1x1:0 to three (See Table on page 109). The actual OC1x value will only be visible on the port pin if the data
direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x
register at the compare match between OCR1x and TCNT1 when the counter increments, and clearing (or setting) the OC1x
register at compare match between OCR1x and TCNT1 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 OCR1x register represents special cases when generating a PWM waveform output in the phase
correct PWM mode. If the OCR1x 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 (WGM13:0 = 9) and COM1A1:0 = 1, the OC1A output will toggle with a 50% duty
cycle.
clkI/O
clkTn
(clkI/O/1)
OCFnx
Figure 15-11 shows the same timing data, but with the prescaler enabled.
Figure 15-11. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O/8)
OCFnx
clkI/O
clkTn
(clkI/O/1)
TCNTn
(CTC and FPWM) TOP - 1 TOP BOTTOM BOTTOM + 1
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP -1 TOP -2
TOVn (FPWM)
and ICFn
(if used as TOP)
Figure 15-13 shows the same timing data, but with the prescaler enabled.
clkI/O
clkTn
(clkI/O/8)
TCNTn
(CTC and FPWM) TOP - 1 TOP BOTTOM BOTTOM + 1
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
TOVn (FPWM)
and ICFn
(if used as TOP)
Table 15-3 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the fast PWM mode.
Table 15-4. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM(1)
If external pin modes are used for the Timer/Counter1, transitions on the T1 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 (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for
write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and low bytes are read and written
simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary high byte register
(TEMP). This temporary register is shared by all the other 16-bit registers. See Section 15.3 Accessing 16-bit Registers on
page 91.
Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a compare match between TCNT1
and one of the OCR1x registers.
Writing to the TCNT1 register blocks (removes) the compare match on the following timer clock for all compare units.
The output compare registers contain a 16-bit value that is continuously compared with the counter value (TCNT1). A match
can be used to generate an output compare interrupt, or to generate a waveform output on the OC1x 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 Section 15.3 Accessing 16-bit Registers on page 91.
The input capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 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 Section 15.3 Accessing 16-bit Registers on page 91.
Tn D Q D Q D Q Tn_sync
(to Clock
Select Logic)
LE
clkI/O
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 T1/T0 pin to the counter is updated.
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least one system clock cycle,
otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. The
external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty
cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling
frequency (nyquist sampling theorem). However, due to variation of the system clock frequency and duty cycle caused by
oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external
clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
CK/8
CK/64
CK/256
CK/1024
PSRSYNC
T0 Synchronization
T1 Synchronization 0 0
CS10 CS00
CS11 CS01
CS12 CS02
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 16-1.
17.1 Features
Single channel counter
Clear timer on compare match (auto reload)
Glitch-free, phase correct pulse width modulator (PWM)
Frequency generator
10-bit Clock prescaler
Overflow and compare match interrupt sources (TOV2, OCF2A and OCF2B)
Allows clocking from external 32kHz watch crystal independent of the I/O clock
17.2 Overview
Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. A simplified block diagram of the 8-bit
Timer/Counter is shown in Figure 17-1. For the actual placement of I/O pins, refer to Section 1-1 Pinout on page 3. 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 Section 17.11 Register Description on page 127.
The PRTIM2 bit in Section 9.10 Minimizing Power Consumption on page 36 must be written to zero to enable
Timer/Counter2 module.
(from Prescaler)
TOP BOTTOM
Timer/Counter
TCNTn
= = 0
Waveform
= Generation
OCnA
OCRnA
Fixed
TOP
DATA BUS
Waveform
= Generation
OCnB
OCRnB
TCCRnA TCCRnB
17.2.2 Definitions
Many register and bit references in this document are written in general form. A lower case n replaces the Timer/Counter
number, in this case 2. However, when using the register or bit defines in a program, the precise form must be used, i.e.,
TCNT2 for accessing Timer/Counter2 counter value and so on.
The definitions in Table 17-1 are also used extensively throughout the section.
TOSC1
count T/C
Oscillator
clear clkTn
TCNTn Control Logic Prescaler TOSC2
direction
clkI/O
bottom top
OCRnx TCNTn
= (8-bit Comparator)
top
FOCn
WGMn1:0 COMnx1:0
COMnx1
COMnx0 Waveform
Generator D Q
FOCnx
1
OCnx
OCnx Pin
0
D Q
D Q
DDR
clkI/O
The general I/O port function is overridden by the output compare (OC2x) from the waveform generator if either of the
COM2x1:0 bits are set. However, the OC2x pin direction (input or output) is still controlled by the data direction register
(DDR) for the port pin. The data direction register bit for the OC2x pin (DDR_OC2x) must be set as output before the OC2x
value is visible on the pin. The port override function is independent of the waveform generation mode.
The design of the output compare pin logic allows initialization of the OC2x state before the output is enabled. Note that
some COM2x1:0 bit settings are reserved for certain modes of operation. See Section 17.11 Register Description on page
127.
TCNTn
OCnx (COMnA1:0 = 1)
(Toggle)
1 2 3 4
Period
An interrupt can be generated each time the counter value reaches the TOP value by using the OCF2A flag. If the interrupt
is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to
BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does
not have the double buffering feature. If the new value written to OCR2A is lower than the current value of TCNT2, 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 OC2A output can be set to toggle its logical level on each compare
match by setting the compare output mode bits to toggle mode (COM2A1:0 = 1). The OC2A 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
fOC2A = fclk_I/O/2 when OCR2A 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, 32, 64, 128, 256, or 1024).
As for the normal mode of operation, the TOV2 flag is set in the same timer clock cycle that the counter counts from MAX to
0x00.
OCRnx Interrupt
Flag Set
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3 4 5 6 7
Period
The Timer/Counter overflow flag (TOV2) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt
handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin. Setting the COM2x1:0 bits to
two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM2x1:0 to three. TOP
is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7. (See Table 17-3 on page 128). The actual OC2x
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 OC2x register at the compare match between OCR2x and TCNT2, and clearing (or setting) the
OC2x 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, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A register represent special cases when generating a PWM waveform output in the fast
PWM mode. If the OCR2A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle.
Setting the OCR2A equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by
the COM2A1:0 bits.)
OCnx Interrupt
Flag Set
OCRnx Update
TOVn Interrupt
Flag Set
TCNTn
OCnx (COMnx1:0 = 2)
OCnx (COMnx1:0 = 3)
1 2 3
Period
The Timer/Counter overflow flag (TOV2) 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.
f clk_I/O
f OCnxPCPWM = -------------------
N 510
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A register represent special cases when generating a PWM waveform output in the phase
correct PWM mode. If the OCR2A 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 17-7 on page 123 OCnx has a transition from high to low even though there is no
compare match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a
transition without compare match.
OCR2A changes its value from MAX, like in Figure 17-7 on page 123. When the OCR2A 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 OCR2A, 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
clkI/O
clkTn
(clkI/O/8)
TOVn
Figure 17-10 shows the setting of OCF2A in all modes except CTC mode.
Figure 17-10. Timer/Counter Timing Diagram, Setting of OCF2A, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O/8)
OCFnx
Figure 17-11 shows the setting of OCF2A and the clearing of TCNT2 in CTC mode.
Figure 17-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with Prescaler (fclk_I/O/8)
clkI/O
clkTn
(clkI/O/8)
TCNTn
(CTC) TOP - 1 TOP BOTTOM BOTTOM + 1
OCRnx TOP
OCFnx
clkI/O
clkT2S
10-bit T/C Prescaler
Clear
TOSC1
clkT2S/8
clkT2S/32
clkT2S/64
clkT2S/128
clkT2S/256
clkT2S/1024
AS2
PSRASY
0
CS20
CS21
CS22
The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main system I/O clock clkIO. By
setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously clocked from the TOSC1 pin. This enables use of
Timer/Counter2 as a real time counter (RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected from port C. A
crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock source for
Timer/Counter2. The oscillator is optimized for use with a 32.768kHz crystal.
For Timer/Counter2, the possible prescaled selections are: clkT2S/8, clkT2S/32, clkT2S/64, clkT2S/128, clkT2S/256, and
clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected. Setting the PSRASY bit in GTCCR resets the prescaler.
This allows the user to operate with a predictable prescaler.
Table 17-3 shows the COM2A1:0 bit functionality when the WGM21:0 bits are set to fast PWM mode.
Table 17-4 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to phase correct PWM mode.
Table 17-6 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to fast PWM mode.
Table 17-7 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to phase correct PWM mode.
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 TCNT2 register blocks (removes) the compare match on the following timer clock. Modifying the counter
(TCNT2) while the counter is running, introduces a risk of missing a compare match between TCNT2 and the OCR2x
registers.
The output compare register A contains an 8-bit value that is continuously compared with the counter value (TCNT2). A
match can be used to generate an output compare interrupt, or to generate a waveform output on the OC2A pin.
The output compare register B contains an 8-bit value that is continuously compared with the counter value (TCNT2). A
match can be used to generate an output compare interrupt, or to generate a waveform output on the OC2B pin.
18.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
18.2 Overview
The serial peripheral interface (SPI) allows high-speed synchronous data transfer between the ATmega328P and peripheral
devices or between several AVR devices.
The USART can also be used in master SPI mode, see Section 20. USART in SPI Mode on page 166. The PRSPI bit in
Section 9.10 Minimizing Power Consumption on page 36 must be written to zero to enable SPI module.
S MISO
M
MSB LSB M
XTAL MOSI
8 Bit Shift Register S
Read Data Buffer Pin
Divider Control
/2/4/8/16/32/64/128 Logic
Clock
SPI Clock (Master)
Select Clock S SCK
Logic M
SPI2X
SPR1
SPR0
SS
DORD
MSTR
SPE
MSTR
SPE
SPI Control
WCOL
SPI2X
DORD
8
MSTR
CPHA
CPOL
SPIF
SPR1
SPR0
SPIE
SPE
8 8
Note: 1. Refer to Figure 1-1 on page 3, and Table 13-3 on page 65 for SPI pin placement.
MOSI MOSI
Shift
SPI SCK SCK Enable
Clock Generator
SS SS
The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to
be transmitted cannot be written to the SPI data register before the entire shift cycle is completed. When receiving data,
however, a received character must be read from the SPI data register before the next character has been completely
shifted in. Otherwise, the first byte is lost.
In SPI slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of the clock
signal, the minimum low and high periods should be:
Low periods: Longer than 2 CPU clock cycles.
High periods: Longer than 2 CPU clock cycles.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 18-1. For
more details on automatic port overrides, refer to Section 13.3 Alternate Port Functions on page 63.
SPI_MasterTransmit:
; Start transmission of data (r16)
out SPDR,r16
Wait_Transmit:
; Wait for transmission complete
in r16, SPSR
sbrs r16, SPIF
rjmp Wait_Transmit
ret
C Code Example(1)
void SPI_MasterInit(void)
{
/* Set MOSI and SCK output, all others input */
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
/* Enable SPI, Master, set clock rate fck/16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
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;
}
Note: 1. See Section 5. About Code Examples on page 8.
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
The SPI data register is a read/write register used for data transfer between the register file and the SPI shift register. Writing
to the register initiates data transmission. Reading the register causes the shift register Receive buffer to be read.
19.1 Features
Full duplex operation (independent serial receive and transmit registers)
Asynchronous or synchronous operation
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
19.2 Overview
The universal synchronous and asynchronous serial receiver and transmitter (USART) is a highly flexible serial
communication device.
The USART0 can also be used in master SPI mode, see Section 20. USART in SPI Mode on page 166. The power
reduction USART bit, PRUSART0, in Section 9.10 Minimizing Power Consumption on page 36 must be disabled by writing
a logical zero to it.
A simplified block diagram of the USART transmitter is shown in Figure 19-1 on page 144. CPU accessible I/O registers and
I/O pins are shown in bold.
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 formats. 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.
Clock Generator
UBRRn [H:L]
OSC
Transmitter
TX
UDRn (Transmit)
Control
Parity
Generator
DATA BUS
Pin
Transmit Shift Register TxDn
Control
Receiver
Clock RX
Recovery Control
Data Pin
Receive Shift Register RxDn
Recovery Control
Parity
UDRn (Receive)
Checker
Note: 1. Refer to Figure 1-1 on page 3 and Table 13-9 on page 70 for USART0 pin placement.
foscn U2Xn
Prescaling UBRRn+1
Down-Counter /2 /4 /2
0
1
OSC 0
txclk
DDR_XCKn 1
Sync Edge
xcki Register Detector 0
XCKn UMSELn
xcko 1
Pin
0
DDR_XCKn UCPOLn rxclk
1
Signal description:
txclk Transmitter clock (Internal Signal).
rxclk Receiver base clock (Internal Signal).
xcki Input from XCK pin (internal Signal). Used for synchronous slave operation.
xcko Clock output to XCK pin (Internal Signal). Used for synchronous master operation.
fosc XTAL pin frequency (System Clock).
f OSC
Asynchronous normal mode (U2Xn = 0) BAUD = --------------------------------------- f OSC
UBRRn = ----------------------- 1
16 UBRRn + 1 16BAUD
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)
Some examples of UBRRn values for some system clock frequencies are found in Table 19-9 on page 163.
f OSC
f XCK -----------
4
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 19-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.
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
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 samples 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 recovery 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 19-7 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame.
Figure 19-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 19-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 D + 2 S
R slow = --------------------------------------------- R fast = ------------------------------------
S 1 + D S + SF D + 1 S + S M
Table 19-2. Recommended Maximum Receiver Baud Rate Error for Normal Speed Mode (U2Xn = 0)
Table 19-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 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 register (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 transmitter. 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.
UCPOLn Transmitted Data Changed (Output of TxDn Pin) Received Data Sampled (Input on RxDn Pin)
0 Rising XCKn edge Falling XCKn edge
1 Falling XCKn edge Rising XCKn edge
Table 19-9. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies
Table 19-11. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies
fosc = 8.0000MHz fosc = 11.0592MHz fosc = 14.7456MHz
Baud
Rate U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1
(bps) UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn 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.5Mbps 1Mbps 691.2kbps 1.3824Mbps 921.6kbps 1.8432Mbps
Note: 1. UBRRn = 0, error = 0.0%
fosc = 16.0000MHz
U2Xn = 0 U2Xn = 1
Baud Rate (bps) UBRRn Error UBRRn Error
2400 416 0.1% 832 0.0%
4800 207 0.2% 416 0.1%
9600 103 0.2% 207 0.2%
14.4k 68 0.6% 138 0.1%
19.2k 51 0.2% 103 0.2%
28.8k 34 0.8% 68 0.6%
38.4k 25 0.2% 51 0.2%
57.6k 16 2.1% 34 0.8%
76.8k 12 0.2% 25 0.2%
115.2k 8 3.5% 16 2.1%
230.4k 3 8.5% 8 3.5%
250k 3 0.0% 7 0.0%
0.5M 1 0.0% 3 0.0%
1M 0 0.0% 1 0.0%
(1)
Max. 1Mbps 2Mbps
Note: 1. UBRRn = 0, error = 0.0%
20.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
20.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.
f OSC f OSC
Synchronous master mode BAUD = ------------------------------------ UBRRn = -------------------- 1
2 UBRRn + 1 2BAUD
Note: 1. The baud rate is defined to be the transfer rate in bit per second (bps)
XCK XCK
XCK XCK
UCPHA = 0
21.1 Features
Simple yet powerful and flexible communication interface, only two bus lines needed
Both master and slave operation supported
Device can operate as transmitter or receiver
7-bit address space allows up to 128 different slave addresses
Multi-master arbitration support
Up to 400kHz data transfer speed
Slew-rate limited output drivers
Noise suppression circuitry rejects spikes on bus lines
Fully programmable slave address with general call support
Address recognition causes wake-up when AVR is in sleep mode
Compatible with Phillips I2C protocol
SDA
SCL
The PRTWI bit in Section 9.10 Minimizing Power Consumption on page 36 must be written to zero to enable the 2-wire
serial interface.
SDA
SCL
Data Change
SDA
SCL
SDA
SCL
1 2 7 8 9
START
Aggregate
SDA
SDA from
Transmitter
SDA from
Receiver
SCL from
Master
1 2 7 8 9
STOP, REPEATED
SLA + R/W Data Byte
START or next
Data Byte
Addr MSB Addr LSB R/W ACK Data MSB Data LSB ACK
SDA
SCL
1 2 7 8 9 1 2 7 8 9
START SLA + R/W Data Byte STOP
SCL from
Master A
SCL from
Master B
SCL Bus
Line
TBlow TBhigh
Arbitration is carried out by all masters continuously monitoring the SDA line after outputting data. If the value read from the
SDA line does not match the value the master had output, it has lost the arbitration. Note that a master can only lose
arbitration when it outputs a high SDA value while another master outputs a low value. The losing master should
immediately go to slave mode, checking if it is being addressed by the winning master. The SDA line should be left high, but
losing masters are allowed to generate a clock signal until the end of the current data or address packet.
Arbitration will continue until only one master remains, and this may take many bits. If several masters are trying to address
the same slave, arbitration will continue into the data packet.
SDA from
Master A
SDA from
Master B
SDA Line
Synchronized
SCL Line
SCL SDA
START/ STOP
Spike Suppression Prescaler
Control
TWI Unit
Address Register Status Register Control Register
(TWAR) (TWSR) (TWCR)
3. Check TWSR to see if START was 5. Check TWSR to see if SLA + W was 7. Check TWSR to see if data was sent
1. Application
Application
sent. Application loads SLA + W into sent and ACK received. and ACK received.
writes to TWCR to
Action
TWDR, and loads appropriate control Application loads data intoTWDR, and Application loads appropriate control
initiate
signals into TWCR, making sure that loads appropriate control signals into signals to send STOP into TWCR,
transmission of
TWINT is written to one, TWCR, making sure that TWINT is makin sure that TWINT is
START
and TWSTA is written to zero. written to one written to one
Indicates
Hardware
Device 1 Device 2
Master Slave Device 3 ........ Device n R1 R2
Transmitter Receiver
SDA
SCL
TWEN must be set to enable the 2-wire serial interface, TWSTA must be written to one to transmit a START condition and
TWINT must be written to one to clear the TWINT flag. The TWI will then test the 2-wire serial bus and generate a START
condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT flag is set by
hardware, and the status code in TWSR will be 0x08 (see Table 21-3). In order to enter MT mode, SLA+W must be
transmitted. This is done by writing SLA+W to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to
continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 1 X 0 0 X 1 0 X
When SLA+W have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of
status codes in TWSR are possible. Possible status codes in master mode are 0x18, 0x20, or 0x38. The appropriate action
to be taken for each of these status codes is detailed in Table 21-3.
When SLA+W has been successfully transmitted, a data packet should be transmitted. This is done by writing the data byte
to TWDR. TWDR must only be written when TWINT is high. If not, the access will be discarded, and the write collision bit
(TWWC) will be set in the TWCR register. After updating TWDR, the TWINT bit should be cleared (by writing it to one) to
continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 1 X 0 0 X 1 0 X
This scheme is repeated until the last byte has been sent and the transfer is ended by generating a STOP condition or a
repeated START condition. A STOP condition is generated by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 1 X 0 1 X 1 0 X
After a repeated START condition (state 0x10) the 2-wire serial interface can access the same slave again, or a new slave
without transmitting a STOP condition. Repeated START enables the master to switch between slaves, master transmitter
mode and master receiver mode without losing control of the bus.
Successfull
transmission S SLA W A DATA A P
to a slave
receiver
Next transfer
started with a RS SLA W
repeated start
condition
$10
Not acknowledge
received after the A P R
slave address
$20
MR
Not acknowledge
A P
received after a
data byte
$30
$38 $38
To corresponding
$68 $78 $B0
states in slave mode
Device 1 Device 2
Master Slave Device 3 ........ Device n R1 R2
Receiver Transmitter
SDA
SCL
TWEN must be written to one to enable the 2-wire serial interface, TWSTA must be written to one to transmit a START
condition and TWINT must be set to clear the TWINT flag. The TWI will then test the 2-wire serial bus and generate a
START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT flag is set by
hardware, and the status code in TWSR will be 0x08 (See Table 21-3 on page 186). In order to enter MR mode, SLA+R must
be transmitted. This is done by writing SLA+R to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to
continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 1 X 0 0 X 1 0 X
When SLA+R have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of
status codes in TWSR are possible. Possible status codes in master mode are 0x38, 0x40, or 0x48. The appropriate action
to be taken for each of these status codes is detailed in Table 21-4 on page 189. Received data can be read from the TWDR
register when the TWINT flag is set high by hardware. This scheme is repeated until the last byte has been received. After
the last byte has been received, the MR should inform the ST by sending a NACK after the last received data byte. The
transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing
the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 1 X 0 1 X 1 0 X
After a repeated START condition (state 0x10) the 2-wire serial interface can access the same slave again, or a new slave
without transmitting a STOP condition. Repeated START enables the master to switch between slaves, master transmitter
mode and master receiver mode without losing control over the bus.
Successfull
reception S SLA R A DATA A DATA A P
from a slave
receiver
Next transfer
started with a RS SLA R
repeated start
condition
$10
Not acknowledge
received after the A P W
slave address
$48
MT
Arbitration lost in slave Other master Other master
A or A A or A
address or data byte continues continues
$38 $38
To corresponding
$68 $78 $B0
states in slave mode
Device 1 Device 2
Slave Master Device 3 ........ Device n R1 R2
Receiver Transmitter
SDA
SCL
The upper 7 bits are the address to which the 2-wire serial interface will respond when addressed by a master. If the LSB is
set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 0 1 0 0 0 1 0 X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of
the devices own slave address or the general call address. TWSTA and TWSTO must be written to zero.
When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general
call address if enabled) followed by the data direction bit. If the direction bit is 0 (write), the TWI will operate in SR mode,
otherwise ST mode is entered. After its own slave address and the write bit have been received, the TWINT flag is set and a
valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The
appropriate action to be taken for each status code is detailed in Table 21-5. The slave receiver mode may also be entered if
arbitration is lost while the TWI is in the master mode (see states 0x68 and 0x78).
If the TWEA bit is reset during a transfer, the TWI will return a not acknowledge (1) to SDA after the next received data
byte. This can be used to indicate that the slave is not able to receive any more bytes. While TWEA is zero, the TWI does not
acknowledge its own slave address. However, the 2-wire serial bus is still monitored and address recognition may resume at
any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the 2-wire serial
bus.
In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can
still acknowledge its own slave address or the general call address by using the 2-wire serial bus clock as a clock source.
The part will then wake up from sleep and the TWI will hold the SCL clock low during the wake up and until the TWINT flag is
cleared (by writing it to one). Further data reception will be carried out as normal, with the AVR clocks running as normal.
Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data
transmissions.
Note that the 2-wire serial interface data register TWDR does not reflect the last byte present on the bus when waking up
from these sleep modes.
$88
$98
$78
Device 1 Device 2
Slave Master Device 3 ........ Device n R1 R2
Transmitter Receiver
SDA
SCL
To initiate the slave transmitter mode, TWAR and TWCR must be initialized as follows:
TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
value Devices Own Slave Address
The upper seven bits are the address to which the 2-wire serial interface will respond when addressed by a master. If the
LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN TWIE
value 0 1 0 0 0 1 0 X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of
the devices own slave address or the general call address. TWSTA and TWSTO must be written to zero.
When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general
call address if enabled) followed by the data direction bit. If the direction bit is 1 (read), the TWI will operate in ST mode,
otherwise SR mode is entered. After its own slave address and the write bit have been received, the TWINT flag is set and a
valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The
appropriate action to be taken for each status code is detailed in Table 21-6 on page 195. The slave transmitter mode may
also be entered if arbitration is lost while the TWI is in the master mode (see state 0xB0).
If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte of the transfer. State 0xC0 or state 0xC8
will be entered, depending on whether the master receiver transmits a NACK or ACK after the final byte. The TWI is
switched to the not addressed slave mode, and will ignore the master if it continues the transfer. Thus the master receiver
receives all 1 as serial data. State 0xC8 is entered if the master demands additional data bytes (by transmitting ACK), even
though the slave has transmitted the last byte (TWEA zero and expecting NACK from the master).
While TWEA is zero, the TWI does not respond to its own slave address. However, the 2-wire serial bus is still monitored
and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to
temporarily isolate the TWI from the 2-wire serial bus.
In all sleep modes other than idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still
acknowledge its own slave address or the general call address by using the 2-wire serial bus clock as a clock source. The
part will then wake up from sleep and the TWI will hold the SCL clock will low during the wake up and until the TWINT flag is
cleared (by writing it to one). Further data transmission will be carried out as normal, with the AVR clocks running as
normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking
other data transmissions.
Note that the 2-wire serial interface data register TWDR does not reflect the last byte present on the bus when waking up
from these sleep modes.
$B0
$C8
SDA
SCL
Own NO 38 TWI bus will be released and not addressed slave mode will be entered
Address/ General Call A START condition will be transmitted when the bus becomes free
received
YES
Write 68/78 Data byte will be received and NOT ACK will be returned
Direction
Data byte will be received and ACK will be returned
Read Last data byte will be transmitted and NOT ACK should be received
B0 Data byte will be transmitted and ACK should be received
The TWCR is used to control the operation of the TWI. It is used to enable the TWI, to initiate a master access by applying a
START condition to the bus, to generate a receiver acknowledge, to generate a stop condition, and to control halting of the
bus while the data to be written to the bus are written to the TWDR. It also indicates a write collision if data is attempted
written to TWDR while the register is inaccessible.
To calculate bit rates, see Section 21.5.2 Bit Rate Generator Unit on page 180. The value of TWPS1..0 is used in the
equation.
In transmit mode, TWDR contains the next byte to be transmitted. In receive mode, the TWDR contains the last byte
received. It is writable while the TWI is not in the process of shifting a byte. This occurs when the TWI interrupt flag (TWINT)
is set by hardware. Note that the data register cannot be initialized by the user before the first interrupt occurs. The data in
TWDR remains stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted in. TWDR
always contains the last byte present on the bus, except after a wake up from a sleep mode by the TWI interrupt. In this
case, the contents of TWDR is undefined.
In the case of a lost bus arbitration, no data is lost in the transition from master to slave. Handling of the ACK bit is controlled
automatically by the TWI logic, the CPU cannot access the ACK bit directly.
The TWAR should be loaded with the 7-bit slave address (in the seven most significant bits of TWAR) to which the TWI will
respond when programmed as a slave transmitter or receiver, and not needed in the master modes. In multi master
systems, TWAR must be set in masters which can be addressed as slaves by other masters.
The LSB of TWAR is used to enable recognition of the general call address (0x00). There is an associated address
comparator that looks for the slave address (or general call address if enabled) in the received serial address. If a match is
found, an interrupt request is generated.
TWAR0
Address
Match
Address
Bit 0
TWAMR0
Address Bit Comparator 0
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
comparators 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 comparator output rise, fall
or toggle. A block diagram of the comparator and its surrounding logic is shown in Figure 22-1.
The power reduction ADC bit, PRADC, in Section 9.10 Minimizing Power Consumption on page 36 must be disabled by
writing a logical zero to be able to use the ADC input MUX.
Bandgap VCC
Reference
ACBG
ACD
ACIE
AIN0
Analog
+
Interrupt Comparator
Select IRQ
-
AIN1 ACI
ACME
ADEN
To T/C1 Capture
ACO Trigger MUX
ADC Multiplexer
Output(1)
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.
23.1 Features
10-bit resolution
0.5 LSB integral non-linearity
2 LSB absolute accuracy
65 to 260s conversion time
Up to 15kSPS
6 multiplexed single ended input channels
2 additional multiplexed single ended input channels
Temperature sensor input channel
Optional left adjustment for ADC result readout
0 to VCC ADC input voltage range
Selectable 1.1V ADC reference voltage
Free running or single conversion mode
Interrupt on ADC conversion complete
Sleep mode noise canceler
23.2 Overview
The Atmel ATmega328P features a 10-bit successive approximation ADC. The ADC is connected to an 8-channel analog
multiplexer which allows eight single-ended voltage inputs constructed from the pins of Port A. The single-ended voltage
inputs refer to 0V (GND).
The ADC contains a sample and hold circuit which ensures that the input voltage to the ADC is held at a constant level
during conversion. A block diagram of the ADC is shown in Figure 23-1 on page 206.
The ADC has a separate analog supply voltage pin, AVCC. AVCC must not differ more than 0.3V from VCC. See Section 23.6
ADC Noise Canceler on page 211 on how to connect this pin.
Internal reference voltages of nominally 1.1V or AVCC are provided on-chip. The voltage reference may be externally
decoupled at the AREF pin by a capacitor for better noise performance.
The power reduction ADC bit, PRADC, in Section 9.10 Minimizing Power Consumption on page 36 must be disabled by
writing a logical zero to enable the ADC.
The ADC converts an analog input voltage to a 10-bit digital value through successive approximation. The minimum value
represents GND and the maximum value represents the voltage on the AREF pin minus 1 LSB. Optionally, AVCC or an
internal 1.1V reference voltage may be connected to the AREF pin by writing to the REFSn bits in the ADMUX register. The
internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity.
ADIE
ADIF
15 0
ADC Multiplexer ADC CTRL and Status ADC Data Register
REFS1 Select (ADMUX) Register (ADCSRA) (ADCH/ADCL)
REFS0
ADLAR
MUX3
MUX2
MUX1
MUX0
ADEN
ADSC
ADFR
ADIF
ADPS2
ADPS1
ADPS0
ADC[9:0]
MUX Decoder Prescaler
Channel Selection
Internal 1.1V
Reference Sample and Hold
Comparator
Temperature
Sensor
GND
Bandgap
Reference
ADC7
ADC3
ADC2
ADC1
ADC0
The analog input channel is selected by writing to the MUX bits in ADMUX. Any of the ADC input pins, as well as GND and a
fixed bandgap voltage reference, can be selected as single ended inputs to the ADC. The ADC is enabled by setting the
ADC Enable bit, ADEN in ADCSRA. Voltage reference and input channel selections will not go into effect until ADEN is set.
The ADC does not consume power when ADEN is cleared, so it is recommended to switch off the ADC before entering
power saving sleep modes.
The ADC generates a 10-bit result which is presented in the ADC data registers, ADCH and ADCL. By default, the result is
presented right adjusted, but can optionally be presented left adjusted by setting the ADLAR bit in ADMUX.
If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must
be read first, then ADCH, to ensure that the content of the data registers belongs to the same conversion. Once ADCL is
read, ADC access to data registers is blocked.
START CLKADC
ADIF ADATE
SOURCE 1
.
Conversion
. Logic
.
. Edge
Detector
SOURCE n
ADSC
Using the ADC interrupt flag as a trigger source makes the ADC start a new conversion as soon as the ongoing conversion
has finished. The ADC then operates in free running mode, constantly sampling and updating the ADC data register. The
first conversion must be started by writing a logical one to the ADSC bit in ADCSRA. In this mode the ADC will perform
successive conversions independently of whether the ADC interrupt flag, ADIF is cleared or not.
If auto triggering is enabled, single conversions can be started by writing ADSC in ADCSRA to one. ADSC can also be used
to determine if a conversion is in progress. The ADSC bit will be read as one during a conversion, independently of how the
conversion was started.
CK/2
CK/4
CK/8
CK/16
CK/32
CK/64
CK/128
ADPS0
ADPS1
ADPS2
By default, the successive approximation circuitry requires an input clock frequency between 50kHz and 200kHz to get
maximum resolution. If a lower resolution than 10 bits is needed, the input clock frequency to the ADC can be higher than
200kHz to get a higher sample rate.
The ADC module contains a prescaler, which generates an acceptable ADC clock frequency from any CPU frequency above
100kHz. The prescaling is set by the ADPS bits in ADCSRA. The prescaler starts counting from the moment the ADC is
switched on by setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is
continuously reset when ADEN is low.
When initiating a single ended conversion by setting the ADSC bit in ADCSRA, the conversion starts at the following rising
edge of the ADC clock cycle.
A normal conversion takes 13 ADC clock cycles. The first conversion after the ADC is switched on (ADEN in ADCSRA is set)
takes 25 ADC clock cycles in order to initialize the analog circuitry.
When the bandgap reference voltage is used as input to the ADC, it will take a certain time for the voltage to stabilize. If not
stabilized, the first value read after the first conversion may be wrong.
The actual sample-and-hold takes place 1.5 ADC clock cycles after the start of a normal conversion and 13.5 ADC clock
cycles after the start of an first conversion. When a conversion is complete, the result is written to the ADC data registers,
and ADIF is set. In single conversion mode, ADSC is cleared simultaneously. The software may then set ADSC again, and a
new conversion will be initiated on the first rising ADC clock edge.
When auto triggering is used, the prescaler is reset when the trigger event occurs. This assures a fixed delay from the trigger
event to the start of conversion. In this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on
the trigger source signal. Three additional CPU clock cycles are used for synchronization logic.
In free running mode, a new conversion will be started immediately after the conversion completes, while ADSC remains
high. For a summary of conversion times, see Table 23-1 on page 210.
Cycle Number 1 2 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3
ADC Clock
ADEN
ADSC
ADIF
Cycle Number 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3
ADC Clock
ADSC
ADIF
Cycle Number 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2
ADC Clock
Trigger
Source
ADATE
ADIF
Cycle Number 11 12 13 1 2 3 4
ADC Clock
ADSC
ADIF
IIH
ADCn
1 to 100k
VCC/2
PC4 (ADC4/SDA)
PC5 (ADC5/SCL)
PC3 (ADC3)
PC2 (ADC2)
VCC
PC1 (ADC1)
PC0 (ADC0)
ADC7
GND
10H
AREF
ADC6
100nF
AVCC
PB5
Output Code
Ideal ADC
Actual ADC
Offset
Error
VREF Input Voltage
Ideal ADC
Actual ADC
Integral non-linearity (INL): After adjusting for offset and gain error, the INL is the maximum deviation of an actual
transition compared to an ideal transition for any code. Ideal value: 0 LSB.
Output Code
INL
Ideal ADC
Actual ADC
Output Code
0x3FF
1 LSB
DNL
0x000
Quantization error: Due to the quantization of the input voltage into a finite number of codes, a range of input voltages
(1 LSB wide) will code to the same value. Always 0.5 LSB.
Absolute accuracy: The maximum deviation of an actual (unadjusted) transition compared to an ideal transition for
any code. This is the compound effect of offset, gain error, differential error, non-linearity, and quantization error. Ideal
value: 0.5 LSB.
V IN 1024
ADC = ---------------------------
V REF
where VIN is the voltage on the selected input pin and VREF the selected voltage reference (see Table 23-3 on page 217 and
Table 23-4 on page 218). 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one
LSB.
--------------------------------------------------------------------------------------------------------------------------------------------------------
ADCH<<8 + ADCL 273 + 100 TS_OFFSET 128-
+ 25
TS_GAIN
Where:.
a. ADCH and ADCL are the ADC data registers,
b. is the temperature sensor gain
c. TS_OFFSET is the temperature sensor offset correction term
TS_GAIN is the unsigned fixed point 8-bit temperature sensor gain factor in
1/128th units stored in the signature row.
TS_OFFSET is the signed twos complement temperature sensor offset reading
stored in the signature row. See Table 26-5 on page 236 for signature row parameter address
The following code example allows to read signature row data
.equ TS_GAIN = 0x0003
.equ TS_OFFSET = 0x0002
LDI R30,LOW(TS_GAIN)
LDI R31,HIGH (TS_GAIN)
RCALL Read_signature_row
MOV R17,R16; Save R16 result
LDI R30,LOW(TS_OFFSET)
LDI R31,HIGH (TS_OFFSET)
RCALL Read_signature_row
; R16 holds TS_OFFSET and R17 holds TS_GAIN
Read_signature_row:
IN R16,SPMCSR; Wait for SPMEN ready
SBRC R16,SPMEN; Exit loop here when SPMCSR is free
RJMP Read_signature_row
LDI R16,((1<<SIGRD)|(1<<SPMEN)); We need to set SIGRD and SPMEN together
OUT SPMCSR,R16; and execute the LPM within 3 cycles
LPM R16,Z
RET
23.9.3.1 ADLAR = 0
Bit 15 14 13 12 11 10 9 8
(0x79) ADC9 ADC8 ADCH
(0x78) ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 ADCL
7 6 5 4 3 2 1 0
Read/Write R R R R R R R R
R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
23.9.3.2 ADLAR = 1
Bit 15 14 13 12 11 10 9 8
(0x79) ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADCH
(0x78) ADC1 ADC0 ADCL
7 6 5 4 3 2 1 0
Read/Write R R R R R R R R
R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
When an ADC conversion is complete, the result is found in these two registers.
When ADCL is read, the ADC data register is not updated until ADCH is read. Consequently, if the result is left adjusted and
no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then ADCH.
The ADLAR bit in ADMUX, and the MUXn bits in ADMUX affect the way the result is read from the registers. If ADLAR is set,
the result is left adjusted. If ADLAR is cleared (default), the result is right adjusted.
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.
VCC
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.
When designing a system where debugWIRE will be used, the following observations must be made for correct operation:
Pull-up resistors on the dW/(RESET) line must not be smaller than 10k. The pull-up resistor is not required for
debugWIRE functionality.
Connecting the RESET pin directly to VCC will not work.
Capacitors connected to the RESET pin must be disconnected when using debugWire.
All external reset sources must be disconnected.
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.
25.1 Overview
In Atmel ATmega328P, there is no read-while-write support, and no separate boot loader section. The SPM instruction can
be executed from the entire flash.
The device provides a self-programming mechanism for downloading and uploading program code by the MCU itself. The
self-programming can use any available data interface and associated protocol to read code and write (program) that code
into the program memory.
The program memory is updated in a page by page fashion. Before programming a page with the data stored in the
temporary page buffer, the page must be erased. The temporary page buffer is filled one word at a time using SPM and the
buffer can be filled either before the page erase command or between a page erase and a page write operation:
Alternative 1, fill the buffer before a page erase
Fill temporary page buffer
Perform a page erase
Perform a page write
Alternative 2, fill the buffer after page erase
Perform a page erase
Fill temporary page buffer
Perform a page write
If only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page
buffer) before the erase, and then be re-written. When using alternative 1, the boot loader provides an effective read-modify-
write feature which allows the user software to first read the page, do the necessary changes, and then write back the
modified data. If alternative 2 is used, it is not possible to read the old data while loading since the page is already erased.
The temporary page buffer can be accessed in a random sequence. It is essential that the page address used in both the
page erase and page write operation is addressing the same page.
Since the flash is organized in pages (see Table 27-9 on page 245), the program counter can be treated as having two
different sections. One section, consisting of the least significant bits, is addressing the words within a page, while the most
significant bits are addressing the pages. This is shown in Figure 26-3 on page 233. Note that the page erase and page write
operations are addressed independently. Therefore it is of major importance that the software addresses the same page in
both the page erase and page write operation.
The LPM instruction uses the Z-pointer to store the address. Since this instruction addresses the flash byte-by-byte, also the
LSB (bit Z0) of the Z-pointer is used.
PCMSB PAGEMSB
Program
Counter PCPAGE PCWORD
Page Address Word Address
within the Flash within a Page
01
02
PAGEEND
Note: 1. The different variables used in Figure 26-3 on page 233 are listed in Table 27-9 on page 245.
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 SELFPRGEN bits in SPMCSR. When an LPM instruction
is executed within three cycles after the BLBSET and SELFPRGEN bits are set in the SPMCSR, the value of the fuse low
byte (FLB) will be loaded in the destination register as shown below.See Table 27-5 on page 243 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 (FHB), load 0x0003 in the Z-pointer. When an LPM instruction is executed within
three cycles after the BLBSET and SELFPRGEN bits are set in the SPMCSR, the value of the fuse high byte will be loaded
in the destination register as shown below. See Table 27-4 on page 242 for detailed description and mapping of the
extended fuse byte.
Bit 7 6 5 4 3 2 1 0
Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0
Similarly, when reading the extended fuse byte (EFB), load 0x0002 in the Z-pointer. When an LPM instruction is executed
within three cycles after the BLBSET and SELFPRGEN bits are set in the SPMCSR, the value of the extended fuse byte will
be loaded in the destination register as shown below. See Table 27-5 on page 243 for detailed description and mapping of
the extended fuse byte.
Bit 7 6 5 4 3 2 1 0
Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0
Fuse and lock bits that are programmed, will be read as zero. Fuse and lock bits that are unprogrammed, will be read as
one.
Do_spm:
;check for previous SPM complete
Wait_spm:
in temp1, SPMCSR
sbrc temp1, SELFPRGEN
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
26.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 27-9 on page 245) used during
programming. The page organization does not affect normal operation.
26.2 Overview
The boot loader support provides a real read-while-write self-programming mechanism for downloading and uploading
program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a
flash-resident boot loader program. The boot loader program can use any available data interface and associated protocol to
read code and write (program) that code into the flash memory, or read the code from the program memory. The program
code within the boot loader section has the capability to write into the entire flash, including the boot loader memory. The
boot loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. The
size of the boot loader memory is configurable with fuses and the boot loader has two separate sets of boot lock bits which
can be set independently. This gives the user a unique flexibility to select different levels of protection.
Z-pointer
Addresses NRWW
Z-pointer Section
Addresses RWW
Section No Read While Write
(NRWW) Section CPU is Halted During
the Operation
Code located in
NRWW Section
can be Read During
the Operation
Read-While-Write Section
Read-While-Write Section
Application Flash Section Application Flash Section
No Read-While-
Write Section
Write Section
Application Flash Section Application Flash Section
End Application
End Application
Start Boot Loader
Start Boot Loader Boot Loader Flash Section
Boot Loader Flash Section Flashend Flashend
No Read-While-
Write Section
Write Section
Table 26-3. Boot Lock Bit1 Protection Modes (Boot Loader Section)(1)
BLB1 Mode BLB12 BLB11 Protection
1 1 1 No restrictions for SPM or LPM accessing the boot loader section.
2 1 0 SPM is not allowed to write to the boot loader section.
SPM is not allowed to write to the boot loader section, and LPM executing
from the application section is not allowed to read from the boot loader
3 0 0
section. If interrupt vectors are placed in the application section, interrupts
are disabled while executing from the boot loader section.
LPM executing from the application section is not allowed to read from the
4 0 1 boot loader section. If interrupt vectors are placed in the application section,
interrupts are disabled while executing from the boot loader section.
Note: 1. 1 means unprogrammed, 0 means programmed
Since the flash is organized in pages (see Table 27-9 on page 245), the program counter can be treated as having two
different sections. One section, consisting of the least significant bits, is addressing the words within a page, while the most
significant bits are addressing the pages. This is1 shown in Figure 26-3. Note that the page erase and page write operations
are addressed independently. Therefore it is of major importance that the boot loader software addresses the same page in
both the page erase and page write operation. Once a programming operation is initiated, the address is latched and the
Z-pointer can be used for other operations.
The only SPM operation that does not use the Z-pointer is setting the boot loader lock bits. The content of the Z-pointer is
ignored and will have no effect on the operation. The LPM instruction does also use the Z-pointer to store the address. Since
this instruction addresses the flash byte-by-byte, also the LSB (bit Z0) of the Z-pointer is used.
PCMSB PAGEMSB
Program
Counter PCPAGE PCWORD
Page Address Word Address
within the Flash within a Page
01
02
PAGEEND
See Table 26-2 on page 232 and Table 26-3 on page 232 for how the different settings of the boot loader bits affect the flash
access.
If bits 5..0 in R0 are cleared (zero), the corresponding lock bit will be programmed if an SPM instruction is executed within
four cycles after BLBSET and SELFPRGEN are set in SPMCSR. The Z-pointer is dont care during this operation, but for
future compatibility it is recommended to load the Z-pointer with 0x0001 (same as used for reading the lOck bits). For future
compatibility it is also recommended to set bits 7 and 6 in R0 to 1 when writing the lock bits. When programming the lock
bits the entire flash can be read during the operation.
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 SELFPRGEN bits in SPMCSR. When an LPM instruction
is executed within three cycles after the BLBSET and SELFPRGEN 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 27-5 on page 243 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
When reading the extended fuse byte, load 0x0002 in the Z-pointer. When an LPM instruction is executed within three cycles
after the BLBSET and SELFPRGEN 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 27-4 on page 242 for detailed description and mapping of the
extended fuse byte.
Bit 7 6 5 4 3 2 1 0
Rd EFB3 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.
Do_spm:
;check for previous SPM complete
Wait_spm:
in temp1, SPMCSR
sbrc temp1, SELFPRGEN
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
For details about these two section, see Section 26.4.2 NRWW No Read-While-Write Section on page 230 and Section
26.4.1 RWW Read-While-Write Section on page 230.
Table 26-9. Explanation of Different Variables used in Figure 26-3 and the Mapping to the Z-pointer, ATmega328P
Corresponding
Variable Z-value(1) Description
Most significant bit in the program counter. (the program
PCMSB 13
counter is 14 bits PC[13:0])
Most significant bit which is used to address the words within
PAGEMSB 5
one page (64 words in a page requires 6 bits PC [5:0])
Bit in Z-register that is mapped to PCMSB. Because Z0 is not
ZPCMSB Z14
used, the ZPCMSB equals PCMSB + 1.
Bit in Z-register that is mapped to PAGEMSB. Because Z0 is
ZPAGEMSB Z6
not used, the ZPAGEMSB equals PAGEMSB + 1.
Program counter page address: Page select, for page erase
PCPAGE PC[13:6] Z14: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. Z15: always ignored
Z0: should be zero for all SPM commands, byte select for the LPM instruction.
See Section 26.7 Addressing the Flash During Self-Programming on page 233 for details about the use of
Z-pointer during self-programming.
Table 27-9. No. of Words in a Page and No. of Pages in the Flash
Device Flash Size Page Size PCWORD No. of Pages PCPAGE PCMSB
16K words
ATmega328P 64 words PC[5:0] 256 PC[13:6] 13
(32K bytes)
Table 27-10. No. of Words in a Page and No. of Pages in the EEPROM
Device EEPROM Size Page Size PCWORD No. of Pages PCPAGE EEAMSB
ATmega328P 1K bytes 4 bytes EEA[1:0] 256 EEA[9:2] 9
XA0 PD5
PC[1:0]:PB[5:0] DATA
XA1 PD6
PAGEL PD7
+12V RESET
BS2 PC2
XTAL1
GND
Note: VCC to 0.3V < AVCC < VCC + 0.3V, however, AVCC should always be within 4.5 to 5.5V
Signal Name in
Programming Mode Pin Name I/O Function
0: Device is busy programming, 1: Device is ready for
RDY/BSY PD1 O
new command
OE PD2 I Output enable (active low)
WR PD3 I Write pulse (active low)
BS1 PD4 I Byte select 1 (0 selects low byte, 1 selects high byte)
XA0 PD5 I XTAL action Bit 0
XA1 PD6 I XTAL action Bit 1
PAGEL PD7 I Program memory and EEPROM data page load
Byte select 2 (0 selects low byte, 1 selects 2nd high
BS2 PC2 I
byte)
DATA {PC[1:0]: PB[5:0]} I/O Bi-directional data bus (output when OE is low)
01
02
PAGEEND
Note: 1. PCPAGE and PCWORD are listed in Table 27-9 on page 245.
A B C D E B C D E G H
DATA 0x10 ADDR. LOW DATA LOW DATA HIGH XX ADDR. LOW DATA LOW DATA HIGH XX ADDR. HIGH XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
Note: 1. XX is dont care. The letters refer to the programming description above.
A G B C E B C E L
DATA 0x11 ADDR. HIGH ADDR. LOW DATA XX ADDR. LOW DATA XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
A C A C A C
DATA 0x40 DATA XX 0x40 DATA XX 0x40 DATA XX
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
DATA
BS2
Lock Bits 0
BS1
Fuse High Byte 1
BS2
VCC
+ 1.8V to 5.5V(2)
MOSI
AVCC
MISO
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 2.7 to 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 < 12MHz, 3 CPU clock cycles for fck 12MHz
High: > 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck 12MHz
Table 27-16. Typical Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FLASH 4.5ms
tWD_EEPROM 3.6ms
tWD_ERASE 9.0ms
Instruction Format
Instruction/Operation Byte 1 Byte 2 Byte 3 Byte4
Programming enable $AC $53 $00 $00
Chip erase (program memory/EEPROM) $AC $80 $00 $00
Poll RDY/BSY $F0 $00 $00 data byte out
Load instructions
Load extended address byte(1) $4D $00 Extended adr $00
Load program memory page, high byte $48 $00 adr LSB high data byte in
Load program memory page, low byte $40 $00 adr LSB low data byte in
Load EEPROM memory page (page
$C1 $00 0000 000aa data byte in
access)
Read instructions
Read program memory, high byte $28 adr MSB adr LSB high data byte out
Read program memory, low byte $20 adr MSB adr LSB low data byte out
Read EEPROM memory $A0 0000 00aa aaaa aaaa data byte out
Read lock bits $58 $00 $00 data byte out
Read signature byte $30 $00 0000 000aa data byte out
Read fuse bits $50 $00 $00 data byte out
Read fuse high bits $58 $08 $00 data byte out
Read extended fuse bits $50 $08 $00 data byte out
Read calibration byte $38 $00 $00 data byte out
(6)
Write instructions
Write program memory page $4C adr MSB adr LSB $00
Write EEPROM memory $C0 0000 00aa aaaa aaaa data byte in
Write EEPROM memory page (page
$C2 0000 00aa aaaa aa00 $00
access)
Write lock bits $AC $E0 $00 data byte in
Write fuse bits $AC $A0 $00 data byte in
Write fuse high bits $AC $A8 $00 data byte in
Write extended fuse bits $AC $A4 $00 data byte in
Notes: 1. Not all instructions are applicable for all parts.
2. a = address.
3. Bits are programmed 0, unprogrammed 1.
4. To ensure future compatibility, unused fuses and lock bits should be unprogrammed (1).
5. Refer to the corresponding section for fuse and lock bits, calibration and signature bytes and page size.
6. Instructions accessing program memory use a word address. This address may be random within the page
range.
7. See http://www.atmel.com/avr for application notes regarding programming and programmers.
Load Program Memory Page (High/Low Byte)/ Write Program Memory Page/
Load EEPROM Memory Page (page access) Write EEPROM Memory Page
Bit 15 B 0 Bit 15 B 0
Page Buffer
Page Offset
Page 0
Page 1
Page 2
Page Number
Page N-1
Program Memory/
EEPROM Memory
SAMPLE
For characteristics of the SPI module see Section 28.7 SPI Timing Characteristics on page 262.
28.2 DC Characteristics
TA = 40C to +125C, VCC = 2.7V to 5.5V (unless otherwise noted)
16MHz
VIH1
VIL1
tCLCX
tCLCL
BODLEVEL 2:0 Fuses Min VBOT Typ VBOT Max VBOT Units
111 BOD disabled
110 Reserved
101 2.5 2.7 2.9 V
100 4.0 4.3 4.6
011
010
Reserved
001
000
Note: 1. VBOT may be below nominal minimum operating voltage for some devices. For devices where this is the case,
the device is tested down to VCC = VBOT during the production test. This guarantees that a brown-out reset will
occur before VCC drops to a voltage where correct operation of the microcontroller is no longer guaranteed.
The test is performed using BODLEVEL = 100 and BODLEVEL = 101 for ATmega328P.
SS
6 1
SCK
(CPOL = 0)
2 2
SCK
(CPOL = 1)
4 5 3
MISO
(Data Input) MSB ... LSB
7 8
MOSI
MSB ... LSB
(Data Output)
SS
9 10 16
SCK
(CPOL = 0)
11 11
SCK
(CPOL = 1)
13 14 12
MOSI
(Data Input) MSB ... LSB
15 17
MISO
MSB ... LSB X
(Data Output)
V CC 0.4V 1000ns
fSCL 100kHz ---------------------------- -----------------
3mA Cb
Value of pull-up resistor Rp
V CC 0.4V 300ns
fSCL > 100kHz ---------------------------- --------------
3mA Cb
SCL
tSU,STA tHD,STA tHD,DAT tSU,DAT tSU,STO
SDA
tBUF
Figure 28-6. Parallel Programming Timing, Including some General Timing Requirements
tXLWL
XTAL1 tXHXL
tDVXH tXLDX
Data and Control
(DATA, XA0/1, BS1, BS2)
tBVPH tPLBX tBVWL tWLBX
PAGEL tPHPL
tWLWH
WR
tPLWL
tWLRL
RDY/BSY
tWLRH
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 28-6 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation.
Figure 28-8. 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 28-6 on page 266 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading
operation.
14
12
5.5
10
ICC (mA)
5.0
8 4.5
3.6
6
3.3
4 3.0
2 2.7
0
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
3.5
3
5.5
2.5
ICC (mA)
5.0
2 4.5
3.6
1.5
3.3
1 3.0
0.5 2.7
0
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
Figure 29-3. Power-Down Supply Current versus VCC (Watchdog Timer Disabled)
25
20
15
ICC (A)
125
10 85
25
-45
5
0
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Figure 29-4. Power-Down Supply Current versus VCC (Watchdog Timer Enabled)
35
30
25
ICC (A)
20
125
15 85
25
10
-45
0
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Figure 29-5. I/O Pin Pull-up Resistor Current versus Input Voltage (VCC = 5V)
160
140
120
125
100
IOP (A)
85
80 25
60 -45
40
20
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VOP (V)
Figure 29-6. Reset Pull-up Resistor Current versus Reset Pin Voltage (VCC = 5 V)
120
100
80 125
IRESET (A)
85
60 25
-45
40
20
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VRESET (V)
Figure 29-7. I/O Pin Output Voltage versus Sink Current (VCC = 3 V)
1.2
0.8 125
85
VOL (V)
0.6 25
-45
0.4
0.2
0
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
0.6
0.5
125
85
VOL (V)
0.4
25
0.3
-45
0.2
0.1
0
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
Figure 29-9. I/O Pin Output Voltage versus Source Current (VCC = 3 V)
3.5
2.5
125
85
VOH (V)
2
25
1.5 -45
0.5
0
0 2 4 6 8 10 12 14 16 18 20
IOH (mA)
Figure 29-10. I/O Pin Output Voltage versus Source Current (VCC = 5 V)
5.1
4.9
4.8 125
85
VOH (V)
4.7
25
4.6
-45
4.5
4.4
4.3
4.2
0 2 4 6 8 10 12 14 16 18 20
IOH (mA)
Figure 29-11. I/O Pin Input Threshold Voltage versus VCC (VIH, I/O Pin read as 1)
3.5
2.5
125
Threshold (V)
2 85
25
1.5
-45
0.5
0
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Figure 29-12. I/O Pin Input Threshold Voltage versus VCC (VIL, I/O Pin read as 0)
2.5
125
Threshold (V)
1.5 85
25
1 -45
0.5
0
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Figure 29-13. Reset Input Threshold Voltage versus VCC (VIH, I/O Pin read as 1)
125
Threshold (V)
1.5 85
25
1 -45
0.5
0
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
2.9
Threshold (V)
2.8
1
2.7
0
2.6
2.5
2.4
-60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140
Temperature (C)
4.5
Threshold (V)
4.4
1
4.3
0
4.2
4.1
4
-60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140
Temperature (C)
150
140
130 5.5
FRC (kHz)
120 5.0
4.5
110 3.3
100 3.0
2.7
90
80
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120
Temperature (C)
8.3
8.2
5.5
8.1
FRC (MHz)
5.0
8 4.5
3.3
7.9
3.0
7.8 2.7
7.7
7.6
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Temperature (C)
14
12 125
10 85
FRC (MHz)
25
8 -45
6
0
0 50 100 150 200 250
OSCCAL (X1)
32.1 ATmega328P
Speed (MHz)(2) Power Supply Ordering Code Package(1) Operational Range
Automotive
16 2.7 to 5.5V ATmega328P-15AZ MA
(40C to +125C)
Automotive
16 2.7 to 5.5V ATmega328P-15MZ PN
(40C to +125C)
Notes: 1. Pb-free packaging complies to the european directive for restriction of hazardous substances (RoHS directive).
Also halide free and fully green.
2. See Figure 28-3 on page 263.
Package Type
MA, 32 - Lead, 77mm body size, 1.0mm body thickness 0.5mm lead pitch, thin profile plastic quad flat
MA
package (TQFP)
PN PN, 32-Lead, 55mm body, 0.50mm, quad flat no lead package (QFN)
33.1 MA
E1
e
0~7
Top View
C
Side View
D
COMMON DIMENSIONS
(Unit of Measure = mm)
Symbol MIN NOM MAX NOTE
A 1.20
A1 0.05 0.15
E A2 0.95 1.00 1.05
D/E 8.75 9.00 9.25
D1/E1 6.90 7.00 7.10 2
b C 0.09 0.20
L 0.45 0.75
b 0.30 0.45
e 0.80 TYP.
Bottom View n 32
Notes: 1. This drawing is for general information only. Refer to JEDEC Drawing MS-026, Variation ABA.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable protrusion is 0.25mm per side.
Dimensions D1 and E1 are maximum plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.10mm maximum.
02/29/12
1
0.30
Dia. Typ. Laser Marking
Seating Plane
C
0.080 C
Top View
Side View
L D2
b COMMON DIMENSIONS
(Unit of Measure = mm)
Option A
Symbol MIN NOM MAX NOTE
A 0.80 0.85 0.90
A1 0.00 0.05
Pin 1# Chamfer
(C 0.30)
A3 0.20 REF
E2 Option B D/E 5.00 BSC
PIN1 ID D2/E2 3.00 3.10 3.20
L 0.30 0.40 0.50
1
Pin 1# Notch b 0.18 0.25 0.30 2
(C 0.20 R)
e 0.50 BSC
See Options e
n 32
A, B
Bottom View
Notes: 1. This drawing is for general information only. Refer to JEDEC Drawing MO-220, Variation VHHD-2, for proper dimensions, tolerances, datums, etc.
2. Dimensions b applies to metallized terminal and is measured between 0.15mm and 0.30mm from the terminal tip.
If the terminal has the optical radius on the other end of the terminal, the dimensions should not be measured in that radius area.
01/31/12
34.1.1 Revision D
No known errata.
Please note that the following page numbers referred to in this section refer to the specific revision mentioned, not to this
document.
Revision No. History
7810D-AVR-01/15 Put datasheet in the latest template
7810C-AVR-10/12 ATmega88P and ATmega168P references removed
MA package updated
7810B-AVR-03/12
PN package updated
Creation of the automotive version starting from industrial version based on the
7810A-AVR-11/09 ATmega48P/88P/168P/328P datasheet 8025F-AVR-08/08. Temperature and voltage
ranges reflecting automotive requirements.
1. Pin Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 Pin Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Automotive Quality Grade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.1 Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3. Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4. Data Retention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7. AVR Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.2 In-System Reprogrammable Flash Program Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.3 SRAM Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7.4 EEPROM Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
7.5 I/O Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
7.6 Register Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
11. Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
11.1 Interrupt Vectors in ATmega328P . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
11.2 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
13. I/O-Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
13.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
13.2 Ports as General Digital I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
13.3 Alternate Port Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
13.4 Register Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Atmel, Atmel logo and combinations thereof, Enabling Unlimited Possibilities, AVR, AVR Studio , and others are registered trademarks or trademarks of Atmel
Corporation in U.S. and other countries. Other terms and product names may be trademarks of others.
DISCLAIMER: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right
is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE
ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT
SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES
FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this
document and reserves the right to make changes to specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information
contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended,
authorized, or warranted for use as components in applications intended to support or sustain life.
SAFETY-CRITICAL, MILITARY, AND AUTOMOTIVE APPLICATIONS DISCLAIMER: Atmel products are not designed for and will not be used in connection with any applications where
the failure of such products would reasonably be expected to result in significant personal injury or death (Safety-Critical Applications) without an Atmel officer's specific written
consent. Safety-Critical Applications include, without limitation, life support devices and systems, equipment or systems for the operation of nuclear facilities and weapons systems.
Atmel products are not designed nor intended for use in military or aerospace applications or environments unless specifically designated by Atmel as military-grade. Atmel products are
not designed nor intended for use in automotive applications unless specifically designated by Atmel as automotive-grade.