– 130 Powerful Instructions – Most Single Clock Cycle Execution
– 32x8GeneralPurposeWorkingRegisters
– Fully Static Operation
– Up to 8 MIPS Throughput at 8 MHz
– On-chip 2-cycle Multiplier
• Program and Data Memories
– 16K Bytes of Non-volatile In-System Programmable Flash Endurance: 1,000
Write/Erase Cycles
– Optional Boot Code Memory with Independent Lock bits Self-programming of
Program and Data Memories
– 512 Bytes of Non-volatile In-System Programmable EEPROM Endurance: 100,000
Write/Erase Cycles
– 1K Byte of Internal SRAM
– Programming Lock for Software Security
• Peripheral Features
– Two 8-bit Timer/Counters with Separate Prescaler and PWM
– Expanded 16-bit Timer/Counter System with Separate Prescaler, Compare,
Capture Modes and Dual 8-, 9-, or 10-bit PWM
– Dual Programmable Serial UARTs
– Master/Slave SPI Serial Interface
– Real-time Counter with Separate Oscillator
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
• Special Microcontroller Features
– Power-on Reset
– External and Internal Interrupt Sources
– Three Sleep Modes: Idle, Power-save and Power-down
– 2.7V - 5.5V for the ATmega161L
– 4.0V - 5.5V for the ATmega161
• Speed Grades
– 0 - 4 MHz for the ATmega161L
– 0 - 8 MHz for the ATmega161
• Commercial and Industrial Temperature Ranges
®
8-bit Microcontroller
8-bit
Microcontroller
with 16K Bytes
of In-System
Programmable
Flash
ATmega161
ATmega161L
Disclaimer
Typical values contained in this data sheet are based on simulations and characterization of other AVR microcontrollers manufactured on the same process technology.
Min and Max values will be available after the device is characterized.
* NC = Do not connect
(Can be used in future devices)
2
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
DescriptionThe ATmega161 is a low-power CMOS 8-bit microcontroller based on the AVR RISC
architecture. By executing powerful instructions in a single clock cycle, the ATmega161
achieves throughputs approaching 1 MIPS per MHz allowing the system designer to
optimize power consumption versus processing speed. 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 ATmega161 provides the following features: 16K bytes of In-System or Selfprogrammable Flash, 512 bytes EEPROM, 1K byte of SRAM, 35 general purpose I/O
lines, 32 general purpose working registers, Real-time Counter, three flexible
Timer/Counters with Compare modes, internal and external interrupts, two programmable serial UARTs, programmable Watchdog Timer with internal Oscillator, an SPI serial
port and three software-selectable power saving modes. The Idle mode stops the CPU
while allowing the SRAM, Timer/Counters, SPI port and interrupt system to continue
functioning. The Power-down mode saves the register and SRAM contents but freezes
the Oscillator, disabling all other chip functions until the next External Interrupt or Hardware Reset. In Power-save mode, the timer Oscillator continues to run, allowing the
user to maintain a timer base while the rest of the device is sleeping.
The device is manufactured using Atmel’s high-density non-volatile memory technology.
The On-chip Flash Program memory can be reprogrammed using the Self-programming
capability through the Boot Block and an ISP through the SPI port, or by using a conventional non-volatile Memory programmer. By combining an enhanced RISC 8-bit CPU
with In-System Programmable Flash on a monolithic chip, the Atmel ATmega161 is a
powerful microcontroller that provides a highly flexible and cost-effective solution to
many embedded control applications.
The ATmega161 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.
1228C–AVR–08/02
3
Block DiagramFigure 1. The ATmega161 Block Diagram
PA0-PA7
VCC
PC0-PC7
GND
PORTA DRIVERS
DATA REGISTER
PORTA
PROGRAM
COUNTER
PROGRAM
FLASH
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
CONTROL
LINES
DATA DIR.
REG. PORTA
STACK
POINTER
SRAM
GENERAL
PURPOSE
REGISTERS
ALU
STATUS
REGISTER
X
Y
Z
DATA REGISTER
8-BIT DATA BUS
PORTC DRIVERS
PORTC
INTERNAL
OSCILLATOR
WATCHDOG
TIMER
MCU CONTROL
REGISTER
TIMER/
COUNTERS
INTERRUPT
UNIT
EEPROM
DATA DIR.
REG. PORTC
OSCILLATOR
TIMING AND
CONTROL
XTAL1
XTAL2
RESET
PROGRAMMING
TOR
ARA
ANALOG
COMP
+
-
LOGIC
DATA REGISTER
PORTB
DATA DIR.
REG. PORTB
PORTB DRIVERS
PB0 - PB7
SPI
DATA REGISTER
PORTD
PORTD DRIVERS
UARTS
REG. PORTD
PD0 - PD7
DATA DIR.
DATA REG.
PORTE
PORTE DRIVERS
PE0 - PE2
DATA DIR
REG. PORTE
4
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Pin Descriptions
VCCSupply voltage.
GNDGround.
Port A (PA7..PA0)Port A is an 8-bit bi-directional I/O port. Port pins can provide internal pull-up resistors
(selected for each bit). The Port A output buffers can sink 20 mA and can drive LED displays directly. When pins PA0 to PA7 are used as inputs and are externally pulled low,
they will source current if the internal pull-up resistors are activated. The Port A pins are
tri-stated when a reset condition becomes active, even if the clock is not running.
Port A serves as a Multiplexed Address/Data port when using external memory
interface.
Port B (PB7..PB0)Port B is an 8-bit bi-directional I/O port with internal pull-up resistors. The Port B output
buffers can sink 20 mA. As inputs, Port B pins that are externally pulled low will source
current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset
condition becomes active, even if the clock is not running.
Port B also serves the functions of various special features of the ATmega161 as listed
on page 92.
Port C (PC7..PC0)Port C is an 8-bit bi-directional I/O port with internal pull-up resistors. The Port C output
buffers can sink 20 mA. As inputs, Port C pins that are externally pulled low will source
current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset
condition becomes active, even if the clock is not running.
Port C also serves as an address high output when using external memory interface.
Port D (PD7..PD0)Port D is an 8-bit bi-directional I/O port with internal pull-up resistors. The Port D output
buffers can sink 20 mA. As inputs, Port D pins that are externally pulled low will source
current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset
condition becomes active, even if the clock is not running.
Port D also serves the functions of various special features of the ATmega161 as listed
on page 101.
Port E (PE2..PE0)Port E is a 3-bit bi-directional I/O port with internal pull-up resistors. The Port E output
buffers can sink 20 mA. As inputs, Port E pins that are externally pulled low will source
current if the pull-up resistors are activated. The Port E pins are tri-stated when a reset
condition becomes active, even if the clock is not running.
Port E also serves the functions of various special features of the ATmega161 as listed
on page 107.
RESET
Reset input. A low level on this pin for more than 500 ns will generate a Reset, even if
the clock is not running. Shorter pulses are not guaranteed to generate a Reset.
XTAL1Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.
XTAL2Output from the inverting Oscillator amplifier.
1228C–AVR–08/02
5
Crystal OscillatorXTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier that can
be configured for use as an on-chip Oscillator, as shown in Figure 2. Either a quartz
crystal or a ceramic resonator may be used. To drive the device from an external clock
source, XTAL2 should be left unconnected while XTAL1 is driven as shown in Figure 3.
Figure 2. Oscillator Connections
C2
C1
Figure 3. External Clock Drive Configuration
NC
EXTERNAL
OSCILLATOR
SIGNAL
XTAL2
XTAL1
GND
XTAL2
XTAL1
GND
6
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Architectural
Overview
The fast-access Register File concept contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This means that during one single clock
cycle, one Arithmetic Logic Unit (ALU) operation is executed. 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 three
address pointers is also used as the address pointer for the constant table look-up function. These added function registers are the 16-bit X-register, Y-register and Z-register.
The ALU supports arithmetic and logic functions between registers or between a constant and a register. Single register operations are also executed in the ALU. Figure 4
shows the ATmega161 AVR RISC microcontroller architecture.
Figure 4. The ATmega161 AVR RISC Architecture
Data Bus 8-bit
8K x 16
Program
Memory
Instruction
Register
Instruction
Decoder
Control Lines
Program
Counter
Direct Addressing
Status
and Control
32 x 8
General
Purpose
Registers
ALU
Indirect Addressing
1024 x 8
Data
SRAM
Interrupt
Unit
SPI
Unit
Serial
UART0
Serial
UART1
8-bit
Timer/Counter
with PWM
and RTC
16-bit
Timer/Counter
with PWM
8-bit
Timer/Counter
with PWM
1228C–AVR–08/02
512 x 8
EEPROM
32
I/O Lines
Watchdog
Timer
Analog
Comparator
7
In addition to the register operation, the conventional Memory Addressing modes can be
used on the Register File. This is enabled by the fact that the Register File is assigned
the 32 lowermost Data Space addresses ($00 - $1F), allowing them to be accessed as
though they were ordinary memory locations.
The I/O memory space contains 64 addresses for CPU peripheral functions such as
Control Registers, Timer/Counters, 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,
$20 - $5F.
The AVR uses a Harvard architecture concept – with separate memories and buses for
program and data. The Program memory is executed with a two-stage pipeline. 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 Self-programmable Flash memory.
With the jump and call instructions, the whole 8K word address space is directly
accessed. Most AVR instructions have a single 16-bit word format. Every Program
memory address contains a 16- or 32-bit instruction.
During interrupts and subroutine calls, the return address Program Counter (PC) is
stored on the Stack. The Stack is effectively allocated in the general data SRAM and,
consequently, the Stack size is only limited by the total SRAM size and the usage of the
SRAM. All user programs must initialize the SP (Stack Pointer) in the reset routine
(before subroutines or interrupts are executed). The 16-bit Stack Pointer is read/write
accessible in the I/O space.
The 1K byte data SRAM can be easily 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.
8
ATmega161(L)
1228C–AVR–08/02
Figure 5. Memory Maps
ATmega161(L)
Program Memory
Program Flash
(8K x 16)
$000
Data Memory
32 Gen. Purpose
Working Registers
64 I/O Registers
Internal SRAM
(1024 x 8)
External SRAM
(0 - 63K x 8)
$0000
$001F
$0020
$005F
$0060
$045F
$0460
$1FFF
$FFFF
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 the different interrupts have a separate Interrupt Vector in the Interrupt Vector table at the beginning of the Program
memory. The different interrupts have priority in accordance with their Interrupt Vector
position. The lower the Interrupt Vector address, the higher the priority.
1228C–AVR–08/02
9
The General Purpose
Register File
Figure 6 shows the structure of the 32 general purpose working registers in the CPU.
Figure 6. AVR CPU General Purpose Working Registers
70Addr.
R0$00
R1$01
R2$02
…
R13$0D
GeneralR14$0E
PurposeR15$0F
WorkingR16$10
RegistersR17$11
…
R26$1AX-register Low Byte
R27$1BX-register High Byte
R28$1CY-register Low Byte
R29$1DY-register High Byte
R30$1EZ-register Low Byte
R31$1FZ-register High Byte
All the register operating instructions in the instruction set have direct and single cycle
access to all registers. The only exceptions are the five constant arithmetic and logic
instructions SBCI, SUBI, CPI, ANDI, and ORI between a constant and a register, and
the LDI instruction for load immediate constant data. These instructions apply to the
second half of the registers in the Register File – R16..R31. The general SBC, SUB, CP,
AND, and OR, and all other operations between two registers or on a single register
apply to the entire Register File.
The X-register, Y-register and
Z-register
As shown in Figure 6, 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-registers can be set to index any
register in the file.
The registers R26..R31 have some added functions to their general purpose usage.
These registers are address pointers for indirect addressing of the Data Space. The
three indirect address registers X, Y, and Z are defined as:
Figure 7. X-, Y-, and Z-registers
150
X-register7070
R27 ($1B)R26 ($1A)
150
Y-register7070
R29 ($1D)R28 ($1C)
150
Z-register7070
R31 ($1F)R30 ($1E)
10
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
In the different Addressing modes, these address registers have functions as fixed displacement, automatic increment and decrement (see the descriptions for the different
instructions).
ALU – Arithmetic Logic
Unit
Self-programmable Flash
Program Memory
The high-performance AVR ALU operates in direct connection with all the 32 general
purpose working registers. Within a single clock cycle, ALU operations between registers in the Register File are executed. The ALU operations are divided into three main
categories – arithmetic, logical and bit functions. ATmega161 also provides a powerful
multiplier supporting both signed/unsigned multiplication and fractional format. See the
Instruction Set section for a detailed description.
The ATmega161 contains 16K bytes of On-chip Self-programmable and In-System Programmable Flash memory for program storage. Since all instructions are 16- or 32-bit
words, the Flash is organized as 8K x 16. The Flash memory has an endurance of at
least 1,000 write/erase cycles. The ATmega161 Program Counter (PC) is 13 bits wide,
thus addressing the 8,192 Program memory locations.
See page 110 for a detailed description of Flash data downloading.
See page 13 for the different Program Memory Addressing modes.
EEPROM Data MemoryThe ATmega161 contains 512 bytes of data EEPROM memory. It is organized as a sep-
arate data space in which single bytes can be read and written. The EEPROM has an
endurance of at least 100,000 write/erase cycles per location. The interface between the
EEPROM and the CPU is described on page 60, specifying the EEPROM Address Registers, the EEPROM Data Register and the EEPROM Control Register.
For the SPI data downloading, see page 125 for a detailed description.
1228C–AVR–08/02
11
SRAM Data MemoryFigure 8 shows how the ATmega161 SRAM memory is organized.
Figure 8. SRAM Organization
Register FileData Address Space
R0$0000
R1$0001
R2$0002
……
R29$001D
R30$001E
R31$001F
I/O Registers
$00$0020
$01$0021
$02$0022
……
$3D$005D
$3E$005E
$3F$005F
Internal SRAM
$0060
$0061
…
$045E
$045F
The lower 1120 Data memory locations address the Register File, the I/O memory and
the internal data SRAM. The first 96 locations address the Register File and I/O memory
and the next 1K locations address the internal data SRAM. An optional external Data
memory device can be placed in the same SRAM memory space. This memory device
will occupy the locations following the internal SRAM and up to as much as 64K - 1,
depending on external memory size.
When the addresses accessing the Data memory space exceed the internal data SRAM
locations, the memory device is accessed using the same instructions as for the internal
data SRAM access. When the internal data space is accessed, the read and write
strobe pins (RD
and WR) are inactive during the whole access cycle. External memory
operation is enabled by setting the SRE bit in the MCUCR Register. See “Interface to
External Memory” on page 84 for details.
Accessing external memory takes one additional clock cycle per byte compared to
access of the internal SRAM. This means that the commands LD, ST, LDS, STS,
PUSH, and POP take one additional clock cycle. If the Stack is placed in external memory, interrupts, subroutine calls and returns take two clock cycles extra because the 2byte Program Counter is pushed and popped. When external memory interface is used
with wait state, two additional clock cycles are used per byte. This has the following
effect: Data transfer instructions take two extra clock cycles, whereas interrupt, subroutine calls and returns will need four clock cycles more than specified in the Instruction
Set manual.
12
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
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 features a 63-address locations reach 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 and incremented.
The 32 general purpose working registers, 64 I/O Registers and the 1K byte of internal
data SRAM in the ATmega161 are all accessible through all these Addressing modes.
See the next section for a detailed description of the different Addressing modes.
Program and Data
Addressing Modes
Register Direct, Single
Register Rd
Register Direct, Two Registers
Rd and Rr
The ATmega161 AVR RISC microcontroller supports powerful and efficient Addressing
modes for access to the Program memory (Flash) and Data memory (SRAM, Register
File and I/O memory). This section describes the different Addressing modes supported
by the AVR architecture. In the figures, OP means the operation code part of the instruction word. To simplify, not all figures show the exact location of the addressing bits.
Figure 9. Direct Single Register Addressing
15
REGISTER FILE
40
OPd
0
d
31
The operand is contained in register d (Rd).
Figure 10. Direct Register Addressing, Two Registers
REGISTER FILE
1595 40
OPrd
0
1228C–AVR–08/02
d
r
31
13
Operands are contained in registers r (Rr) and d (Rd). The result is stored in register d
(Rd).
I/O DirectFigure 11. I/O Direct Addressing
15
nOP
Operand address is contained in six bits of the instruction word. n is the destination or
Source Register Address.
Data DirectFigure 12. Direct Data Addressing
31
OPRr/Rd
150
20 19
16 LSBs
I/O MEMORY
05
P
Data Space
16
0
63
$0000
14
$FFFF
A 16-bit data address is contained in the 16 LSBs of a two-word instruction. Rd/Rr specify the destination or source register.
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Data Indirect with
Figure 13. Data Indirect with Displacement
Displacement
15
Y OR Z - REGISTER
15
OPan
Operand address is the result of the Y- or Z-register contents added to the address contained in six bits of the instruction word.
Data IndirectFigure 14. Data Indirect Addressing
X, Y, OR Z - REGISTER
Data Space
$0000
0
05610
$FFFF
Data Space
$0000
015
Data Indirect with Predecrement
$FFFF
Operand address is the contents of the X-, Y-, or Z-register.
Figure 15. Data Indirect Addressing with Pre-decrement
Data Space
$0000
015
X, Y, OR Z - REGISTER
-1
$FFFF
The X-, Y-, or Z-register is decremented before the operation. Operand address is the
decremented contents of the X-, Y-, or Z-register.
1228C–AVR–08/02
15
Data Indirect with Postincrement
Figure 16. Data Indirect Addressing with Post-increment
Data Space
$0000
015
X, Y, OR Z - REGISTER
1
$FFFF
The X-, Y-, or Z-register is incremented after the operation. Operand address is the contents of the X-, Y-, or Z-register prior to incrementing.
Constant Addressing Using
the LPM Instruction
Indirect Program Addressing,
IJMP and ICALL
Figure 17. Code Memory Constant Addressing
PROGRAM MEMORY
151 0
Z-REGISTER
$000
$1FFF
Constant byte address is specified by the Z-register contents. The 15 MSBs select word
address (0 - 8K), the LSB selects Low byte if cleared (LSB = 0) or High byte if set
(LSB = 1).
Figure 18. Indirect Program Memory Addressing
PROGRAM MEMORY
150
Z-REGISTER
$000
16
$1FFF
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Program execution continues at address contained by the Z-register (i.e., the PC is
loaded with the contents of the Z-register).
Relative Program Addressing,
RJMP and RCALL
Direct Program Addressing,
JMP and CALL
Figure 19. Relative Program Memory Addressing
15
1512 11
OPk
PROGRAM MEMORY
0
PC
0
$000
$1FFF
Program execution continues at address PC + k + 1. The relative address k is -2048 to
2047.
Figure 20. Direct Program Addressing
31
OP
150
21 20
16 LSBs
16
PROGRAM MEMORY
$0000
Memory Access Times
and Instruction
Execution Timing
1228C–AVR–08/02
$1FFF
Program execution continues at the address immediate in the instruction words.
This section describes the general access timing concepts for instruction execution and
internal memory access.
TheAVRCPUisdrivenbytheSystemClockØ, directly generated from the external
clock crystal for the chip. No internal clock division is used.
Figure 21 shows the parallel instruction fetches and instruction executions enabled by
the Harvard architecture and the fast-access Register File concept. This is the basic
pipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique results
for functions per cost, functions per clocks and functions per power unit.
17
Figure 21. The Parallel Instruction Fetches and Instruction Executions
T1T2T3T4
System Clock Ø
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
Figure 22 shows the internal timing concept for the Register File. In a single clock cycle
an ALU operation using two register operands is executed and the result is stored back
to the destination register.
Figure 22. Single Cycle ALU Operation
T1T2T3T4
System Clock Ø
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
The internal data SRAM access is performed in two System Clock cycles as described
in Figure 23.
Figure 23. On-chip Data SRAM Access Cycles
T1T2T3T4
System Clock Ø
Address
Data
WR
Data
RD
Prev. Address
Address
Write
Read
18
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
l/O MemoryThe I/O space definition of the ATmega161 is shown in Table 1.
$08 ($28)ACSRAnalog Comparator Control and Status Register
$07 ($27)PORTEData Register, Port E
$06 ($26)DDREData Direction Register, Port E
$05 ($25)PINEInput Pins, Port E
$03 ($23)UDR1UART1 I/O Data Register
$02 ($22)UCSR1AUART1 Control and Status Register
$01 ($21)UCSR1BUART1 Control and Status Register
$00 ($20)UBRR1UART1 Baud Rate Register
Note:1. Reserved and unused locations are not shown in this table.
20
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
All ATmega161 I/Os and peripherals are placed in the I/O space. The I/O locations are
accessed by the IN and OUT instructions transferring data between the 32 general purpose working registers and the I/O space. I/O Registers within the address range $00 $1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the
value of single bits can be checked by using the SBIS and SBIC instructions. Refer to
the instruction set section for more details. When using the I/O specific commands IN
and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O Registers as
SRAM, $20 must be added to this address. All I/O Register addresses throughout this
document are shown with the SRAM address in parentheses.
For compatibility with future devices, reserved bits should be written to zero if accessed.
Reserved I/O memory addresses should never be written.
Some of the Status Flags are cleared by writing a logical “1” to them. Note that the CBI
and SBI instructions will operate on all bits in the I/O Register, writing a one back into
any flag read as set, thus clearing the Flag. The CBI and SBI instructions work with registers $00 to $1F only.
The I/O and Peripherals Control Registers are explained in the following sections.
Status Register – SREGThe AVR Status Register (SREG) at I/O space location $3F ($5F) is defined as:
Bit76543210
$3F ($5F)ITHSVNZCSREG
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
• Bit 7
– I: Global Interrupt Enable
The Global Interrupt Enable bit must be set (one) for the interrupts to be enabled. The
individual interrupt enable control is then performed in separate control registers. If the
Global Interrupt Enable bit is cleared (zero), none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an
interrupt has occurred and is set by the RETI instruction to enable subsequent
interrupts.
• Bit 6
– T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source
and destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction and a bit in T can be copied into a bit in a register in the
Register File by the BLD instruction.
• Bit 5
– H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. See the
Instruction Set description for detailed information.
• Bit 4
– S: Sign Bit, S = N ⊕ V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement Overflow Flag V. See the Instruction Set description for detailed information.
• Bit 3
– V: Two’s Complement Overflow Flag
1228C–AVR–08/02
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See
the Instruction Set Description for detailed information.
21
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result after the different arithmetic and logic
operations. See the Instruction Set description for detailed information.
• Bit 1
– Z: Zero Flag
The Zero Flag Z indicates a zero result after the different arithmetic and logic operations. See the Instruction Set description for detailed information.
• Bit 0
– C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the Instruction
Set description for detailed information.
Note that the Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt routine. This must be handled by
software.
Stack Pointer – SPThe ATmega161 Stack Pointer is implemented as two 8-bit registers in the I/O space
locations $3E ($5E) and $3D ($5D). As the ATmega161 supports up to 64-Kbyte memory, all 16 bits are used.
Bit151413121110 9 8
$3E ($5E)SP15SP14SP13SP12SP11SP10SP9SP8SPH
$3D ($5D)SP7SP6SP5SP4SP3SP2SP1SP0SPL
76543210
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
00000000
Reset and Interrupt
Handling
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the
program before any subroutine calls are executed or interrupts are enabled. The Stack
Pointer must be set to point above $60. The Stack Pointer is decremented by 1 when
data is pushed onto the Stack with the PUSH instruction, and it is decremented by 2
when an address is pushed onto the Stack with subroutine calls and interrupts. The
Stack Pointer is incremented by 1 when data is popped from the Stack with the POP
instruction, and it is incremented by 2 when an address is popped from the Stack with
return from subroutine RET or return from interrupt (RETI).
The ATmega161 provides 20 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 that must be set (one) together with the
I-bit in the Status Register in order to enable the interrupt.
The lowest addresses in the Program memory space are automatically defined as the
Reset and Interrupt vectors. The complete list of Vectors is shown in Table 2. The list
also determines the priority levels of the different interrupts. The lower the address, the
higher the priority level. RESET has the highest priority, and next is INT0 (the External
Interrupt Request 0) and so on.
22
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Table 2. Reset and Interrupt Vectors
(1)
Vector
No.Program AddressSourceInterrupt Definition
1$000RESETExternal Pin, Power-on Reset and
Watchdog Reset
2$002INT0External Interrupt Request 0
3$004INT1External Interrupt Request 1
4$006INT2External Interrupt Request 2
5$008TIMER2 COMPTimer/Counter2 Compare Match
6$00aTIMER2 OVFTimer/Counter2 Overflow
7$00cTIMER1 CAPTTimer/Counter1 Capture Event
8$00eTIMER1 COMPATimer/Counter1 Compare Match A
9$010TIMER1 COMPBTimer/Counter1 Compare Match B
10$012TIMER1 OVFTimer/Counter1 Overflow
11$014TIMER0 COMPTimer/Counter0 Compare Match
12$016TIMER0 OVFTimer/Counter0 Overflow
13$018SPI, STCSerial Transfer Complete
14$01aUART0, RXUART0, Rx Complete
15$01cUART1, RXUART1, Rx Complete
16$01eUART0, UDREUART0 Data Register Empty
17$020UART1, UDREUART1 Data Register Empty
18$022UART0, TXUART0, Tx Complete
19$024UART1, TXUART1, Tx Complete
20$026EE_RDYEEPROM Ready
21$028ANA_COMPAnalog Comparator
Note:1. If BOOTRST fuse is programmed, the Reset Vector is located on program address
$1e00, see Table 39 on page 112 for details.
The most typical and general program setup for the Reset and Interrupt Vector
addresses are:
AddressLabelsCodeComments
$000jmpRESET; Reset Handler
$002jmpEXT_INT0; IRQ0 Handler
$004jmpEXT_INT1; IRQ1 Handler
$006jmpEXT_INT2; IRQ2 Handler
$008jmpTIM2_COMP; Timer2 Compare Handler
$00ajmpTIM2_OVF; Timer2 Overflow Handler
$00cjmpTIM1_CAPT; Timer1 Capture Handler
$00ejmpTIM1_COMPA; Timer1 CompareA Handler
$010jmpTIM1_COMPB; Timer1 CompareB Handler
$012jmpTIM1_OVF; Timer1 Overflow Handler
$014jmpTIM0_COMP; Timer0 Compare Handler
$016jmpTIM0_OVF; Timer0 Overflow Handler
$018jmpSPI_STC;; SPI Transfer Complete Handler
1228C–AVR–08/02
23
$01ajmpUART_RXC0; UART0 RX Complete Handler
$01cjmpUART_RXC1; UART1 RX Complete Handler
$01ejmpUART_DRE0; UDR0 Empty Handler
$020jmpUART_DRE1; UDR1 Empty Handler
$022jmpUART_TXC0; UART0 TX Complete Handler
$024jmpUART_TXC1; UART1 TX Complete Handler
$026jmpEE_RDY; EEPROM Ready Handler
$028jmpANA_COMP; Analog Comparator Handler
;
$02aMAIN:ldi r16,high(RAMEND) ; Main program start
$02bout SPH,r16
$02cldi r16,low(RAMEND)
$02dout SPL,r16
$02e<instr> xxx
…………
When the BOOTRST fuse is programmed, the most typical and general program setup
for the Reset and Interrupt Vector addresses are:
AddressLabelsCodeComments
.org $002; Reset is located at $1e000
$002jmpEXT_INT0; IRQ0 Handler
$004jmpEXT_INT1; IRQ1 Handler
$006jmpEXT_INT2; IRQ2 Handler
$008jmpTIM2_COMP; Timer2 Compare Handler
$00ajmpTIM2_OVF; Timer2 Overflow Handler
$00cjmpTIM1_CAPT; Timer1 Capture Handler
$00ejmpTIM1_COMPA; Timer1 CompareA Handler
$010jmpTIM1_COMPB; Timer1 CompareB Handler
$012jmpTIM1_OVF; Timer1 Overflow Handler
$014jmpTIM0_COMP; Timer0 Compare Handler
$016jmpTIM0_OVF; Timer0 Overflow Handler
$018jmpSPI_STC;; SPI Transfer Complete Handler
$01ajmpUART_RXC0; UART0 RX Complete Handler
$01cjmpUART_RXC1; UART1 RX Complete Handler
$01ejmpUART_DRE0; UDR0 Empty Handler
$020jmpUART_DRE1; UDR1 Empty Handler
$022jmpUART_TXC0; UART0 TX Complete Handler
$024jmpUART_TXC1; UART1 TX Complete Handler
$026jmpEE_RDY; EEPROM Ready Handler
$028jmpANA_COMP; Analog Comparator Handler
;
$02aMAIN:ldi r16,high(RAMEND); Main program start
$02bout SPH,r16
$02cldi r16,low(RAMEND)
$02dout SPL,r16
$02e<instr> xxx
;
.org $1e00
$1e00jmpRESET; Reset handler
…………
24
ATmega161(L)
1228C–AVR–08/02
Reset SourcesThe ATmega161 has three sources of Reset:
•Power-on Reset. The MCU is reset when the supply voltage is below the Power-on
Reset threshold (V
POT
).
•External Reset. The MCU is reset when a low level is present on the RESET
more than 500 ns.
•Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and
the Watchdog is enabled.
During Reset, all I/O Registers are then set to their initial values and the program starts
execution from address $000. The instruction placed in address $000 must be a JMP
(relative jump) instruction to the reset handling routine. If the program never enables an
interrupt source, the Interrupt Vectors are not used and regular program code can be
placed at these locations. The circuit diagram in Figure 24 shows the Reset Logic. Table
3 and Table 4 define the timing and electrical parameters of the reset circuitry.
Figure 24. Reset Logic
DATA BU S
MCU Status
Register (MCUSR)
ATmega161(L)
pin for
CK
PORF
WDRF
EXTRF
CKSEL[2:0]
Delay Counters
Full
1228C–AVR–08/02
25
Table 3. Reset Characteristics (V
=5.0V)
CC
(1)
SymbolParameterMinTypMaxUnits
V
V
POT
RST
Power-on Reset Threshold Voltage (rising)1.01.41.8V
Power-on Reset Threshold Voltage (falling)
RESET Pin Threshold Voltage0.85 V
(1)
0.40.60.8V
CC
Note:1. The Power-on Reset will not work unless the supply voltage has been below V
(falling).
‘
Table 4. Reset Delay Selections
CKSEL
[2:0]
Start-up Time, VCC=2.7V,
SUT Unprogrammed
(3)
Start-up Time, VCC=4.0V,
SUT Programmed
Recommended
(1)
Usage
0004.2 ms + 6 CK5.8 ms + 6 CKExternal Clock, Fast
Rising Power
00130 µs + 6 CK10 µs + 6 CKExternal Clock
(2)
01067 ms + 16K CK92 ms + 16K CKCrystal Oscillator,
Slowly Rising
Power
0114.2 ms + 16K CK5.8 ms + 16K CKCrystal Oscillator,
Fast Rising Power
10030 µs + 16K CK10 µs + 16K CKCrystal Oscillator
10167 ms + 1K CK92 ms + 1K CKCeramic
Resonator/External
Clock, Slowly Rising
Power
V
POT
(2)
1104.2 ms + 1K CK5.8 ms + 1K CKCeramic Resonator,
Fast Rising Power
11130 µs + 1K CK10 µs + 1K CKCeramic
Resonator
(2)
Notes: 1. The CKSEL fuses control only the start-up time. The Oscillator is the same for all
selections. On Power-up, the real-time part of the start-up time is increased with typ.
0.6 ms.
2. External Power-on Reset.
3. Table 4 shows the Start-up Times from Reset. From sleep, only the clock counting
part of the start-up time is used. The Watchdog Oscillator is used for timing the realtime part of the start-up time. The number WDT Oscillator cycles used for each timeout is shown in Table 5.
Table 5. Number of Watchdog Oscillator Cycles
SUTTime-outNumber of Cycles
Unprogrammed4.2 ms (at V
Unprogrammed67 ms (at V
Programmed5.8 ms (at V
Programmed92 ms (at V
=2.7V)1K
CC
= 2.7V)16K
CC
=4.0V)4K
CC
= 4.0V)64K
CC
The frequency of the Watchdog Oscillator is voltage-dependent as shown in the Electrical Characteristics section. The device is shipped with CKSEL = 010.
26
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Power-on ResetA Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detec-
tion level is nominally 1.4V (rising V
the detection level. The POR circuit can be used to trigger the Start-up Reset, as well as
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 a delay counter, which determines
the delay, for which the device is kept in RESET after V
the delay counter can be defined by the user through the CKSEL fuses. The eight different selections for the delay period are presented in Table 4. The RESET signal is
activated again, without any delay, when the V
External ResetAn External Reset is generated by a low level on the RESET pin. Reset pulses longer
than 500 ns 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 (V
Time-out period (t
TOUT
) on its positive edge, the delay timer starts the MCU after the
RST
) has expired.
Figure 27. External Reset during Operation
Watchdog ResetWhen the Watchdog times out, it will generate a short reset pulse of 1 XTAL cycle dura-
tion. On the falling edge of this pulse, the delay timer starts counting the Time-out period
(t
). Refer to page 58 for details on operation of the Watchdog.
TOU T
Figure 28. Watchdog Reset during Operation
28
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
MCU Status Register –
MCUSR
The MCU Status Register provides information on which reset source caused an MCU
Reset.
Bit76543210
$34 ($54)––––WDRF–EXTRFPORFMCUSR
Read/WriteRRRRR/WRR/WR/W
Initial Value0000See Bit Description
• Bits 7..4
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and always read as zero.
• Bit 3
– WDRF: Watchdog Reset Flag
This bit is set if a Watchdog Reset occurs. The bit is cleared by a Power-on Reset or by
writing a logical “0” to the Flag.
• Bit 2
– Res: Reserved Bit
This bit are reserved bit in the ATmega161 and always read as zero.
• Bit 1
– EXTRF: External Reset Flag
This bit is set if an External Reset occurs. The bit is cleared by a Power-on Reset or by
writing a logical “0” to the Flag.
• Bit 0
– PORF: Power-on Reset Flag
This bit is set if a Power-on Reset occurs. The bit is cleared only by writing a logical “0”
to the Flag.
To make use of the Reset Flags to identify a reset condition, the user should read and
then clear the MCUSR as early as possible in the program. If the register is cleared
before another reset occurs, the source of the reset can be found by examining the
Reset Flags.
Interrupt HandlingThe ATmega161 has two 8-bit Interrupt Mask Control Registers; GIMSK (General Inter-
rupt Mask Register) and TIMSK (Timer/Counter Interrupt Mask Register).
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared (zero) and all interrupts are disabled. The user software can set (one) the I-bit to enable nested interrupts.
The I-bit is set (one) when a Return from Interrupt instruction (RETI) is executed.
When the Program Counter is vectored to the actual Interrupt Vector in order to execute
the interrupt handling routine, hardware clears the corresponding flag that generated the
interrupt. Some of the Interrupt Flags can also be cleared by writing a logical “1” to the
Flag bit position(s) to be cleared.
If an interrupt condition occurs when the corresponding interrupt enable bit is cleared
(zero), the Interrupt Flag will be set and remembered until the interrupt is enabled or the
Flag is cleared by software.
If one or more interrupt conditions occur when the global interrupt enable bit is cleared
(zero), the corresponding Interrupt Flag(s) will be set and remembered until the global
interrupt enable bit is set (one), and will be executed by order of priority.
1228C–AVR–08/02
Note that external level interrupt does not have a flag and will only be remembered for
as long as the interrupt condition is present.
29
Note that the Status Register is not automatically stored when entering an interrupt routine or restored when returning from an interrupt routine. This must be handled by
software.
Interrupt Response TimeThe interrupt execution response for all the enabled AVR interrupts is four clock cycles
minimum. After four clock cycles, the Program Vector address for the actual interrupt
handling routine is executed. During this four-clock-cycle period, the Program Counter
(13 bits) is pushed onto the Stack. The Vector is normally a jump to the interrupt routine,
and this jump takes three clock cycles. If an interrupt occurs during execution of a multicycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in Sleep mode, the interrupt execution response time is
increased by four clock cycles.
A return from an interrupt handling routine takes four clock cycles. During these four
clock cycles, the Program Counter (2 bytes) is popped back from the Stack, the Stack
Pointer is incremented by 2, and the I-Flag in SREG is set. When AVR exits from an
interrupt, it will always return to the main program and execute one more instruction
before any pending interrupt is served.
General Interrupt Mask
Register – GIMSK
Bit76543210
$3B ($5B)INT1INT0INT2–––––GIMSK
Read/WriteR/WR/WRRRRRR
InitialValue00000000
• Bit 7
– INT1: External Interrupt Request 1 Enable
When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one),
the external pin interrupt is enabled. The Interrupt Sense Control1 bits 1/0 (ISC11 and
ISC10) in the MCU general Control Register (MCUCR) define whether the external
interrupt is activated on rising and/or falling edge of the INT1 pin or is level-sensed.
Activity on the pin will cause an interrupt request even if INT1 is configured as an output.
The corresponding interrupt of External Interrupt Request 1 is executed from Program
memory address $004. See also “External Interrupts”.
• Bit 6
– INT0: External Interrupt Request 0 Enable
When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one),
the external pin interrupt is enabled. The Interrupt Sense Control0 bits 1/0 (ISC01 and
ISC00) in the MCU general Control Register (MCUCR) define whether the external
interrupt is activated on rising and/or falling edge of the INT0 pin or is level-sensed.
Activity on the pin will cause an interrupt request even if INT0 is configured as an output.
The corresponding interrupt of External Interrupt Request 0 is executed from Program
memory address $002. See also “External Interrupts.”
30
• Bit 5 – INT2: External Interrupt Request 2 Enable
When the INT2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one),
the external pin interrupt is activated. The Interrupt Sense Control2 bit (ISC02 in the
Extended MCU Control Register [EMCUCR]) defines whether the external interrupt is
activated on rising or falling edge of the INT2 pin. Activity on the pin will cause an interrupt request even if INT2 is configured as an output. The corresponding interrupt of
External Interrupt Request 2 is executed from Program memory address $006. See also
“External Interrupts.”
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
• Bits 4..0 – Res: Reserved Bits
These bits are reserved bits in the ATmega161 and always read as zero.
General Interrupt Flag
Register – GIFR
Bit76543210
$3A ($5A)INTF1INTF0INTF2–––––GIFR
Read/WriteR/WR/WR/WRRRRR
InitialValue00000000
• Bit 7
– INTF1: External Interrupt Flag1
When an event on the INT1 pin triggers an interrupt request, INTF1 becomes set (one).
If the I-bit in SREG and the INT1 bit in GIMSK are set (one), the MCU will jump to the
Interrupt Vector at address $004. The Flag is cleared when the interrupt routine is executed. Alternatively, the Flag can be cleared by writing a logical “1” to it.
• Bit 6
– INTF0: External Interrupt Flag0
When an event on the INT0 pin triggers an interrupt request, INTF0 becomes set (one).
If the I-bit in SREG and the INT0 bit in GIMSK are set (one), the MCU will jump to the
Interrupt Vector at address $002. The Flag is cleared when the interrupt routine is executed. Alternatively, the Flag can be cleared by writing a logical “1” to it.
• Bit 5
– INTF2: External Interrupt Flag2
When an event on the INT2 pin triggers an interrupt request, INTF2 becomes set (one).
If the I-bit in SREG and the INT2 bit in GIMSK are set (one), the MCU will jump to the
Interrupt Vector at address $006. The Flag is cleared when the interrupt routine is executed. Alternatively, the Flag can be cleared by writing a logical “1” to it.
Timer/Counter Interrupt Mask
Register – TIMSK
• Bits 4..0
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and always read as zero.
When the TOIE1 bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter1 Overflow interrupt is enabled. The corresponding interrupt (at Vector
$012) is executed if an overflow in Timer/Counter1 occurs, i.e., when the TOV1 bit is set
in the Timer/Counter Interrupt Flag Register (TIFR).
• Bit 6
– OCE1A: Timer/Counter1 Output CompareA Match Interrupt Enable
When the OCIE1A bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter1 CompareA Match interrupt is enabled. The corresponding interrupt (at
Vector $00e) is executed if a Compare A Match in Timer/Counter1 occurs, i.e., when the
OCF1A bit is set in the Timer/Counter Interrupt Flag Register (TIFR).
1228C–AVR–08/02
31
• Bit 5 – OCIE1B: Timer/Counter1 Output CompareB Match Interrupt Enable
When the OCIE1B bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter1 CompareB Match interrupt is enabled. The corresponding interrupt (at
Vector $010) is executed if a Compare B Match in Timer/Counter1 occurs, i.e., when the
OCF1B bit is set in the Timer/Counter Interrupt Flag Register (TIFR).
• Bit 4
– TOIE2: Timer/Counter2 Overflow Interrupt Enable
When the TOIE2 bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt (at Vector
$00a) is executed if an overflow in Timer/Counter2 occurs, i.e., when the TOV2 bit is set
in the Timer/Counter Interrupt Flag Register (TIFR).
When the TICIE1 bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter1 Input Capture Event Interrupt is enabled. The corresponding interrupt
(at Vector $00C) is executed if a capture-triggering event occurs on pin 31, ICP, i.e.,
when the ICF1 bit is set in the Timer/Counter Interrupt Flag Register (TIFR).
• Bit 2
– OCIE2: Timer/Counter2 Output Compare Match Interrupt Enable
When the OCIE2 bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match interrupt is enabled. The corresponding interrupt (at
Vector $008) is executed if a Compare2 match in Timer/Counter2 occurs, i.e., when the
OCF2 bit is set in the Timer/Counter Interrupt Flag Register (TIFR).
• Bit 1
– TOIE0: Timer/Counter0 Overflow Interrupt Enable
When the TOIE0 bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt (at Vector
$016) is executed if an overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set
in the Timer/Counter Interrupt Flag Register (TIFR).
32
• Bit 0
When the OCIE0 bit is set (one) and the I-bit in the Status Register is set (one), the
Timer/Counter0 Compare Match interrupt is enabled. The corresponding interrupt (at
Vector $014) is executed if a Compare 0 Match in Timer/Counter0 occurs, i.e., when the
OCF0 bit is set in the Timer/Counter Interrupt Flag Register (TIFR).
ATmega161(L)
– OCIE0: Timer/Counter0 Output Compare Match Interrupt Enable
1228C–AVR–08/02
Timer/Counter Interrupt Flag
Register – TIFR
ATmega161(L)
Bit76543210
$38 ($58)TOV1OCF1AOCIFBTOV2ICF1OCF2TOV0OCF0TIFR
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
• Bit 7
– TOV1: Timer/Counter1 Overflow Flag
The TOV1 is set (one) when an overflow occurs in Timer/Counter1. TOV1 is cleared by
hardware when executing the corresponding Interrupt Handling Vector. Alternatively,
TOV1 is cleared by writing a logical “1” to the Flag. When the I-bit in SREG, and TOIE1
(Timer/Counter1 Overflow Interrupt Enable), and TOV1 are set (one), the
Timer/Counter1 Overflow Interrupt is executed. In PWM mode, this bit is set when
Timer/Counter1 changes counting direction at $0000.
• Bit 6
– OCF1A: Output Compare Flag 1A
The OCF1A bit is set (one) when a compare match occurs between the Timer/Counter1
and the data in OCR1A (Output Compare Register 1A). OCF1A is cleared by hardware
when executing the corresponding Interrupt Handling Vector. Alternatively, OCF1A is
cleared by writing a logical “1” to the Flag. When the I-bit in SREG and OCIE1A
(Timer/Counter1 Compare Match Interrupt A Enable) and OCF1A are set (one), the
Timer/Counter1 Compare A Match Interrupt is executed.
• Bit 5
– OCF1B: Output Compare Flag 1B
The OCF1B bit is set (one) when a compare match occurs between the Timer/Counter1
and the data in OCR1B (Output Compare Register 1B). OCF1B is cleared by hardware
when executing the corresponding Interrupt Handling Vector. Alternatively, OCF1B is
cleared by writing a logical “1” to the Flag. When the I-bit in SREG and OCIE1B
(Timer/Counter1 Compare Match Interrupt B Enable) and OCF1B are set (one), the
Timer/Counter1 Compare B Match Interrupt is executed.
1228C–AVR–08/02
• Bit 4
– TOV2: Timer/Counter2 Overflow Flag
The bit TOV2 is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared
by hardware when executing the corresponding Interrupt Handling Vector. Alternatively,
TOV2isclearedbywritingalogical“1” to the Flag. When the SREG I-bit and TOIE2
(Timer/Counter2 Overflow Interrupt Enable) and TOV2 are set (one), the
Timer/Counter2 Overflow interrupt is executed.
• Bit 3
– ICF1: Input Capture Flag 1
The ICF1 bit is set (one) to flag an Input Capture Event, indicating that the
Timer/Counter1 value has been transferred to the Input Capture Register (ICR1). ICF1
is cleared by hardware when executing the corresponding Interrupt Handling Vector.
Alternatively, ICF1 is cleared by writing a logical “1” to the Flag. When the SREG I-bit
and TICIE1 (Timer/Counter1 Input Capture Interrupt Enable) and ICF1 are set (one), the
Timer/Counter1 Capture Interrupt is executed.
• Bit 2
– OCF2: Output Compare Flag 2
The OCF2 bit is set (one) when a Compare Match occurs between the Timer/Counter2
and the data in OCR2 (Output Compare Register 2). OCF2 is cleared by hardware when
executing the corresponding Interrupt Handling Vector. Alternatively, OCF2 is cleared
by writing a logical “1” to the Flag. When the I-bit in SREG and OCIE2 (Timer/Counter2
33
Compare match InterruptA Enable) and the OCF2 are set (one), the Timer/Counter2
Compare match Interrupt is executed.
• Bit 1
– TOV0: Timer/Counter0 Overflow Flag
The bit TOV0 is set (one) when an overflow occurs in Timer/Counter0. TOV0 is cleared
by hardware when executing the corresponding Interrupt Handling Vector. Alternatively,
TOV0isclearedbywritingalogical“1” to the Flag. When the SREG I-bit and TOIE0
(Timer/Counter0 Overflow Interrupt Enable) and TOV0 are set (one), the
Timer/Counter0 Overflow interrupt is executed.
• Bit 2
– OCF0: Output Compare Flag 0
The OCF0 bit is set (one) when compare match occurs between the Timer/Counter0
and the data in OCR0 (Output Compare Register 0). OCF0 is cleared by hardware when
executing the corresponding Interrupt Handling Vector. Alternatively, OCF0 is cleared
by writing a logical “1” to the Flag. When the I-bit in SREG and OCIE0 (Timer/Counter0
Compare match InterruptA Enable) and the OCF0 are set (one), the Timer/Counter0
Compare match Interrupt is executed.
External InterruptsThe external interrupts are triggered by the INT0, INT1, and INT2 pins. Observe that, if
enabled, the interrupts will trigger even if the INT0/INT1/INT2 pins are configured as outputs. This feature provides a way of generating a software interrupt. The external
interrupts can be triggered by a falling or rising edge or a low level (INT2 is only an edge
triggered interrupt). This is set up as indicated in the specification for the MCU Control
Register – MCUCR (INT0/INT1) and EMCUCR (INT2). When the external interrupt is
enabled and is configured as level triggered (only INT0/INT1), the interrupt will trigger as
long as the pin is held low.
MCU Control Register –
MCUCR
The MCU Control Register contains control bits for general MCU functions.
Bit76543210
$35 ($55)SRESRW10SESM1ISC11ISC10ISC01ISC00MCUCR
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
• Bit 7
– SRE: External SRAM Enable
When the SRE bit is set (one), the external Data memory interface is enabled and the
pin functions AD0 - 7 (Port A), A8 - 5 (Port C), ALE (Port E), WR,
and RD (Port D) are
activated as the alternate pin functions. The SRE bit overrides any pin direction settings
in the respective Data Direction Registers. See Figure 50 through Figure 53 for a
description of the external memory pin functions. When the SRE bit is cleared (zero),
the external Data memory interface is disabled and the normal pin and data direction
settings are used.
• Bit 6
– SRW10: External SRAM Wait State
The SRW10 bit is used to set up extra wait states in the external memory interface. See
“Double-speed Transmission” on page 78 for a detailed description.
• Bit 5
– SE: Sleep Enable
The SE bit must be set (one) to make the MCU enter the Sleep mode when the SLEEP
instruction is executed. To avoid the MCU entering the Sleep mode unless it is the pro-
34
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
grammer’s purpose, it is recommended to set the Sleep Enable (SE) bit just before the
execution of the SLEEP instruction.
• Bit 4
– SM1: Sleep Mode Select Bit 1
The SM1 bit, together with the SM0 control bit in EMCUCR, selects between the three
available Sleep modes as shown in Table 6.
Table 6. Sleep Mode Select
SM1SM0Sleep Mode
00Idle
01Reserved
10Power-down
11Power-save
• Bits 3, 2
– ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0
The External Interrupt 1 is activated by the external pin INT1 if the SREG I-Flag and the
corresponding interrupt mask in the GIMSK are set. The level and edges on the external
INT1 pin that activate the interrupt are defined in Table 7. The value on the INT1 pin is
sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last
longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low-level interrupt is selected, the low level must be held
until the completion of the currently executing instruction to generate an interrupt.
Table 7. Interrupt 1 Sense Control
ISC11ISC10Description
00The low level of INT1 generates an interrupt request.
01Any logical change on INT1 generates an interrupt request.
10The falling edge of INT1 generates an interrupt request.
11The rising edge of INT1 generates an interrupt request.
• Bits 1, 0
– ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0
The External Interrupt 0 is activated by the external pin INT0 if the SREG I-Flag and the
corresponding interrupt mask is set. The level and edges on the external INT0 pin that
activate the interrupt are defined in Table 8. The value on the INT0 pin is sampled
before detecting edges. If edge or toggle interrupt is selected, pulses that last longer
than one clock period will generate an interrupt. Shorter pulses are not guaranteed to
generate an interrupt. If low-level interrupt is selected, the low level must be held until
the completion of the currently executing instruction to generate an interrupt.
Table 8. Interrupt 0 Sense Control
ISC01ISC00Description
00The low level of INT0 generates an interrupt request.
01Any logical change on INT0 generates an interrupt request.
10The falling edge of INT0 generates an interrupt request.
11The rising edge of INT0 generates an interrupt request.
1228C–AVR–08/02
35
Extended MCU Control
Register – EMCUCR
The Extended MCU Control Register contains control bits for External Interrupt 2, Sleep
mode bit and control bits for the external memory interface.
Bit76543210
$36 ($56)SM0SRL2SRL1SRL0SRW01SRW00SRW11ISC2EMCUCR
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
• Bit 7
– SM0: Sleep Mode Bit 0
When this bit is set (one) and Sleep mode bit 1 (SM1) in MCUCR is set, Power-save
mode is selected as Sleep mode. Refer to page 36 for a detailed description of the
Sleep modes.
• Bits 6..4
– SRL2, SRL1, SRL0: External SRAM Limit
It is possible to configure different wait states for different external memory addresses in
ATmega161. The SRL2 - SRL0 bits are used to define at which address the different
wait states will be configured. See “Interface to External Memory” on page 84 for a
detailed description.
• Bits 3..1
– SRW01, SRW00, SRW11: External SRAM Wait State Select Bits
The SRW01, SRW00 and SRW11 bits are used to set up extra wait states in the external memory interface. See “Interface to External Memory” on page 84 for a detailed
description.
• Bit 0
– ISC2: Interrupt Sense Control 2
The external interrupt 2 is activated by the external pin INT2 if the SREG I-Flag and the
corresponding interrupt mask in the GIMSK are set. If ISC2 is cleared (zero), a falling
edge on INT2 activates the interrupt. If ISC2 is set (one), a rising edge on INT2 activates
the interrupt. Edges on INT2 are registered asynchronously. Pulses on INT2 wider than
50 ns will generate an interrupt. Shorter pulses are not guaranteed to generate an
interrupt.
When changing the ISC2 bit, an interrupt can occur. Therefore, it is recommended to
first disable INT2 by clearing its Interrupt Enable bit in the GIMSK Register. Then, ISC2
bit can be changed. Finally, the INT2 Interrupt Flag should be cleared by writing a logical
“1” to its Interrupt Flag bit in the GIFR Register before the interrupt is re-enabled.
Sleep ModesTo enter any of the three Sleep modes, the SE bit in MCUCR must be set (one) and a
SLEEP instruction must be executed. The SM1 bit in the MCUCR Register and SM0 bit
in the EMCUCR Register select which Sleep mode (Idle, Power-down or Power-save)
will be activated by the SLEEP instruction (see Table 6). If an enabled interrupt occurs
while the MCU is in a Sleep mode, the MCU awakes. The CPU is then halted for four
cycles, it executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File, SRAM and I/O memory are unaltered.
If a reset occurs during Sleep mode, the MCU wakes up and executes from the Reset
Vector.
Idle ModeWhen the SM1/SM0 bits are set to 00, the SLEEP instruction makes the MCU enter the
Idle mode, stopping the CPU but allowing SPI, UARTs, Analog Comparator,
Timer/Counters, Watchdog, and the Interrupt System to continue operating. This
enables the MCU to wake up from external triggered interrupts as well as internal ones
like the Timer Overflow and UART Receive Complete interrupts. If wake-up from the
36
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Analog Comparator interrupt is not required, the Analog Comparator can be powered
down by setting the ACD bit in the Analog Comparator Control and Status Register
(ACSR). This will reduce power consumption in Idle mode.
Power-down ModeWhen the SM1/SM0 bits are set to 10, the SLEEP instruction makes the MCU enter the
Power-down mode. In this mode, the external Oscillator is stopped while the external
interrupts and the Watchdog (if enabled) continue operating. Only an External Reset, a
Watchdog Reset (if enabled), an external level interrupt on INT0 or INT1, or an external
edge interrupt on INT2 can wake up the MCU.
If INT2 is used for wake-up from Power-down mode, the edge is remembered until the
MCU wakes up.
If a level-triggered interrupt is used for wake-up from Power-down mode, the changed
level must be held for some time to wake up the MCU. This makes the MCU less sensitive to noise. The changed level is sampled twice by the Watchdog Oscillator clock, and
if the input has the required level during this time, the MCU will wake up. The period of
the Watchdog Oscillator is 1 µs (nominal) at 5.0V and 25°C. The frequency of the
Watchdog Oscillator is voltage-dependent as shown in the Electrical Characteristics
section.
When waking up from Power-down mode, a delay from the wake-up condition occurs
until the wake-up becomes effective. This allows the clock to restart and become stable
after having been stopped. The wake-up period is defined by the same CKSEL fuses
that define the Reset Time-out period. The wake-up period is equal to the clock counting
part of the reset period, as shown in Table 4. If the wake-up condition disappears before
the MCU wakes up and starts to execute, e.g., a low level on INT0 is not held long
enough, the interrupt causing the wake-up will not be executed.
Power-save ModeWhen the SM1/SM0 bits are 11, the SLEEP instruction makes the MCU enter the
Power-save mode. This mode is identical to Power-down, with one exception.
If Timer/Counter2 is clocked asynchronously, i.e., the AS2 bit in ASSR is set,
Timer/Counter2 will run during sleep. In addition to the Power-down wake-up sources,
the device can also wake up from either Timer Overflow or Output Compare event from
Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in
TIMSK and the global interrupt enable bit in SREG is set.
If the asynchronous timer is
mended instead of Power-save mode because the contents of the register in the
asynchronous timer should be considered undefined after wake-up in Power-save mode
even if AS2 is 0.
not
clocked asynchronously, Power-down mode is recom-
1228C–AVR–08/02
37
Timer/CountersThe ATmega161 provides three general purpose Timer/Counters – two 8-bit T/Cs and
one 16-bit T/C. Timer/Counter2 can optionally be asynchronously clocked from an external Oscillator. This Oscillator is optimized for use with a 32.768 kHz watch crystal,
enabling use of Timer/Counter2 as a Real-time Clock (RTC). Timer/Counters 0 and 1
have individual prescaling selection from the same 10-bit prescaling timer.
Timer/Counter2 has its own prescaler. Both these prescalers can be Reset by setting
the corresponding control bits in the Special Functions IO Register (SFIOR). Refer to
page 39 for a detailed description. These Timer/Counters can either be used as a timer
with an internal clock time base or as a counter with an external pin connection, which
triggers the counting.
Timer/Counter
Prescalers
Figure 29. Prescaler for Timer/Counter0 and 1
Clear
PSR10
TCK1TCK0
For Timer/Counters 0 and 1, the four prescaled selections are: CK/8, CK/64, CK/256,
and CK/1024, where CK is the Oscillator clock. For the two Timer/Counters 0 and 1, CK,
external source and stop can also be selected as clock sources. Setting the PSR10 bit
in SFIOR Resets the prescaler. This allows the user to operate with a predictable prescaler. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a
Prescaler Reset will affect both Timer/Counters.
38
ATmega161(L)
1228C–AVR–08/02
Figure 30. Timer/Counter2 Prescaler
ATmega161(L)
CK
TOSC1
AS2
PSR2
CS20
CS21
CS22
PCK2
Clear
10-BIT T/C PRESCALER
PCK2/8
PCK2/32
PCK2/64
0
TIMER/COUNTER2 CLOCK SOURCE
TCK2
PCK2/256
PCK2/128
PCK2/1024
The clock source for Timer/Counter2 prescaler is named PCK2. PCK2 is by default connected to the main system clock (CK). By setting the AS2 bit in ASSR, Timer/Counter2
is asynchronously clocked from the PD4(TOSC1) pin. This enables use of
Timer/Counter2 as a Real-time Clock (RTC). When AS2 is set, pins PD4(TOSC1) and
PD5(TOSC2) are disconnected from Port D. A crystal can then be connected between
the PD4(TOSC1) and PD5(TOSC2) pins to serve as an independent clock source for
Timer/Counter2. The Oscillator is optimized for use with a 32.768 kHz crystal. Alternatively, an external clock signal can be applied to PD4(TOSC1). The frequency of this
clock must be lower than one fourth of the CPU clock and not higher than 256 kHz. Setting the PSR2 bit in SFIOR Resets the prescaler. This allows the user to operate with a
predictable prescaler.
Special Function IO Register –
SFIOR
1228C–AVR–08/02
Bit765432 10
$30 ($50)––––––PSR2PSR10SFIOR
Read/WriteRRRRRRR/WR/W
InitialValue000000 00
• Bits 7..2 – Res: Reserved Bits
These bits are reserved bits in the ATmega161 and always read as zero.
• Bit 1
– PSR2: Prescaler Reset Timer/Counter2
When this bit is set (one), the Timer/Counter2 prescaler will be reset. The bit will be
cleared by hardware after the operation is performed. Writing a zero to this bit will have
no effect. This bit will always be read as zero if Timer/Counter2 is clocked by the internal
CPU clock. If this bit is written when Timer/Counter2 is operating in asynchronous
mode, however, the bit will remain as one until the prescaler has been reset. See “Asynchronous Operation of Timer/Counter2” on page 48 for a detailed description of
asynchronous operation.
39
• Bit 0 – PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0
When this bit is set (one), the Timer/Counter1 and Timer/Counter0 prescaler will be
reset. The bit will be cleared by hardware after the operation is performed. Writing a
zero to this bit will have no effect. Note that Timer/Counter1 and Timer/Counter0 share
the same prescaler and a reset of this prescaler will affect both timers. This bit will
always be read as zero.
8-bit Timer/Counters
T/C0 and T/C2
Figure 31 shows the block diagram for Timer/Counter0. Figure 32 shows the block diagram for Timer/Counter2.
Figure 31. Timer/Counter0 Block Diagram
8-BIT DATA BUS
TOIE1
OCIE1B
OCIE1A
TICIE1
TOIE2
TIMER INT. MASK
REGISTER (TIMSK)
7
TIMER/COUNTER0
(TCNT0)
7
8-BIT COMPARATOR
7
OUTPUT COMPARE
REGISTER0 (OCR0)
OCIE2
TOIE0
OCIE0
T/C0 OVER-
FLOW IRQ
0
0
0
T/C0 COMPARE
MATCH IRQ
TIMER INT. FLAG
REGISTER (TIFR)
TOV1
TOV2
OCF1A
OCF1B
T/C CLEAR
T/C CLK SOURCE
UP/DOWN
ICF1
OCF2
TOV0
TOV0
OCF0
REGISTER (TCCR0)
FOC0
OCF0
T/C0 CONTROL
CS02
CTC0
PWM0
COM01
COM00
CONTROL
LOGIC
CS01
SPECIAL FUNCTIONS
IO REGISTER (SFIOR)
CS00
CK
PSR2
PSR10
T0
40
ATmega161(L)
1228C–AVR–08/02
Figure 32. Timer/Counter2 Block Diagram
T/C2 OVER-
FLOW IRQ
T/C2 COMPARE
MATCH IRQ
ATmega161(L)
8-BIT DATA BUS
8-BIT ASYNCH T/C2 DATA BUS
TOIE1
OCIE1B
OCIE1A
TIMER INT. MASK
REGISTER (TIMSK)
7
TIMER/COUNTER2
(TCNT2)
7
8-BIT COMPARATOR
7
OUTPUT COMPARE
REGISTER2 (OCR2)
TOIE2
TICIE1
OCIE2
TCK2
TOIE0
CK
OCIE0
OCF2
0
0
0
TOV2
TIMER INT. FLAG
REGISTER (TIFR)
TOV1
T/C CLEAR
T/C CLK SOURCE
UP/DOWN
ICF1
TOV2
OCF1A
OCF1B
SYNCH UNIT
OCF2
TOV0
T/C2 CONTROL
REGISTER (TCCR2)
FOC2
PWM2
OCF0
CONTROL
CS22
CS21
CTC2
COM21
COM20
LOGIC
ASYNCH. STATUS
REGISTER (ASSR)
AS2
SPECIAL FUNCTIONS
IO REGISTER (SFIOR)
CS20
TC2UB
ICR2UB
OCR2UB
CK
TOSC1
PSR2
PSR10
The 8-bit Timer/Counter0 can select clock source from CK, prescaled CK or an external
pin.The 8-bit Timer/Counter2 can select clock source from CK, prescaled CK or external
TOSC1.
Both Timer/Counters can be stopped as described in sections “Timer/Counter0 Control
Register
– TCCR0” and “Timer/Counter2 Control Register – TCCR2”.
1228C–AVR–08/02
The various Status Flags (Overflow and Compare Match) are found in the
Timer/Counter Interrupt Flag Register (TIFR). Control signals are found in the
Timer/Counter Control Register (TCCR0 and TCCR2). The interrupt enable/disable settings are found in the Timer/Counter Interrupt Mask Register (TIMSK).
When Timer/Counter0 is externally clocked, the external signal is synchronized with the
Oscillator frequency of the CPU. To assure proper sampling of the external clock, the
minimum time between two external clock transitions must be at least one internal CPU
clock period. The external clock signal is sampled on the rising edge of the internal CPU
clock.
The 8-bit Timer/Counters feature both a high resolution and a high accuracy usage with
the lower prescaling opportunities. Similarly, the high prescaling opportunities make the
Timer/Counter0 useful for lower speed functions or exact timing functions with infrequent actions.
Timer/Counters 0 and 2 can also be used as 8-bit Pulse Width Modulators. In this
mode, the Timer/Counter and the Output Compare Register serve as a glitch-free,
stand-alone PWM with centered pulses. Refer to page 44 for a detailed description of
this function.
41
Timer/Counter0 Control
Register – TCCR0
Bit76543210
$33 ($53)FOC0PWM0COM01COM00CTC0CS02CS01CS00TCCR0
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
Timer/Counter2 Control
Register – TCCR2
Bit76543210
$27 ($47)FOC2PWM2COM21COM20CTC2CS22CS21CS20TCCR2
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
Initial Value00000000
• Bit 7
– FOC0/FOC2: Force Output Compare
Writing a logical “1” to this bit forces a change in the compare match output pin PB0
(Timer/Counter0) and PB1 (Timer/Counter2) according to the values already set in
COMn1 and COMn0. If the COMn1 and COMn0 bits are written in the same cycle as
FOC0/FOC2, the new settings will not take effect until the next compare match or
Forced Output Compare Match occurs. The Force Output Compare bit can be used to
change the output pin without waiting for a compare match in the timer. The automatic
action programmed in COMn1 and COMn0 happens as if a Compare Match had
occurred, but no interrupt is generated and the Timer/Counters will not be cleared even
if CTC0/CTC2 is set. The FOC0/FOC2 bits will always be read as zero. The setting of
the FOC0/FOC2 bits has no effect in PWM mode.
• Bit 6
– PWM0/PWM2: Pulse Width Modulator Enable
When set (one), this bit enables PWM mode for Timer/Counter0 or Timer/Counter2.
This mode is described on page 44.
The COMn1 and COMn0 control bits determine any output pin action following a compare match in Timer/Counter0 or Timer/Counter2. Output pin actions affect pins
PB0(OC0) or PB1(OC2). This is an alternative function to an I/O port and the corresponding direction control bit must be set (one) to control an output pin. The control
configuration is shown in Table 9.
Table 9. Compare Mode Select
COMn1COMn0Description
00Timer/Counter disconnected from output pin OCn.
01Toggle the OCn output line.
10Clear the OCn output line (to zero).
11Set the OCn output line (to one).
Notes: 1. In PWM mode, these bits have a different function. Refer to Table 12 for a detailed
description.
2. n = 0 or 2
(1)(2)
• Bit 3 – CTC0/CTC2: Clear Timer/Counter on Compare Match
When the CTC0 or CTC2 control bit is set (one), Timer/Counter0 or Timer/Counter2 is
reset to $00 in the CPU clock cycle after a compare match. If the control bit is cleared,
the Timer/Counter continues counting and is unaffected by a compare match. When a
42
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
prescaling of 1 is used, and the compare register is set to C, the timer will count as follows if CTC0/CTC2 is set:
...|C-1|C|0|1|...
When the prescaler is set to divide by 8, the timer will count like this:
In PWM mode, this bit has a different function. If the CTC0 or CTC2 bit is cleared in
PWM mode, the Timer/Counter acts as an up/down counter. If the CTC0 or CTC2 bit is
set (one), the Timer/Counter wraps when it reaches $FF. Refer to page 44 for a detailed
description.
The Clock Select bits 2, 1, and 0 define the prescaling source of Timer/Counter0 and
Timer/Counter2.
Table 10. Clock 0 Prescale Select
CS02CS01CS00Description
000Stop, the Timer/Counter0 is stopped.
001CK
010CK/8
011CK/64
100CK/256
101CK/1024
110External Pin PB0(T0), falling edge
111External Pin PB0(T0), rising edge
Table 11. Clock 2 Prescale Select
CS22CS21CS20Description
000Stop, the Timer/Counter2 is stopped.
001PCK2
1228C–AVR–08/02
010PCK2/8
011PCK2/32
100PCK2/64
101PCK2/128
110PCK2/256
111PCK2/1024
The Stop condition provides a Timer Enable/Disable function. The prescaled modes are
scaled directly from the CK Oscillator clock for Timer/Counter0 and PCK2 for
Timer/Counter2. If the external pin modes are used for Timer/Counter0, transitions on
PB0/(T0) will clock the counter even if the pin is configured as an output. This feature
can give the user software control of the counting.
43
Timer Counter0 – TCNT0
Bit76543210
$32 ($52)MSBLSBTCNT0
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/ W
InitialValue00000000
Timer/Counter2 – TCNT2
Timer/Counter0 Output
Compare Register – OCR0
Timer/Counter2 Output
Compare Register – OCR2
Bit76543210
$23 ($43)MSBLSBTCNT2
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
These 8-bit registers contain the value of the Timer/Counters.
Both Timer/Counters are realized as up or up/down (in PWM mode) counters with read
and write access. If the Timer/Counter is written to and a clock source is selected, it continues counting in the timer clock cycle following the write operation.
Bit76543210
$31 ($51)MSBLSBOCR0
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
Bit7654 3210
$22 ($42)MSBLSBOCR2
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
The Output Compare Registers are 8-bit read/write registers. The Timer/Counter Output
Compare Registers contain the data to be continuously compared with the
Timer/Counter. Actions on compare matches are specified in TCCR0 and TCCR2. A
software write to the Timer/Counter Register blocks compare matches in the next
Timer/Counter clock cycle. This prevents immediate interrupts when initializing the
Timer/Counter.
Timer/Counters 0 and 2 in
PWM Mode
44
ATmega161(L)
A compare match will set the Compare Interrupt Flag in the CPU clock cycle following
the compare event.
When PWM mode is selected, the Timer/Counter either wraps (overflows) when it
reaches $FF or it acts as an up/down counter.
If the up/down mode is selected, the Timer/Counter and the Output Compare Registers
(OCR0 or OCR2) form an 8-bit, free-running, glitch-free and phase-correct PWM with
outputs on the PB0(OC0/PWM0) or PB1(OC2/PWM2) pin.
If the Overflow mode is selected, the Timer/Counter and the Output Compare Registers
(OCR0 or OCR2) form an 8-bit, free-running and glitch-free PWM, operating with twice
the speed of the up/down counting mode.
1228C–AVR–08/02
ATmega161(L)
PWM Modes (Up/Down and
Overflow)
The two different PWM modes are selected by the CTC0 or CTC2 bit in the
Timer/Counter Control Registers – TCCR0 or TCCR2, respectively.
If CTC0/CTC2 is cleared and PWM mode is selected, the Timer/Counter acts as an
up/down counter, counting up from $00 to $FF, where it turns and counts down again to
zero before the cycle is repeated. When the counter value matches the contents of the
Output Compare Register, the PB0(OC0/PWM0) or PB1(OC2/PWM2) pin is set or
cleared according to the settings of the COMn1/COMn0 bits in the Timer/Counter Control Registers TCCR0 or TCCR2.
If CTC0/CTC2 is set and PWM mode is selected, the Timer/Counters will wrap and start
counting from $00 after reaching $FF. The PB0(OC0/PWM0) or PB1(OC2/PWM2) pin
will be set or cleared according to the settings of COMn1/COMn0 on a Timer/Counter
overflow or when the counter value matches the contents of the Output Compare Register. Refer to Table 12 for details.
Table 12. Compare Mode Select in PWM Mode
CTCnCOMn1COMn0Effect on Compare PinFrequency
000Not connected
001Not connected
Cleared on compare match, up-counting. Set on
01 0
01 1
compare match, down-counting (non-inverted
PWM).
Cleared on compare match, down-counting. Set
on compare match, up-counting (inverted PWM).
(1)
TCK0/2
f
TCK0/2
f
/510
/510
100Not connected
101Not connected
110Cleared on compare match, set on overflowf
111Set on compare match, cleared on overflowf
Note:1. n = 0 or 2
TCK0/2
TCK0/2
/256
/256
Note that in PWM mode, the value to be written to the Output Compare Register is first
transferred to a temporary location and then latched into the OCR when the
Timer/Counter reaches $FF. This prevents the occurrence of odd-length PWM pulses
(glitches) in the event of an unsynchronized OCR0 or OCR2 write. See Figure 33 and
Figure 34 for examples.
1228C–AVR–08/02
45
Figure 33. Effects of Unsynchronized OCR Latching in Up/Down Mode
Compare Value changes
Counter Value
Compare Value
PWM Output OCn
Synchronized OCn Latch
Compare Value changes
Counter Value
Compare Value
PWM Output OCn
Unsynchronized OCn Latch
Glitch
Figure 34. Effects of Unsynchronized OCR Latching in Overflow Mode.
Compare Value changes
Counter Value
Compare Value
PWM Output OCn
Synchronized OCn Latch
Compare Value changes
Counter Value
Compare Value
PWM Output OCn
Unsynchronized OCn Latch
Note:n = 0 or 2 (Figure 33 and Figure 34)
Glitch
During the time between the write and the latch operation, a read from the Output Compare Registers will read the contents of the temporary location. This means that the
most recently written value always will read out of OCR0 and OCR2.
46
When the Output Compare Register contains $00 or $FF, and the up/down PWM mode
is selected, the output PB0(OC0/PWM0)/PB1(OC2/PWM2) is updated to low or high on
the next compare match according to the settings of COMn1/COMn0. This is shown in
Table 13. In overflow PWM mode, the output PB0(OC0/PWM0)/PB1(OC2/PWM2) is
held low or high only when the Output Compare Register contains $FF.
Table 13. PWM Outputs OCRn = $00 or $FF
Note:1. n = 0 or 2
ATmega161(L)
(1)(2)
COMn1COMn0OCRnOutput PWMn
10$00L
10$FFH
11$00H
11$FFL
2. In overflow PWM mode, the table above is only valid for OCRn = $FF.
1228C–AVR–08/02
ATmega161(L)
In up/down PWM mode, the Timer Overflow Flag (TOV0 or TOV2) is set when the
counter advances from $00. In overflow PWM mode, the Timer Overflow Flag is set as
in normal Timer/Counter mode. Timer Overflow Interrupt0 and 2 operate exactly as in
normal Timer/Counter mode, i.e., they are executed when TOV0 or TOV2 are set, provided that Timer Overflow Interrupt and global interrupts are enabled. This also applies
to the Timer Output Compare flag and interrupt.
Asynchronous Status
Register – ASSR
Bit76543210
$26 ($46)––––AS2TCN2UBOCR2UBTCR2UBASSR
Read/WriteRRRRR/WRRR
InitialValue00000 000
• Bits 7..4
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and always read as zero.
• Bit 3
– AS2: Asynchronous Timer/Counter2 Mode
When this bit is cleared (zero), Timer/Counter2 is clocked from the internal system
clock, CK. If AS2 is set, the Timer/Counter2 is clocked from the TOSC1 pin. Pins PD4
and PD5 become connected to a crystal Oscillator and cannot be used as general I/O
pins. When the value of this bit is changed, the contents of TCNT2, OCR2 and TCCR2
might get corrupted.
• Bit 2
– TCN2UB: Timer/Counter2 Update Busy
When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes
set (one). When TCNT2 has been updated from the temporary storage register, this bit
is cleared (zero) by hardware. A logical “0” in this bit indicates that TCNT2 is ready to be
updated with a new value.
• Bit 1
– OCR2UB: Output Compare Register2 Update Busy
1228C–AVR–08/02
When Timer/Counter2 operates asynchronously and OCR2 is written, this bit becomes
set (one). When OCR2 has been updated from the temporary storage register, this bit is
cleared (zero) by hardware. A logical “0” in this bit indicates that OCR2 is ready to be
updated with a new value.
• Bit 0
– TCR2UB: Timer/Counter Control Register2 Update Busy
When Timer/Counter2 operates asynchronously and TCCR2 is written, this bit becomes
set (one). When TCCR2 has been updated from the temporary storage register, this bit
is cleared (zero) by hardware. A logical “0” in this bit indicates that TCCR2 is ready to be
updated with a new value.
If a write is performed to any of the three Timer/Counter2 Registers while its update
Busy Flag is set (one), the updated value might get corrupted and cause an unintentional interrupt to occur.
The mechanisms for reading TCNT2, OCR2 and TCCR2 are different. When reading
TCNT2, the actual timer value is read. When reading OCR2 or TCCR2, the value in the
temporary storage register is read.
47
Asynchronous Operation of
Timer/Counter2
When Timer/Counter2 operates asynchronously, some considerations must be taken:
•Warning: When switching between asynchronous and synchronous clocking of
Timer/Counter2, the Timer Registers TCNT2, OCR2, and TCCR2 might get
corrupted. A safe procedure for switching clock source is:
1. Disable the Timer/Counter2 interrupts by clearing OCIE2 and TOIE2.
2. Select clock source by setting AS2 as appropriate.
3. Write new values to TCNT2, OCR2, and TCCR2.
4. To switch to asynchronous operation: Wait for TCN2UB, OCR2UB, and
TCR2UB.
5. Enable interrupts, if needed.
•The Oscillator is optimized for use with a 32,768 Hz watch crystal. An external clock
signal applied to this pin goes through the same amplifier having a bandwidth of
256 kHz. The external clock signal should therefore be in the interval 0 Hz 256 kHz. The frequency of the clock signal applied to the TOSC1 pin must be lower
than one fourth of the CPU main clock frequency.
•When writing to one of the registers TCNT2, OCR2, or TCCR2, the value is
transferred to a temporary register, and latched after two positive edges on TOSC1.
The user should not write a new value before the contents of the temporary register
have been transferred to its destination. Each of the three mentioned registers have
their individual temporary register, which means that e.g., writing to TCNT2 does not
disturb an OCR2 write in progress. To detect that a transfer to the destination
register has taken place, a Asynchronous Status Register – ASSR has been
implemented.
•When entering Power-save mode after having written to TCNT2, OCR2 or TCCR2,
the user must wait until the written register has been updated if Timer/Counter2 is
used to wake up the device. Otherwise, the MCU will go to sleep before the
changes have had any effect. This is extremely important if the Output Compare2
interrupt is used to wake up the device; output compare is disabled during write to
OCR2 or TCNT2. If the write cycle is not finished (i.e., the MCU enters sleep mode
before the OCR2UB bit returns to zero), the device will never get a compare match
and the MCU will not wake up.
•IfTimer/Counter2isusedtowakeupthedevicefromPower-savemode,
precautions must be taken if the user wants to re-enter Power-save mode: The
interrupt logic needs one TOSC1 cycle to be reset. If the time between wake-up and
re-entering Power-save mode is less than one TOSC1 cycle, the interrupt will not
occur and the device will fail to wake up. If the user is in doubt whether the time
before re-entering Power-save is sufficient, the following algorithm can be used to
ensure that one TOSC1 cycle has elapsed:
1. Write a value to TCCR2, TCNT2, or OCR2.
2. Wait until the corresponding Update Busy Flag in ASSR returns to zero.
3. Enter Power-save mode.
•When asynchronous operation is selected, the 32 kHz Oscillator for Timer/Counter2
is always running, except in Power-down mode. After a Power-up Reset or wake-up
from power-down, the user should be aware of the fact that this Oscillator might take
as long as one second to stabilize. The user is advised to wait for at least one
second before using Timer/Counter2 after power-up or wake-up from power-down.
The contents of all Timer/Counter2 Registers must be considered lost after a wakeup from power-down, due to unstable clock signal upon start-up, regardless of
whether the Oscillator is in use or a clock signal is applied to the TOSC pin.
48
ATmega161(L)
1228C–AVR–08/02
•Description of wake-up from Power-save mode when the timer is clocked
asynchronously: When the interrupt condition is met, the wake-up process is started
on the following cycle of the timer clock, that is, the timer is always advanced by at
least 1 before the processor can read the counter value. The Interrupt Flags are
updated three processor cycles after the processor clock has started. During these
cycles, the processor executes instructions, but the interrupt condition is not
readable and the interrupt routine has not started yet.
•During asynchronous operation, the synchronization of the Interrupt Flags for the
asynchronous timer takes three processor cycles plus one timer cycle. The timer is
therefore advanced by at least 1 before the processor can read the timer value,
causing the setting of the Interrupt Flag. The output compare pin is changed on the
timer clock and is not synchronized to the processor clock.
Timer/Counter1Figure 35 shows the block diagram for Timer/Counter1.
Figure 35. Timer/Counter1 Block Diagram
T/C1 OVER-
FLOW IRQ
T/C1 COMPARE
MATCHA IRQ
T/C1 COMPARE
MATCHB IRQ
T/C1 INPUT
CAPTURE IRQ
ATmega161(L)
OCIE1B
OCIE2
OCIE1A
TOIE1
TIMER INT. MASK
REGISTER (TIMSK)
8-BIT DATA BUS
TIMER/COUNTER1 OUTPUT COMPARE REGISTER A
TOIE0
TICIE1
OCIE0
TOIE2
T/C1 INPUT CAPTURE REGISTER (ICR1)
TIMER/COUNTER1 (TCNT1)
16 BIT COMPARATOR
OCF1B
OCF1A
ICF1
TOV2
TOV1
TIMER INT. FLAG
REGISTER (TIFR)
ICF1
TOV1
TOV2
OCF1A
OCF1B
OCF2
OCF2
TOV0
TOV0
CAPTURE
TRIGGER
OCF0
T/C1 CONTROL
REGISTER A (TCCR1A)
FOC1B
FOC1A
PWM11
OCF0
COM1A1
COM1A0
COM1B0
07815
07815
T/C CLEAR
T/C CLOCK SOURCE
UP/DOWN
07815
07815
TIMER/COUNTER1 OUTPUT COMPARE REGISTER B
PWM10
COM1B1
CONTROL
LOGIC
16 BIT COMPARATOR
T/C1 CONTROL
REGISTER B (TCCR1B)
CS12
CS11
CTC1
ICES1
ICNC1
SPECIAL FUNCTIONS
IO REGISTER (SFIOR)
CS10
07815
07815
PSR2
PSR10
CK
T1
The 16-bit Timer/Counter1 can select clock source from CK, prescaled CK or an external pin. In addition, it can be stopped as described in “Timer/Counter1 Control Register
B
– TCCR1B”. The different Status Flags (Overflow, Compare Match, and Capture
Event) are found in the Timer/Counter Interrupt Flag Register (TIFR). Control signals
are found in the Timer/Counter1 Control Registers (TCCR1A and TCCR1B). The interrupt enable/disable settings for Timer/Counter1 are found in the Timer/Counter Interrupt
Mask Register (TIMSK).
1228C–AVR–08/02
When Timer/Counter1 is externally clocked, the external signal is synchronized with the
Oscillator frequency of the CPU. To assure proper sampling of the external clock, the
minimum time between two external clock transitions must be at least one internal CPU
49
clock period. The external clock signal is sampled on the rising edge of the internal CPU
clock.
The 16-bit Timer/Counter1 features both a high-resolution and a high-accuracy usage
with the lower prescaling opportunities. Similarly, the high-prescaling opportunities
make the Timer/Counter1 useful for lower speed functions or exact timing functions with
infrequent actions.
The Timer/Counter1 supports two Output Compare functions using the Output Compare
Register 1 A and B (OCR1A and OCR1B) as the data sources to be compared to the
Timer/Counter1 contents. The Output Compare functions include optional clearing of
the counter on compareA match and actions on the Output Compare pins on both compare matches.
Timer/Counter1 can also be used as an 8-, 9-, or 10-bit Pulse Width Modulator. In this
mode the counter and the OCR1A/OCR1B Registers serve as a dual glitch-free standalone PWM with centered pulses. Alternatively, the Timer/Counter1 can be configured
to operate at twice the speed in PWM mode, but without centered pulses. Refer to page
55 for a detailed description of this function.
The Input Capture function of Timer/Counter1 provides a capture of the Timer/Counter1
contents to the Input Capture Register (ICR1), triggered by an external event on the
Input Capture Pin (ICP). The actual capture event settings are defined by the
Timer/Counter1 Control Register (TCCR1B). In addition, the Analog Comparator can be
set to trigger the Input Capture. Refer to the section, “The Analog Comparator”,for
details on this. The ICP pin logic is shown in Figure 36.
Timer/Counter1 Control
Register A – TCCR1A
Figure 36. ICP Pin Schematic Diagram
If the noise canceler function is enabled, the actual trigger condition for the Capture
Event is monitored over four samples, and all four must be equal to activate the Capture
Flag.
– COM1A1, COM1A0: Compare Output Mode1A, Bits 1 and 0
The COM1A1 and COM1A0 control bits determine any output pin action following a
compare match in Timer/Counter1. Any output pin actions affect pin OC1A (Output
CompareA pin 1). This is an alternative function to an I/O port, and the corresponding
direction control bit must be set (one) to control an output pin. The control configuration
is shown in Table 14.
The COM1B1 and COM1B0 control bits determine any output pin action following a
compare match in Timer/Counter1. Any output pin actions affect pin OC1B (Output
CompareB). This is an alternative function to an I/O port, and the corresponding direction control bit must be set (one) to control an output pin. The following control
configuration is given:
Table 14. Compare 1 Mode Select
COM1X1COM1X0Description
00Timer/Counter1 disconnected from output pin OC1X
01Toggle the OC1X output line.
10Clear the OC1X output line (to zero).
11Set the OC1X output line (to one).
Note:1. X = A or B
(1)
In PWM mode, these bits have a different function. Refer to Table 18 for a detailed
description.
• Bit 3
– FOC1A: Force Output Compare1A
Writing a logical “1” to this bit forces a change in the compare match output pin PD5
according to the values already set in COM1A1 and COM1A0. If the COM1A1 and
COM1A0 bits are written in the same cycle as FOC1A, the new settings will not take
effect until the next compare match or forced compare match occurs. The Force Output
Compare bit can be used to change the output pin without waiting for a compare match
in the timer. The automatic action programmed in COM1A1 and COM1A0 happens as if
a Compare Match had occurred, but no interrupt is generated and it will not clear the
timer even if CTC1 in TCCR1B is set. The FOC1A bit will always be read as zero. The
setting of the FOC1A bit has no effect in PWM mode.
1228C–AVR–08/02
• Bit 2
– FOC1B: Force Output Compare1B
Writing a logical “1” to this bit forces a change in the compare match output pin PE2
according to the values already set in COM1B1 and COM1B0. If the COM1B1 and
COM1B0 bits are written in the same cycle as FOC1B, the new settings will not take
effect until the next compare match or forced compare match occurs. The Force Output
Compare bit can be used to change the output pin without waiting for a compare match
in the timer. The automatic action programmed in COM1B1 and COM1B0 happens as if
a Compare Match had occurred, but no interrupt is generated. The FOC1B bit will
always be read as zero. The setting of the FOC1B bit has no effect in PWM mode.
When the ICNC1 bit is cleared (zero), the Input Capture trigger noise canceler function
is disabled. The Input Capture is triggered at the first rising/falling edge sampled on the
ICP (Input Capture pin) as specified. When the ICNC1 bit is set (one), four successive
samples are measured on the ICP (Input Capture pin), and all samples must be high/low
according to the Input Capture trigger specification in the ICES1 bit. The actual sampling
frequency is XTAL clock frequency.
• Bit 6
– ICES1: Input Capture1 Edge Select
While the ICES1 bit is cleared (zero), the Timer/Counter1 contents are transferred to the
Input Capture Register (ICR1) on the falling edge of the Input Capture pin (ICP). While
the ICES1 bit is set (one), the Timer/Counter1 contents are transferred to the Input Capture Register (ICR1) on the rising edge of the Input Capture pin (ICP).
• Bits 5, 4
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and always read as zero.
52
• Bit 3
When the CTC1 control bit is set (one), the Timer/Counter1 is reset to $0000 in the clock
cycle after a compareA match. If the CTC1 control bit is cleared, Timer/Counter1 continues counting and is unaffected by a compare match. When a prescaling of 1 is used and
the Compare A Register is set to C, the timer will count as follows if CTC1 is set:
...|C-1|C|0|1|...
When the prescaler is set to divide by 8, the timer will count like this:
In PWM mode, this bit has a different function. If the CTC1 bit is cleared in PWM mode,
the Timer/Counter1 acts as an up/down counter. If the CTC1 bit is set (one), the
Timer/Counter wraps when it reaches the TOP value. Refer to page 55 for a detailed
description.
The Clock Select1 bits 2, 1 and 0 define the prescaling source of Timer/Counter1.
Table 16. Clock 1 Prescale Select
CS12CS11CS10Description
000Stop, the Timer/Counter1 is stopped.
001CK
010CK/8
011CK/64
100CK/256
101CK/1024
110External Pin T1, falling edge
111External Pin T1, rising edge
The Stop condition provides a Timer Enable/Disable function. The CK down divided
modes are scaled directly from the CK Oscillator clock. If the external pin modes are
used for Timer/Counter1, transitions on PB1/(T1) will clock the counter even if the pin is
configured as an output. This feature can give the user software control of the counting.
Timer/Counter1 Register –
TCNT1H AND TCNT1L
Bit151413121110 9 8
$2D ($4D)MSBTCNT1H
$2C ($4C)LSBTCNT1L
76543210
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
00000000
This 16-bit register contains the prescaled value of the 16-bit Timer/Counter1. 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 register (TEMP). This temporary register is also used when accessing OCR1A, OCR1B, and
ICR1. If the main program and interrupt routines perform access to registers using
TEMP, interrupts must be disabled during access from the main program and interrupt
routines.
•TCNT1 Timer/Counter1 Write
When the CPU writes to the High byte TCNT1H, the written data is placed in the TEMP
Register. Next, when the CPU writes the Low byte TCNT1L, this byte of data is combined with the byte data in the TEMP Register and all 16 bits are written to the TCNT1
Timer/Counter1 Register simultaneously. Consequently, the High byte TCNT1H must
be accessed first for a full 16-bit register write operation.
•TCNT1 Timer/Counter1 Read
1228C–AVR–08/02
When the CPU reads the Low byte TCNT1L, the data of the Low byte TCNT1L is sent to
the CPU and the data of the High byte TCNT1H is placed in the TEMP Register. When
the CPU reads the data in the High byte TCNT1H, the CPU receives the data in the
TEMP Register. Consequently, the Low byte TCNT1L must be accessed first for a full
16-bit register read operation.
53
The Timer/Counter1 is realized as an up or up/down (in PWM mode) counter with read
and write access. If Timer/Counter1 is written to and a clock source is selected, the
Timer/Counter1 continues counting in the timer clock cycle after it is preset with the written value.
Timer/Counter1 Output
Compare Register – OCR1AH
AND OCR1AL
Timer/Counter1 Output
Compare Register – OCR1BH
AND OCR1BL
Bit151413121110 9 8
$2B ($4B)MSBOCR1AH
$2A ($4A)LSBOCR1AL
76543210
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
00000000
Bit151413121110 9 8
$29 ($49)MSBOCR1BH
$28 ($48)LSBOCR1BL
76543210
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
00000000
The Output Compare Registers are 16-bit read/write registers.
The Timer/Counter1 Output Compare Registers contain the data to be continuously
compared with Timer/Counter1. Actions on compare matches are specified in the
Timer/Counter1 Control and Status Registers. A software write to the Timer/Counter
Register blocks compare matches in the next Timer/Counter clock cycle. This prevents
immediate interrupts when initializing the Timer/Counter.
Timer/Counter1 Input Capture
Register – ICR1H AND ICR1L
A compare match will set the Compare Interrupt Flag in the CPU clock cycle following
the compare event.
Since the Output Compare Registers (OCR1A and OCR1B) are 16-bit registers, a temporary register (TEMP) is used when OCR1A/B are written to ensure that both bytes are
updated simultaneously. When the CPU writes the High byte, OCR1AH or OCR1BH,
the data is temporarily stored in the TEMP Register. When the CPU writes the Low byte,
OCR1AL or OCR1BL, the TEMP Register is simultaneously written to OCR1AH or
OCR1BH. Consequently, the High byte OCR1AH or OCR1BH must be written first for a
full 16-bit register write operation.
The TEMP Register is also used when accessing TCNT1 and ICR1. If the main program
and interrupt routines perform access to registers using TEMP, interrupts must be disabled during access from the main program and interrupt routines.
Bit151413121110 9 8
$25 ($45)MSBICR1H
$24 ($44)LSBICR1L
76543210
Read/WriteRRRRRRRR
RRRRRRRR
InitialValue00000000
00000000
54
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
The Input Capture Register is a 16-bit read-only register.
When the rising or falling edge (according to the Input Capture edge setting, ICES1) of
the signal at the Input Capture pin (ICP) is detected, the current value of the
Timer/Counter1 Register (TCNT1) is transferred to the Input Capture Register (ICR1). In
the same cycle, the Input Capture Flag (ICF1) is set (one).
Since the Input Capture Register (ICR1) is a 16-bit register, a temporary register
(TEMP) is used when ICR1 is read to ensure that both bytes are read simultaneously.
When the CPU reads the Low byte ICR1L, the data is sent to the CPU and the data of
the High byte ICR1H is placed in the TEMP Register. When the CPU reads the data in
the High byte ICR1H, the CPU receives the data in the TEMP Register. Consequently,
the Low byte ICR1L must be accessed first for a full 16-bit register read operation.
The TEMP Register is also used when accessing TCNT1, OCR1A and OCR1B. If the
main program and interrupt routines perform access to registers using TEMP, interrupts
must be disabled during access from the main program and interrupt routine.
Timer/Counter1 in PWM ModeWhen the PWM mode is selected, Timer/Counter1 and the Output Compare Register1A
(OCR1A) and the Output Compare Register1B (OCR1B) form a dual 8-, 9-, or 10-bit,
free-running, glitch-free, and phase-correct PWM with outputs on the PD5(OC1A) and
PE2(OC1B) pins. In this mode the Timer/Counter1 acts as an up/down counter, counting up from $0000 to TOP (see Table 17), where it turns and counts down again to zero
before the cycle is repeated. When the counter value matches the contents of the 8, 9,
or 10 least significant bits (depends of the resolution) of OCR1A or OCR1B, the
PD5(OC1A)/PE2(OC1B) pins are set or cleared according to the settings of the
COM1A1/COM1A0 or COM1B1/COM1B0 bits in the Timer/Counter1 Control Register
(TCCR1A). Refer to Table 18 for details.
Alternatively, the Timer/Counter1 can be configured to a PWM that operates at twice the
speed as in the mode described above. Then the Timer/Counter1 and the Output Compare Register1A (OCR1A) and the Output Compare Register1B (OCR1B) form a dual
8-, 9- or 10-bit, free-running and glitch-free PWM with outputs on the PD5(OC1A) and
PE2(OC1B) pins.
Table 17. Timer TOP Values and PWM Frequency
CTC1PWM11PWM10PWM ResolutionTimer TOP ValueFrequency
0018-bit$00FF (255)f
0109-bit$01FF (511)f
01110-bit$03FF (1023)f
1018-bit$00FF (255)f
1109-bit$01FF (511)f
11110-bit$03FF (1023)f
TCK1
TCK1
TCK1
TCK1
TCK1
TCK1
/510
/1022
/2046
/256
/512
/1024
As shown in Table 17, the PWM operates at either 8-, 9-, or 10-bit resolution. Note the
unused bits in OCR1A, OCR1B and TCNT1 will automatically be written to zero by hardware, i.e., bits 9 to 15 will be set to zero in OCR1A, OCR1B and TCNT1 if the 9-bit PWM
resolution is selected. This makes it possible for the user to perform read-modify-write
operations in any of the three resolution modes and the unused bits will be treated as
don’t care.
1228C–AVR–08/02
55
Table 18. Compare1 Mode Select in PWM Mode
CTC1COM1X1COM1X0Effect on OCX1
000Not connected
001Not connected
01 0
Cleared on compare match, up-counting. Set on compare
match, down-counting (non-inverted PWM).
(1)
01 1
100Not connected
101Not connected
110Cleared on compare match, set on overflow.
111Set on compare match, cleared on overflow.
Note:1. X = A or B
Cleared on compare match, down-counting. Set on compare
match, up-counting (inverted PWM).
Note that in the PWM mode, the 8, 9 or 10 least significant OCR1A/OCR1B bits
(depends of resolution), when written, are transferred to a temporary location. They are
latched when Timer/Counter1 reaches the value TOP. This prevents the occurrence of
odd-length PWM pulses (glitches) in the event of an unsynchronized OCR1A/OCR1B
write. See Figure 37 and Figure 38 for an example in each mode.
Figure 37. Effects on Unsynchronized OCR1 Latching
Compare V
alue changes
(1)
Counter
V
Compare V
Output OC1X
PWM
alue
alue
SynchronizedOCR1X Latch
56
Compare Value changes
Note:1. Note: X = A or B
ATmega161(L)
UnsynchronizedOCR1X Latch
Glitch
Counter
Value
Compare Value
PWM Output OC1X
1228C–AVR–08/02
ATmega161(L)
Figure 38. Effects of Unsynchronized OCR1 Latching in Overflow Mode
1
PWM Output OC1x
Synchronized OC1x Latch
PWM Output OC1x
Unsynchronized OC1x Latch
Note:1. Note: X = A or B
During the time between the write and the latch operation, a read from OCR1A or
OCR1B will read the contents of the temporary location. This means that the most
recently written value always will read out of OCR1A/B.
When the OCR1X contains $0000 or TOP, and the up/down PWM mode is selected, the
output OC1A/OC1B is updated to low or high on the next compare match according to
the settings of COM1A1/COM1A0 or COM1B1/COM1B0. This is shown in Table 19. In
overflow PWM mode, the output OC1A/OC1B is held low or high only when the Output
Compare Register contains TOP.
Table 19. PWM Outputs OCR1X = $0000 or TOP
(1)
COM1X1COM1X0OCR1XOutput OC1X
10$0000L
10TOP H
11$0000H
11TOP L
Note:1. X = A or B
In overflow PWM mode, the table above is only valid for OCR1X = TOP.
In up/down PWM mode, the Timer Overflow Flag1 (TOV1) is set when the counter
advances from $0000. In overflow PWM mode, the Timer Overflow Flag is set as in normal Timer/Counter mode. Timer Overflow Interrupt1 operates exactly as in normal
Timer/Counter mode, i.e., it is executed when TOV1 is set, provided that Timer Overflow
Interrupt1 and global interrupts are enabled. This also applies to the Timer Output
Compare1 Flags and interrupts.
1228C–AVR–08/02
57
Watchdog TimerThe Watchdog Timer is clocked from a separate On-chip Oscillator that runs at 1 MHz.
This is the typical value at V
V
levels. By controlling the Watchdog Timer prescaler, the Watchdog Reset interval
CC
can be adjusted (see Table 20 for a detailed description). The WDR (Watchdog Reset)
instruction resets the Watchdog Timer. Eight different clock cycle periods can be
selected to determine the reset period. If the reset period expires without another
Watchdog Reset, the ATmega161 resets and executes from the Reset Vector. For timing details on the Watchdog Reset, refer to page 28.
To prevent unintentional disabling of the Watchdog, a special turn-off sequence must be
followed when the Watchdog is disabled. Refer to the description of the Watchdog Timer
Control Register for details.
Figure 39. Watchdog Timer
= 5V. See characterization data for typical values at other
CC
Watchdog Timer Control
Register – WDTCR
58
ATmega161(L)
Bit76543210
$21 ($41)–––WDTOEWDEW DP2WDP1WDP 0WDTCR
Read/WriteRRRR/WR/WR/WR/WR/W
InitialValue00000000
• Bits 7..5
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and will always read as zero.
• Bit 4
– WDTOE: Watchdog Turn-off Enable
This bit must be set (one) when the WDE bit is cleared. Otherwise, the Watchdog will
not be disabled. Once set, hardware will clear this bit to zero after four clock cycles.
Refer to the description of the WDE bit for a Watchdog disable procedure.
• Bit 3
– WDE: Watchdog Enable
When the WDE is set (one), the Watchdog Timer is enabled and if the WDE is cleared
(zero), the Watchdog Timer function is disabled. WDE can only be cleared if the
1228C–AVR–08/02
ATmega161(L)
WDTOE bit is set (one). To disable an enabled Watchdog Timer, the following procedure must be followed:
1. In the same operation, write a logical “1” to WDTOE and WDE. A logical “1” must
be written to WDE even though it is set to one before the disable operation
starts.
2. Within the next four clock cycles, write a logical “0” to WDE. This disables the
Watchdog.
The WDP2, WDP1 and WDP0 bits determine the Watchdog Timer prescaling when the
Watchdog Timer is enabled. The different prescaling values and their corresponding
time-out periods are shown in Table 20.
Table 20. Watchdog Timer Prescale Select
Number of WDT
WDP2WDP1WDP0
00016K47 ms15 ms
00132K94 ms30 ms
01064K0.19 s60 ms
011128K0.38 s0.12 s
100256K0.75 s0.24 s
101512K1.5 s0.49 s
1101,024K3.0 s0.97 s
1112,048K6.0 s1.9 s
Note:1. The frequency of the Watchdog Oscillator is voltage-dependent, as shown in the
Electrical Characteristics section.
The WDR (Watchdog Reset) instruction should always be executed before the
Watchdog Timer is enabled. This ensures that the reset period will be in accordance
with the Watchdog Timer prescale settings. If the Watchdog Timer is enabled without
reset, the Watchdog Timer may not start counting from zero.
To avoid unintentional MCU Reset, the Watchdog Timer should be disabled or reset
before changing the Watchdog Timer Prescale Select.
Oscillator Cycles
(1)
Typical Time-out
at VCC=3.0V
Typical Time-out
at VCC=5.0V
1228C–AVR–08/02
59
EEPROM Read/Write
The EEPROM Access Registers are accessible in the I/O space.
Access
EEPROM Address Register –
EEARH and EEARL
The write access time is in the range of 1.9 - 3.4 ms, depending on the frequency of the
RC Oscillator used to time the EEPROM access time. See Table 22 for details. A selftiming function, however, lets the user software detect when the next byte can be written. If the user code contains code that writes the EEPROM, some precaution must be
taken. In heavily filtered power supplies, V
is likely to rise or fall slowly on power-
CC
up/down. This causes the device for some period of time to run at a voltage lower than
specified as minimum for the clock frequency used. CPU operation under these conditions is likely cause the Program Counter to perform unintentional jumps and eventually
execute the EEPROM write code. To secure EEPROM integrity, the user is advised to
use an external Under-voltage Reset circuit in this case.
In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this.
When the EEPROM is written, the CPU is halted for two clock cycles before the next
instruction is executed. When the EEPROM is read, the CPU is halted for four clock
cycles before the next instruction is executed.
These bits are reserved bits in the ATmega161 and will always read as zero.
• Bits 8..0
– EEAR8..0: EEPROM Address
The EEPROM Address Registers (EEARH and EEARL) specify the EEPROM address
in the 512-byte EEPROM space. The EEPROM data bytes are addressed linearly
between 0 and 511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed.
Bit76543210
$1D ($3D)MSBLSBEEDR
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
• Bits 7..0 – EEDR7..0: EEPROM Data
For the EEPROM write operation, the EEDR Register contains the data to be written to
the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by
EEAR.
60
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
EEPROM Control Register –
EECR
Bit76543210
$1C ($3C)– –––EERIEEEMWEEEWEEEREEECR
Read/WriteRRRRR/WR/WR/WR/W
InitialValue000000X0
• Bits 7..4
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and will always read as zero.
• Bit 3
– EERIE: EEPROM Ready Interrupt Enable
When the I-bit in SREG and EERIE are set (one), the EEPROM Ready Interrupt is
enabled. When cleared (zero), the interrupt is disabled. The EEPROM Ready interrupt
generates a constant interrupt when EEWE is cleared (zero).
• Bit 2
– EEMWE: EEPROM Master Write Enable
The EEMWE bit determines whether setting EEWE to one causes the EEPROM to be
written. When EEMWE is set (one), setting EEWE will write data to the EEPROM at the
selected address. If EEMWE is zero, setting EEWE will have no effect. When EEMWE
has been set (one) by software, hardware clears the bit to zero after four clock cycles.
See the description of the EEWE bit for an EEPROM write procedure.
• Bit 1
– EEWE: EEPROM Write Enable
The EEPROM Write Enable Signal (EEWE) is the write strobe to the EEPROM. When
address and data are correctly set up, the EEWE bit must be set to write the value into
the EEPROM. The EEMWE bit must be set when the logical “1” iswrittentoEEWE,otherwise no EEPROM write takes place. The following procedure should be followed
when writing the EEPROM (the order of steps 2 and 3 is not essential):
1. Wait until EEWE becomes zero.
2. Write new EEPROM address to EEAR (optional).
3. Write new EEPROM data to EEDR (optional).
4. Write a logical “1” to the EEMWE bit in EECR (to be able to write a logical “1” to
theEEMWEbit,theEEWEbitmustbewrittentozerointhesamecycle).
5. Within four clock cycles after setting EEMWE, write a logical “1” to EEWE.
1228C–AVR–08/02
Caution: An interrupt between step 4 and step 5 will make the write cycle fail, since the
EEPROM Master Write Enable will time-out. If an interrupt routine accessing the
EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be
modified, causing the interrupted EEPROM access to fail. It is recommended to have
the Global Interrupt Flag cleared during the four last steps to avoid these problems.
When the write access time has elapsed, the EEWE bit is cleared (zero) by hardware.
The user software can poll this bit and wait for a zero before writing the next byte. When
EEWE has been set, the CPU is halted for two cycles before the next instruction is
executed.
• Bit 0
– EERE: EEPROM Read Enable
The EEPROM Read Enable signal (EERE) is the read strobe to the EEPROM. When
the correct address is set up in the EEAR Register, the EERE bit must be set. When the
EERE bit is cleared (zero) by hardware, requested data is found in the EEDR Register.
The EEPROM read access takes one instruction and there is no need to poll the EERE
61
bit. When EERE has been set, the CPU is halted for four cycles before the next instruction is executed.
The user should poll the EEWE bit before starting the read operation. If a write operation
is in progress when new data or address is written to the EEPROM I/O Registers, the
write operation will be interrupted and the result is undefined.
An RC Oscillator is used to time EEPROM write access. The table below lists the typical
programming time listed for EEPROM access from CPU.
Prevent EEPROM
Corruption
Table 21. EEPROM Access Time from CPU“See “Typical Characteristics” on page 138
to find RC Oscillator frequency.” on page 62
No. of RC
Symbol
EEPROM write (from CPU)20482.0 ms3.4 ms
Note:1. See “Typical Characteristics” on page 138 to find RC Oscillator frequency.
Oscillator Cycles
(1)
Min Programming
Time
Max Programming
Time
During periods of low VCC, the EEPROM data can be corrupted because the supply voltage is too low for the CPU and the EEPROM to operate properly. These issues are the
same as for board-level systems using the EEPROM, and the same design solutions
should be applied.
An EEPROM data corruption can be caused by two situations when the voltage is too
low. First, a regular write sequence to the EEPROM requires a minimum voltage to
operate correctly. Secondly, the CPU itself can execute instructions incorrectly if the
supply voltage for executing instructions is too low.
EEPROM data corruption can easily be avoided by following these design recommendations (one is sufficient):
1. Keep the AVR RESET active (low) during periods of insufficient power supply
voltage. An external low V
2. Keep the AVR core in Power-down Sleep mode during periods of low V
Reset Protection circuit can be applied.
CC
CC
.This
will prevent the CPU from attempting to decode and execute instructions, effectively protecting the EEPROM Registers from unintentional writes.
3. Store constants in Flash memory if the ability to change memory contents from
software is not required. Flash memory cannot be updated by the CPU unless
the boot loader software supports writing to the Flash and the Boot Lock bits are
configured so that writing to the Flash memory from the CPU is allowed. See
“Boot Loader Support” on page 110 for details.
62
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Serial Peripheral
Interface – SPI
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer
between the ATmega161 and peripheral devices or between several AVR devices. The
ATmega161 SPI features include the following:
•
Full-duplex, 3-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 (Slave Mode Only)
• Double-speed (CK/2) Master SPI Mode
Figure 40. SPI Block Diagram
DIVIDER
/2/4/8/16/32/64/128
SPI2X
SPI2X
1228C–AVR–08/02
63
The interconnection between Master and Slave CPUs with SPI is shown in Figure 41.
The PB7(SCK) pin is the Clock Output in the Master mode and is the clock input in the
Slave mode. Writing to the SPI Data Register of the Master CPU starts the SPI clock
generator, and the data written shifts out of the PB5(MOSI) pin and into the PB5(MOSI)
pin of the Slave CPU. After shifting one byte, the SPI clock generator stops, setting the
End-of-Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR
Register is set, an interrupt is requested. The Slave Select input, PB4(SS
), is set low to
select an individual Slave SPI device. The two Shift Registers in the Master and the
Slave can be considered as one distributed 16-bit circular Shift Register. This is shown
in Figure 41. When data is shifted from the Master to the Slave, data is also shifted in
the opposite direction, simultaneously. This means that during one shift cycle, data in
the Master and the Slave are interchanged.
Figure 41. SPI Master-Slave Interconnection
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 byte must be read from the SPI Data Register before the next byte has been
completely shifted in. Otherwise, the first byte is lost.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK and SS
pins is
overridden according to Table 22.
Table 22. SPI Pin Overrides
PinDirection, Master SPIDirection, Slave SPI
MOSIUser DefinedInput
MISOInputUser Defined
SCKUser DefinedInput
SS
Note:1. See “Alternate Functions of Port B” on page 92 for a detailed description of how to
User DefinedInput
define the direction of the user defined SPI pins.
(1)
64
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
SS Pin FunctionalityWhen the SPI is configured as a Master (MSTR in SPCR is set), the user can determine
the direction of the SS
pin, which does not affect the SPI system. If SS
high to ensure Master SPI operation. If the SS
when the SPI is configured as Master with the SS
tem interprets this as another Master selecting the SPI as a Slave and starting to send
data to it. To avoid bus contention, the SPI system takes the following actions:
1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a
result of the SPI becoming a Slave, the MOSI and SCK pins become inputs.
2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled and the I-bit in
SREG is set, the interrupt routine will be executed.
Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a
possibility that SS
still set. Once the MSTR bit has been cleared by a Slave select, it must be set by the
user to re-enable SPI Master mode.
pin. If SS is configured as an output, the pin is a general output
is configured as an input, it must be held
pin is driven low by peripheral circuitry
pin defined as an input, the SPI sys-
is driven low. The interrupt should always check that the MSTR bit is
When the SPI is configured as a Slave, the SS
the SPI is activated and MISO becomes an output if configured so by the user. All other
pins are inputs. When SS
means that it will not receive incoming data. Note that the SPI logic will be reset once
the SS
will stop sending and receiving immediately and both data received and data sent must
be considered lost.
pin is brought high. If the SS pin is brought high during a transmission, the SPI
is driven high, all pins are inputs and the SPI is passive, which
pin is always input. When SS is held low,
Data ModesThere are four combinations of SCK phase and polarity with respect to serial data,
which are determined by control bits CPHA and CPOL. The SPI data transfer formats
are shown in Figure 42 and Figure 43.
Figure 42. SPI Transfer Format with CPHA = 0 and DORD = 0
1228C–AVR–08/02
65
Figure 43. SPI Transfer Format with CPHA = 1 and DORD = 0
SPIControlRegister– SPCR
Bit76543210
$0D ($2D)SPIESPEDORDMSTRCPOLCPHASPR1SPR0SPCR
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
• Bit 7
– SPIE: SPI Interrupt Enable
This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set
and if the global interrupt enable bit in SREG is set.
• Bit 6
– SPE: SPI Enable
When the SPE bit is set (one), the SPI is enabled. This bit must be set to enable any SPI
operations.
• Bit 5
– DORD: Data Order
When the DORD bit is set (one), the LSB of the data word is transmitted first.
When the DORD bit is cleared (zero), the MSB of the data word is transmitted first.
• Bit 4
– MSTR: Master/Slave Select
This bit selects Master SPI mode when set (one), and Slave SPI mode when cleared
(zero). If SS
is configured as an input and is driven low while MSTR is set, MSTR will be
cleared and SPIF in SPSR will become set. The user will then have to set MSTR to reenable SPI Master mode.
66
• Bit 3
When this bit is set (one), SCK is high when idle. When CPOL is cleared (zero), SCK is
low when idle. Refer to Figure 42 and Figure 43 for additional information.
• Bit 2
Refer to Figure 42 or Figure 43 for the functionality of this bit.
These two bits control the SCK rate of the device configured as a Master. SPR1 and
SPR0 have no effect on the Slave. The relationship between SCK and the Oscillator
Clock frequency (f
Table 23. Relationship between SCK and the Oscillator Frequency
SPI2XSPR1SPR0SCK Frequency
000
001
010
011
100
101
110
111
Note:1. When the SPI is configured as Slave, the SPI is only guaranteed to work at fcl/4.
) is shown in Table 23:
cl
f
(1)
f
f
cl
f
f
f
cl
cl
f
f
cl
cl
/4
cl
/16
/64
/128
/2
cl
/8
cl
/32
/64
SPI Status Register – SPSR
Bit76543210
$0E ($2E)SPIFWCOL–––––SPI2XSPSR
Read/WriteRRRRRRRR/W
InitialValue00000000
• Bit 7
– SPIF: SPI Interrupt Flag
When a serial transfer is complete, the SPIF bit is set (one) and an interrupt is generated if SPIE in SPCR is set (one) and global interrupts are enabled. If SS
is an input and
is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is
cleared by hardware when executing the corresponding Interrupt Handling Vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set
(one), then by accessing the SPI Data Register (SPDR).
• Bit 6
– WCOL: Write Collision Flag
The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer.
The WCOL bit (and the SPIF bit) are cleared (zero) by first reading the SPI Status Register with WCOL set (one), and then by accessing the SPI Data Register.
• Bits 5..1
– Res: Reserved Bits
These bits are reserved bits in the ATmega161 and will always read as zero.
• Bit 0
– SPI2X: Double SPI Speed Bit
1228C–AVR–08/02
When this bit is set (one), the SPI speed (SCK frequency) will be doubled when the SPI
is in Master mode (see Table 23). This means that the maximum SCK period will be two
CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to
work at f
/4.
cl
The SPI interface on the ATmega161 is also used for Program memory and EEPROM
downloading or uploading. See page 125 for serial programming and verification.
67
SPI Data Register – SPDR
Bit76543210
$0F ($2F)MSBLSBSPDR
Read/WriteR/WR/ WR/WR/WR/WR/WR/WR/W
InitialValuexxxxxxxxUndefined
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.
68
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
UARTsThe ATmega161 features two full-duplex (separate Receive and Transmit Registers)
Universal Asynchronous Receiver and Transmitters (UARTs). The main features are:
•
Baud Rate Generator Generates any Baud Rate
• High Baud Rates at low XTAL Frequencies
• 8 or 9 Bits Data
• Noise Filtering
• Overrun Detection
• Framing Error Detection
• False Start Bit D etection
• Three Separate Interrupts on TX Complete, TX Data Register Empty, and RX Complete
• Multi-processor Communication Mode
• Double-speed UART Mode
Data TransmissionA block schematic of the UART Transmitter is shown in Figure 44. The two UARTs are
identical and the functionality is described in general for the two UARTs.
Figure 44. UART Transmitter
DATA BU S
XTAL
GENERATOR
CONTROL LOGIC
BAUD RATE
BAUD x 16
STORE UDRn
SHIFT ENABLE
IDLE
/16
BAUD
RXENn
UART CONTROL AND
STATUS REGISTER
(UCSRnB)
TXCIEn
RXCIEn
UDRIEn
UART I/O DATA
REGISTER (UDRn)
10(11)-BIT TX
SHIFT REGISTER
TXENn
CHR9n
RXB8n
TXB8n
DATA BU S
TXCn
UDREn
FEn
(UCSRnA)
TXCn
UDREn
ORn
RXCn
UART CONTROL AND
STATUS REGISTER
U2Xn
PIN CONTROL
LOGIC
TXDn
MPCMPn
PD1/
PB3
1228C–AVR–08/02
n = 0,1
TXCn
IRQ
UDREn
IRQ
Data transmission is initiated by writing the data to be transmitted to the UART I/O Data
Register, UDRn. Data is transferred from UDRn to the Transmit Shift Register when:
•A new character has been written to UDRn after the stop bit from the previous
character has been shifted out. The Shift Register is loaded immediately.
69
•A new character has been written to UDRn before the stop bit from the previous
character has been shifted out. The Shift Register is loaded when the stop bit of the
character currently being transmitted has been shifted out.
If the 10(11)-bit Transmit Shift Register is empty, data is transferred from UDRn to the
Shift Register. At this time the UDREn (UART Data Register Empty) bit in the UART
Control and Status Register, UCSRnA, is set. When this bit is set (one), the UART is
ready to receive the next character. At the same time as the data is transferred from
UDRn to the 10(11)-bit Shift Register, bit 0 of the Shift Register is cleared (start bit) and
bit 9 or 10 is set (stop bit). If 9-bit data word is selected (the CHR9n bit in the UART
Control and Status Register, UCSRnB, is set), the TXB8 bit in UCSRnB is transferred to
bit 9 in the Transmit Shift Register.
On the baud rate clock following the transfer operation to the Shift Register, the start bit
is shifted out on the TXDn pin. Then follows the data, LSB first. When the stop bit has
been shifted out, the Shift Register is loaded if any new data has been written to the
UDRn during the transmission. During loading, UDREn is set. If there is no new data in
the UDRn Register to send when the stop bit is shifted out, the UDREn Flag will remain
set until UDRn is written again. When no new data has been written and the stop bit has
been present on TXDn for one bit length, the TX Complete Flag (TXCn) in UCSRnA
is set.
The TXENn bit in UCSRnB enables the UART Transmitter when set (one). When this bit
iscleared(zero),thePD1(UART0)orPB3(UART1)pincanbeusedforgeneralI/O.
When TXENn is set, the UART Transmitter will be connected to PD1 (UART0) or PB3
(UART1), which is forced to be an output pin regardless of the setting of the DDD1 bit in
DDRD (UART0) or DDB3 in DDRB (UART1). Note that PB3 (UART1) also is used as
one of the input pins to the Analog Comparator. It is therefore not recommended to use
UART1 if the Analog Comparator is also used in the application at the same time.
70
ATmega161(L)
1228C–AVR–08/02
Data ReceptionFigure 45 shows a block diagram of the UART Receiver.
Figure 45. UART Receiver
DATA BU S
XTAL
PD0/
PB2
BAUD RATE
GENERATOR
PIN CONTROL
LOGIC
RXDn
BAUD x 16
DATA RECOVERY
/16
LOGIC
BAUD
STORE UDRn
ATmega161(L)
UART I/O DATA
REGISTER (UDRn)
10(11)-BIT RX
SHIFT REGISTER
ORn
U2Xn
MPCMPn
n = 0,1
RXENn
TXENn
CHR9n
RXB8n
TXB8n
UART CONTROL AND
STATUS REGISTER
(UCSRnB)
TXCIEn
RXCIEn
UDRIEn
DATA BU S
RXCn
TXCn
UDREn
FEn
UART CONTROL AND
STATUS REGISTER
(UCSRnA)
TXCn
RXCn
IRQ
The Receiver front-end logic samples the signal on the RXDn pin at a frequency 16
times the baud rate. While the line is idle, one single sample of logical “0” will be interpreted as the falling edge of a start bit, and the start bit detection sequence is initiated.
Let sample 1 denote the first zero-sample. Following the 1-to-0 transition, the Receiver
samples the RXDn pin at samples 8, 9 and 10. If two or more of these three samples are
found to be logical “1”s, the start bit is rejected as a noise spike and the Receiver starts
looking for the next 1-to-0 transition.
If, however, a valid start bit is detected, sampling of the data bits following the start bit is
performed. These bits are also sampled at samples 8, 9 and 10. The logical value found
in at least two of the three samples is taken as the bit value. All bits are shifted into the
Transmitter Shift Register as they are sampled. Sampling of an incoming character is
shown in Figure 46. Note that the description above is not valid when the UART transmission speed is doubled. See “Double-speed Transmission” on page 78 for a detailed
description.
1228C–AVR–08/02
71
Figure 46. Sampling Received Data
Note:1. This figure is not valid when the UART speed is doubled. See “Double-speed
Transmission” on page 78
When the stop bit enters the Receiver, the majority of the three samples must be one to
accept the stop bit. If two or more samples are logical “0”s, the Framing Error (FEn) Flag
in the UART Control and Status Register (UCSRnA) is set. Before reading the UDRn
Register, the user should always check the FEn bit to detect framing errors.
Whether or not a valid stop bit is detected at the end of a character reception cycle, the
dataistransferredtoUDRnandtheRXCnFlaginUCSRnAisset.UDRnisinfacttwo
physically separate registers, one for transmitted data and one for received data. When
UDRn is read, the Receive Data Register is accessed, and when UDRn is written, the
Transmit Data Register is accessed. If 9-bit data word is selected (the CHR9n bit in the
UART Control and Status Register [UCSRnB] is set), the RXB8n bit in UCSRnB is
loaded with bit 9 in the Transmit Shift Register when data is transferred to UDRn.
If, after having received a character, the UDRn Register has not been read since the last
receive, the OverRun (ORn) Flag in UCSRnB is set. This means that the last data byte
shifted into the Shift Register could not be transferred to UDRn and has been lost. The
ORn bit is buffered and is updated when the valid data byte in UDRn is read. Thus, the
user should always check the ORn bit after reading the UDRn Register in order to detect
any overruns if the baud rate is high or CPU load is high.
(1)
for a detailed description.
When the RXEN bit in the UCSRnB Register is cleared (zero), the Receiver is disabled.
This means that the PD0 pin can be used as a general I/O pin. When RXEN is set, the
UART Receiver will be connected to PD0 (UART0) or PB2 (UART1), which is forced to
be an input pin regardless of the setting of the DDD0 in DDRD (UART0) or DDB2 bit in
DDRB (UART1). When PD0 (UART0) or PB2 (UART1) is forced to input by the UART,
the PORTD0 (UART0) or PORTB2 (UART1) bit can still be used to control the pull-up
resistor on the pin.
Note that PB2 (UART1) also is used as one of the input pins to the Analog Comparator.
It is therefore not recommended to use UART1 if the Analog Comparator also is used in
the application at the same time.
When the CHR9n bit in the UCSRnB Register is set, transmitted and received characters are nine bits long plus start and stop bits. The ninth data bit to be transmitted is the
TXB8n bit in UCSRnB Register. This bit must be set to the wanted value before a transmission is initiated by writing to the UDRn Register. The ninth data bit received is the
RXB8n bit in the UCSRnB Register.
72
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Multi-processor
Communication Mode
The Multi-processor Communication mode enables several Slave MCUs to receive data
from a master MCU. This is done by first decoding an address byte to find out which
MCU has been addressed. If a particular Slave MCU has been addressed, it will receive
the following data bytes as normal, while the other Slave MCUs will ignore the data
bytes until another address byte is received.
For an MCU to act as a master MCU, it should enter 9-bit transmission mode (CHR9n in
UCSRnB set). The ninth bit must be one to indicate that an address byte is being transmitted, and zero to indicate that a data byte is being transmitted.
For the Slave MCUs, the mechanism appears slightly different for 8-bit and 9-bit reception mode. In 8-bit reception mode (CHR9n in UCSRnB cleared), the stop bit is one for
an address byte and zero for a data byte. In 9-bit reception mode (CHR9n in UCSRnB
set), the ninth bit is one for an address byte and zero for a data byte, whereas the stop
bit is always high.
The following procedure should be used to exchange data in Multi-processor Communication mode:
1. All Slave MCUs are in Multi-processor Communication mode (MPCMn in UCS-
RnA is set).
2. The master MCU sends an address byte and all Slaves receive and read this
byte. In the Slave MCUs, the RXCn Flag in UCSRnA will be set as normal.
3. Each Slave MCU reads the UDRn Register and determines if it has been
selected. If so, it clears the MPCMn bit in UCSRnA; otherwise, it waits for the
next address byte.
4. For each received data byte, the receiving MCU will set the Receive Complete
Flag (RXCn in UCSRnA). In 8-bit mode, the receiving MCU will also generate a
framing error (FEn in UCSRnA set), since the stop bit is zero. The other Slave
MCUs, which still have the MPCMn bit set, will ignore the data byte. In this case,
the UDRn Register and the RXCn, FEn, or Flags will not be affected.
5. After the last byte has been transferred, the process repeats from step 2.
UART Control
UART0 I/O Data Register –
UDR0
UART1 I/O Data Register –
UDR1
UART0 Control and Status
Registers – UCSR0A
1228C–AVR–08/02
Bit76543210
$0C ($2C)MSBLSBUDR0
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
Bit76543210
$03 ($23)MSBLSBUDR1
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
The UDRn Register is actually two physically separate registers sharing the same I/O
address. When writing to the register, the UART Transmit Data Register is written.
When reading from UDRn, the UART Receive Data Register is read.
Bit76543210
$0B ($2B)RXC0TXC0UDRE0FE0OR0–U2X0MPCM0UCSR0A
Read/WriteRR/WRRRRR/WR/W
InitialValue00100000
73
UART1 Control and Status
Registers – UCSR1A
Bit76543210
$02 ($22)RXC1TXC1UDRE1FE1OR1–U2X1MPCM1UCSR1A
Read/WriteRR/WRRRRR/WR/W
InitialValue00100000
• Bit 7
– RXC0/RXC1: UART Receive Complete
This bit is set (one) when a received character is transferred from the Receiver Shift
Register to UDRn. The bit is set regardless of any detected framing errors. When the
RXCIEn bit in UCSRnB is set, the UART Receive Complete interrupt will be executed
when RXCn is set (one). RXCn is cleared by reading UDRn. When interrupt-driven data
reception is used, the UART Receive Complete Interrupt routine must read UDRn in
order to clear RXCn; otherwise, a new interrupt will occur once the interrupt routine
terminates.
• Bit 6
– TXC0/TXC1: UART Transmit Complete
This bit is set (one) when the entire character (including the stop bit) in the Transmit
Shift Register has been shifted out and no new data has been written to UDRn. This
Flag is especially useful in half-duplex communications interfaces, where a transmitting
application must enter Receive mode and free the communications bus immediately
after completing the transmission.
When the TXCIEn bit in UCSRnB is set, setting of TXCn causes the UART Transmit
Complete interrupt to be executed. TXCn is cleared by hardware when executing the
corresponding Interrupt Handling Vector. Alternatively, the TXCn bit is cleared (zero) by
writing a logical “1” to the bit.
• Bit 5
– UDRE0/UDRE1: UART Data Register Empty
This bit is set (one) when a character written to UDRn is transferred to the Transmit Shift
Register. Setting of this bit indicates that the Transmitter is ready to receive a new character for transmission.
74
When the UDRIEn bit in UCSRnB is set, the UART Transmit Complete interrupt will be
executed as long as UDREn is set and the global interrupt enable bit in SREG is set.
UDREn is cleared by writing UDRn. When interrupt-driven data transmittal is used, the
UART Data Register Empty Interrupt routine must write UDRn in order to clear UDREn,
otherwise a new interrupt will occur once the interrupt routine terminates.
UDREn is set (one) during reset to indicate that the Transmitter is ready.
• Bit 4
This bit is set if a Framing Error condition is detected, i.e., when the stop bit of an incoming character is zero.
The FEn bit is cleared when the stop bit of received data is one.
• Bit 3
This bit is set if an Overrun condition is detected, i.e., when a character already present
in the UDRn Register is not read before the next character has been shifted into the
Receiver Shift Register. The ORn bit is buffered, which means that it will be set once the
valid data still in UDRn is read.
The ORn bit is cleared (zero) when data is received and transferred to UDRn.
ATmega161(L)
– FE0/FE1: Framing Error
– OR0/OR1: OverRun
1228C–AVR–08/02
ATmega161(L)
• Bit 2 – Res: Reserved Bit
This bit is reserved bit in the ATmega161 and will always read as zero.
UART0 Control and Status
Registers – UCSR0B
UART1 Control and Status
Registers – UCSR1B
• Bit 1
– U2X0/U2X1: Double the UART Transmission Speed
When this bit is set (one), the UART speed will be doubled. This means that a bit will be
transmitted/received in 8 CPU clock periods instead of 16 CPU clock periods. For a
detailed description, see “Double-speed Transmission” on page 78.
• Bit 0
– MPCM0/MPCM1: Multi-processor Communication Mode
This bit is used to enter Multi-processor Communication mode. The bit is set when the
Slave MCU waits for an address byte to be received. When the MCU has been
addressed, the MCU switches off the MPCMn bit and starts data reception.
For a detailed description, see “Multi-processor Communication mode”.
When this bit is set (one), a setting of the RXCn bit in UCSRnA will cause the Receive
Complete interrupt routine to be executed, provided that global interrupts are enabled.
• Bit 6
– TXCIE0/TXCIE1: TX Complete Interrupt Enable
When this bit is set (one), a setting of the TXCn bit in UCSRnA will cause the Transmit
Complete interrupt routine to be executed, provided that global interrupts are enabled.
• Bit 5
– UDRIE0/UDREI1: UART Data Register Empty Interrupt Enable
When this bit is set (one), a setting of the UDREn bit in UCSRnA will cause the UART
Data Register Empty interrupt routine to be executed, provided that global interrupts are
enabled.
• Bit 4
– RXEN0/RXEN1: Receiver Enable
This bit enables the UART Receiver when set (one). When the Receiver is disabled, the
TXCn, ORn and FEn Status Flags cannot become set. If these flags are set, turning off
RXEN does not cause them to be cleared.
• Bit 3
– TXEN0/TXEN1: Transmitter Enable
This bit enables the UART Transmitter when set (one). When disabling the Transmitter
while transmitting a character, the Transmitter is not disabled before the character in the
Shift Register plus any following character in UDRn has been completely transmitted.
1228C–AVR–08/02
75
• Bit 2 – CHR90/CHR91: 9-bit Characters
When this bit is set (one), transmitted and received characters are nine bits long, plus
start and stop bits. The ninth bit is read and written by using the RXB8n and TXB8 bits in
UCSRnB, respectively. The ninth data bit can be used as an extra stop bit or a parity bit.
• Bit 1
– RXB80/RXB81: Receive Data Bit 8
When CHR9n is set (one), RXB8n is the ninth data bit of the received character.
• Bit 0
– TXB80/TXB81: Transmit Data Bit 8
When CHR9n is set (one), TXB8n is the ninth data bit in the character to be transmitted.
Baud Rate GeneratorThe baud rate generator is a frequency divider that generates baud rates according to
the following equation:
f
CK
BAUD
•BAUD = Baud rate
•f
= Crystal clock frequency
CK
•UBR = Contents of the UBRRH and UBRR Registers (0 - 4095)
•Note that this equation is not valid when the UART transmission speed is doubled.
See “Double-speed Transmission” for a detailed description.
For standard crystal frequencies, the most commonly used baud rates can be generated
by using the UBR settings in Table 24. UBR values that yield an actual baud rate differing less than 2% from the target baud rate are boldface in the table. However, using
baud rates that have more than 1% error is not recommended. High error ratings give
less noise resistance.
----------------------------------=
16(UBR1)+
76
ATmega161(L)
1228C–AVR–08/02
Table 24. UBR Settings at Various Crystal Frequencies
UART0 and UART1 High B yte
Baud Rate Register UBRRHI
Bit76543210
$20 ($40)MSB1LSB1MSB0LSB0UBRRHI
Read/WriteR/WR /WR/WR/WR/WR/WR/WR/W
InitialValue00000000
The UART Baud Register is a 12-bit register. The four most significant bits are located in
a separate register, UBRRHI. Note that both UART0 and UART1 share this register. Bit
7 to bit 4 of UBRRHI contain the four most significant bits of the UART1 Baud Register.
Bit 3 to bit 0 contain the four most significant bits of the UART0 Baud Register.
UART0 Baud Rate Register
Low Byte – UBRR0
UART1 Baud Rate Register
Low Byte – UBRR1
Double-speed
Transmission
Bit76543210
$09 ($29)MSBLSBUBRR0
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
Bit76543210
$00 ($20)MSBLSBUBRR1
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
UBRRn stores the eight least significant bits of the UART Baud Rate Register.
The ATmega161 provides a separate UART mode that allows the user to double the
communication speed. By setting the U2X bit in UART Control and Status Register
UCSRnA, the UART speed will be doubled. The data reception will differ slightly from
Normal mode. Since the speed is doubled, the Receiver front-end logic samples the signals on RXDn pin at a frequency 8 times the baud rate. While the line is idle, one single
sample of logical “0” will be interpreted as the falling edge of a start bit, and the start bit
detection sequence is initiated. Let sample 1 denote the first zero-sample. Following the
1-to-0 transition, the Receiver samples the RXDn pin at samples 4, 5 and 6. If two or
more of these three samples are found to be logical “1”s, the start bit is rejected as a
noise spike and the Receiver starts looking for the next 1-to-0 transition.
If, however, a valid start bit is detected, sampling of the data bits following the start bit is
performed. These bits are also sampled at samples 4, 5 and 6. The logical value found
in at least two of the three samples is taken as the bit value. All bits are shifted into the
Transmitter Shift Register as they are sampled. Sampling of an incoming character is
shown in Figure 47.
78
Figure 47. Sampling Received Data when the Transmission Speed is Doubled
RECEIVER
SAMPLING
ATmega161(L)
RXD
START BITD0D1D2D3D4D5D6D7STOP BIT
1228C–AVR–08/02
ATmega161(L)
The Baud Rate Generator in
Double UART Speed Mode
Note that the baud rate equation is different from the equation on page 76 when the
UART speed is doubled:
f
CK
BAUD
•BAUD = Baud rate
•f
•UBR = Contents of the UBRRHI and UBRR Registers (0 - 4095)
•Note that this equation is only valid when the UART transmission speed is doubled.
For standard crystal frequencies, the most commonly used baud rates can be generated
by using the UBR settings in Table 24. UBR values that yield an actual baud rate differing less than 1.5% from the target baud rate are boldface in the table. However, since
the number of samples are reduced and the system clock might have some variance
(this applies especially when using resonators), it is recommended that the baud rate
error be less than 0.5%.
= Crystal Clock frequency
CK
------------------------------=
8(UBR1)+
1228C–AVR–08/02
79
Table 2 5. UBR Settings at Various Crystal Frequencies in Double-speed Mode
Analog ComparatorThe Analog Comparator compares the input values on the positive input PB2 (AIN0) and
negative input PB3 (AIN1). When the voltage on the positive input PB2 (AIN0) is higher
than the voltage on the negative input PB3 (AIN1), the Analog Comparator Output
(ACO) is set (one). The comparator’s output can be set to trigger the Timer/Counter1
Input Capture function. In addition, the comparator can trigger a separate interrupt,
exclusive to the Analog Comparator. The user can select interrupt triggering on comparator output rise, fall or toggle. A block diagram of the comparator and its surrounding
logic is shown in Figure 48.
Figure 48. Analog Comparator Block Diagram
Analog Comparator Control
and Status Register – ACSR
Bit76543210
$08 ($28)ACDAINB GACOACIAC IEACICACIS 1ACI S0ACSR
Read/WriteR/WR/WRR/WR/WR/WR/WR/W
Initial Value00N/A00000
• Bit 7
– ACD: Analog Comparator Disable
When this bit is set (one), the power to the Analog Comparator is switched off. This bit
can be set at any time to turn off the Analog Comparator. This will reduce power consumption in active and Idle mode. When changing the ACD bit, the Analog Comparator
Interrupt must be disabled by clearing the ACIE bit in ACSR. Otherwise, an interrupt can
occur when the bit is changed.
• Bit 6
– AINBG: Analog Comparator Bandgap Select
When this bit is set, a fixed bandgap voltage of 1.22 ± 0.05V replaces the normal input
to the positive input (AIN0) of the comparator. When this bit is cleared, the normal input
pin PB2 is applied to the positive input of the comparator.
• Bit 5
– ACO: Analog Comparator Output
ACO is directly connected to the comparator output.
1228C–AVR–08/02
81
• Bit 4 – ACI: Analog Comparator Interrupt Flag
This bit is set (one) when a comparator output event triggers the interrupt mode defined
by ACI1 and ACI0. The Analog Comparator Interrupt routine is executed if the ACIE bit
is set (one) and the I-bit in SREG is set (one). ACI is cleared by hardware when executing the corresponding Interrupt Handling Vector. Alternatively, ACI is cleared by writing
a logical “1” to the Flag.
• Bit 3
– ACIE: Analog Comparator Interrupt Enable
When the ACIE bit is set (one) and the I-bit in the Status Register is set (one), the Analog Comparator Interrupt is enabled. When cleared (zero), the interrupt is disabled.
• Bit 2
– ACIC: Analog Comparator Input Capture Enable
When set (one), this bit enables the Input Capture function in Timer/Counter1 to be triggered by the Analog Comparator. The comparator output is, in this case, directly
connected to the Input Capture front-end logic, making the comparator utilize the noise
canceler and edge select features of the Timer/Counter1 Input Capture Interrupt. When
cleared (zero), no connection between the Analog Comparator and the Input Capture
function is given. To make the comparator trigger the Timer/Counter1 Input Capture
Interrupt, the TICIE1 bit in the Timer Interrupt Mask Register (TIMSK) must be set (one).
• Bits 1, 0
– ACIS1, ACIS0: Analog Comparator Interrupt Mode Select
These bits determine which comparator events trigger the Analog Comparator Interrupt.
The different settings are shown in Table 26.
Table 26. ACIS1/ACIS0 Settings
ACI S1AC IS0Interrupt Mode
00Comparator Interrupt on Output Toggle
01Reserved
10Comparator Interrupt on Falling Output Edge
(1)
82
11Comparator Interrupt on Rising Output Edge
Note:1. When changing the ACIS1/ACIS0 bits, the Analog Comparator Interrupt must be dis-
abled by clearing its Interrupt Enable bit in the ACSR Register. Otherwise, an
interrupt can occur when the bits are changed.
Caution: Using the SBI or CBI instruction on bits other than ACI in this register will write
a one back into ACI if it is read as set, thus clearing the Flag.
The Analog Comparator pins (PB2 and PB3) are also used as the TXD1 and RXD1 pins
for UART1. Note that if the UART1 transceiver or Receiver is enabled, the UART1 will
override the settings in the DDRB Register even if the Analog Comparator is enabled.
Therefore, it is not recommended to use UART1 if the Analog Comparator is needed in
the same application at the same time. See “UARTs” on page 69 for more details.
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Internal Voltage
Reference
Voltage Reference
Enable Signals and Startup Time
ATmega161 features an internal voltage reference with a nominal voltage of 1.22V. This
reference can be used as an input to the Analog Comparator.
The voltage reference has a start-up time that may have an influence on the way it
should be used. The maximum start-up time is TBD. To save power, the reference is on
only when the AINBG bit in ACSR is set. Thus the user must always allow the reference
to start up before the output from the Analog Comparator is used. The bandgap reference uses approximately 10
mode, the user can turn off the reference when entering this mode.
µA, and to reduce the power consumption in Power-down
1228C–AVR–08/02
83
Interface to External
Memory
With all the features the external memory interface provides, it is well suited to operate
as an interface to memory devices such as external SRAM and Flash, and peripherals
such as LCD display, A/D, D/A, etc. The control bits for the external memory interface
are located in two registers, the MCU Control Register (MCUCR) and the Extended
MCU Control Register (EMCUCR).
MCU Control Register –
MCUCR
Extended MCU Control
Register – EMCUCR
Bit76543210
$35 ($55)SRESRW10
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
Bit76543210
$36 ($56)
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
InitialValue00000000
SM0SRL2SRL1SRL0SRW01SRW00SRW11ISC20EMCUCR
SESM1ISC11ISC10ISC01ISC00MCUCR
• Bit 7 MCUCR – SRE: External SRAM Enable
When the SRE bit is set (one), the external memory interface is enabled and the pin
functions AD0 - 7 (Port A), A8 - 15 (Port C), ALE (Port E), WR
and RD (Port D) are activated as the alternate pin functions. The SRE bit overrides any pin direction settings in
the respective Data Direction Registers. See Figure 50 through Figure 53 for a description of the external memory pin functions. When the SRE bit is cleared (zero), the
external Data memory interface is disabled and the normal pin and data direction settings are used
It is possible to configure different wait states for different external memory addresses.
The external memory address space can be divided into two pages with different wait
state bits. The SRL2, SRL1 and SRL0 bits select the split of the pages (see Table 28
and Figure 49). As defaults, the SRL2, SRL1 and SRL0 bits are set to zero and the
entire external memory address space is treated as one page. When the entire SRAM
address space is configured as one page, the wait states are configured by the SRW11
and SRW10 bits.
84
• Bit 1 EMCUCR and Bit 6 MCUCR – SRW11, SRW10: Wait State Select Bits for
Upper Page
The SRW11 and SRW10 bits control the number of wait states for the upper page of the
external memory address space (see Table 27). Note that if the SRL2, SRL1, and SRL0
bits are set to zero, the SRW11 and SRW10 bit settings will define the wait state of the
entire SRAM address space.
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
• Bits 3..2 EMCUCR – SRW01, SRW00: Wait State Select Bits for Lower Page
The SRW01 and SRW00 bits control the number of wait states for the lower page of the
external memory address space (see Table 27).
Table 27. Wait States
SRWn1SRWn0Wait States
00No wait states
01Wait one cycle during read/write strobe
10Wait two cycles during read/write strobe
11Wait two cycles during read/write and wait one cycle before driving
Note:1. n = 0 or 1 (lower/upper page)
For further details of the timing and wait states of the external memory interface, see
Figure 50 through Figure 53 for how the setting of the SRW bits affects the timing.
Table 28. Page Limits with Different Settings of SRL2..0
SRL2SRL1SRL0Page Limits
000
001
010
011
(1)
out new address
Lower page = N/A
Upper page = $0460-$FFFF
Lower page = $0460-$1FFF
Upper page = $2000-$FFFF
Lower page = $0460-$4FFF
Upper page = $4000-$FFFF
Lower page = $0460-$5FFF
Upper page = $6000-$FFFF
100
101
110
111
Lower page = $0460-$7FFF
Upper page = $8000-$FFFF
Lower page = $0460-$9FFF
Upper page = $A000-$FFFF
Lower page = $0460-$BFFF
Upper page = $C000-$FFFF
Lower page = $0460-$DFFF
Upper page = $E000-$FFFF
1228C–AVR–08/02
85
Figure 49. External Memory with Page Select
Data Memory
Internal memory
Lower page
SRW01
SRW00
$0000
$0460
SRL[2..0]
External Memory
(0-63K x 8)
Figure 50. External Data Memory Cycles without Wait State (SRWn1 = 0 and SRWn0
page) or SRW00 (lower page).
The ALE pulse in period T4 is only present if the next instruction accesses the RAM
(internal or external). The Data and Address will only change in T4 if ALE is present
(the next instruction accesses the RAM).
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Figure 51. External Data Memory Cycles with SRWn1 = 0 and SRWn0 = 1
page) or SRW00 (lower page). The ALE pulse in period T5 is only present if the next
instruction accesses the RAM (internal or external). The Data and Address will only
change in T5 if ALE is present (the next instruction accesses the RAM).
Figure 52. External Data Memory Cycles with SRWn1 = 1 and SRWn0 = 0
page) or SRW00 (lower page). The ALE pulse in period T6 is only present if the next
instruction accesses the RAM (internal or external). The Data and Address will only
change in T6 if ALE is present (the next instruction accesses the RAM).
Figure 53. External Data Memory Cycles with SRWn1 = 1 and SRWn0 = 1
page) or SRW00 (lower page). The ALE pulse in period T7 is only present if the next
instruction accesses the RAM (internal or external). The Data and Address will only
change in T7 if ALE is present (the next instruction accesses the RAM).
Write
Read
1228C–AVR–08/02
87
Using the External
Memory Interface
The interface consists of:
Port A: multiplexed low-order address bus and data bus
Port C: high-order address bus
The ALE pin: address latch enable
The RD
The external memory interface is enabled by setting the external SRAM enable bit
(SRE) of the MCU Control Register (MCUCR) and will override the setting of the Data
Direction Registers DDRA, DDRD and DDRE. When the SRE bit is cleared (zero), the
external memory interface is disabled and the normal pin and data direction settings are
used. When SRE is low, the address space above the internal SRAM boundary is not
mapped into the internal SRAM, as in AVR parts do not have an external memory
interface.
When ALE goes from high to low, there is a valid address on Port A. ALE is low during a
data transfer. RD
When the external memory interface is enabled, the ALE signal may have short pulses
when accessing the internal RAM, but the ALE signal is stable when accessing the
external memory.
Figure 54 sketches how to connect an external SRAM to the AVR using eight latches
that are transparent when G is high.
Figure 54. External SRAM Connected to the AVR
and WR pin: read and write strobes
and WR are active when accessing the external memory only.
Por t A
DQ
D[7:0]
A[7:0]
ALE
AVR
Por t C
RD
WR
For details on the timing for the SRAM interface, please see Figure 83 through Figure 86
and Table 51 through Table 58.
G
SRAM
A[15:8]
RD
WR
88
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
I/O PortsAll 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 for changing drive value (if configured as output) or enabling/disabling of pull-up
resistors (if configured as input).
Port APort A is an 8-bit bi-directional I/O port.
Three I/O memory address locations are allocated for the Port A, one each for the Data
Register – PORTA, $1B($3B), Data Direction Register – DDRA, $1A($3A) and the Port
A Input Pins – PINA, $19($39). The Port A Input Pins address is read-only, while the
Data Register and the Data Direction Register are read/write.
All port pins have individually selectable pull-up resistors. The Port A output buffers can
sink 20 mA and thus drive LED displays directly. When pins PA0 to PA7 are used as
inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated.
The Port A pins have alternate functions related to the optional external memory interface. Port A can be configured to be the multiplexed low-order address/data bus during
accesses to the external Data memory. In this mode, Port A has internal pull-up
resistors.
Port A Data Register – PORTA
Port A Data Direction Register
– DDRA
Port A Input Pins Address –
PINA
When Port A is set to the alternate function by the SRE (External SRAM Enable) bit in
the MCUCR (MCU Control Register), the alternate settings override the Data Direction
Register.
The Port A Input Pins address (PINA) is not a register; this address enables access to
the physical value on each Port A pin. When reading PORTA, the Port A Data Latch is
read and when reading PINA, the logical values present on the pins are read.
Port A as General Digital I/OAll eight pins in Port A have equal functionality when used as digital I/O pins.
PAn, general I/O pin: The DDAn bit in the DDRA Register selects the direction of this
pin. If DDAn is set (one), PAn is configured as an output pin. If DDAn is cleared (zero),
PAn is configured as an input pin. If PORTAn is set (one) when the pin is configured as
an input pin, the MOS pull-up resistor is activated. To switch the pull-up resistor off, the
PORTAn has to be cleared (zero) or the pin has to be configured as an output pin. The
1228C–AVR–08/02
89
Port A pins are tri-stated when a reset condition becomes active, even if the clock is not
running.
Table 29. DDAn Effects on Port A Pins
DDAnPORTAnI/OPull-upComment
00InputNoTri-state (high-Z)
01InputYesPAn will source current if ext. pulled low.
10OutputNoPush-pull Zero Output
11OutputNoPush-pull One Output
Note:1. n: 7,6…0, pin number
(1)
Port A SchematicsNote that all port pins are synchronized. The synchronization latch is, however, not
shown in the figure.
Figure 55. Port A Schematic Diagrams (Pins PA0 - PA7)
90
ATmega161(L)
1228C–AVR–08/02
Port BPort B is an 8-bit bi-directional I/O port.
Three I/O memory address locations are allocated for the Port B, one each for the Data
Register – PORTB, $18($38), Data Direction Register – DDRB, $17($37) and the Port B
Input Pins – PINB, $16($36). The Port B Input Pins address is read-only, while the Data
Register and the Data Direction Register are read/write.
All port pins have individually selectable pull-up resistors. The Port B output buffers can
sink 20 mA and thus drive LED displays directly. When pins PB0 to PB7 are used as
inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated.
The Port B pins with alternate functions are shown in Table 30.
The Port B Input Pins address (PINB) is not a register; this address enables access to
the physical value on each Port B pin. When reading PORTB, the Port B Data Latch is
read and when reading PINB, the logical values present on the pins are read.
91
Port B as General Digital I/OAll eight pins in Port B have equal functionality when used as digital I/O pins.
PBn, general I/O pin: The DDBn bit in the DDRB Register selects the direction of this
pin. If DDBn is set (one), PBn is configured as an output pin. If DDBn is cleared (zero),
PBn is configured as an input pin. If PORTBn is set (one) when the pin is configured as
an input pin, the MOS pull-up resistor is activated. To switch the pull-up resistor off, the
PORTBn has to be cleared (zero) or the pin has to be configured as an output pin. The
Port B pins are tri-stated when a reset condition becomes active, even if the clock is not
running.
Table 31. DDBn Effects on Port B Pins
DDBnPORTBnI/OPull-upComment
00InputNoTri-state (high-Z)
01InputYesPBn will source current if ext. pulled low.
10OutputNoPush-pull Zero Output
11OutputNoPush-pull One Output
Note:1. n: 7,6…0, pin number
(1)
Alternate Functions of Port BThe alternate pin configuration is as follows:
• SCK
– Port B, Bit 7
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 DDB7.
When the SPI is enabled as a master, the data direction of this pin is controlled by
DDB7. When the pin is forced to be an input, the pull-up can still be controlled by the
PORTB7 bit. See the description of the SPI port for further details.
• MISO
– Port B, Bit 6
MISO: Master data input, Slave data output pin for SPI channel. When the SPI is
enabled as a master, this pin is configured as an input regardless of the setting of
DDB6. When the SPI is enabled as a Slave, the data direction of this pin is controlled by
DDB6. When the pin is forced to be an input, the pull-up can still be controlled by the
PORTB6 bit. See the description of the SPI port for further details.
92
• MOSI
MOSI: SPI Master data output, Slave data input for SPI channel. When the SPI is
enabled as a Slave, this pin is configured as an input regardless of the setting of DDB5.
When the SPI is enabled as a master, the data direction of this pin is controlled by
DDB5. When the pin is forced to be an input, the pull-up can still be controlled by the
PORTB5 bit. See the description of the SPI port for further details.
• SS
SS
as an input regardless of the setting of DDB5. As a Slave, the SPI is activated when this
pin is driven low. When the SPI is enabled as a master, the data direction of this pin is
controlled by DDB5. When the pin is forced to be an input, the pull-up can still be controlled by the PORTB5 bit. See the description of the SPI port for further details.
ATmega161(L)
– Port B, Bit 5
– Port B, Bit 4
: Slave port select input. When the SPI is enabled as a Slave, this pin is configured
1228C–AVR–08/02
ATmega161(L)
• TXD1/AIN1 – Port B, Bit 3
AIN1, Analog Comparator Negative Input. This pin also serves as the negative input of
the On-chip Analog Comparator.
TXD1, Transmit Data (Data output pin for the UART1). When the UART1 Transmitter is
enabled, this pin is configured as an output regardless of the value of DDRB3.
• RXD1/AIN0
– Port B, Bit 2
AIN0, Analog Comparator Positive Input. This pin also serves as the positive input of the
On-chip Analog Comparator.
RXD1, Receive Data (Data input pin for the UART1). When the UART1 Receiver is
enabled, this pin is configured as an input regardless of the value of DDRB2. When the
UART1 forces this pin to be an input, a logical “1” in PORTB2 will turn on the internal
pull-up.
• OC2/T1
– Port B, Bit 1
T1: Timer/Counter1 counter source. See “Timer/Counter1” on page 49 for further
details.
OC2, Output compare match output: The PB1 pin can serve as an external output when
the Timer/Counter2 compare matches. The PB1 pin has to be configured as an output
(DDB1 set [one]) to serve this function. See “8-bit Timer/Counters T/C0 and T/C2” on
page 40 for further details. The OC2 pin is also the output pin for the PWM mode timer
function.
• OC0/T0
– Port B, Bit 0
T0: Timer/Counter0 counter source. See “8-bit Timer/Counters T/C0 and T/C2” on page
40 further details.
OC0, Output compare match output: The PB0 pin can serve as an external output when
the Timer/Counter0 compare matches. The PB0 pin has to be configured as an output
(DDB0 set [one]) to serve this function. See “8-bit Timer/Counters T/C0 and T/C2” on
page 40 for further details and how to enable the output. The OC0 pin is also the output
pin for the PWM mode timer function.
1228C–AVR–08/02
93
Port B SchematicsNote that all port pins are synchronized. The synchronization latches are, however, not
shown in the figures.
Figure 56. Port B Schematic Diagram (Pins PB0 and PB1)
DDBn
PBn
WP:
WRITE PORTB
WD:
WRITE DDRB
RL:
READ PORTB LATCH
RP:
READ PORTB PIN
RD:
READ DDRB
n: 0,1
x: 0,2
CSn2
CSn1
CSn0
PORTBn
COMx0
COMx1
COMP. MATCH x
PWMx
FOCx
94
ATmega161(L)
1228C–AVR–08/02
Figure 57. Port B Schematic Diagram (Pin PB2)
MOS
PULLUP
PB2
WP:
WRITE PORTB
WD:
WRITE DDRB
RL:
READ PORTB LATCH
RP:
READ PORTB PIN
RD:
READ DDRB
RXD1:
UART1 RECEIVE DATA
RXEN1:
UART1 RECEIVE ENABLE
AIN0: ANALOG COMPARATOR POSITIVE INPUT
ATmega161(L)
RD
RESET
D
Q
DDB2
C
WD
RESET
D
Q
PORTB2
C
RL
RP
WP
RXEN1
RXD1
AIN0
TA BUS
DA
Figure 58. Port B Schematic Diagram (Pin PB3)
MOS
PULLUP
PB3
WP:
WRITE PORTB
WD:
WRITE DDRB
RL:
READ PORTB LATCH
RP:
READ PORTB PIN
RD:
READ DDRB
TXD1:
UART1 TRANSMIT DATA
TXEN1:
UART1 TRANSMIT ENABLE
AIN1:ANALOG COMPARATOR NEGATIVE INPUT
RD
RESET
R
D
Q
DDB3
C
WD
RESET
R
Q
D
PORTB3
C
RL
RP
WP
TXEN1
TXD1
AIN1
TA BUS
DA
1228C–AVR–08/02
95
Figure 59. Port B Schematic Diagram (Pin PB4)
MOS
PULLUP
PB4
RL
RP
RD
RESET
Q
DDB4
WD
RESET
Q
PORTB4
WP
D
C
D
C
DATA BUS
WRITE PORTB
WP:
WRITE DDRB
WD:
READ PORTB LATCH
RL:
READ PORTB PIN
RP:
READ DDRB
RD:
SPI MASTER ENABLE
MSTR:
SPI ENABLE
SPE:
Figure 60. Port B Schematic Diagram (Pin PB5)
MOS
PULLUP
PB5
MSTR
SPE
SPI SS
RD
RESET
R
D
Q
DDB5
C
WD
RESET
R
Q
D
PORTB5
C
RL
WP
RP
DATA BUS
96
ATmega161(L)
WRITE PORTB
WP:
WRITE DDRB
WD:
READ PORTB LATCH
RL:
READ PORTB PIN
RP:
READ DDRB
RD:
SPI ENABLE
SPE:
MASTER SELECT
MSTR
MSTR
SPE
SPI MASTER
OUT
SPI SLAVE
IN
1228C–AVR–08/02
Figure 61. Port B Schematic Diagram (Pin PB6)
MOS
PULLUP
PB6
WRITE PORTB
WP:
WRITE DDRB
WD:
READ PORTB LATCH
RL:
READ PORTB PIN
RP:
READ DDRB
RD:
SPI ENABLE
SPE:
MASTER SELECT
MSTR
ATmega161(L)
RD
RESET
R
D
Q
DDB6
C
WD
RESET
R
Q
D
PORTB6
C
RL
WP
RP
MSTR
SPE
SPI SLAVE
OUT
SPI MASTER
IN
DATA B US
Figure 62. Port B Schematic Diagram (Pin PB7)
MOS
PULLUP
PB7
WRITE PORTB
WP:
WRITE DDRB
WD:
READ PORTB LATCH
RL:
READ PORTB PIN
RP:
READ DDRB
RD:
SPI ENABLE
SPE:
MASTER SELECT
MSTR
RD
RESET
R
D
Q
DDB7
C
WD
RESET
R
Q
D
PORTB7
C
RL
WP
RP
MSTR
SPE
SPI ClLOCK
OUT
SPI CLOCK
IN
DATA B US
1228C–AVR–08/02
97
Port CPort C is an 8-bit bi-directional I/O port.
Three I/O memory address locations are allocated for the Port C, one each for the Data
Register – PORTC, $15($35), Data Direction Register – DDRC, $14($34) and the Port C
Input Pins – PINC, $13($33). The Port C Input Pins address is read-only, while the Data
Register and the Data Direction Register are read/write.
All port pins have individually selectable pull-up resistors. The Port C output buffers can
sink 20 mA and thus drive LED displays directly. When pins PC0 to PC7 are used as
inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated.
The Port C pins have alternate functions related to the optional external memory interface. Port C can be configured to be the high-order address byte during accesses to
external Data memory.
When Port C is set to the alternate function by the SRE (External SRAM Enable) bit in
the MCUCR (MCU Control Register), the alternate settings override the Data Direction
Register.
The Port C Input Pins address (PINC) is not a register; this address enables access to
the physical value on each Port C pin. When reading PORTC, the Port C Data Latch is
read and when reading PINC, the logical values present on the pins are read.
Port C as General Digital I/OAll eight pins in Port C have equal functionality when used as digital I/O pins.
PCn, general I/O pin: The DDCn bit in the DDRC Register selects the direction of this
pin. If DDCn is set (one), PCn is configured as an output pin. If DDCn is cleared (zero),
PCn is configured as an input pin. If PORTCn is set (one) when the pin is configured as
an input pin, the MOS pull-up resistor is activated. To switch the pull-up resistor off,
PORTCn has to be cleared (zero) or the pin has to be configured as an output pin. The
Port C pins are tri-stated when a reset condition becomes active, even if the clock is not
running.
98
ATmega161(L)
1228C–AVR–08/02
ATmega161(L)
Table 32. DDCn Effects on Port C Pins
DDCnPORTCnI/OPull-upComment
00InputNoTri-state (high-Z)
01InputYesPCn will source current if ext. pulled low
10OutputNoPush-pull Zero Output
11OutputNoPush-pull One Output
Note:1. n:7,6,…0, pin number
(1)
Port C SchematicsNote that all port pins are synchronized. The synchronization latch is, however, not
shown in the figure.
Figure 63. Port C Schematic Diagram (Pins PC0 - PC7)
1228C–AVR–08/02
99
Port DPort D is an 8-bit bi-directional I/O port with internal pull-up resistors.
Three I/O address locations are allocated for the Port D, one each for the Data Register
– PORTD, $12($32), Data Direction Register – DDRD, $11($31) and the Port D Input
Pins – PIND, $10($30). The Port D Input Pins address is read-only, while the Data Register and the Data Direction Register are read/write.
The Port D output buffers can sink 20 mA. As inputs, Port D pins that are externally
pulled low will source current if the pull-up resistors are activated.
Some Port D pins have alternate functions as shown in Table 33.
Table 33. Port D Pin Alternate Functions
Port PinAlternate Function
PD0RXD0 (UART0 Input Line)
PD1TXD0 (UART0 Output Line)
PD2INT0 (External Interrupt0 Input)
PD3INT1 (External Interrupt1 Input)
PD3TOSC1 (RTC Oscillator Timer/Counter2)
Port D Data Register – PORTD
Port D Data Direction Register
– DDRD
Port D Input Pins Address –
PIND
PD5
PD6WR
PD7RD
TOSC2 (RTC Oscillator Timer/Counter2)/OC1A (Timer/Counter1 Output
CompareA Match Output)
(Write Strobe to External Memory)
(Read Strobe to External Memory)
When the PD5 pin is used for the alternate function (OC1A), the DDRD and PORTD
Registers have to be set according to the alternate function description.
The Port D Input Pins address (PIND) is not a register; this address enables access to
the physical value on each Port D pin. When reading PORTD, the Port D Data Latch is
read and when reading PIND, the logical values present on the pins are read.
Port D as General Digital I/OPDn, general I/O pin: The DDDn bit in the DDRD Register selects the direction of this
pin. If DDDn is set (one), PDn is configured as an output pin. If DDDn is cleared (zero),
PDn is configured as an input pin. If PORTDn is set (one) when configured as an input
pin, the MOS pull-up resistor is activated. To switch the pull-up resistor off, the PORTDn
100
ATmega161(L)
1228C–AVR–08/02
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.