– 123 Powe rful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 20 MIPS Throughput at 20 MHz
• High Endurance Non-volatile Memory Segments
– 2/4/8K Bytes of In-System Self-Programmable Flash Program Memory
• Endurance: 10,000 Write/Erase Cycles
– 128/256/512 Bytes of In-System Programmable EEPROM
• Endurance: 100,000 Write/Erase Cycles
– 128/256/512 Bytes of Internal SRAM
– Data retention: 20 Years at 85°C / 100 Years at 25°C
– In-System Programmab le via SPI Port
– Programming Lock for Software Security
• Peripheral Features
– One 8/16-bit Timer/Counter with Prescaler
– One 8/10-bit High Speed Timer/Counter with Prescaler
• 3 High Frequency PWM Outputs with Separate Output Compare Registers
• Programmable Dead Time Generator
– 10-bit ADC
• 11 Single-Ended Channels
• 16 Differential ADC Channel Pairs
• 15 Differential ADC Channel Pairs with Programmab le Gain (1x, 8x, 20x, 32x)
– On-Chip Analog Comparator
– Programmable Watchdog Timer with Separate On-Chip Oscillator
– Universal Serial Interface with Start Condition Detector
– Interrupt and Wake-up on Pin Change
• Special Microcontroller Features
– debugWIRE On-Chip Debug System
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated Oscillator
– External and Internal Interrupt Sources
– Four Sleep Modes: Low Power Idle, ADC Noise Reduction, Standby and Power-
Note:To ensure mechanical stability the center pad unde rneath the QFN/MLF package should be soldered to ground on the board.
2
ATtiny261A/461A/861A
8197C–AVR–05/11
1.1Pin Descriptions
1.1.1VCC
Supply voltage.
1.1.2GND
Ground.
1.1.3AVCC
Analog supply voltage. This is the supply voltage pin for the Analog-to-digital Converter (ADC),
the analog comparator, the Brown-Out Detector (BOD), the internal voltage reference and Port
A. It should be externally connected to VCC, even if some peripherals such as the ADC are not
used. If the ADC is used AVCC should be connected to VCC through a low-pass filter.
1.1.4AGND
Analog ground.
1.1.5Port A (PA7:PA0)
An 8-bit, bi-directional I/O port with internal pull-up resistors, individually selectable for each bit.
Output buffers have symmetrical drive characteristics with both high sink and source capability.
As inputs, port pins that are externally pulled low will source current if pull-up resistors have
been activated. Port pins are tri-stated when a reset condition becomes active, even if the clock
is not running.
ATtiny261A/461A/861A
Port A also serves the functions of various special features of the device, as listed on page 62.
1.1.6Port B (PB7:PB0)
An 8-bit, bi-directional I/O port with internal pull-up resistors, individually selectable for each bit.
Output buffers have symmetrical drive characteristics with both high sink and source capability.
As inputs, port pins that are externally pulled low will source current if pull-up resistors have
been activated. Port 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 device, as listed on page 65.
1.1.7
RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running and provided the reset pin ha s not been disabled. Th e minimum pulse length is given in Table 19-4 on page 188. Shorter pulses are not guaranteed to
generate a reset.
The reset pin can also be used as a (weak) I/O pin.
8197C–AVR–05/11
3
2.Overview
2.1Block Diagram
ATtiny261A/461A/861A are low-power CMOS 8-bit microcontrollers based on the AVR
enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the
devices achieve throughputs approa ching 1 MIPS pe r MHz allowing the system designe r to optimize power consumption versus processing speed.
Figure 2-1.Block Diagram
DATABUS
GND
Watchdog
Timer
Watchdog
Oscillator
Oscillator
Circuits /
Clock
Generation
EEPROM
Timer/Counter0A/D Conv.
USI
Power
Supervision
POR / BOD &
RESET
Timer/Counter1
Analog Comp.
VCC
debugWIRE
PROGRAM
LOGIC
SRAMFlash
CPU
Internal
Bandgap
AVCC
AGND
AREF
3
PORT A (8)PORT B (8)
PA[0:7]PB[0:7]
11
RESET
XTAL[1:2]
The AVR core combines a rich instruction set with 32 general purpose working registers. All 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.
4
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
The ATtiny261A/461A/861A prov ides the follow ing featu res: 2/4/8K byte of In-Syste m Program mable Flash, 128/256/512 bytes EEPROM, 128/256/512 bytes SRAM, 16 general purpose I/O
lines, 32 general purpose working registers, an 8-bit Timer/Counter with compare modes, an 8bit high speed Timer/Counter, a Universal Serial Interface, Internal and External Interrupts, an
11-channel, 10-bit ADC, a programmable Watchdog Timer with internal oscillator, and four software selectable power saving modes. Idle mode stops the CPU while allowing the SRAM,
Timer/Counter, ADC, Analog Comparator, and Interrupt system to continue functioning. Powerdown mode saves the register contents, disabling all chip functions until the next Interrupt or
Hardware Reset. ADC Noise Reduction mode stops the CPU and all I/O modules except ADC,
to minimize switching noise during ADC conversions. In Standby mode, the crystal/resonator
oscillator is running while the rest of the device is sleeping, allowing very fast start-up combined
with low power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The
On-chip ISP Flash allows the Program memory to be re-programmed In-System through an SPI
serial interface, by a conventional non-volatile memory programmer or by an On-chip boot code
running on the AVR core.
The ATtiny261A/461A/861A AVR is supported by a full suite of program and system development tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators, and
Evaluation kits.
8197C–AVR–05/11
5
3.General Information
3.1Resources
A comprehensive set of drivers, application notes, data sheet s and descr iption s on development
tools are available for download at http://www.atmel.com/avr.
3.2Code Examples
This documentation contains simple code examples t hat brief ly show h ow to us e various parts of
the device. These code examples assume that the part specific header file is included b efore
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent . Please con firm wit h the C com piler d ocume ntation for more details.
For I/O Registers located in the extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI”
instructions must be replaced with instructions that allow access to extended I/O. Typically, this
means “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”. Note that not all
AVR devices include an extended I/O map.
3.3Capacitive Touch Sensing
Atmel QTouch Library provides a simple to use solution for touch sensitive interfaces on Atmel
AVR microcontrollers. The QTouch Library includes support for QTouch
tion methods.
®
and QMatrix® acquisi-
3.4Data Retention
Touch sensing is easily added to any application by linking the QTouch Library and using the
Application Programming Interface (API) of the library to define th e touch ch annels and senso rs.
The application then calls the API to retrieve channel information and determine the state of the
touch sensor.
The QTouch Library is free and can be downloaded from the Atmel website. For more information and details of implementation, refer to the QTouch Library User Guide – also available from
the Atmel website.
Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.
6
ATtiny261A/461A/861A
8197C–AVR–05/11
4.CPU Core
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
Watchdog
Timer
Analog
Comparator
I/O Module 2
I/O Module1
I/O Module n
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
4.1Architectural Overview
Figure 4-1.Block Diagram of the AVR Architecture
ATtiny261A/461A/861A
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the Program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the Program memo ry. This concept enables instructions to be executed
in every clock cycle. The Program memory is In-System Reprogrammable Flash memory.
8197C–AVR–05/11
7
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointe rs
can also be used as an address pointer for look up tables in Flash Program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the AL U. After an arith metic operation, the Status Register is updated to reflect informat ion about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every Program memory address contains a 16- or 32-bit instruction.
During interrupts and subroutine calls, the return address Prog ram Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O memory can be acces sed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F.
4.2ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a register and an immediate are execut ed . The ALU ope ra tio ns are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction Set” section for a detailed description.
4.3Status Register
The Status Register contains information abou t th e result o f th e most r ecently exe cuted arith metic instruction. This information can be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Refe rence. This wil l in many cases remove the n eed for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Register is neither automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt. This must be handled by software.
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.
ATtiny261A/461A/861A
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful
in BCD arithmetic. See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N
⊕ V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
8197C–AVR–05/11
9
4.4General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order t o achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 4-2 below shows the structure of the 32 general purpose working registe rs in the CPU.
Figure 4-2.AVR CPU General Purpose Working Registers
GeneralR140x0E
PurposeR150x0F
WorkingR160x10
RegistersR170x11
70Addr.
R0 0x00
R10x01
R20x02
…
R130x0D
…
R260x1AX-register Low Byte
R270x1BX-register High Byte
R280x1CY-register Low Byte
R290x1DY-register High Byte
R300x1EZ-register Low Byte
R310x1FZ-register High Byte
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 4-2, each register is also assigned a Data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
4.4.1The X-register, Y-register, and Z-register
The registers R26:R31 have some added functions to their gener al purpose usage. Th ese registers are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 4-3.
Figure 4-3.The X-, Y-, and Z-registers
15XHXL0
X-register7070
R27 (0x1B)R26 (0x1A)
10
ATtiny261A/461A/861A
8197C–AVR–05/11
4.5Stack Pointer
ATtiny261A/461A/861A
15YHYL0
Y-register7070
R29 (0x1D)R28 (0x1C)
15ZHZL0
Z-register7070
R31 (0x1F)R30 (0x1E)
In different addressing modes these address registers function as automatic increment and
automatic decrement (see the instruction set reference for details).
The Stack is mainly used for storing temporary dat a, local variables and return add resses for
interrupts and subroutine calls. The Stack Pointer Register alwa ys point s to th e top of th e Sta ck,
in the data SRAM Stack area where the subroutine and interrupt stacks are located.
The Stack in the data SRAM must be defined by the program before any subroutine calls ar e
executed or interrupts are enabled. The Stack Pointer must be set to point above start of the
SRAM (see Figure 5-2 on page 16). The initial Stack Pointer value equals th e last address of the
internal SRAM.
Note that the Stack is implemented as growing from higher to lower memory locations. This
means a Stack PUSH command decreases the Stack Pointer. See Table 4-1.
Table 4-1.Stack Pointer instructions
InstructionStack pointerDescription
PUSHDecremented by 1Data is pushed onto the stack
ICALL
RCALL
Decremented by 2
POPIncremented by 1Data is popped from the stack
RET
RETI
Incremented by 2
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent.
Note that the data space in some implementations of the AVR architecture is so small that only
SPL is needed. In this case, the SPH Register will not be present.
Return address is pushed onto the stack with a
subroutine call or interrupt
Return address is popped from the stack with return
from subroutine or return from interrupt
8197C–AVR–05/11
11
4.6Instruction Execution Timing
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1T2T3T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1T2T3T4
clk
CPU
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clk
chip. No internal clock division is used.
Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Har-
vard architecture and the fast access Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
Figure 4-4.The Parallel Instruction Fetches and Instruction Executions
, directly generated from the selected clock source for the
CPU
4.7Reset and Interrupt Handling
12
ATtiny261A/461A/861A
Figure 4-5 shows the internal timing concept for th e Regi ster File . In a single clock cycl e an ALU
operation using two register operands is executed, and the result is stored back to the destination register.
Figure 4-5.Single Cycle ALU Operation
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate Program Vector in the Program memory space. All interrupts are
assigned individual enable bits which must be written logic one toge ther with the Glo bal Interru pt
Enable bit in the Status Register in order to enable the int errupt.
The lowest addresses in the Program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 49. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
8197C–AVR–05/11
ATtiny261A/461A/861A
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt
Request 0.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the fl ag bit position(s)
to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is
cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is
cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt
Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the
Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Int errupt Flags. If the interrup t condition disappears before t he
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt rou tine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.
Assembly Code Example
in r16, SREG; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE; start EEPROM write
sbi EECR, EEPE
out SREG, r16; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1<<EEMPE); /* start EEPROM write */
EECR |= (1<<EEPE);
SREG = cSREG; /* restore SREG value (I-bit) */
8197C–AVR–05/11
Note:See “Code Examples” on page 6.
13
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in the following examples.
Assembly Code Example
sei; set Global Interrupt Enable
sleep; enter sleep, waiting for interrupt
C Code Example
_SEI(); /* set Global Interrupt Enable */
_SLEEP(); /*enter sleep, waiting for interrupt */
Note:See “Code Examples” on page 6.
4.7.1Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the Program Vector address for the a ctual interru pt handling routine
is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack.
The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If
an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed
before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt
execution response time is increased by four clock cycles. This increase comes in ad dition to the
start-up time from the selected sleep mode.
; note: will enter sleep before any pending interrupt(s)
/* note: will enter sleep before any pending interrupt(s) */
A return from an interrupt handling routine takes four clock cycles. During these four clock
cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is
incremented by two, and the I-bit in SREG is set.
14
ATtiny261A/461A/861A
8197C–AVR–05/11
5.Memories
0x0000
0x03FF/0x07FF/0x0FFF
Program Memory
This section describes the different memories of the ATtiny261A/461A/861A. The AVR architecture has two main memory spaces, the Data memory and the Program memory space. In
addition, the ATtiny261A/461A/861A features an EEPROM Memory for data storage. All three
memory spaces are linear and regular.
5.1In-System Re-programmable Flash Program Memory
The ATtiny261A/461A/861A contains 2/4/8K byte On-chip In-System Reprogrammable Flash
memory for program storage. Since all AVR instructions are 16 or 32 bits wide , the Flash is organized as 1024/2048/4096 x 16.
The Flash memory has an endurance of at least 10,000 write/erase cycles. The
ATtiny261A/461A/861A Program Counter (PC) is 10/1 1/12 bits wide, thus capable of add ressing
the 1024/2048/4096 Program memory locations. “Memory Programming” on page 168 contains
a detailed description on Flash data serial downloading using the SPI pins.
Constant tables can be allocated within the entire address space of progra m memory (see the
LPM – Load Program memory instruction description).
Timing diagrams for instruction fetch and execution are presented in “Instruction Execution Tim-
ing” on page 12.
ATtiny261A/461A/861A
Figure 5-1.Program Memory Map
5.2SRAM Data Memory
Figure 5-2 on page 16 shows how the ATtiny261A/461A/861A SRAM Me mory is organized.
The lower data memory locations address both the Register File, the I/O memory and the internal data SRAM. The first 32 locations address the Register File, the next 64 locations the
standard I/O memory, and the last 128/256/512 locations address the internal data SRAM.
The five different addressing modes for the Data memory cover: Dire ct, 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.
8197C–AVR–05/11
The direct addressing reaches the entire data space.
The Indirect with Displacement mode reaches 63 address locations f rom the base address given
by the Y- or Z-register.
15
When using register indirect addressing modes with automatic pre-decrement and post-incre-
32 Registers
64 I/O Registers
Internal SRAM
(128/256/512 x 8)
0x0000 - 0x001F
0x0020 - 0x005F
0x0DF/0x15F/0x25F
0x0060
Data Memory
clk
WR
RD
Data
Data
Address
Address valid
T1T2T3
Compute Address
Read
Write
CPU
Memory Access Instruction
Next Instruction
ment, the address registers X, Y, and Z are decremented or incremented.
The 32 general purpose working registers, 64 I/O Registers, and the 128/256/512 bytes of inter-
nal data SRAM in the ATtiny261A/461A/861A are all accessible through all these addressing
modes. The Register File is described in “General Purpose Register File” on page 10.
Figure 5-2.Data Memory Map
5.2.1Data Memory Access Times
This section describes the general access timing concepts for internal memory access. The
internal data SRAM access is performed in two clk
Figure 5-3.On-chip Data SRAM Access Cycles
cycles as illustrated in Figure 5-3.
CPU
5.3EEPROM Data Memory
16
The ATtiny261A/461A/861A contains 128/256/512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM
has an endurance of at least 100,000 writ e/erase cycles. Th e access between the EEPROM and
the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM
Data Register, and the EEPROM Control Register. For a detailed description of Serial data
downloading to the EEPROM, see “Electrical Characteristics” on page 185.
ATtiny261A/461A/861A
8197C–AVR–05/11
5.3.1EEPROM Read/Write Access
The EEPROM Access Registers are accessible in the I/O space.
The write access times for the EEPROM are given in Table 5-1 on page 22. A self-timing func-
tion, however, lets the user software detect when the next byte can be written. If the user code
contains instructions that write the EEPROM, some precautions must be taken. In heavily filtered power supplies, V
device for some period of time to run at a voltage lower than specified as minimum for the clock
frequency used. See “Preventing EEPROM Corruption” on page 19 for details on how to avoid
problems in these situations.
In order to prevent unintentional EEPROM writes, a specific write procedure must be followed.
Refer to “Atomic Byte Programming” on page 17 and “Split Byte Programming” on page 17 for
details on this.
When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is
executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next
instruction is executed.
5.3.2Atomic Byte Programming
Using Atomic Byte Programming is the simplest mode. When writing a byte to the EEPROM, the
user must write the address into the EEARL Register and data into EEDR Register. If the
EEPMn bits are zero, writing EEPE (within four cycles after EEMPE is written) will trigger the
erase/write operation. Both the erase and write cycle are done in one operation and the total
programming time is given in Table 5-1 on page 22. The EEPE bit remains set until the erase
and write operations are completed. While the device is busy with programming, it is not possible to do any other EEPROM operations.
ATtiny261A/461A/861A
is likely to rise or fall slowly on Power-up/down. This causes the
CC
5.3.3Split Byte Programming
It is possible to split the erase and write cycle in two different operations. This may be useful if
the system requires short access time for some limited period of time (typically if the power supply voltage falls). In order to take advantage of this method, it is required that the locations to be
written have been erased before the write operation. But since the erase and write operations
are split, it is possible to do the erase operations whe n the system allows doing time-critical
operations (typically after Power-up).
5.3.4Erase
To erase a byte, the address must be written to EEAR. If the EEPMn bits are 0b01, writing the
EEPE within four cycles after EEMPE is written will trigger the erase operation only (programming time is given in Table 5-1 on page 22). The EEPE bit remains set until the erase operation
completes. While the device is busy programming, it is not possible to do any other EEPROM
operations.
5.3.5Write
To write a location, the user must write the address into EEAR and the data into EEDR. If the
EEPMn bits are 0b10, writing the EEPE (within four cycles after EEMPE is written) will trigger
the write operation only (programming time is given in Table 5-1 on page 22). The EEPE bit
remains set until the write operation completes. If the location to be written has not been erased
before write, the data that is stored must be considered as lost. While the device is busy with
programming, it is not possible to do any other EEPROM operations.
8197C–AVR–05/11
17
The calibrated Oscillator is used to time the EEPROM accesses. Make sure the Oscillator frequency is within the requirements described in “OSCCAL – Oscillator Calibration Register” on
page 32.
5.3.6Program Examples
The following code examples show one assembly and one C function for erase, write, or atomic
write of the EEPROM. The examples assume that interrupts are controlled (e.g., by disabling
interrupts globally) so that no interrupts will occur during execution of these functions.
The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of
these functions.
During periods of low V
too low for the CPU and the EEPROM to operate properly. These issues a re the same as for
board level systems using 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 is too low.
, the EEPROM data can be corrupted because the supply voltage is
CC
8197C–AVR–05/11
EEPROM data corruption can easily be avoided by following this design recommendation:
Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can
be done by enabling the internal Brown-out Detector (BOD). If the detection level of the internal
BOD does not match the needed detection level, an external low V
reset protection circuit can
CC
19
5.4I/O Memory
be used. If a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient.
The I/O space definition of the ATtiny261A/461A/861A is shown in “Register Summary” on page
277.
All I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed using the
LD/LDS/LDD and ST/STS/STD instructions, enabling data transfer between the 32 general purpose working registers and the I/O space. I/O Registers within the address range 0x00 - 0x1F
are directly bit-accessible using the SBI and CBI instructions. In these r egister s, the value o f single bits can be checked by using the SBIS and SBIC instructions. Refer to the instruction set
section for more details. When using the I/O specific commands IN and OUT, the I/O addresses
0x00 - 0x3F must be used. When addressing I/O Registers as data space using LD and ST
instructions, 0x20 must be added to these addresses.
For compatibility with future devices, reserved bits should be written to zero if accessed.
Reserved I/O memory addresses should never be written.
Some of the Status Flags are cleared by writing a logical one to them. Note that, the CBI and
SBI instructions will only operate on the specified bit, and can therefore be used on registers
containing such Status Flags. The CBI and SBI instructions work on registers in the address
range 0x00 to 0x1F, only.
The I/O and Peripherals Control Registers are explained in later sections.
5.4.1General Purpose I/O Registers
The ATtiny261A/461A/861A contains three General Purpose I/O Registers. These registers can
be used for storing any information, and they are particularly useful for storing global variables
and Status Flags. General Purpose I/O Registers within the address range 0x00 - 0x1F are
directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
These bits are reserved and will always read as zero.
• Bit 0 – EEAR8: EEPROM Address
This is the most significant EEPROM address bit of ATtiny861A. In devices with less EEPROM,
i.e. ATtiny261A/ATtiny461A, this bit is reserved and will always read zero. The initial value of the
EEPROM Address Register (EEAR) is undefined and a proper value must therefore be written
before the EEPROM is accessed.
This is the most significant EEPROM address bit of ATtiny461A. In devices with less EEPROM,
i.e. ATtiny261A, this bit is reserved and will always read zero. The initial value of the EEPROM
Address Register (EEAR) is undefined and a proper value must therefore be written before the
EEPROM is accessed.
• Bits 6:0 – EEAR[6:0]: EEPROM Address
These are the (low) bits of the EEPROM Address Register. The EEPROM data bytes are
addressed linearly in the range 0
proper value must be therefore be written before the EEPROM may be accessed.
...128/256/512. The initial value of EEAR is undefined and a
• Bits 7:0 – EEDR[7:0]: EEPROM Data
For the EEPROM write operation the EEDR Register contains the data to be written to the
EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the
EEDR contains the data read out from the EEPROM at the address given by EEAR.
This bit is reserved for future use and will always read zero. For compatibility with future AVR
devices, always write this bit to zero. After reading, mask out this bit.
• Bit 6 – Res: Reserved Bit
This bit is reserved and will always read as zero.
The EEPROM Programming mode bits setting defines which programming action that will be
triggered when writing EEPE. It is possible to program data in on e atomic operation (e rase the
8197C–AVR–05/11
21
old value and program the new value) or to split the Erase and Write operations in two different
operations. The Programming times for the different modes are shown in Table 5-1.
Table 5-1.EEPROM Mode Bits
Programming
EEPM1EEPM0
003.4 msErase and Write in one operation (Atomic Operation)
011.8 msErase Only
101.8 msWrite Only
11–Reserved for future use
TimeOperation
When EEPE is set, any write to EEPMn will be ignored. During reset, the EEPMn bits will be
reset to 0b00 unless the EEPROM is busy programming.
• Bit 3 – EERIE: EEPROM Ready Interrupt Enable
Writing EERIE to one enables the EEPROM Ready Interrupt if the I-bit in SREG is set. Writing
EERIE to zero disables the interrupt. The EEPROM Ready Interrupt generates a constant interrupt when Non-volatile memory is ready for programming.
• Bit 2 – EEMPE: EEPROM Master Program Enable
The EEMPE bit determines whether writing EEPE to one will have effect or not.
When EEMPE is set, setting EEPE within four clock cycles will program the EEPROM at the
selected address. If EEMPE is zero, setting EEPE will have no effect. When EEMPE has been
written to one by software, hardware clears the bit to zero after four clock cycles.
• Bit 1 – EEPE: EEPROM Program Enable
The EEPROM Program Enable Signal EEPE is the programming enable signal to the EEPROM.
When EEPE is written, the EEPROM will be programmed according to the EEPMn bits setting.
The EEMPE bit must be written to one before a logical one is written to EEPE, otherwise no
EEPROM write takes place. When the write access time has elapsed, the EEPE bit is cleared
by hardware. When EEPE has been set, the CPU is halted for two cycles before the next
instruction is executed.
• Bit 0 – EERE: EEPROM Read Enable
The EEPROM Read Enable Signal – EERE – is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be written to one to trigger the
EEPROM read. The EEPROM read access takes one instruction, and the requested data is
available immediately. When the EEPROM is read, the CPU is halted for four cycles before the
next instruction is executed. The user should poll the EEPE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change
the EEAR Register.
Figure 6-1 presents the principal clock systems and their distribution. All of the clocks need not
be active at a given time. In order to reduce power consumption, the clocks to modules not being
used can be halted by using different sleep modes, as described in “Power Managem ent and
Sleep Modes” on page 35.
Figure 6-1.Clock Distribution
6.1Clock Subsystems
6.1.1CPU Clock – clk
6.1.2I/O Clock – clk
24
ATtiny261A/461A/861A
The clock subsystems are detailed in the sections below.
CPU
The CPU clock is routed to parts of the system concerned with operation of the AVR core.
Examples of such modules are the General Purpose Register File, the Status Register and the
Data memory holding the Stack Pointer. Halting the CPU clock inhibits the core from performing
general operations and calculations.
I/O
The I/O clock is used by the majority o f the I/O modules, like T imer/Counter. The I/O clock is
also used by the External Interrupt module, but note that some external interrupts are detected
by asynchronous logic, allowing such interrupts to be detected even if the I/O clock is halted.
8197C–AVR–05/11
ATtiny261A/461A/861A
6.1.3Flash Clock – clk
FLASH
The Flash clock controls operation of the Flash inte rface. The Fla sh clock is usually active simultaneously with the CPU clock.
6.1.4ADC Clock – clk
ADC
The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks
in order to reduce noise generated by digital cir cuit ry. Th is gives mo re accurat e ADC conversion
results.
6.1.5Fast Peripheral Clock – clk
Selected peripherals can be clocked at a frequency higher than the CPU core. The fast peripheral clock is generated by an on-chip PLL circuit.
6.1.6PLL System Clock – clk
ADC
The PLL can also be used to generate a system clock. The clock signal can be prescaled to
avoid overclocking the CPU.
6.2Clock Sources
The device has the following clock source options, selec table by Flash Fuse bits as shown
below. The clock from the selected so ur ce is i npu t to th e AVR clo c k gene ra to r, and r ou te d to t he
appropriate modules.
Table 6-1.Device Clocking Options Select
PCK
(1)
vs. PB4 and PB5 Functionality
Device Clocking Option CKSEL[3:0]PB4PB5
External Clock (see page 26)0000XTAL1I/O
High-Frequency PLL Clock (see page 26)0001I/OI/O
Calibrated Internal 8 MHz Oscillator (see page 28)0010I/OI/O
Internal 128 kHz Oscillator (see page 29)0011I/OI/O
Low-Frequency Crystal Oscillator (see page 29)01xxXTAL1XTAL2
Crystal Oscillator / Ceramic Resonator
0.4...0.9 MHz (see page 30)
Crystal Oscillator / Ceramic Resonator
0.9...3.0 MHz (see page 30)
Crystal Oscillator / Ceramic Resonator
3...8 MHz (see page 30)
Crystal Oscillator / Ceramic Resonator
8...20 MHz (see page 30)
Note:1. For all fuses “1” means unprogrammed and “0” means programmed.
1000
1001
1010
1011
1100
1101
1110
1111
XTAL1XTAL2
XTAL1XTAL2
XTAL1XTAL2
XTAL1XTAL2
The various choices for each clocking option is given in the following sections. When the CPU
wakes up from Power-down or Power-save, the selected clock source is used to time the startup, ensuring stable oscillator operation before instruction execution starts. When the CPU starts
from reset, there is an additional delay allowing the power to reach a stable level before com-
8197C–AVR–05/11
25
6.2.1External Clock
EXTERNAL
CLOCK
SIGNAL
CLKI
GND
mencing normal operation. The watchdog oscillator is used for timing this real-time part of the
start-up time. The number of WD oscillator cycles used for each time-out is shown in Table 6-2.
Table 6-2.Number of Watchdog Oscillator Cycles
Typ Time-outNumber of Cycles
4 ms512
64 ms8K (8,192)
To drive the device from an extern al cloc k source, CLKI should be driven as shown in Figure 6-
2. To run the device on an external clock, the CKSEL Fuses must be programmed to “0000”.
Figure 6-2.External Clock Drive Configuration
6.2.2High-Frequency PLL Clock
When this clock source is selected, start-up times are determined by the SUT Fuses as shown in
Table 6-3.
Table 6-3.Start-up Times for the External Clock Selection
Start-up Time from Power-
SUT[1:0]
006 CK14CKBOD enabled
016 CK14CK + 4 msFast rising power
106 CK14CK + 64 msSlowly rising power
11Reserved
When applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable operation of the MCU. A variation in frequency of more than 2% from
one clock cycle to the next can lead to unpredictable behavior. It is required to ensure that the
MCU is kept in Reset during such changes in the clock frequency.
Note that the system clock prescale r can be us ed to implem ent run- time c hange s of th e inte rnal
clock frequency. See “System Clock Prescaler” on page 31 for details.
The internal PLL generates a clock signal with a frequency eight times higher than the source
input. The PLL uses the output of the internal 8 MHz oscillator as source and the default setting
generates a fast peripheral clock signal of 64 MHz.
down and Power-save
Additional Delay from
ResetRecommended Usage
26
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
1/2
8 MHz
LSM
8 MHz
OSCILLATOR
PLL
8x
CKSEL3:0PLLEOSCCAL
4 MHz
1/4
LOCK
DETECTOR
PRESCALER
CLKPS3:0
clk
PLL
PLOCK
clk
PCK
OSCILLATORS
XTAL1
XTAL2
64 / 32 MHz
8 MHz
16 MHz
The fast peripheral clock, clk
prescaled version of the PLL output, clk
, can be selected as the clock source for Timer/Counter1 and a
PCK
, can be selected as system clock. See Figure 6-3 for
PLL
a detailed illustration on the PLL clock system.
Figure 6-3.PCK Clocking System
The internal PLL is enabled when CKSEL fuse bits are programmed t o ‘0001’an d the PLLE bit of
PLLCSR is set. The internal oscillator and the PLL are switched off in power down and stand-by
sleep modes.
When the LSM bit of PLLCSR is set, the PLL switches from using the output of the internal 8
MHz oscillator to using the output divided by two. The frequency of the fast peripheral clock is
effectively divided by two, resulting in a clock freque ncy of 3 2 MHz. T he LSM bit can no t be set if
PLL
is used as a system clock.
CLK
Since the PLL is locked to the output of the internal 8 MHz oscillator, adjusting the oscillator frequency via the OSCCAL register also changes the frequency of the fast peripheral clock. It is
possible to adjust the frequency of the internal oscillator to well above 8 MHz but the fast peripheral clock will saturate and remain oscillating at about 85 MHz. In this case the PLL is no longer
locked to the internal oscillator clock signal. Therefore, in order to keep the PLL in the correct
operating range, it is recommended to program the OSCCAL registers such that the oscillator
frequency does not exceed 8 MHz.
8197C–AVR–05/11
The PLOCK bit in PLLCSR is set when PLL is locked.
Programming CKSEL fuse bits to ‘0001’, the PLL output divided by four will be used as a system
clock, as shown in Table 6-4.
Table 6-4.PLLCK Operating Modes
CKSEL[3:0]Nominal Frequency
000116 MHz
27
When the PLL output is selected as clock source, the start-up t imes are deter mined by SUT fuse
bits as shown in Table 6-5.
By default, the Internal Oscillator provides an approximately 8 MHz clock signal. Though voltage
and temperature dependent, this clock can be very accurately calibrated by the user. See Table
19-2 on page 187 and “Internal Oscillators” on page 222 for more details. The device is shipped
with the CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 31 for more details.
This clock may be selected as the system cloc k by p rogr am m in g th e CKS E L Fus es a s sh own in
Table 6-6. If selected, it will operate with no external components. During reset, hardware loads
the pre-programmed calibration value into th e OSCCAL Re giste r a nd the reby aut omat ica lly calibrates the internal oscillator. The accuracy of this calibration is shown as Factory calibration in
Notes:1. The device is shipped with this option selected.
2. If the oscillator frequency exceeds the specification of the device (depends on V
CKDIV8 Fuse can be programmed to divide the internal frequency by 8.
CC
), the
When this oscillator is selected, start-up times are determined by SUT fuses as shown in Table
6-7.
Table 6-7.Start-up Times for the Internal Calibrated Oscillator Clock Selection
Start-up Time
SUT[1:0]
006 CK14CK
016 CK14CK + 4 msFast rising power
(2)
10
11Reserved
Note:1. If the RSTDISBL fuse is programmed, this start-up time will be increa sed to 14CK + 4 ms to
ensure programming mode can be entered.
2. The device is shipped with this option selected.
from Power-down
6 CK14CK + 64 msSlowly rising power
Additional Delay from
Reset (VCC = 5.0V)
(1)
Recommended
Usage
BOD enabled
28
ATtiny261A/461A/861A
8197C–AVR–05/11
It is possible to reach a higher accuracy than factory calibration by changing the OSCCAL register from software. See “OSCCAL – Oscillator Calibration Register” on page 32. The accuracy of
this calibration is shown as User calibration in Table 19-2 on page 187.
When this oscillator is used as device clock, the Watchdog Oscillator will still be used for the
Watchdog Timer and for the Reset Time-out. For more information on the pre-programmed calibration value, see section “Calibration Byte” on page 170.
6.2.4Internal 128 kHz Oscillator
The 128 kHz internal oscillator is a low power oscillator providing a clock of 128 kHz. The frequency depends on supply voltage, temperature and batch variations. This clock may be select
as the system clock by programming the CKSEL Fuses to “0011”.
When this clock source is selected, start-up times are determined by the SUT Fuses as shown in
Table 6-8.
Table 6-8.Start-up Times for the 128 kHz Internal Oscillator
ATtiny261A/461A/861A
Start-up Time from Power-
SUT[1:0]
006 CK14CK
016 CK14CK + 4 msFast rising power
106 CK14CK + 64 msSlowly rising power
11Reserved
Note:1. If the RSTDISBL fuse is programmed, this start-up time will be increa sed to 14CK + 4 ms to
down and Power-save
ensure programming mode can be entered.
6.2.5Low-Frequency Crystal Oscillator
To use a 32.768 kHz watch crystal as the clock source for the device, the low-frequency crystal
oscillator must be selected by setting CKSEL fuses to ‘0100’. The crystal should be connected
as shown in Figure 6-4. To find suitable capacitors please consult the manufacturer’s dat asheet.
When this oscillator is selected, start-up times are determined by the SUT fuses as shown in
Table 6-9.
Table 6-9.Start-up Times for the Low Frequency Crystal Oscillator Clock Selection
Start-up Time
SUT[1:0]
001K (1024) CK
011K (1024) CK
1032K (32768) CK64 msStable frequency at start-up
from Power Down
Additional Delay from
ResetRecommended Usage
(1)
Additional Delay
from ResetRecommended usage
(1)
(1)
4 msFast rising power or BOD enabled
64 msSlowly rising power
BOD enabled
8197C–AVR–05/11
11Reserved
Notes:1. These options should be used only if frequency stability at start-up is not important.
The Low-frequency Crystal Oscillator provides an internal load capacitance, see Table 6-10 at
each TOSC pin.
Table 6-10.Capacitance of Low-Frequency Crystal Oscillator
XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier which can be configured for use as an On-chip Oscillator, as shown in Figure 6-4. Either a quartz crystal or a
ceramic resonator may be used.
Figure 6-4.Crystal Oscillator Connections
C1 and C2 should always be equal for both crystals and resonators. The optimal value of the
capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the
electromagnetic noise of the environment. Some initial guidelines for choosing capacitors for
use with crystals are given in Table 6-11. For ceramic resonators, the capacitor values given by
the manufacturer should be used.
Table 6-11.Crystal Oscillator Operating Modes
CKSEL[3:1] Frequency Range (MHz)Re commended C1 and C2 Value (pF)
Notes:1. This option should not be used with crystals, only with ceramic resonators.
0.4 - 0.9–
The Oscillator can operate in three different modes, each optimized for a specific frequency
range. The operating mode is selected by fuses CKSEL[3:1] as shown in Table 6-11.
The CKSEL0 Fuse together with the SUT[1:0] F uses select t he sta rt-u p t ime s as shown in Table
6-12.
Table 6-12.Start-up Times for the Crystal Oscillator Clock Selection
Start-up Time from
Power-down and
CKSEL0SUT[1:0]
000258 CK
001258 CK
Power-save
(1)
(1)
Additional Delay
from Reset
(VCC = 5.0V)Recommended Usage
14CK + 4 ms
14CK + 64 ms
Ceramic resonator,
fast rising power
Ceramic resonator,
slowly rising power
30
0101K (1024) CK
ATtiny261A/461A/861A
(2)
14CK
Ceramic resonator,
BOD enabled
8197C–AVR–05/11
ATtiny261A/461A/861A
Table 6-12.Start-up Times for the Crystal Oscillator Clock Selection (Continued)
CKSEL0SUT[1:0]
Notes:1. These options should only be used when not operating close to the maximum frequency of the
6.2.7Default Clock Source
The device is shipped with CKSEL = “0010”, SUT = “ 10”, and CKDIV8 programmed. The default
clock source setting is therefore the Internal Oscillator running at 8 MHz with long est start-up
time and an initial system clock prescaling of 8. This default setting ensure s that all u sers can
make their desired clock source setting using an In-System or High-voltage Programmer.
Start-up Time from
Power-down and
Power-save
0111K (1024)CK
1001K (1024)CK
10116K (16384) CK14CK
11016K (16384) CK 14CK + 4 ms
11116K (16384) CK14CK + 64 ms
device, and only if frequency stability at start-up is not important for the application. These
options are not suitable for crystals.
2. These options are intended for use with cer amic resonators and will ensure frequency stability
at start-up. They can also be used with crystals when not operating close to the maximum frequency of the device, and if frequency stability at start-up is not important for the application.
(2)
(2)
Additional Delay
from Reset
(VCC = 5.0V)Recommended Usage
14CK + 4 ms
14CK + 64 ms
Ceramic resonator,
fast rising power
Ceramic resonator,
slowly rising power
Crystal Oscillator,
BOD enabled
Crystal Oscillator,
fast rising power
Crystal Oscillator,
slowly rising power
It should be noted that unprogramming the CKDIV8 fuse may result in overclocking. At low voltages the devices are rated for clock frequencies below that of the internal oscillator. See Section
19.3 on page 187 for maximum operating frequency versus supply voltage.
6.3System Clock Prescaler
The system clock can be divided by setting the “CLKPR – Clock Prescale Register” on page 32.
This feature can be used to decrease power consumption when the requirement for processing
power is low. This can be used with all clock source options, and it will affect the clock frequency
of the CPU and all synchronous peripherals. clk
factor as shown in Table 6-13 on page 33.
6.3.1Switching Time
When switching between prescaler settings, the System Clock Prescaler ensures that no
glitches occur in the clock system and that no intermediate frequency is higher than neither the
clock frequency corresponding to the previous setting, nor the clock frequency corresponding to
the new setting.
The ripple counter that implements the prescaler runs at the frequency of the undivided clock,
which may be faster than the CPU’s clock frequency. Hence, it is not possible to determine the
state of the prescaler – even if it were readable, and the exact time it takes to switch from one
clock division to another cannot be exactly predicted.
I/O
, clk
ADC
, clk
, and clk
CPU
are divided by a
FLASH
8197C–AVR–05/11
31
From the time the CLKPS values are written, it takes between T1 + T2 and T1 + 2*T2 before the
new clock frequency is active. In this interval, two active clock edges are produced. Here, T1 is
the previous clock period, and T2 is the period corresponding to the new prescaler setting.
6.4Clock Output Buffer
The device can output the system clock on the CLKO pin (when not used as XTAL2 pin). To
enable the output, the CKOUT Fuse has t o be progr ammed. This mode is su itable when the chip
clock is used to drive other circuits on the system. Note that the clock will not be output during
reset and the normal operation of I/O pin will be overridden when the fuse is programmed. Internal RC Oscillator, WDT Oscillator, PLL, and external clock (CLKI) can be selected when the
clock is output on CLKO. Crystal oscillators (XTAL1, XTAL2) can not be used for clock output on
CLKO. If the System Clock Prescaler is used, it is the divided system clock tha t is out put.
• Bits 7:0 – CAL[7:0]: Oscillator Calibration Value
The Oscillator Calibration Register is used to trim the Calibrated Internal Oscillator to remove
process variations from the oscillator frequency. A pre-programmed calibration value is automatically written to this register during chip reset, giving the Factory calibrated frequency as
specified in Table 19-2 on page 187. The application software can write this register to change
the oscillator frequency. The oscillator can be calibrated to frequencies as specified in Table 19-
2 on page 187. Calibration outside that range is not guaranteed.
Note that this oscillator is used to time EEPROM and Flash write accesses, and these write
times will be affected accordingly. If the EEPROM or Flash are written, do not calibrate to more
than 8.8 MHz. Otherwise, the EEPROM or Flash write may fail.
The CAL[7:0] bits are used to tune the frequency of the oscillator. A setting of 0x00 gives the
lowest frequency, and a setting of 0xFF gives the hig he st .
6.5.2CLKPR – Clock Prescale Register
Bit76543210
0x28 (0x48)CLKPCE–––CLKPS3CLKPS2CLKPS1CLKPS0CLKPR
Read/WriteR/WRRRR/WR/WR/WR/W
Initial Value0000See Bit Description
• Bit 7 – CLKPCE: Clock Prescaler Change Enable
The CLKPCE bit must be written to logic one to enable change of the CLKPS bits. The CLKPCE
bit is only updated when the other bits in CLKPR are simultaniosly written to zero. CLKPCE is
cleared by hardware four cycles after it is written or when the CLKPS bits are written. Rewriting
the CLKPCE bit within this time-out period does neither extend the time-out period, nor clear the
CLKPCE bit.
32
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
• Bits 6:4 – Res: Reserved Bits
These bits are reserved and will always read as zero.
These bits define the division factor between the selected clock source and the internal system
clock. These bits can be written run-time to vary the clock frequency to suit the application
requirements. As the divider divides the master clock input to t he MCU, the speed o f all synchronous peripherals is reduced when a division factor is used. The division factors are given in
Table 6-13.
To avoid unintentional changes of clock frequency, a special write procedure must be followed
to change the CLKPS bits:
1.Write the Clock Prescaler Change Enable (CLKPCE) bit to one and all other bits in
CLKPR to zero.
2.Within four cycles, write the desired value to CLKPS while writing a zero to CLKPCE.
Interrupts must be disabled when changing prescaler setting to make sure t he write procedur e is
not interrupted.
The CKDIV8 Fuse determines the initial value of the CLKPS bits. If CKDIV8 is unprogrammed,
the CLKPS bits will be reset to “0000”. If CKDIV8 is programmed, CLKPS bits are reset to
“0011”, giving a division factor of eight at start up. This feature should be used if the sele cted
clock source has a higher frequency than the maximum frequency of the device at the present
operating conditions. Note that any value can be written to the CLKPS bits regardless of the
CKDIV8 Fuse setting. The Application software must ensure that a sufficient d ivision factor is
chosen if the selcted clock source has a higher frequency than the maximum frequency of the
device at the present operating conditions. The device is shipped with the CKDIV8 Fuse
programmed.
The high performance and industry leading code efficiency makes the AVR microcontrollers an
ideal choise for low power applications. In addition, sleep modes enable the application to shut
down unused modules in the MCU, thereby saving power. The AVR provides various sleep
modes allowing the user to tailor the power consumption to the application’s requirements.
7.1Sleep Modes
Figure 6-1 on page 24 presents the different clock systems and their distribution. The figure is
helpful in selecting an appropriate sleep mode. Table 7-1 shows the different sleep modes and
their wake up sources.
Table 7-1.Active Clock Domains and Wake-up Sources in Different Sleep Modes
Active Clock DomainsOsc.Wake-up Sources
CPU
FLASH
clk
Sleep Mode
IdleXXXX
ADC Noise Reduct.XX
Power-downX
StandbyX
clk
ADC
clkIOclk
PCK
clk
ATtiny261A/461A/861A
PLL
clk
Main Clock
Source Enabled
INT0, INT1 and
Pin Change
SPM/EEPROM
Ready Interrupt
ADC
Interrupt
USI
Interrupt
Other
(2)
X XXXXXX
(2)
XX
(1)
XXXX
(1)
(1)
XX
XX
I/O
Watchdog
Interrupt
7.1.1Idle Mode
Note:1. For INT0 and INT1, only level interrupt.
2. When PLL selected as system clock.
To enter any of the sleep modes, the SE bit in MCUCR must be written to logic one and a
SLEEP instruction must be executed. The SM[1:0] bits in the MCUCR Register select which
sleep mode (Idle, ADC Noise Reduction, Power-down, or Standby) will be activated by the
SLEEP instruction. See Table 7-2 for a summary.
If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU
is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and
resumes execution from the instruction following SLEEP. The contents of the Register File and
SRAM are unaltered when the device wakes up from slee p. I f a r eset occurs d uri ng sle ep mode,
the MCU wakes up and executes from the Reset Vector.
Note that if a level triggered interrupt is used for wake-up the changed level must be held for
some time to wake up the MCU (and for the MCU to enter the interrupt service routine). See
“External Interrupts” on page 50 for details.
When bits SM[1:0] are written to 00, the SLEEP instruction makes the MCU enter Idle mode,
stopping the CPU but allowing Analog Comparator, ADC, Timer/Counter, Watchdog, and the
interrupt system to continue operating. This sleep mode basically halts clk
CPU
and clk
FLASH
, while
allowing the other clocks to run.
8197C–AVR–05/11
35
Idle mode enables the MCU to wake up from external triggered interrupts as well a s internal
ones like the Timer Overflow. If wake-up from the 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. If the
ADC is enabled, a conversion starts automatically when this mode is entered.
7.1.2ADC Noise Reduction Mode
When the SM[1:0] bits are written to 01, the SLEEP instruction makes the MCU ent er ADC
Noise Reduction mode, stopping the CPU but allowing the ADC, the external interrupts, and the
Watchdog to continue operating (if enabled). This sleep mode halts clk
while allowing the other clocks to run.
This mode improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is enabled, a conversion starts automatically when this mode is entered. Apart
form the ADC Conversion Complete interrupt, only an External Reset, a Watchdog Reset, a
Brown-out Reset, an SPM/EEPROM ready interrupt, an external level interrupt on INT0 or a pin
change interrupt can wake up the MCU from ADC Noise Reduction mode.
7.1.3Power-Down Mode
When the SM[1:0] bits are written to 10, the SLEEP instruction makes the MCU enter Powerdown mode. In this mode, the Oscillator is stopped, while the external interrupts, and the Watchdog continue operating (if enabled). Only an External Reset, a Watchd og Reset, a Brown-out
Reset, an external level interrupt on INT0, or a pin change interrupt can wake up the MCU. This
sleep mode halts all generated clocks, allowing operation of asynchronous modules, only.
I/O
, clk
, and clk
CPU
FLASH
,
7.1.4Standby Mode
When the SM[1:0] bits are written to 11 and an external crystal/resonator clock option is
selected, the SLEEP instruction makes the MCU enter Standby mode. This mode is identical to
Power-down with the exception that the Oscillator is kept running. From Standby mode, the
device wakes up in six clock cycles.
7.2Software BOD Disable
When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses (see Table 18-4 on page
169), the BOD is actively monitoring the supply voltage during a sleep period. It is possible to
save power by disabling the BOD by software in Power-Down sleep mode. The sleep mode
power consumption will then be at the same level as when BOD is globally disabled by fuses.
If BOD is disabled by software, the BOD function is turned off immediately after entering the
sleep mode. Upon wake-up from sleep, BOD is automatically enabled again. This ensures safe
operation in case the V
When the BOD has been disabled, the wake-up time from sleep mode will be approximately
60µs to ensure that the BOD is working correctly before the MCU continues executing code.
BOD disable is controlled by the BODS (BOD Sleep) bit of BOD Control Register, see “MCUCR
– MCU Control Register” on page 38. Writing this bit to one turns off BOD in Power-Down and
Stand-By, while writing a zero keeps the BOD active. The default setting is zero, i.e. BOD active.
Writing to the BODS bit is controlled by a timed sequence and an enable bit, see “MCUCR –
MCU Control Register” on page 38.
level has dropped during the sleep period.
CC
36
ATtiny261A/461A/861A
8197C–AVR–05/11
7.3Po wer Reduction Register
The Power Reduction Register (PRR), see “PRR – Power Reduction Register” on page 39, pro-
vides a method to stop the clock to individual peripherals to reduce power consumption. The
current state of the peripheral is frozen and the I/O registers can not be read or written.
Resources used by the peripheral when stopping the clock will remain occupied, hence the
peripheral should in most cases be disabled before stopping the clock. Waking up a module,
which is done by clearing the bit in PRR, puts the module in t he sa me stat e a s befor e shut down.
Module shutdown can be used in Idle mode and Active mode to significantly reduce the overall
power consumption. In all other sleep modes, the clock is already stopped. See “Supply Current
of I/O modules” on page 197 for examples. In all other sleep modes, the clock is already
stopped.
7.4Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR
controlled system. In general, sleep modes should be used as much as possible, and the sleep
mode should be selected so that as few as possible of the device’s functions are operating. All
functions not needed should be disabled. In particular, the following modules may need special
consideration when trying to achieve the lowest possible power consumption.
ATtiny261A/461A/861A
7.4.1Analog Comparator
When entering Idle mode, the Analog Comparator should be disabled if not used. When entering
ADC Noise Reduction mode, the Analog Comparator should be disabled. In the other sleep
modes, the Analog Comparator is automatically disabled. However, if the Analog Comparator is
set up to use the Internal Voltage Reference as input, the Analog Comparator should be disabled in all sleep modes. Otherwise, the Internal Voltage Reference will be enabled,
independent of sleep mode. Refer to “AC – Analog Comparator” on page 136 for details on how
to configure the Analog Comparator .
7.4.2Analog to Digital Converter
If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be disabled before entering any sleep mode. When the ADC is turned off and on again, the next
conversion will be an extended conversion. Refer to “ADC – Analog to Digital Converter” on
page 141 for details on ADC operation.
7.4.3Brown-out Detector
If the Brown-out Detector is not needed in the ap plication, this module should be turne d off. If the
Brown-out Detector is enabled by the BODLEVEL Fuses, it will be enabled in all sleep modes,
and hence, always consume power. In the deeper sleep modes, this will contribute significantly
to the total current consumption. Refer to “Brown- out Detection” on page 42 for details on how to
configure the Brown-out Detector.
7.4.4Internal Voltage Reference
The Internal Voltage Reference will be enabled when needed by the Brown-out Detection, the
Analog Comparator or the ADC. If these modules are disabled as described in the sections
above, the internal voltage reference will be disabled and it will not be consuming power. When
turned on again, the user must allow the reference to start up before the output is used. If the
reference is kept on in sleep mode, the output can be used immediately. Refer to “Internal Volt-
age Reference” on page 43 for details on the start-up time.
8197C–AVR–05/11
37
7.4.5Watchdog Timer
If the Watchdog Timer is not needed in the application, this module should be turned off. If the
Watchdog Timer is enabled, it will be enabled in all sleep modes, and hence, always consume
power. In the deeper sleep modes, this will contribute significantly to the total current consumption. Refer to “Watchdog Timer” on page 43 for details on how to configu re t he Wa tchd og Time r.
7.4.6Port Pins
When entering a sleep mode, all port pins should be configured to use minimum power. The
most important thing is then to ensure that no pins drive resistive loads. In sleep modes where
both the I/O clock (clk
will be disabled. This ensures that no power is consumed by the input logic when not needed. In
some cases, the input logic is needed for detecting wake-up conditions, and it will then be
enabled. Refer to the section “Digital Input Enable and Sleep Modes” on page 58 for details on
which pins are enabled. If the input buffer is enab led and the in put sig nal is le ft fl oati ng or ha s an
analog signal level close to V
For analog input pins, the digital input buffer should be disabled at all times. An analog signal
level close to V
input buffers can be disabled by writing to the Digital Input Disable Registers (DIDR0, DIDR1).
Refer to “DIDR0 – Digital Input Disable Register 0” on page 160 or “DIDR1 – Digital Input Dis-
able Register 1” on page 160 for details.
7.5Register Description
) and the ADC clock (clk
I/O
/2, the input buffer will use excessive power.
CC
/2 on an input pin can cause significant current even in active mode. Digital
CC
) are stopped, the input buffers of the device
ADC
7.5.1MCUCR – MCU Control Register
The MCU Control Register contains control bits for power management .
In order to disable BOD during sleep the BODS bit must be writte n to logic one. This is contr olled
by a timed sequence and the enable bit, BODSE. First, both BODS and BODSE must be set to
one. Second, within four clock cycles, BODS must be set to one and BODSE must be set to
zero. The BODS bit is active three clock cycles after it is set. A sleep instruction must be executed while BODS is active in order to turn off the BOD for the actual sleep mode. The BODS bit
is automatically cleared after three clock cycles.
• Bit 5 – SE: Sleep Enable
The SE bit must be written to logic one to make the MCU enter the sleep mode when th e SLEEP
instruction is executed. To avoid the MCU enteri ng th e sleep mode unless it is the programmer’s
purpose, it is recommended to write the Sleep Enable (SE) b it to one just befor e the exe cution of
the SLEEP instruction and to clear it immediately after waking up.
These bits are reserved and will always read zero.
• Bit 3 – PRTIM1: Power Reduction Timer/Counter1
Writing a logic one to this bit shuts down the Timer/Counter1 module. When the Timer/Counter1
is enabled, operation will continue like before the shutdown.
• Bit 2 – PRTIM0: Power Reduction Timer/Counter0
Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0
is enabled, operation will continue like before the shutdown.
• Bit 1 – PRUSI: Power Reduction USI
Writing a logic one to this bit shuts down the USI by stopping the clock to the module. When
waking up the USI again, the USI should be re initialized to ensure proper operation.
• Bit 0 – PRADC: Power Reduction ADC
Writing a logic one to this bit shuts do wn the ADC. The ADC mu st be disabled b efore shut down.
Also analog comparator needs this clock.
8197C–AVR–05/11
39
8.System Control and Reset
8.1Resetting the AVR
During reset, all I/O Registers are set to their initial values, and the program starts execution
from the Reset Vector. The instruction placed at the Reset Vector must be a RJMP – 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 8-1 shows the reset logic. Electrical parameters of the
reset circuitry are given in Table 19-4 on page 188.
Figure 8-1.Reset Logic
VCC
Power-on Reset
Circuit
DATA BUS
MCU Status
Register (MCUSR)
PORF
BORF
WDRF
EXTRF
BODLEVEL [2:0]
RESET
Pull-up Resistor
SPIKE
FILTER
Brown-out
Reset Circuit
Reset Circuit
Watchdog
Timer
Watchdog
Oscillator
Clock
Generator
CKSEL[1:0]
SUT[1:0]
CK
Delay Counters
COUNTER RESET
TIMEOUT
Q
S
R
The I/O ports of the AVR are immediately reset to their initial state when a reset source goes
active. This does not require any clock source to be running.
After all reset sources have gone inactive, a delay counter is invoked, stretching the internal
reset. This allows the power to reach a stable level before normal operation starts. The time-out
period of the delay counter is defined by the user through the SUT and CKSEL Fuses. The different selections for the delay period are presented in “Clock Sources” on page 25.
INTERNAL RESET
40
ATtiny261A/461A/861A
8197C–AVR–05/11
8.2Reset Sources
V
RESET
TIME-OUT
INTERNAL
RESET
t
TOUT
V
POT
V
RST
CC
RESET
TIME-OUT
INTERNAL
RESET
t
TOUT
V
POT
V
RST
V
CC
8.2.1Power-on Reset
ATtiny261A/461A/861A
The ATtiny261A/461A/861A has four sources of reset:
• Power-on Reset. The MCU is reset when the supply voltage is below the Power-on Reset
threshold (V
• External Reset. The MCU is reset when a low level is present on the RESET
than the minimum pulse length.
• W atchdog Reset. The MCU is reset when the Watchdog Timer period expires and the
Watchdog is enabled.
• Brown-out Reset. The MCU is reset when the supply voltage V
Reset threshold (V
A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level
is defined in “System and Reset Characteristics” on page 188. The POR is activated whenever
is below the detection level. The POR circuit can be used to trigger the Start-up Reset, as
V
CC
well as to detect a failure in supply voltage.
A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reac hing the
Power-on Reset threshold voltage invokes the delay counter, which determines how long the
device is kept in RESET after V
when V
decreases below the detection level.
CC
POT
).
) and the Brown-out Detector is enabled.
BOT
rise. The RESET signal is activated again, without any delay,
An External Reset is generated by a low level on the RESET
than the minimum pulse width (see “Syste m a nd Re se t Char act er ist ics” o n p age 18 8) will gener-
ate 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
edge, the delay counter starts the MCU afte r the Time-out period – t
Figure 8-4.External Reset During Operation
8.2.3Brown-out Detection
A Brown-out Detection (BOD) circuit monitors the V
fixed trigger level. The trigger level for the BOD can be selected by the BODLEVEL Fuses. The
trigger level has a hysteresis to ensure spike free Brown-out Detection. The hysteresis on the
detection level should be interpreted as V
When the BOD is enabled, and V
8-5), the Brown-out Reset is immediately activated. When V
(V
BOT+
expired.
pin if enabled. Reset pulses longer
– on its positive
RST
has expired.
TOUT –
level during operation by comparing it to a
CC
= V
BOT+
decreases to a value below the trigger level (V
CC
BOT
+ V
/2 and V
HYST
increases above the trigger level
CC
BOT-
= V
BOT
- V
BOT-
HYST
in Figure 8-5), the delay counter starts the MCU after the Time-out period t
/2.
in Figure
has
TOUT
42
The BOD circuit will only detect a drop in V
ger than t
given in “System and Reset Characteristics” on page 188.
BOD
Figure 8-5.Brown-out Reset During Operation
ATtiny261A/461A/861A
if the voltage stays below the trigger level for lon-
CC
8197C–AVR–05/11
8.2.4Watchdog Reset
CK
CC
ATtiny261A/461A/861A
When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On
the falling edge of this pulse, the delay timer starts counting the Time-out period t
“Watchdog Timer” on page 43 for details on operation of the Watchdog Timer.
Figure 8-6.Watchdog Reset During Operation
TOUT
. Refer to
8.3Internal Voltage Reference
ATtiny261A/461A/861A features an internal bandgap reference. This reference is used for
Brown-out Detection, and it can be used as an input to the Analog Comparator or the ADC. The
bandgap voltage varies with supply voltage and temperature, as ca n be seen in Figure 20-45 on
page 221.
8.3.1Voltage Reference Enable Signals and Start-up Time
The voltage reference has a start-up time that may influence the way it should be used. T he
start-up time is given in “System and Reset Characteristics” on page 188. To save power, the
reference is not always turned on. The reference is on during the following situations:
1.When the BOD is enabled (by programming the BODLEVEL[2:0] Fuse bits).
2.When the bandgap reference is connected to the Analog Comparator (by setting the
ACBG bit in ACSR) .
3.When the ADC is enabled.
Thus, when the BOD is not enabled, after setting the ACBG bit or enabling the ADC, the user
must always allow the reference to start up before the output from the Analog Comparator or
ADC is used. To reduce power consumption in Power-down mode, the user can avoid the three
conditions above to ensure that the reference is turned off before entering Power-down mode.
8.4Watchdog Timer
The Watchdog Timer is clocked from an on-chip oscillator, which runs at 128 kHz. By controlling
the Watchdog Timer prescaler, the Watchdog Reset interval can be adjusted as shown in Table
8-3 on page 48. The WDR – Watchdog Reset – instruction resets the Watchdog Timer. The
Watchdog Timer is also reset when it is disabled and when a device reset occurs. Ten different
clock cycle periods can be selected to determine the reset period. If the reset period expires
without another Watchdog Reset, the device resets and executes from the Reset Vector. For
timing details on the Watchdog Reset, refer to Table 8-3 on page 48.
8197C–AVR–05/11
43
The Wathdog Timer can also be configured to generate an interrupt instead of a reset. This can
be very helpful when using the Watchdog to wake-up from Power-down.
To prevent unintentional disabling of the Watchd og or unintentional chan ge of time-out period,
two different safety levels are selected by the fuse WDTON as shown in Table 8-1 Refer to
“Timed Sequences for Changing the Configuration of the Watchdog Timer” on page 44 for
details.
Table 8-1.WDT Configuration as a Function of the Fuse Settings of WDTON
8.4.1Timed Sequences for Changing the Configuration of the Watchdog Timer
The sequence for changing configuration differs slightly between the two safety levels. Separate
procedures are described for each level.
OSC/32K
OSC/64K
How to Change Timeout
OSC/512K
OSC/128K
OSC/256K
OSC/1024K
8.4.1.1Safety Level 1
8.4.1.2Safety Level 2
44
ATtiny261A/461A/861A
In this mode, the Watchdog Timer is initially disabled, but can be enabled by writing the WDE bit
to one without any restriction. A timed sequence is needed when disabling an enabled Watchdog Timer. To disable an enabled Watchdog Timer, the following procedure must be followed:
1.In the same operation, write a logic one to WDCE and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit.
2.Within the next four clock cycles, in the same operation, write the WDE and WDP bits
as desired, but with the WDCE bit cleared.
In this mode, the Watchdog Timer is always enabled, and the WDE bit will always read as one. A
timed sequence is needed when changing the Watchdog Time-out period. To change the
Watchdog Time-out, the following procedure must be followed:
8197C–AVR–05/11
8.4.2Code Examples
ATtiny261A/461A/861A
1.In the same operation, write a logical one to WDCE and WDE. Even though the WDE
always is set, the WDE must be written to one to start the timed sequence.
2.Within the next four clock cycles, in the same operat ion, write the WDP bit s a s de sir ed,
but with the WDCE bit cleared. The value written to the WDE bit is irrelev ant.
The following code example shows one assembly and one C function for turning off the WDT.
The example assumes that interrupts are controlled (e.g. , by disabling interrupt s globally) so that
no interrupts will occur during execution of these functions.
Assembly Code Example
WDT_off:
wdr
; Clear WDRF in MCUSR
ldir16, (0<<WDRF)
outMCUSR, r16
; Write logical one to WDCE and WDE
; Keep old prescaler setting to prevent unintentional Watchdog Reset
in r16, WDTCSR
ori r16, (1<<WDCE)|(1<<WDE)
out WDTCSR, r16
; Turn off WDT
ldi r16, (0<<WDE)
out WDTCSR, r16
ret
C Code Example
void WDT_off(void)
{
_WDR();
/* Clear WDRF in MCUSR */
MCUSR = 0x00
/* Write logical one to WDCE and WDE */
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* Turn off WDT */
WDTCSR = 0x00;
}
Note:See “Code Examples” on page 6.
8197C–AVR–05/11
45
8.5Register Description
8.5.1MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU Reset.
Bit76543210
0x34 (0x54)––––WDRFBORFEXTRFPORFMCUSR
Read/WriteRRRRR/WR/WR/WR/W
Initial Value0000See Bit Description
• Bits 7:4 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 3 – WDRF: Watchdog Reset Flag
This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.
• Bit 2 – BORF: Brown-out Reset Flag
This bit is set if a Brown-out Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.
• Bit 1 – EXTRF: External Reset Flag
This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.
• Bit 0 – PORF: Power-on Reset Flag
This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag.
To make use of the Reset Flags to identify a r eset condition, t he user should r ead and t hen reset
the MCUSR as early as possible in the prog ram. If the register is cle ared before anot her reset
occurs, the source of the reset can be found by examining the Reset Flags.
This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt
handling vector. Alternatively, WDIF is clear ed by writing a logic on e to the f lag. Whe n the I-bi t in
SREG and WDIE are set, the Watchdog Time-out Interrupt is executed .
• Bit 6 – WDIE: Watchdog Timeout Interrupt Enable
When this bit is written to one, WDE is cleared, and the I-bit in the Status Register is set, th e
Watchdog Time-out Interrupt is enabled. In this mode the corresponding interr upt is executed
instead of a reset if a timeout in the Watchdog Timer occurs.
46
If WDE is set, WDIE is automatically cleared by hardware when a time-out occurs. This is useful
for keeping the Watchdog Reset security while using the interrupt. After the WDIE bit is cleared,
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
the next time-out will generate a reset. To avoid the Watchdog Reset, WDIE must be set after
each interrupt.
This bit must be set when the WDE bit is written to logic zero. Otherwise, the Watchdog will not
be disabled. Once written to one, hardware will clear this bit after four clock cycles. Refer to the
description of the WDE bit for a Watchdog disable procedure. This bit must also be set when
changing the prescaler bits. See “Timed Sequences for Changing the Configuration of the
Watchdog Timer” on page 44.
• Bit 3 – WDE: Watc hdog Enable
When the WDE is written to logic one, the Watchdog Timer is enabled, and if the WDE is written
to logic zero, the Watchdog Timer function is di sabled. WDE can on ly be clear ed if the WDCE bit
has logic level one. To disable an enabled Watchdog Timer, the following procedure must be
followed:
1.In the same operation, write a logic one to WDCE and WDE. A logic one 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 logic 0 to WDE. This disables the Watchdog.
In safety level 2, it is not possible to disable the Watchdog Timer, even with the algorithm
described above. See “Timed Sequences for Changing the Configuration of the Watchdog
Timer” on page 44.
In safety level 1, WDE is overridden by WDRF in MCUSR. See “MCUSR – MCU Status Regis-
ter” on page 46 for description of WDRF. This means that WDE is always set when WDRF is set.
To clear WDE, WDRF must be cleared before disabling the Watchdog with the procedure
described above. This feature ensures multiple resets during conditions causing failure, and a
safe start-up after the failure.
Note:If the watchdog timer is not going to be used in the application, it is important to go through a
watchdog disable procedure in the initialization of the device. If the Watchdog is accidentally
enabled, for example by a runaw ay pointer or brown-out condition, the device will be reset, which
in turn will lead to a new watchdog reset. To avoid this situation, the application software should
always clear the WDRF flag and the WDE control bit in the initialization routine.
The WDP[3:0] bits determine the Watchdog Timer prescaling when the Watchdog Timer is
enabled. The different prescaling values and their corresponding Timeout Periods are shown in
Table 8-3.
Table 8-3.Watchdog Timer Prescale Select
Number of WDT Oscillator
WDP3WDP2WDP1WDP0
00002K (2048) cycles16 ms
00014K (4096) cycles32 ms
00108K (8192) cycles64 ms
001116K (16384) cycles0.125 s
010032K (32764) cycles0.25 s
010164K (65536) cycles0.5 s
0110128K (131072) cycles1.0 s
0111256K (262144) cycles2.0 s
1000512K (524288) cycles4.0 s
10011024K (1048576) cycles8.0 s
1010
1011
1100
1101
1110
1111
Cycles
Reserved
Typical Time-out at
VCC = 5.0V
(1)
48
Notes:1. If selected, one of the valid settings below 0b1010 will be used.
ATtiny261A/461A/861A
8197C–AVR–05/11
9.Interrupts
This section describes the specifics of the interrupt handling as performed in
ATtiny261A/461A/861A. For a general explanation of the AVR interrupt handling, refer to “Reset
and Interrupt Handling” on page 12.
9.1Interrupt Vectors
Interrupt vectors of ATtiny261A/461A/861A are described in Table 9-1 below.
Table 9-1.Reset and Interrupt Vectors
ATtiny261A/461A/861A
Vector
No.
10x0000RESET
20x0001INT0External Interrupt Request 0
30x0002PCINTPin Change Interrupt Request
40x0003TIMER1_COMPATimer/Counter1 Compare Match A
50x0004TIMER1_COMPBTimer/Counter1 Compare Match B
60x0005TIMER1_OVFTimer/Counter1 Overflow
70x0006TIMER0_OVFTimer/Counter0 Overflow
80x0007USI_STARTUSI Start
90x0008USI_OVFUSI Overflow
100x0009EE_RDYEEPROM Ready
110x000AANA_COMPAnalog Comparator
120x000BADCADC Conversion Complete
130 x 000CWDTWatchdog Time-out
140x000DINT1External Interrupt Request 1
150x000ETIMER0_COMPATimer/Counter0 Compare Match A
160x000FTIMER0 _COMPBTimer/Counter0 Compare Match B
170x0010TIMER0_CAPTTimer/Counter1 Capture Event
180x0011TIMER1_COMPDTimer/Counter1 Compare Match D
190x0012FAULT_PROTECTIONTimer/Counter1 Fault Protection
If the program never enables an interr upt sou rce, the I nter rupt Vect ors ar e n ot used , and regu lar
program code can be placed at these locations.
The most typical and general program setup for the Reset and Interrupt Vector Addresses in
ATtiny261A/461A/861A is shown in the following program example.
0x0013RESET: ldir16, low(RAMEND) ; Main program start
0x0014ldir17, high(RAMEND); Tiny861 have also SPH
0x0015outSPL, r16; Set Stack Pointer to top of RAM
0x0016outSPH, r17; Tiny861 have also SPH
0x0017sei; Enable interrupts
0x0018<instr>
......
9.2External Interrupts
The External Interrupts are triggered by the INT0 or INT1 pin or any of the PCINT[15:0] pins.
Observe that, if enabled, the interrupts will trigger even if the INT0, INT1 or PCINT[15:0] pins are
configured as outputs. This feature provides a way of generating a software interrupt. Pin
change interrupts PCI will trigger if any enabled PCINT[15:0] pin toggles. The PCMSK Register
control which pins contribute to the pin change interrupts. Pin change interrupts on PCINT[15:0]
are detected asynchronously. This implies that these interrupts can be used for waking the part
also from sleep modes other than Idle mode.
The INT0 and INT1 interrupts can be triggered by a falling or rising ed ge or a low level. This is
set up as indicated in the specification for the MCU Control Register – MCUCR. When the INT0
interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the
pin is held low. Note that recognition of falling or rising edge interrupts on INT0 or INT1 requires
the presence of an I/O clock, described in “Clock Subsystems” on page 24.
50
ATtiny261A/461A/861A
8197C–AVR–05/11
9.2.1Low Level Interrupt
A low level interrupt on INT0 is detected asynchronously. This means that the interrupt source
can be used for waking the part also from sleep modes other than Idle (the I/O clock is halted in
all sleep modes except Idle).
Note that if a level triggered interrupt is used for wake-up from Power -down, the required level
must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If
the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined by the SUT and CKSEL Fuses as described
in “Clock System” on page 24.
If the low level on the interrupt pin is removed before the device has woken up then program
execution will not be diverted to the interrupt service routine but continue from the instruction following the SLEEP command.
9.3Register Description
9.3.1MCUCR – MCU Control Register
The MCU Register contains control bits for interrupt sense control.
• Bits 1:0 – ISC0[1:0]: Interrupt Sense Control 0 Bit 1 and Bit 0
The External Interrupt 0 is activated by the external pin INT0 or INT1 if the SREG I-flag and the
corresponding interrupt mask are set. The level and edges on the external INT0 or INT1 pin that
activate the interrupt are defined in Table 9-2. The value on the INT0 or 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 9-2.Interrupt 0 Sense Control
ISC01ISC00Description
00The low level of INT0 or INT1 generates an interrupt request.
01Any logical change on INT0 or INT1 generate s an interrupt request.
10The falling edge of INT0 or INT1 generates an interrupt request.
11The r ising edge of INT0 or INT1 generates an interrupt request.
• 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 I nterrupt Sen se Control0 bits 1/ 0 (ISC0 1 and ISC0 0) in the MCU
51
Control Register (MCUCR) define whether the exter nal inter rupt is activate d on r ising and/ or falling edge of the INT1 pin or 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 the INT1 Interrupt Vector.
• 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 I nterrupt Sen se Control0 bits 1/ 0 (ISC0 1 and ISC0 0) in the MCU
Control Register (MCUCR) define whether the exter nal inter rupt is activate d on r ising and/ or falling edge of the INT0 pin or 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 the INT0 Interrupt Vector.
• Bit 5 – PCIE1: Pin Change Interrupt Enable
When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt is enabled. Any change on any enabled PCINT[7:0] or PCINT[15:12] pin will
cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed
from the PCI Interrupt Vector. PCINT[7:0] and PCINT[15:12] pins are enabled individually by the
PCMSK0 and PCMSK1 Register.
• Bit 4 – PCIE0: Pin Change Interrupt Enable
When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt is enabled. Any cha nge on an y enabled PCINT[11:8] pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI Interrupt
Vector. PCINT[11:8] pins are enabled individually by the PCMSK1 Register.
• Bits 3:0 – Res: Reserved Bits
These bits are reserved and will always read as zero.
When an edge or logic change on the INT1 pin triggers an interrup t requ est, INTF1 be comes set
(one). If the I-bit in SREG and the INT1 bit in GIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared
when INT1 is configured as a level interrupt.
• Bit 6 – INTF0: External Interrupt Flag 0
When an edge or logic change on the INT0 pin triggers an interrup t requ est, INTF0 be comes set
(one). If the I-bit in SREG and the INT0 bit in GIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared
when INT0 is configured as a level interrupt.
52
ATtiny261A/461A/861A
8197C–AVR–05/11
• Bit 5 – PCIF: Pin Change Interrupt Flag
When a logic change on any PCINT15 pin triggers an interrupt request, PCIF becomes set
(one). If the I-bit in SREG and the PCIE bit in GIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it.
• Bits 4:0 – Res: Reserved Bits
These bits are reserved and will always read as zero.
Each PCINT[7:0] bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT[7:0] is set and the PCIE1 bit in GIMSK is set, pin change interrupt is enabled on
the corresponding I/O pin. If PCINT[7:0] is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
Each PCINT[15:8] bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT[11:8] is set and the PCIE0 bit in GIMSK is set, pin change interrupt is enabled on
the corresponding I/O pin, and if PCINT[15:12] is set and the PCIE1 bit in GIMSK is set, pin
change interrupt is enabled on the corresponding I/O pin. If PCINT[15:8] is cleared, pin change
interrupt on the corresponding I/O pin is disabled.
8197C–AVR–05/11
53
10. I/O Ports
C
PIN
Logic
R
PU
See Figure
"General Digital I/O" for
Details
Pxn
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports.
This means that the direction of one port pin can be changed without unintentionally changing
the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/ disabling of p ull-up resist ors (if con figured as
input). Each output buffer has symmetrical drive characteristics with both high sink and source
capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have
protection diodes to both V
istics” on page 185 for a complete list of parameters.
Figure 10-1.I/O Pin Equivalent Schematic
and Ground as indicated in Figure 10-1. See “Electrical Character-
CC
All registers and bit references in this section are written in general form. A lower case “x” r epresents the numbering letter for the port, and a lower case “n” rep resents the bit number. However,
when using the register or bit defines in a program , the precise form must be used. For examp le,
PORTB3 for bit no. 3 in Port B, here documented ge ner ally as PO RTxn . The physical I /O Registers and bit locations are listed in “Register Description” on page 68.
Three I/O memory address locations are allocated for each port, one each for the Data Register
– PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins
I/O location is read only, while the Data Register and the Data Direction Register are read/write.
However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register. In addition, the Pull-up Disable – PUD bit in MCUCR disables the
pull-up function for all pins in all ports when set.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on page
55. Most port pins are multiplexed with alternate func tions for the peripheral featur es on the
device. How each alternate function interferes with the port pin is described in “Alternate Port
Functions” on page 59. Refer to the individual module sections for a full description of the alter-
nate functions.
Note that enabling the alternate function of some of the port pins does not affect the use of the
other pins in the port as general digital I/O.
54
ATtiny261A/461A/861A
8197C–AVR–05/11
10.1Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a functional description of one I/O-port pin, here generically called Pxn.
ATtiny261A/461A/861A
Figure 10-2.General Digital I/O
Pxn
SLEEP
(1)
SYNCHRONIZER
DLQ
Q
D
PINxn
PUD
Q
D
DDxn
Q
CLR
RESET
WDx
RDx
Q
PORTxn
Q
CLR
D
1
0
DATA BU S
RESET
WRx
RRx
RPx
Q
Q
WPx
Note:1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clk
10.1.1Configuring the Pin
Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in “Register
Description” on page 68, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits
at the PORTx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one,
Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input
pin.
If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is
activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the pin h as to
be configured as an output pin. The port pi ns are tri-stated when re set condition b ecomes active,
even if no clocks are running.
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven
high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port
pin is driven low (zero).
10.1.2Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn.
Note that the SBI instruction can be used to toggle one single bit in a port.
10.1.3Switching Between Input and Output
When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn}
= 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output
low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver
and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all
pull-ups in all ports.
Switching between input with pull-up and output low generates the same problem. The user
must use either the tri-sta te ({DDxn, PORTxn} = 0b00) o r the o utput high state ({DDxn, PORTxn}
= 0b10) as an intermediate step.
Table 10-1 summarizes the control signals for the pin value.
Table 10-1.Port Pin Configurations
DDxnPORTxn
00XInputNoTri-state (Hi-Z)
010InputYe sPxn will source current if ext. pulled low
011InputNoTri-state (Hi-Z)
10XOutputNoOutput Low (Sink)
11XOutputNoOutput High (Source)
10.1.4Reading the Pin Value
Independent of the setting of Data Direction b it DDxn, the port pin can be read through the
PINxn Register bit. As shown in Figure 10-2, t he PINxn Regist er bit a nd th e prece ding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value
near the edge of the internal clock, but it also intro duces a delay. Fi gure 10-3 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and
minimum propagation delays are deno te d t
PUD
(in MCUCR)I/OPull-upComment
pd,max
and t
respectively.
pd,min
56
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
XXXin r17, PINx
0x000xFF
INSTRUCTIONS
SYNC LATCH
PINxn
r17
XXX
SYSTEM CLK
t
pd, max
t
pd, min
out PORTx, r16nopin r17, PINx
0xFF
0x000xFF
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
t
pd
Figure 10-3.Synchronization when Reading an Externally Applied Pin value
Consider the clock period starting shortly after the first falling edge of the system clock. The latch
is closed when the clock is low, and goes transparent when the clock is high, as indicated by the
shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock
goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed
between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 10-4. The out instruction sets the “SYNC LATCH” signal at the positive edge of
the clock. In this case, the delay tpd through the synchronizer is one system clock period.
Figure 10-4.Synchronization when Reading a Software Assigned Pin Value
8197C–AVR–05/11
57
10.1.5Digital Input Enable and Sleep Modes
As shown in Figure 10-2, the digital input signal can be clamped to ground at the input of the
schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in
Power-down mode, Power-save mode, and Standb y mode to avoid high power co nsumption if
some input signals are left floating, or have an analog signal level close to V
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt
request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various
other alternate functions as described in “Alternate Port Functions” on page 59.
If a logic high level (“one”) is present on an asynchronous external interrupt pin configured as
“Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the extern al interrupt
is not enabled, the corresponding External Interrupt Flag will be set when resuming from the
above mentioned Sleep mode, as the clamping in these sleep mode produces the requested
logic change.
10.1.6Unconnected Pins
If some pins are unused, it is recommended to ensure t hat these pins have a defi ned level. Even
though most of the digital inputs are disabled in th e deep sleep modes as de scribed above, floating inputs should be avoided to reduce current consumption in all other modes where the digital
inputs are enabled (Reset, Active mode and Idle mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up.
In this case, the pull-up will be disabled during reset. If low power consumption during reset is
important, it is recommended to use an external pull-up or pulldown. Connecting unused pins
directly to V
or GND is not recommended, since this may caus e excessiv e currents if t he pin is
CC
accidentally configured as an output.
CC
/2.
10.1.7Program Examples
The following code examples show how to set port B pins 0 and 1 high, 2 and 3 low, and define
the port pins from 4 to 5 as input with a pull-up assigned to port pin 4. T he resulting pin values
are read back again, but as previously discussed, a nop instruction is in cluded to be able t o read
back the value recently assigned to some of the pins.
Assembly Code Example
Note:Two temporar y registers are used to minimize the time from pull-ups are set on pins 0, 1 and 4,
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldir16,(1<<PB4)|(1<<PB1)|(1<<PB0)
ldir17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0)
outPORTB,r16
outDDRB,r17
; Insert nop for synchronization
nop
; Read port pins
inr16,PINB
...
until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as
strong high drivers.
58
ATtiny261A/461A/861A
8197C–AVR–05/11
C Code Example
unsigned char i;
...
/* Define pull-ups and set outputs high */
/* Define directions for port pins */
PORTB = (1<<PB4)|(1<<PB1)|(1<<PB0);
DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0);
/* Insert nop for synchronization*/
_NOP();
/* Read port pins */
i = PINB;
...
Note:See “Code Examples” on page 6.
10.2Alternate Port Functions
Most port pins have alternate functions in addition to being general digital I/Os. Figure 10-5
shows how the port pin control signals from th e simplified Figure 10-2 can be overridden by
alternate functions. The overriding signals may not be present in all port pins, but the figure
serves as a generic description applicable to all port pins in the AVR microcontroller family.
ATtiny261A/461A/861A
8197C–AVR–05/11
59
Figure 10-5.Alternate Port Functions
clk
RPx
RRx
WRx
RDx
WDx
PUD
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
PUD: PULLUP DISABLE
clk
I/O
: I/O CLOCK
RDx: READ DDRx
DLQ
Q
SET
CLR
0
1
0
1
0
1
DIxn
AIOxn
DIEOExn
PVOVxn
PVOExn
DDOVxn
DDOExn
PUOExn
PUOVxn
PUOExn: Pxn PULL-UP OVERRIDE ENABLE
PUOVxn: Pxn PULL-UP OVERRIDE VALUE
DDOExn: Pxn DATA DIRECTION OVERRIDE ENABLE
DDOVxn: Pxn DATA DIRECTION OVERRIDE VALUE
PVOExn: Pxn PORT VALUE OVERRIDE ENABLE
PVOVxn: Pxn PORT VALUE OVERRIDE VALUE
DIxn: DIGITAL INPUT PIN n ON PORTx
AIOxn: ANALOG INPUT/OUTPUT PIN n ON PORTx
RESET
RESET
Q
Q D
CLR
Q
Q
D
CLR
Q
Q
D
CLR
PINxn
PORTxn
DDxn
DATA BUS
0
1
DIEOVxn
SLEEP
DIEOExn: Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE
DIEOVxn: Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE
SLEEP:SLEEP CONTROL
Pxn
I/O
0
1
PTOExn
PTOExn: Pxn, PORT TOGGLE OVERRIDE ENABLE
WPx:WRITE PINx
WPx
(1)
Note:1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clk
SLEEP, and PUD are common to all ports. All other signals are unique for each pin.
I/O
,
60
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
Table 10-2 summarizes the function of the o verridin g signals. Th e pin and por t indexes f rom Fig-
ure 10-5 are not shown in the succeeding tables. The overriding signals ar e gen erat ed intern ally
in the modules having the alternate function.
Table 10-2.Generic Description of Overriding Signals for Alternate Functions
Signal NameFull NameDescription
If this signal is set, the pull-up enable is controlled by the PUOV
signal. If this signal is cleared, the pull-up is enabled when
{DDxn, PORTxn, PUD} = 0b010.
If PUOE is set, the pull-up is enabled/disabled when PUOV is
set/cleared, regardless of the setting of the DDxn, PORTxn,
and PUD Register bits.
If this signal is set, the Output Driver Enable is controlled by the
DDOV signal. If this signal is cleared, the Output driver is
enabled by the DDxn Register bit.
If DDOE is set, the Output Driver is enabled/disabled when
DDOV is set/cleared, regardless of the setting of the DDxn
Register bit.
If this signal is set and the Output Driver is enabled, the port
value is controlled by the PVOV signal. If PVOE is cleared, and
the Output Driver is enabled, the port Value is controlled by the
PORTxn Register bit.
PUOE
PUOV
DDOE
DDOV
PVOE
Pull-up Override
Enable
Pull-up Override
Value
Data Direction
Override Enable
Data Direction
Override Value
Port Value
Override Enable
PVOV
PTOE
DIEOE
DIEOV
DIDigital Input
AIO
Port Value
Override Value
Port Toggle
Override Enable
Digital Input
Enable Override
Enable
Digital Input
Enable Override
Value
Analog
Input/Output
If PVOE is set, the port value is set to PVOV, regardless of the
setting of the PORTxn Register bit.
If PTOE is set, the PORTxn Register bit is inverted.
If this bit is set, the Digital Input Enable is controlled by the
DIEOV signal. If this signal is cleared, the Digital Input Enable
is determined by MCU state (Normal mode, sleep mode).
If DIEOE is set, the Digital Input is enabled/disabled when
DIEOV is set/cleared, regardless of the MCU state (Normal
mode, sleep mode).
This is the Digital Input to alternate functions. In the figure, the
signal is connected to the output of the schmitt-trigger but
before the synchronizer. Unless the Digital Input is used as a
clock source, the module with the alternate function will use its
own synchronizer.
This is the Analog Input/Output to/from alternate functions. The
signal is connected directly to the pad, and can be used bidirectionally.
The following subsections shortly describe the alternate functions for each port, and relate the
overriding signals to the alternate function. Refer to the alternate function description for further
details.
8197C–AVR–05/11
61
10.2.1Alternate Functions of Port A
The Port A pins with alternate function are shown in Table 10-3.
• AIN0: Analog Comparator Input. Configure the port pin as input with the internal pull-up
switched off to avoid the digital port function from interfering with the fu nction of the Analog
Comparator.
• PCINT7: Pin Change Interrupt source 8.
• Port A, Bit 6 – ADC5/AIN1/PCINT6
• ADC5: Analog to Digital Converter, Channel 5.
• AIN1: Analog Comparator Input. Configure the port pin as input with the internal pull-up
switched off to avoid the digital port function from interfering with the fu nction of the Analog
Comparator.
• PCINT6: Pin Change Interrupt source 6.
62
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
• Port A, Bit 5 – ADC4/AIN2/PCINT5
• ADC4: Analog to Digital Converter, Channel 4.
• AIN2: Analog Comparator Input. Configure the port pin as input with the internal pull-up
switched off to avoid the digital port function from interfering with the fu nction of the Analog
Comparator.
• PCINT5: Pin Change Interrupt source 5.
• Port A, Bit 4 – ADC3/ICP0/PCINT4
• ADC3: Analog to Digital Converter, Channel 3.
• ICP0: Timer/Counter0 In put Capture Pin.
• PCINT4: Pin Change Interrupt source 4.
• Port A, Bit 3 – AREF/PCINT3
• AREF: External analog reference for ADC. Pullup and output driver are disabled on PA3
when the pin is used as an external reference or internal voltage reference with external
capacitor at the AREF pin.
• PCINT3: Pin Change Interrupt source 3.
• Port A, Bit 2 – ADC2/INT1/USCK/SCL/PCINT2
• ADC2: Analog to Digital Converter, Channel 2.
• INT1: The PA2 pin can serve as an External Interrupt source 1.
• USCK: Three-wire mode Universal Serial Interface Clock.
• SCL: Two-wire mode Serial Clock for USI Two-wire mode.
• PCINT2: Pin Change Interrupt source 2.
• Port A, Bit 1 – ADC1/DO/PCINT1
• ADC1: Analog to Digital Converter, Channel 1.
• DO: Three-wire mode Universal Serial Interface Data output. Three-wire mode Data output
overrides PORTA1 value and it is driven to the port when data direction bit DDA1 is set.
PORTA1 still enables the pull-up, if the direction is input and PORTA1 is set.
• PCINT1: Pin Change Interrupt source 1.
• Port A, Bit 0 – ADC0/DI/SDA/PCINT0
• ADC0: Analog to Digital Converter, Channel 0.
• DI: Data Input in USI Three-wir e mode. USI Three-wire mode does not override normal port
functions, so pin must be configure as an input for DI function.
• SDA: Two-wire mode Serial Interface Data.
• PCINT0: Pin Change Interrupt source 0.
8197C–AVR–05/11
63
Table 10-4 and Table 10-5 relate the alternate functions of Port A to the overriding signals
shown in Figure 10-5 on page 60.
Table 10-4.Overriding Signals for Alternate Functions in PA[7:4]
OC1B: Timer/Counter1 Compare Match B Output
PCINT11:Pin Change Interrupt 0, Source 11
USCK: USI Clock (Three Wire Mode)
PB2
PB1
PB0
• Port B, Bit 7 – RESET
SCL :USI Clock (Two Wire Mode)
: Inverted Timer/Counter1 Compare Match B Output
OC1B
PCINT10:Pin Change Interrupt 0, Source 10
DO:USI Data Output (Three Wire Mode)
OC1A: Timer/Counter1 Compare Match A Output
PCINT9:Pin Change Interrupt 1, Source 9
DI:USI Data Input (Three Wire Mode)
SDA:USI Data Input (Two Wire Mode)
OC1A
: Inverted Timer/Counter1 Compare Match A Output
PCINT8:Pin Change Interrupt 1, Source 8
/dW/ADC10/PCINT15
• RESET, Reset pin: When the RSTDISBL Fuse is programmed, this pin functi ons as a normal
I/O pin, and the part will have to rely on Power-on Reset and Brown-out Reset as its reset
sources. When the RSTDISBL Fuse is unprogrammed, the reset circuitry is connected to the
pin, and the pin can not be used as an I/O pin.
• If PB7 is used as a reset pin, DDB7, PORTB7 and PINB7 will all read 0.
• dW: When the debugWIRE Enable (DWEN) Fuse is programmed and Lock bits are
unprogrammed, the RESET port pin is configured as a wire-AND (open-drain) bi-directional
I/O pin with pull-up enabled and becomes the communication gateway between target and
emulator.
8197C–AVR–05/11
65
• ADC10: ADC input Channel 10. Note that ADC input channel 10 uses analog power.
• PCINT15: Pin Change Interrupt source 15.
• Port B, Bit 6 – ADC9/T0/INT0/PCINT14
• ADC9: ADC input Channel 9. Note that ADC input channel 9 uses analog power.
• T0: Timer/Counter0 counter source.
• INT0: The PB6 pin can serve as an External Interrupt source 0.
• PCINT14: Pin Change Interrupt source 14.
• Port B, Bit 5 – XTAL2/CLKO/ADC8/PCINT13
• XTAL2: Chip clock Oscillator pin 2. Used as clock pin for crystal Oscillator or Low-frequency
crystal Oscillator. When used as a clock pin, the pin can not be used as an I/O pin.
• CLKO: The divided system clock can be output on the PB5 pin, if the CKOUT Fuse is
programmed, regardless of the PORTB5 and DDB5 settings. It will also be output during
reset.
• OC1D Output Compare Match output: The PB5 pin can serve as an external output for the
Timer/Counter1 Compare Match D when configured as an output (DDA1 set). The OC1D pin
is also the output pin for the PWM mode timer function.
• ADC8: ADC input Channel 8. Note that ADC input channel 8 uses analog power.
• PCINT13: Pin Change Interrupt source 13.
• Port B, Bit 4 – XTAL1/CLKI/OC1B/ADC7/PCINT12
• XTAL1/CLKI: Chip clock Oscillator pin 1. Used for all chip clock sources except internal
calibrated oscillator. When used as a clock pin, the pin can not be used as an I/O pin.
•OC1D
• ADC7: ADC input Channel 7. Note that ADC input channel 7 uses analog power.
• PCINT12: Pin Change Interrupt source 12.
• Port B, Bit 3 – OC1B/PCINT11
• OC1B, Output Compare Match output: The PB3 pin can serve as an external output for the
• PCINT11: Pin Change Interrupt source 11.
• Port B, Bit 2 – SCK/USCK/SCL/OC1B
• USCK: Three-wire mode Universal Serial Interface Clock.
• SCL: Two-wire mode Serial Clock for USI Two-wire mode.
•OC1B
• PCINT10: Pin Change Interrupt source 10.
: Inverted Output Compare Match output: The PB4 pin can serve as an external output
for the Timer/Counter1 Compare Match D when configured as an output (DDA0 set). The
OC1D
pin is also the inverted output pin for the PWM mode timer function.
Timer/Counter1 Compare Match B. The PB3 pin has to be configured as an output (DDB3
set (one)) to serve this function. The OC1B pin is also the output pin f or the PWM mode timer
function.
/PCINT10
: Inverted Output Compare Match output: Th e PB2 pin can se rve as an external output
for the Timer/Counter1 Compare Match B when configured as an output (DDB2 set). The
OC1B
pin is also the inverted output pin for the PWM mode timer function.
66
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
• Port B, Bit 1 – MISO/DO/OC1A/PCINT9
• DO: Three-wire mode Universal Serial Interface Data output. Three-wire mode Data output
overrides PORTB1 value and it is driven to the port when data direction bit DDB1 is set (one).
PORTB1 still enables the pull-up, if the direction is input and PORTB1 is set (one).
• OC1A: Output Compare Match output: The PB1 pin can serve as an external output for the
Timer/Counter1 Compare Match B when configured as an ou tput (DDB1 set). The OC1A pin
is also the output pin for the PWM mode timer function.
• PCINT9: Pin Change Interrupt source 9.
• Port B, Bit 0 – MOSI/DI/SDA/OC1A
/PCINT8
• DI: Data Input in USI Three-wir e mode. USI Three-wire mode does not override normal port
functions, so pin must be configure as an input for DI function.
• SDA: Two-wire mode Serial Interface Data.
•OC1A
: Inverted Output Compare Match output: Th e PB0 pin can se rve as an external output
for the Timer/Counter1 Compare Match B when configured as an output (DDB0 set). The
OC1A
pin is also the inverted output pin for the PWM mode timer function.
• PCINT8: Pin Change Interrupt source 8.
Table 10-7 and Table 10-8 relate the alternate functions of Port B to the overriding signals
shown in Figure 10-5 on page 60.
Table 10-7.Overriding Signals for Alternate Functions in PB[7:4]
When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and
PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01). See “Con-
figuring the Pin” on page 55 for more details about this feature.
• Four Independent Interrupt Sources (TOV0, OCF0A, OCF0B, ICF0)
• 8-bit Mode with Two Independent Output Compare Units
• 16-bit Mode with One Independent Output Compare Unit
11.2Overview
Timer/Counter0 is a general purpose 8/16-bit Timer/Counter module, with two/one Output Compare units and Input Capture feature.
The general operation of Timer/Counter0 is described in 8/16-bit mode. A simplified block diagram of the 8/16-bit Timer/Counter is shown in Figure 11-1. CPU accessible I/O Registers,
including I/O bits and I/O pins, are shown in bold. For actual placement of I/O pins, refer to “Pin-
out ATtiny261A/461A/861A” on page 2. Device-specific I/O Register and bit locations are listed
in the “Register Description” on page 83.
Figure 11-1.8-/16-bit Timer/Counter Block Diagram
11.2.1Registers
70
The Timer/Counter0 Low Byte Register (TCNT0L) and Output Compare Registers (OCR0A and
ATtiny261A/461A/861A
OCR0B) are 8-bit registers. Interr upt r equest ( abbre viated I nt. Req. in Figure 11-1) sign als are al l
8197C–AVR–05/11
11.2.2Definitions
ATtiny261A/461A/861A
visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the
Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure.
In 16-bit mode one more 8-bit register is available, the Timer/Counter0 High Byte Register
(TCNT0H). Also, in 16-bit mode, there is only one output compare unit as the two Output Compare Registers, OCR0A and OCR0B, are combined to one, 16-bit Output Compare Register,
where OCR0A contains the low byte and OCR0B contains the high byte of the word. When
accessing 16-bit registers, special procedures described in section “Accessing Registers in 16-
bit Mode” on page 79 must be followed.
Many register and bit references in this section are written in genera l form. A lower case “n”
replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Compare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or
bit defines in a program, the precise form must be used, i.e. TCNT0L for accessing
Timer/Counter0 counter value, and so on.
The definitions in Table 11-1 are also used extensively throughout the document.
Table 11-1.Definitions
ConstantDescription
BOTTOMThe counter reaches BOTTOM when it becomes 0x00
MAXThe counter reaches its MAXimum when it becomes 0xFF (decimal 255)
11.3Clock Sources
11.3.1Prescaler
The counter reaches the TOP when it becomes equal to the highest value in the count
TOP
sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the
value stored in the OCR0A Register. The assignment depends on the mode of operation
The Timer/Counter can be clocked internally, via th e prescaler, or b y an external clo ck source on
the T0 pin. The Clock Select logic is controlled by the Clock Select (CS0[2:0]) bits located in the
Timer/Counter Control Register 0 B (TCCR0B), and controls which clock source and edge the
Timer/Counter uses to increm ent its value . The Tim er/Counter is inactive when no clock sourc e
is selected. The output from the Clock Select logic is referred to as the timer clock (clk
T0
).
The Timer/Counter can be clocked directly by the system clock (by setting the CSn[2:0] = 1).
This provides the fastest operation, with a maximum Timer/Counter clock frequency equal to
system clock frequency (f
). Alternatively, one of four taps from the prescaler can be used
CLK_I/O
as a clock source.
See Figure 11-2 for an illustration of the prescaler unit.
8197C–AVR–05/11
71
Figure 11-2.Prescaler for Timer/Counter0
clk
I/O
PSR0
T0
Synchronization
Clear
clk
T0
Note:1. The synchronization logic on the input pins (T0) is shown in Figure 11-3.
The prescaled clock has a frequency of f
Table 11-4 on page 84 for details.
11.3.1.1Prescaler Re se t
The prescaler is free running, i.e. it operates independe ntly of the Clock Select logic of the
Timer/Counter. Since the prescaler is not affected by the Timer/Counter’s clock select, the state
of the prescaler will have implications for situations where a prescaled clock is used. One example of prescaling artifacts occurs when the timer is enable d and clocked by the prescaler (6 >
CSn[2:0] > 1). The number of system clock cycles from when the timer is enabled to the first
count occurs can be from 1 to N+1 system clock cycles, where N equals the prescaler diviso r (8,
64, 256, or 1024). It is possible to us e the Prescaler Reset for sync hronizing the T imer/Counte r
to program execution.
11.3.2External Clock Source
An external clock source applied to the T0 pin can be used as Timer/Cou nter clo ck (clk
T0 pin is sampled once every system clock cycle by the pin synchronization logic. The synchronized (sampled) signal is then passed through the edge detector.
equivalent block diagram of the T0 synchronization and edge detector logic. The registers are
clocked at the positive edge of the internal system clock (
high period of the internal system clock.
CLK_I/O
/8, f
CLK_I/O
/64, f
clk
I/O
/256, or f
CLK_I/O
Figure 11-3 shows a functional
CLK_I/O
). The latch is transparent in the
/1024. See
). The
T0
72
The edge detector generates one clk
(CSn[2:0] = 6) edge it detects. See Table 11-4 on page 84 for details.
ATtiny261A/461A/861A
pulse for each positive (CSn[2:0] = 7) or negative
0
T
8197C–AVR–05/11
Figure 11-3.T0 Pin Sampling
DATA BUS
TCNTnControl Logic
count
TOVn
(Int.Req.)
Clock Select
top
Tn
Edge
Detector
( From Prescaler )
clk
Tn
ATtiny261A/461A/861A
11.4Counter Unit
Tn
clk
DQDQ
LE
I/O
DQ
Edge DetectorSynchronization
Tn_sync
(To Clock
Select Logic)
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the T0 pin to the counter is updated.
Enabling and disabling of the clock input must be done when T0 has been stable for at least one
system clock cycle, otherwise it is a risk that a false Timer/Count er clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the system clock frequency (f
ExtClk
< f
/2) given a 50/50% duty cycle. Since the edge detec tor uses
clk_I/O
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than f
clk_I/O
/2.5.
An external clock source can not be prescaled.
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
11-4 shows a block diagram of the counter and its surroundings.
Table 11-2.Counter Unit Block Diagram
Signal description (internal signals):
countIncrement or decrement TCNT0 by 1.
clk
topSignalize that TCNT0 has reached maximum value.
The counter is incremented at each timer clock (clk
restarts from BOTTOM. The counting sequence is determined by the setting of the CTC0 bit
located in the Timer/Counter Control Register (TCCR0A). For more details about counting
sequences, see “Modes of Operation” on page 76. clk
8197C–AVR–05/11
Tn
Timer/Counter clock, referred to as clkT0 in the following.
) until it passes its TOP value and then
T0
can be generated from an external or
T0
73
internal clock source, selected by the Clock Select bits (CS0[2:0]). When no clock source is
ICF0 (Int.Req.)
Analog
Comparator
WRITE
ICR0 (16-bit Register)
OCR0B (8-bit)
Noise
Canceler
ICP0
Edge
Detector
TEMP (8-bit)
DATA BUS (8-bit)
OCR0A (8-bit)
TCNT0 (16-bit Counter)
TCNT0H (8-bit)TCNT0L (8-bit)
ACIC0*ICNC0ICES0
ACO*
selected (CS0[2:0] = 0) the timer is stopped. However , the TCNT0 value can be acce ssed by the
CPU, regardless of whether clk
counter clear or count operations. The Timer/Counter Overflow Flag (TOV0) is set when the
counter reaches the maximum value and it can be used for generating a CPU interrupt.
11.5Input Capture Unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give
them a time-stamp indicating time of occurrence. The externa l signal indica ting an event , or multiple events, can be applied via the ICP0 pin or al ternat ively, via the analog-comp arator unit . The
time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. Alternatively the time-stamps can be used for creating a log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 11-4. The elements of
the block diagram that are not directly a part of the Input Capture unit are gray shaded.
Figure 11-4.Input Capture Unit Block Diagram
is present or not. A CPU write overrides (has priority over) all
T0
74
ATtiny261A/461A/861A
The Output Compare Register OCR0A is a dual-purpose register that is also used as an 8-bit
Input Capture Register ICR0. In 16-bit Input Capture mode the Output Compare Register
OCR0B serves as the high byte of the Input Capture Regist er IC R0 . In 8- bit Input Captu re mode
the Output Compare Register OCR0B is fr ee to be us ed as a nor mal O utput Co mpare Regis ter,
but in 16-bit Input Capture mode the Output Compare Unit cannot be used as there are no free
Output Compare Register(s). Even though the Input Capture register is called ICR0 in this section, it is refering to the Output Compare Register(s).
When a change of the logic level (an event) occurs on the I nput Ca ptur e pin (ICP0), a ltern atively
on the Analog Comparator output (ACO), and this change confirms to the setting of the edge
detector, a capture will be triggered. When a capture is triggered, the value of the counter
(TCNT0) is written to the Input Capture Register (ICR0). The Input Capture Flag (ICF0) is set at
8197C–AVR–05/11
the same system clock as the TCNT0 value is copied into Input Capture Register. If enabled
(TICIE0 = 1), the Input Capture Fla g genera tes a n Inp ut Captur e inte rrup t. The I CF0 fl ag is a utomatically cleared when the interrupt is executed. Alternatively the ICF0 flag can be cleared by
software by writing a logical one to its I/O bit location.
11.5.1Input Capture Trigger Source
The default trigger source for the Input Capture unit is the Input Capture pin (ICP0).
Timer/Counter0 can alternatively use the Analog Comparator output as trigger source for the
Input Capture unit. The Analog Comparator is selected as trigger source by setting the Ana log
Comparator Input Capture Enable (ACIC0) bit in the Timer/Counter Control Register A
(TCCR0A). Be aware that changing trigger source can trigger a captur e. The Inp ut Ca pt ure Flag
must therefore be cleared after the change.
Both the Input Capture pin (ICP0) and the Analog Comparator output (ACO) inputs are sampled
using the same technique as for the T0 pin (Figure 11-4 on page 84). The edge detector is also
identical. However, when the noise canceler is enabled, additional logic is inserted before the
edge detector, which increases the delay by four syst em clock cycles. An In put Capture can also
be triggered by software by controlling the port of the ICP0 pin.
11.5.2Noise Canceler
The noise canceler improves noise immunity by using a simple digital filtering scheme. The
noise canceler input is monitored over four samples, and all four must be equal for changing the
output that in turn is used by the edge detector.
ATtiny261A/461A/861A
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNC0) bit in
Timer/Counter Control Register B (TCCR0B). When enabled t he noise canceler int roduces additional four system clock cycles of delay from a change applied to the input, to the update of the
ICR0 Register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.
11.5.3Using the Input Capture Unit
The main challenge when using the Input Cap ture unit is to assign enough p rocessor capacity
for handling the incoming events. The time bet ween two events is critical . If the processor has
not read the captured value in the ICR0 Register before the next event occurs, the ICR0 will be
overwritten with a new value. In this case the result of the capture will be incorrect.
When using the Input Capture interrupt, the ICR0 Register should be read as early in the interrupt handler routine as possible. The maximum interrupt response time is dependent on the
maximum number of clock cycles it takes to handle any of the other interrupt requests.
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after
each capture. Changing the edge sensin g must be done as early as possib le after the ICR0
Register has been read. After a change of the edge, the Input Capture Flag (ICF0) must be
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the trigger edge change is not required (if an inter rupt handler is used).
11.6Output Compare Unit
The comparator continuously compares Timer/Counter (TCNT0) with the Output Compare Registers (OCR0A and OCR0B), and whenever the Timer/Counter equals to the Output Compare
Regisers, the comparator signals a match. A match will set the Output Compare Flag at the next
timer clock cycle. In 8-bit mode the match can set either the Output Compare Flag OCF0A or
8197C–AVR–05/11
75
OCF0B, but in 16-bit mode the match can set only the Output Compare Flag OCF0A as there is
OCFnx (Int.Req.)
= (8/16-bit Comparator )
OCRnx
DATA BUS
TCNTn
only one Output Compare Unit. If the corresponding interrupt is enabled, the Output Compare
Flag generates an Output Compare interrupt. The Out put Co mpare Fla g is aut omatica lly cleared
when the interrupt is executed. Alternatively, the f lag can be cleared by software by writing a logical one to its I/O bit location. Figure 11-5 shows a block diagram of the Output Compare unit.
Figure 11-5.Output Compare Unit, Block Diagram
11.6.1Compare Match Blocking by TCNT0 Write
All CPU write operations to the TCNT0H/L Register will block any Compare Match that occur in
the next timer clock cycle, even when the timer is stopped. This feature allows OCR0A/B to be
initialized to the same value as TCNT0 without triggering an interrupt when the Timer/Counter
clock is enabled.
11.6.2Using the Output Compare Unit
Since writing TCNT0H/L will block all Compare Matches for one timer clock cycle, there are risks
involved when changing TCNT0H/L when using the Output Compare Unit, independently of
whether the Timer/Counter is running or not. If the value written to TCNT0H/L equals the
OCR0A/B value, the Compare Match will be missed.
11.7Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is
defined by the Timer/Counter Width (TCW0), Input Capture Enable (ICEN0) and Wave Generation Mode (CTC0) bits. See “TCCR0A – Timer/Counter0 Control Register A” on page 83.
Table 11-3 summarises the different modes of operation.
Table 11-3.Modes of operation
ModeICEN0TCW0CTC0Mode of OperationTOPUpdate of OCRx atTOV Flag Set on
In Normal 8-bit mode (see Table 11-3), the counter (TCNT0L) is incrementing until it overruns
when it passes its maximum 8-bit value (MAX = 0xFF) and then restarts from the bottom (0x00).
76
ATtiny261A/461A/861A
8197C–AVR–05/11
The Overflow Flag (TOV0) is set in the same timer clock cycle as when TCNT0L becomes zero.
TCNTn
OCnx Interrupt Flag Set
14
Period
23
The TOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 Flag, the
timer resolution can be increased by software. There are no special cases to consider in the
Normal 8-bit mode, a new counter value can be written anytime. The Output Compare Unit can
be used to generate interrupts at some given time.
11.7.2Clear Timer on Compare Match (CTC) 8-bit Mode
In Clear Timer on Compare or CTC mode, see Table 11-3 on page 76, the OCR0A Register is
used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the
counter value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter,
hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 11-6. The counter value (TCNT0)
increases until a Compare Match occurs between TCNT0 and OCR0A, and then counter
(TCNT0) is cleared.
Figure 11-6.CTC Mode, Timing Diagram
ATtiny261A/461A/861A
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR0A is lower than the current
value of TCNT0, the counter will miss the Compare Match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the Co mpare Match can
occur. As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle
that the counter counts from MAX to 0x00.
11.7.3Normal, 16-bit Mode
In 16-bit mode, see Table 11-3 on page 76, the counter (TCNT0H/L) is a incrementin g until it
overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the
bottom (0x0000). The Overflow Flag (TOV0) will be set in the same timer clock cycle as the
TCNT0H/L becomes zero. The TOV0 Flag in this case behaves like a 17th bit, except that it is
only set, not cleared. However, combined with the timer overflow interrupt that automatically
clears the TOV0 Flag, the timer resolution can be increased by softw are. There are no specia l
cases to consider in the Normal mode, a new counter value can be written anytime. The Output
Compare Unit can be used to generate interrupts at some given time.
8197C–AVR–05/11
77
11.7.48-bit Input Capture Mode
clk
Tn
(clk
I/O
/1)
TOVn
clk
I/O
TCNTnMAX - 1MAXBOTTOMBOTTOM + 1
TOVn
TCNTn
MAX - 1MAXBOTTOMBOTTOM + 1
clk
I/O
clk
Tn
(clk
I/O
/8)
The Timer/Counter0 can also be used in an 8-bit Input Capture mode, see Table 11-3 on page
76 for bit settings. For full description, see the section “Input Capture Unit” on page 74.
11.7.516-bit Input Capture Mode
The Timer/Counter0 can also be used in a 16-bit Input Capture mode, see Table 11-3 on page
76 for bit settings. For full description, see the section “Input Capture Unit” on page 74.
11.8Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT0) is therefore shown as a
clock enable signal in the following figures. Th e figures include information on whe n Interrupt
Flags are set. Figure 11-7 contains timing data for basic Timer/Counter op eration. The figure
shows the count sequence close to the MAX value.
Figure 11-7.Timer/Counter Timing Diagram, no Prescaling
Figure 11-8 shows the same timing data, but with the prescaler enabled.
Figure 11-8.Timer/Counter Timing Diagram, with Prescaler (f
clk_I/O
/8)
Figure 11-9 on page 79 shows the setting of OCF0A and OCF0B in Normal mode.
78
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1OCRnxOCRnx + 1OCRnx + 2
clk
I/O
clk
Tn
(clk
I/O
/8)
OCFnx
OCRnx
TCNTn
(CTC)
TOP
TOP - 1TOPBOTTOMBOTTOM + 1
clk
PCK
clk
Tn
(clk
PCK
/8)
Figure 11-9.Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (f
Figure 11-10 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode.
Figure 11-10.Timer/Counter Timing Diagram, CTC mode, with Prescaler (f
clk_I/O
clk_I/O
/8)
/8)
11.9Accessing Registers in 16-bit Mode
In 16-bit mode (the TCW0 bit is set to one) the TCNT0H/L and OCR0A/B or TCNT0L/H and
OCR0B/A are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus. The
16-bit register must be byte accessed using two read or write operations. The 16-bit
Timer/Counter has a single 8-bit register for temporary storing of the high byte of the 16-bit
access. The same temporary register is shared between all 16-bit registers. Accessing the low
byte triggers the 16-bit read or write operation. When the low byte of a 16-bit register is written
by the CPU, the high byte stored in the t emporary reg ister, and the low byte writ ten are both copied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read
by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same
clock cycle as the low byte is read.
There is one exception in the temporary register usage. In the Output Compare mode the 16-bit
Output Compare Register OCR0A/B is read without the temporary register, because the Output
Compare Register contains a fixed value that is only changed by CPU access. However, in 16bit Input Capture mode the ICR0 register formed by the OCR0A and OCR0B registers must be
accessed with the temporary register.
To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low
byte must be read before the high byte.
8197C–AVR–05/11
79
The following code examples show how to access the 16-bit timer registers assuming that no
interrupts updates the temporary register. The same principle can be used directly for accessing
the OCR0A/B registers.
Assembly Code Example
...
; Set TCNT0 to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNT0H,r17
out TCNT0L,r16
; Read TCNT0 into r17:r16
in r16,TCNT0L
in r17,TCNT0H
...
C Code Example
unsigned int i;
...
/* Set TCNT0 to 0x01FF */
TCNT0H = 0x01;
TCNT0L = 0xff;
/* Read TCNT0 into i */
i = TCNT0L;
i |= ((unsigned int)TCNT0H << 8);
...
Note:See “Code Examples” on page 6.
The assembly code example returns the TCNT0H/L value in the r17:r16 register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt
occurs between the two instructions access ing the 16-bit register, and the interrup t code
updates the temporary register by accessing the same or any other of the 16-bit timer registers,
then the result of the access outside the interrupt will be corrupted. Therefore , when both the
main code and the interrupt code update the temporary register, the main code must disable the
interrupts during the 16-bit access.
80
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
The following code examples show how to do an atomic read of the TCNT0 register contents.
Reading any of the OCR0 register can be done by using the sam e principle.
Assembly Code Example
TIM0_ReadTCNT0:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT0 into r17:r16
in r16,TCNT0L
in r17,TCNT0H
; Restore global interrupt flag
out SREG,r18
ret
C Code Example
unsigned int TIM0_ReadTCNT0( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNT0 into i */
i = TCNT0L;
i |= ((unsigned int)TCNT0H << 8);
/* Restore global interrupt flag */
SREG = sreg;
return i;
}
8197C–AVR–05/11
Note:See “Code Examples” on page 6.
The assembly code example returns the TCNT0H/L value in the r17:r16 register pair.
81
The following code examples show how to do an atomic write of the TCNT0H/L register contents. Writing any of the OCR0A/B registers can be done by using the same principle.
Assembly Code Example
TIM0_WriteTCNT0:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT0 to r17:r16
out TCNT0H,r17
out TCNT0L,r16
; Restore global interrupt flag
out SREG,r18
ret
C Code Example
void TIM0_WriteTCNT0( unsigned int i )
{
unsigned char sreg;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNT0 to i */
TCNT0H = (i >> 8);
TCNT0L = (unsigned char)i;
/* Restore global interrupt flag */
SREG = sreg;
}
Note:See “Code Examples” on page 6.
The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNT0H/L.
11.9.1Reusing the temporary high byte register
If writing to more than one 16-bit register where the hig h byte is the same for all regist ers writte n,
then the high byte only needs to be written once. However, note that the same rule of atomic
operation described previously also applies in this case.
When this bit is written to one 16-bit mode is selected as described Figure 11-7 on page 78.
Timer/Counter0 width is set to 16-bits and the Output Compare Registers OCR0A and OCR0B
are combined to form one 16-bit Output Compare Register. Because the 16-bit registers
TCNT0H/L and OCR0B/A are accessed by the AVR CPU via the 8-bit data bus, special procedures must be followed. These procedures are described in section “Accessing Registers in 16-
bit Mode” on page 79.
• Bit 6 – ICEN0: Input Capture Mode Enable
When this bit is written to onem, the Input Capture Mode is enabled.
• Bit 5 – ICNC0: Input Capture Noise Canceler
Setting this bit activates the Input Capture Noise Canceler. When the noise canceler is activated, the input from the Input Capture Pin (ICP0) is filtered. The filter function requires four
successive equal valued samples of the ICP0 pin for changing its output. T he Input Capture is
therefore delayed by four System Clock cycles when the noise canceler is enabled.
ATtiny261A/461A/861A
• Bit 4 – ICES0: Input Capture Edge Select
This bit selects which edge on the Input Capture Pin (ICP0) that is used to trigger a cap ture
event. When the ICES0 bit is written to zero, a falling (negative) edge is used as trigger, and
when the ICES0 bit is written to one, a rising (positive) edge will trigger the capture. When a capture is triggered according to the ICES0 setting, the coun ter value is copied into the Input
Capture Register. The event will also set the Input Capture Flag (ICF0), and this can be used to
cause an Input Capture Interrupt, if this interrupt is enabled.
• Bit 3 – ACIC0: Analog Compar ator Input Capture Enable
When written logic one, this bit enables the input capture function in Timer/Counter0 to be triggered by the Analog Comparator. The comparat or out put is in this case directly connected to t he
input capture front-end logic, making the comparator utilize the noise canceler and edge select
features of the Timer/Counter0 Input Capture interrupt. When written logic zero, no conn ection
between the Analog Comparator and the input capture function exists. To make the comparator
trigger the Timer/Counter0 Input Captur e interrupt, the TICIE0 bit in the Timer Inte rrupt Mask
Register (TIMSK) must be set.
• Bits 2:1 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 0 – CTC0: Waveform Generation Mode
This bit controls the counting sequence of the counter, the source for maximum (TOP) counter
value, see Figure 11-7 on page 78. M odes of operatio n supported by the Timer /Count er unit ar e:
Normal mode (counter) and Clear Timer on Compare Match (CTC) mode (see “Modes of Oper-
Writing the TSM bit to one activates the Timer/Counter Synchronization mo d e. In th is m o de , th e
value that is written to the PSR0 bit is kept, hence keeping the Prescaler Reset signal asserted.
This ensures that the Timer/Counter is halted and can be configured without the risk of advancing during configuration. When the TSM bit is written to zero, the PSR0 bit is cleared by
hardware, and the Timer/Counter start counting.
• Bit 3 – PSR0: Prescaler Reset Timer/Counter0
When this bit is one, the Timer/Counter0 prescaler will be Reset. This bit is normally cleared
immediately by hardware, except if the TSM bit is set.
• Bits 2:0 – CS0[2:0]: Clock Select0, Bits 2 - 0
The Clock Select0 bits 2, 1, and 0 define the prescaling source of Timer0.
Table 11-4.Clock Select Bit Description
CS02CS01CS00Description
000No clock source (Timer/Counter stopped)
001clk
010clk
011clk
100clk
101clk
110External clock source on T0 pin. Clock on falling edge.
111External clock source on T0 pin. Clock on rising edge.
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
The Timer/Counter0 Register Low Byte, TCNT0L, gives direct access, both for read and write
operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0L Register blocks (disables) the Compare Match on the following timer clock. Modifying the counter (TCNT0L) while
the counter is running, introduces a risk of missing a Compare Match between TCNT0L and the
OCR0x Registers. In 16-bit mode the TCNT0L register contains the lower part of the 16-bit
Timer/Counter0 Register.
When 16-bit mode is selected (the TCW0 bit is set to one) the Timer/Counter Register TCNT0H
combined to the Timer/Counter Register TCNT0L gives direct access, both for rea d and write
operations, to the Timer/Counter un it 16-bit co unter. To ensure tha t both the high and low bytes
are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by
all the other 16-bit registers. See “Accessing Registers in 16-bit Mode” on page 79
11.10.5OCR0A – Timer/Counter0 Output Compare Register A
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT0L). A match can be used to generate an Output Compare interrupt.
ATtiny261A/461A/861A
In 16-bit mode the OCR0A register contains the low byte of the 1 6-bit Out put Compar e Regist er.
To ensure that both the high and the low bytes are written simultaneously when the CPU writes
to these registers, the access is performed using an 8-bit temporary high byte register (TEMP).
This temporary register is shared by all the other 16-bit registers. See “Accessing Registers in
16-bit Mode” on page 79.
11.10.6OCR0B – Timer/Counter0 Output Compare Register B
The Output Compare Register B contains an 8-bit value that is continuously compared with the
counter value (TCNT0L in 8-bit mode and TCNTH in 16-bit mode). A match can be used to generate an Output Compare interrupt.
In 16-bit mode the OCR0B register contains the high byte of the 16-bit Output Compare Register. To ensure that both the high and the low bytes are written simultaneously when the CPU
writes to these registers, the access is performed using an 8-bit temporary high byte register
(TEMP). This temporary register is shared by a ll the ot he r 1 6- bit regist er s. Se e “Accessing Reg-
isters in 16-bit Mode” on page 79.
11.10.7TIMSK – Timer/Counter0 Interrupt Ma sk Register
• Bit 4 – OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable
When the OCIE0A bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter0 Compare Ma tch A interrupt is enabled. The co rr esponding interrupt is execute d
85
if a Compare Match in Timer/Counter0 occurs, i.e., when the OCF0A bit is set in the
Timer/Counter 0 Interrupt Flag Register – TIFR0.
• Bit 3 – OCIE0B: Timer/Counter Output Compare Match B Interrupt Enable
When the OCIE0B bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter Compare Match B interrupt is enabled. The correspondin g interrupt is ex ecuted if
a Compare Match in Timer/Counter occurs, i.e., when the OCF0B bit is set in the Timer/Counter
Interrupt Flag Register – TIFR0.
• Bit 1 – TOIE0: Timer /Counter0 Overflow Interrupt Enable
When the TOIE0 bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter0 occurs, i.e., when the TO V0 bit is set in the Timer/Cou nter 0 Interrupt Flag Register – TIFR0.
• Bit 0 – TICIE0: Timer/Counter0, Input Capture Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Inpu t Capture interrupt is enabled. The corre sponding Interrupt
Vector (See “Interrupts” on page 49.) is executed when the ICF0 flag, located in TIFR, is set.
11.10.8TIFR – Timer/Counter0 Interrupt Flag Register
The OCF0A bit is set when a Compare Match occurs between the Timer/Counter0 and the data
in OCR0A – Output Compare Register0. OCF0A is clear ed by hardware when e xecuting the co rresponding interrupt handling vector. Alternatively, OCF0A is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIE0A (Timer/Counter0 Compare Match Interrupt Enable),
and OCF0A are set, the Timer/Counter0 Compare Match Interrupt is executed.
The OCF0A is also set in 16-bit mode wh en a Compare Match occurs between the Timer/Counter and 16-bit data in OCR0B/A. The OCF0A is not set in Input Capture mode when the Output
Compare Register OCR0A is used as an Input Capture Register.
• Bit 3 – OCF0B: Output Compare Flag 0 B
The OCF0B bit is set when a Compare Match occurs betwee n the Timer/Count er and the data in
OCR0B – Output Compare Register0 B. OCF0B is cleared by hard ware when executing the corresponding interrupt handling vector. Alternatively, OCF0B is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Match Interrupt Enable),
and OCF0B are set, the Timer/Counter Compare Match Interrupt is executed.
The OCF0B is not set in 16-bit Output Compare mode when the Output Compare Register
OCR0B is used as the high byte of the 16-bit Output Compare Register or in 16 -bit Input Capture mode when the Output Compare Register OCR0B is used as the high byte of the Input
Capture Register.
86
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
• Bit 1 – TOV0: Timer/Counter0 Overflow Flag
The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by
writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt
Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed.
• Bits 0 – ICF0: Timer/Counter0, Input Capture Flag
This flag is set when a capture event occurs on the ICP0 pin. When the Input Capture Register
(ICR0) is set to be used as the TOP value, the ICF0 flag is set when the counter reaches the
TOP value.
ICF0 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively,
ICF0 can be cleared by writing a logic one to its bit location.
8197C–AVR–05/11
87
12. Timer/Counter1
8-BIT DATABUS
T/C INT. FLAG
REGISTER (TIFR)
10-BIT COMPARATOR
8-BIT OUTPUT COMPARE
REGISTER A (OCR1A)
T/C INT. MASK
REGISTER (TIMSK)
TIMER/COUNTER1
(TCNT1)
DIRECTION
TIMER/COUNTER1 CONTROL LOGIC
OCF1B
TOV1
TOIE1
OCIE1B
OCIE1A
OCF1A
TOV1OCF1BOC1AOCF1A
T/C CONTROL
REGISTER A (TCCR1A)
COM1B1
PWM1A
PWM1B
COM1B0
FOC1A
FOC1B
10-BIT COMPARATOR
8-BIT OUTPUT COMPARE
REGISTER B (OCR1B)
COM1A1
COM1A0
T/C CONTROL
REGISTER B (TCCR1B)
CS12
PSR1
CS11
CS10
CS13
OC1A
OC1B
OC1B
DEAD TIME GENERATOR
DEAD TIME GENERATOR
10-BIT COMPARATOR
8-BIT OUTPUT COMPARE
REGISTER C (OCR1C)
10-BIT COMPARATOR
8-BIT OUTPUT COMPARE
REGISTER D (OCR1D)
COM1A1
PWM1D
COM1A0
FOC1D
T/C CONTROL
REGISTER C (TCCR1C)
OCF1D
OCF1D
OCIE1D
OC1D
OC1D
DEAD TIME GENERATOR
PSR1
PSR1
OCW1A
OCW1B
OCW1D
2-BIT HIGH BYTE
REGISTER (TC1H)
W
GM11
FPEN1
T/C CONTROL
REGISTER D (TCCR1E)
COM1B1
COM1B0
COM1D1
COM1D0
FPNC1
FPES1
FPAC1
10-BIT OUTPUT
COMPARE REGISTER B
10-BIT OUTPUT
COMPARE REGISTER C
10-BIT OUTPUT
COMPARE REGISTER D
10-BIT OUTPUT
COMPARE REGISTER A
CLEAR
COUNT
CLK
T/C CONTROL
REGISTER C (TCCR1D)
FAULT_PROTECTION
W
GM10
FPIE1
FPF1
OC1OE5
OC1OE4
OC1OE3
OC1OE2
OC1OE1
OC1OE0
FPIE1
FPF1
12.1Features
• 8/10-Bit Accuracy
• Three Independent Output Compare Units
• Clear Timer on Compare Match (Auto Reload)
• Glitch Free, Phase and Frequency Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• High Speed Asynchronous and Synchronous Clocking with Dedicated Prescaler
• Independent Dead Time Generators for Each PWM Channel
• Fault Protection Unit Can Disable PWM Output Pins
• Five Independent Interrupt Sources (TOV1, OCF1A, OCD1B, OCF1D, FPF1)
12.2Overview
Timer/Counter1 is a general purpose high speed Timer/Counter module, with three independent
Output Compare Units, and with PWM support.
The Timer/Counter1 features a high resolution and a high accu racy usage with the lo wer prescaling opportunities. It can also support three accurate and high speed Pulse Width Modulators
using clock speeds up to 64 MHz. In PWM mode Timer/Counter1 and the output co mpa re registers serve as triple stand-alone PWMs with non-overlapping non-inverted and inverted outputs.
Similarly, the high prescaling opportunities make this unit useful for lower speed functions or
exact timing functions with infrequent actions. A simplified block diagram of the Timer/Counter1
is shown in Figure 12-1.
Figure 12-1.Timer/Counter1 Block Diagram
88
ATtiny261A/461A/861A
8197C–AVR–05/11
12.2.1Speed
12.2.2Accuracy
ATtiny261A/461A/861A
For actual placement of the I/O pins, refer to “Pin out ATtiny261A/461A/861A” on page 2. The
device-specific I/O register and bit locations ar e liste d in the “Register Description” on page 111.
The maximum speed of the Timer/Counter1 is 64 MHz. However, if a supply voltage below 2.7
volts is used, it is recommended to use the Low Speed Mode (LSM), because the
Timer/Counter1 is not running fast enough on low voltage levels. In the Low Speed Mode the
fast peripheral clock is scaled down to 32 MHz. For more details about the Low Speed Mode,
see “PLLCSR – PLL Control and Status Register” on page 119.
The Timer/Counter1 is a 10-bit Ti mer/Cou nter modu le that can alternatively be used as an 8-bit
Timer/Counter. The Timer/Counter1 registers are basically 8-bit registers, but on top of that
there is a 2-bit High Byte Register (TC1H) that can be used as a common temporary buffer to
access the two MSBs of the 10-bit Timer/Counter1 registers by the AVR CPU via the 8-bit data
bus, if the 10-bit accuracy is used. Whereas, if the two MSBs of the 10-bit registers are writ ten to
zero the Timer/Counter1 is working as an 8-b it Time r/Coun ter. When readin g the low byte of any
8-bit register the two MSBs are written to the TC1H register, and when writing the low byte of
any 8-bit register the two MSBs are written from the TC1H register. Special procedures must be
followed when accessing the 10-bit Timer/Counter1 values via the 8-bit data bus. These procedures are described in the section “Accessing 10-Bit Registers” on page 107.
12.2.3Registers
12.2.4Synchronization
The Timer/Counter (TCNT1) and Output Compare Registers (OCR1A, OCR1B, OCR1C and
OCR1D) are 8-bit registers that are used as a data source to be compared with the TCNT1 contents. The OCR1A, OCR1B and OCR1D registers deter mine the actio n on the O C1A, OC1B and
OC1D pins and they can also generate the compare match interrupts. The OCR1C holds the
Timer/Counter TOP value, i.e. the clear o n compare match value. The Timer/Counter1 High
Byte Register (TC1H) is a 2-bit register that is used as a comm on te mporary buffer to access the
MSB bits of the Timer/Counter1 registers, if the 10-bit accuracy is used.
Interrupt request (overflow TOV1, and compare matches OCF1A, OCF1B, OCF1D and fault protection FPF1) signals are visible in the Timer Interrupt Flag Register (TIFR) and Timer/Counter1
Control Register D (TCCR1D). The interrupts are individually masked with the Timer Interrupt
Mask Register (TIMSK) and the FPIE1 bit in the Timer/Co unter1 Control Register D (TCCR1D).
Control signals are found in the Timer/Counter Control Registers TCCR1A, TCCR1B, TCCR1C,
TCCR1D and TCCR1E.
In asynchronous clocking mode the Timer/Counter1 and the prescaler allow running the CPU
from any clock source while the pr es ca ler is o p er ating on the fast peripheral clock (PCK) having
frequency of 64 MHz (or 32 M Hz in Low Sp eed Mode) . This is possib le becaus e there is a synchronization boundary between the CPU clock domain and the fast peripheral clock domain.
chronization delays in between registers. Note that all clock gating details are not shown in the
figure.
8197C–AVR–05/11
The Timer/Counter1 register values go through the internal synchronization registers, which
cause the input synchronization delay, before affecting the counter operation. The registers
TCCR1A, TCCR1B, TCCR1C, TCCR1D, OCR1A, OCR1B, OCR1C and OCR1D can be read
89
back right after writing the register. The read back value s are delayed for the Time r/Counter1
8-BIT DATABUS
OCR1AOCR1A_SI
TCNT1_SO
OCR1BOCR1B_SI
OCR1COCR1C_SI
TCCR1ATCCR1A_SI
TCCR1BTCCR1B_SI
TCNT1TCNT1_SI
OCF1AOCF1A_SI
OCF1BOCF1B_SI
TOV1TOV1_SI
TOV1_SO
OCF1B_SO
OCF1A_SO
TCNT1
S
A
S
A
PCKE
CK
PCK
IO-registersInput synchronization
registers
Timer/Counter1Output synchronization
registers
SYNC
MODE
ASYNC
MODE
1 CK Delay1/2 CK Delay
~1/2 CK Delay1 PCK Delay1 PCK Delay~1 CK Delay
TCNT1
OCF1A
OCF1B
TOV1
1/2 CK Delay1 CK Delay
OCR1DOCR1D_SI
TC1HTC1H_SI
TCCR1CTCCR1C_SI
TCCR1D
OCF1DOCF1D_SI
OCF1D_SO
OCF1D
TC1H_SO
TC1H
TCCR1D_SI
(TCNT1) register, Timer/Counter1 High Byte Register (TC1H) and flags (OCF1A, OCF1B,
OCF1D and TOV1), because of the input and output synchronization.
The system clock frequency must be lower than half of the PCK frequency, because the synchronization mechanism of the asynchronous Timer/Counter1 needs at least two edges of the
PCK when the system clock is high. If the frequency of the system clock is too high, it is a risk
that data or control values are lost.
Many register and bit references in this section are written in genera l form. A lower case “n”
replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Compare Unit, in this case Compare Unit A, B, C or D. However, when using the register or bit
defines in a program, the precise form must be used, i.e., TCNT1 for accessing Timer/Counter1
8197C–AVR–05/11
12.3Clock Sources
TIMER/COUNTER1 COUNT ENABLE
PSR1
CS10
CS11
CS12
PCK
64/32 MHz
0
CS13
14-BIT
T/C PRESCALER
T1CK/2
T1CK
T1CK/4
T1CK/8
T1CK/16
T1CK/32
T1CK/64
T1CK/128
T1CK/256
T1CK/512
T1CK/1024
T1CK/2048
T1CK/4096
T1CK/8192
T1CK/16384
S
A
CK
PCKE
T1CK
12.3.1Prescaler
ATtiny261A/461A/861A
counter value and so on. The definitions in Table 12-1 are used exten sively throughout the
document.
Table 12-1.Definitions
ConstantDescription
BOTTOMThe counter reaches BOTTOM when it becomes 0x00
MAXThe counter reaches its MAXimum when it becomes 0xFF (decimal 255)
The counter reaches the TOP when it becomes equal to the highest value in the count
TOP
The Timer/Counter is clocked internally, either from CK or PCK. See bits CSxx in Table 12-17 on
page 115 and bit PCKE in “PLLCSR – PLL Control and Status Register” on page 119.
Figure 12-3 shows the Timer/Counter1 prescaler that supports two clocking modes, a synchro-
nous clocking mode and an asynchronous clocking mode. The synchronous clocki ng mode uses
the system clock (CK) as a clock timebase and asynchronous mode uses the fast peripheral
clock (PCK) as a clock time base. The PCKE bit from the PLLCSR register enables the asynchronous mode when it is set (‘1’).
sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the
value stored in the OCR0A Register. The assignment depends on the mode of operation
Figure 12-3.Timer/Counter1 Prescaler
In the asynchronous clocking mode the clock selections are from PCK to PCK/16384 and stop,
and in the synchronous clocking mode the clock selections are from CK to CK/16384 and stop.
The clock options are illustrated in Figure 12-3 and desribed in “TCCR1B – Timer/Counter1
Control Register B” on page 114.
The frequency of the fast peripheral clock is 64 MHz or 3 2 MHz in Low Speed mode (the LSM bit
in PLLCSR register is set to one). The Low Speed Mode is recommended to use when the supply voltage below 2.7 volts are used.
8197C–AVR–05/11
91
12.3.1.1Prescaler Re se t
DATA BUS
TCNT1Control Logic
count
TOV1
top
Timer/Counter1 Count Enable
( From Prescaler )
bottom
direction
clear
PCK
CK
PCKE
clk
T1
Setting the PSR1 bit in TCCR1B registe r re se ts the prescaler. It is possible to use the Prescaler
Reset for synchronizing the Timer/Counter to program execution.
12.3.1.2Prescaler Initialization for Asynchronous Mode
To change Timer/Counter1 to the asynchronous mode follow the procedure below:
1. Enable PLL.
2. Wait 100 µs for PLL to stabilize.
3. Poll the PLOCK bit until it is set.
4. Set the PCKE bit in the PLLCSR register which enables the asynchronous mode.
12.4Counter Unit
The main part of the Timer/Counter1 is the programmable bi-directional counter unit. Figure 12-
4 shows a block diagram of the counter and its surroundings.
Figure 12-4.Counter Unit Block Diagram
Signal description (internal signals):
countTCNT1 increment or decrement enable.
directionSelect between increment and decrement.
clearClear TCNT1 (set all bits to zero).
clk
Tn
topSignalize that TCNT1 has reached maximum value.
bottomSignalize that TCNT1 has reached minimum value (zero).
Depending on the mode of operation used, the cou nt er is cleared , in cr eme nted , o r decr em ent ed
at each timer clock (clk
asynchronous PLL clock using the Clock Select bits (CS1[3:0]) and the PCK Enable bit (PCKE).
When no clock source is selected (CS1[3:0] = 0) the timer is stopped. However, the TCNT1
value can be accessed by the CPU, regardless of whether clk
overrides (has priority over) all counter clear or count operations.
The counting sequence of the Timer/Counter1 is determined by bits WGM1[1:0], PWM1A and
PWM1B, located in the Timer/ Counter1 Co ntrol Registers (TCCR1A, TCCR1C and TCCR1D).
For more details about advanced counting sequences and waveform generation, see “Modes of
Operation” on page 98. The Timer/Counter Overflow Flag (TOV1) is set according to the mode
of operation and can be used for generating a CPU int errupt.
92
ATtiny261A/461A/861A
Timer/Counter clock, referred to as clkT1 in the following.
). The timer clock is generated from an synchronous system clock or an
T1
is present or not. A CPU write
T1
8197C–AVR–05/11
12.4.1Counter Initialization for Asynchronous Mode
OCF n x (Int.Req.)
=
(10-bit Comparator )
8-BIT DATA BUS
TCNTn
WGM10
Waveform Generator
C O MnX [1:0]
PWMnx
TCnH
OCWnx
10-B IT T C N T n10-B IT O C Rnx
OCR nx
FOCn
TOP
BOTTOM
To set Timer/Counter1 to asynchronous mode follow the procedure below:
1.Enable PLL.
2.Wait 100 µs for PLL to stabilize.
3.Poll the PLOCK bit until it is set.
4.Set the PCKE bit in the PLLCSR register which enables the asynchronous mode.
12.5Output Compare Unit
The comparator continuously compares TCNT1 with the Output Compare Registers (OCR1A,
OCR1B, OCR1C and OCR1D). Whenever TCNT1 equals to the Output Compare Register, the
comparator signals a match. A match will set the Output Compare Flag (OCF1A, OCF1B or
OCF1D) at the next timer clock cycle. If the corresponding inter ru pt is enable d, the Outpu t Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically
cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. The Waveform Generator uses the match signal to
generate an output according to operating mode set by bits PWM1A, PWM1B, WGM1[1:0] and
COM1x[1:0]. The top and bottom signals are used by the Waveform Generator for handling the
special cases of the extreme values in some modes of operation (See “Modes of Operation” on
page 98.). Figure 12-5 shows a bl ock diagram of the Output Compare unit.
ATtiny261A/461A/861A
Figure 12-5.Output Compare Unit, Block Diagram
8197C–AVR–05/11
The OCR1x Registers are double buffered when using any of the Pulse Width Modulation
(PWM) modes. For the normal mode of operation, the double buffering is disabled. The double
buffering synchronizes the update of the OCR1x Compare Registers to either top or bottom of
the counting sequence. The synchronization prevents the occurrence of odd-length, non-sym-
93
metrical PWM pulses, thereby making the output glitch-free. See Figure 12-6 for an example.
Output Compare
Waveform OCWnx
Output Compare
Wafeform OCWnx
Unsynchronized WFnx Latch
Synchronized WFnx Latch
Counter Value
Compare Value
Counter Value
Compare Value
Compare Value changes
Glitch
Compare Value changes
During the time between the write and the update operation, a read from OCR1A, OCR1B,
OCR1C or OCR1D will read the contents of the temporary location. This means that the most
recently written value always will read out of OCR1A, OCR1B, OCR1C or OCR1D.
Figure 12-6.Effects of Unsynchronized OCR Latching
12.5.1Force Output Compare
In non-PWM waveform generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC1x) bit. Forcing Compare Match will not set the
OCF1x Flag or reload/clear the timer, but the Waveform Output (OCW1x) will be updated as if a
real Compare Match had occurred (the COM1x[1:0] bits settings define whe ther the Waveform
Output (OCW1x) is set, cleared or toggled).
12.5.2Compare Match Blocking by TCNT1 Write
All CPU write operations to the TCNT1 Register will block any Compare Match that occur in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the same value as TCNT1 without triggering an inte rrupt when the Timer/Counte r clock is
enabled.
12.5.3Using the Output Compare Unit
Since writing TCNT1 in any mode of operation will block all Compare Matches for one timer
clock cycle, there are risks involved when changing TCNT1 when using the Output Compare
Unit, independently of whether the Timer/Counter is running or not. If the va lue written to TCNT1
equals the OCR1x value, the Compare Match will be missed, resulting in incorrect waveform
generation. Similarly, do not write the TCNT1 value equal to BOT TOM when the counter is
down-counting.
The setup of the Waveform Output (OCW1x) sh ould be perf ormed befor e setting t he Data Direction Register for the port pin to output. The easiest way of setting the OCW1x value is to use the
Force Output Compare (FOC1x) strobe bits in Normal mode. The O C1x keeps its value even
when changing between Waveform Generation modes.
Be aware that the COM1x[1:0] bits are not double buffered together with the compare value.
Changing the COM1x[1:0] bits will take effect immediately.
94
ATtiny261A/461A/861A
8197C–AVR–05/11
12.6Dead Time Generator
OCnx
pin
WGM10
Waveform Generator
top
FOCn
COMnx
bottom
PWMnx
OCWnx
Dead Time Generator
OCnx
pin
DTnHDTnL
DTPSn
CK OR PCK
CLOCK
OCnx
OCnx
CLOCK CONTROL
OCnx
OCnx
CK OR PCK
CLOCK
OCWnx
4-BIT COUNTER
COMPARATOR
DTnL
DTnH
DEAD TIME
PRE-SCALER
DTPSn
DTn I/O REGISTER
DATA BUS (8-bit)
TCCRnB REGISTER
PWM1X
PWM1X
The Dead Time Generator is provided for the Timer/Counter1 PWM output pairs to allow driving
external power control switches safely. The Dead Time G enerator is a separate block that can
be used to insert dead times (non-overlapping times) for the Timer/Counter1 complementary
output pairs OC1x and OC1x
to “01”. See Figure 12-7 below.
Figure 12-7.Block Diagram of Waveform Generator and Dead Time Generator.
The tasks are shared as follows: the Waveform Generator generates the output (OCW1x) and
the Dead Time Generator generates the non-overlapping PWM output pair from the output.
Three Dead Time Generators are provided, one for each PWM output. The non-overlap time is
adjustable and the PWM output and it’s complem entary output are adjusted se parately, and
independently for both PWM outputs.
ATtiny261A/461A/861A
when the PWM mode is enabled and the COM1x[1 :0] bits are set
8197C–AVR–05/11
The Dead Time Generation is based on 4-bit down counters that count the dead time, as shown
in Figure 12-8.
Figure 12-8.Dead Time Generator
There is a dedicated prescaler in front of the Dead Time Generator that can divide the
Timer/Counter1 clock (PCK or CK) by 1, 2, 4 or 8. This provides for large range of dead times
that can be generated. The prescaler is controlled by two control bi ts DTPS1[1:0]. T he block has
also a rising and falling edge detector that is used to start the dead time counting period.
Depending on the edge, one of the tran sitions on the rising edges, O C1x or OC1x
until the counter has counte d to zero . The com parato r is us ed to comp are the counte r with zer o
and stop the dead time insertion when zero has been reached. The counter is loa ded with a 4- bit
is delayed
DT1H or DT1L value from DT1 I/O register, depending on the edge of the Waveform Output
(OCW1x) when the dead time insertion is started. The Output Compare Output are delayed by
one timer clock cycle at minimum from the Waveform Output when the De ad T ime is a djusted to
95
zero. The outputs OC1x and OC1x are inverted, if the PWM Inversion Mode bit PWM1X is set.
This will also cause both outputs to be high during the dead time.
The length of the counting period is user adjustable by selecting the dead time prescaler setting
by using the DTPS1[1:0] control bits, and selecting then the dead time value in I/O register DT1.
The DT1 register consists of two 4-bit fields, DT1H and DT1L that control the dead time periods
of the PWM output and its' complementary output separately in terms of the number of prescaled dead time generator clock cycles. Thus the rising edge of OC1x and OC1x
different dead time periods as the t
t
The Compare Output Mode (COM1x[1:0]) bits have two functions. The Waveform Generator
uses the COM1x[1:0] bits for defining the inverted or non- inverted Waveform Out put (OCW1x) at
the next Compare Match. Also, the COM1x[1:0] bits control the OC1x and OC1x
source. Figure 12-10 on page 97 shows a simplified schematic of the logic affected by the
COM1x[1:0] bit setting. The I/O R egisters, I/O bi ts, and I/O pins in the figure ar e shown in bold.
Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by
the COM1x[1:0] bits are shown.
In Normal Mode (non-PWM) the Dead Time Generator is disabled and it is working like a synchronizer: the Output Compare (OC1x) is delayed from the Waveform Output (OCW1x) by one
timer clock cycle. Whereas in Fast PWM Mode and in Phase and Frequency Correct PWM
Mode when the COM1x[1:0] bits are set to “01” both the non-inverted and the inverted Output
Compare output are generated, and an user programmable Dead Time delay is inserted for
these complementary output pairs (OC1x and OC1x
to Normal mode when any other COM1x[1:0] bit setup is used. When referring to the OC1x
state, the reference is for the Output Compare output (OC1x) from the Dead Time Generator,
not the OC1x pin. If a system reset occur, the OC1x is reset to “0”.
pin output
). The functionality in PWM modes is similar
96
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
DATA BUS
PORTB0
DDRB0
DQ
DDRB1
PORTB1
DQ
DQ
DQ
clk
I/O
PORTB2
DDRB2
D
Q
DDRB3
PORTB3
D
Q
D
Q
D
Q
PORTB4
DDRB4
DQ
DDRB5
PORTB5
DQ
DQ
DQ
1
0
1
0
OC1D
PIN
2
1
0
Dead Time
Generator D
Q
Q
OCW1D
clk
Tn
OC1D
PIN
Output Compare
Pin Conguration
COM1D[1:0]
WGM11
OC1OE[5:4]
1
0
1
0
1
0
OC1B
PIN
2
1
0
Dead Time
Generator B
Q
Q
OCW1B
clk
Tn
OC1B
PIN
Output Compare
Pin Conguration
COM1B[1:0]
WGM11
OC1OE[3:2]
1
0
1
0
OC1A
PIN
0
1
Dead Time
Generator A
Q
Q
OCW1A
clk
Tn
OC1A
PIN
Output Compare
Pin Conguration
COM1A[1:0]
WGM11
OC1OE[1:0]
1
0
OC1A
OC1A
OC1B
OC1B
OC1D
OC1D
Figure 12-10.Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC1x / OC1x
Dead Time Generator if either of the COM1x[1:0] bits are set. However, the OC1x pin direction
(input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data
Direction Register bit for the OC1x and OC1x
output before the OC1x and OC1x
independent of the Output Compare mode.
) from the
pins (DDR_OC1x and DDR_OC1x) must be set as
values are visible on the pin. The port override function is
8197C–AVR–05/11
97
The design of the Output Compare Pin Configuration logic allows initialization of the OC1x state
TCNTn
OCWnx
(COMnx=1)
OCnx Interrupt Flag Set
14
Period
23
TOVn Interrupt Flag Set
before the output is enabled. Note that some COM1x[1:0] bit settings are reserved for certain
modes of operation. For Output Compare Pin Configurations refer to Table 12-2 on page 99,
Table 12-3 on page 101, Table 12-4 on page 103, Table 12-5 on page 104, Table 12-6 on page
104, and Table 12-7 on page 105.
12.7.1Compare Output Mode and Waveform Ge neration
The Waveform Generator uses the COM1x[1:0] bits differently in Normal mode and PWM
modes. For all modes, setting the COM1x[1:0] = 0 tells the Waveform Generator that no action
on the OCW1x Output is to be performed on the next Compare Match. For compa re output
actions in the non-PWM modes refer to Table 12-8 on page 111. For fast PWM mode, refer to
Table 12-9 on page 111, and for the Phase and Frequency Correct PWM refer to Table 12-10 on
page 112. A change of the COM1x[1:0] bits state will have effect at the first Compare Match
after the bits are written. For non-PWM modes, the action can be forced to have immediate
effect by using the FOC1x strobe bits.
12.8Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is
defined by the combination of waveform ge neration mode bits (PWM1A, PWM1B, and
WGM1[1:0]) and compare output mode bits (COM1x[1:0]). The Compare Output mode bits do
not affect the counting sequence, while the Waveform Generation mode b its do. The
COM1x[1:0] bits control whether the PWM output generated should be inverted, non-inverted or
complementary. For non-PWM modes the COM1x[1:0] bits contro l whether th e outpu t should be
set, cleared, or toggled at a Compare Match.
12.8.1Normal Mode
The simplest mode of operation is Normal mode (PWM1A/PWM1B = 0), wher e the counter
counts from BOTTOM to TOP (defined as OCR1C) then restarts from BOTTOM. The OCR1C
defines the TOP value for the counter, hence also its resolution, and allows control of the Compare Match output frequency. In toggle Compare Output Mode the Waveform Output (OCW1x)
is toggled at Compare Match between TCNT1 and OCR1x. In non-inverting Compare Output
Mode the Waveform Output is cleared on the Compare Match. In inverting Compare Output
Mode the Waveform Output is set on Compare Match. The timing diagram for Normal mo de is
shown in Figure 12-11.
Figure 12-11.Normal Mode, Timing Diagram
98
ATtiny261A/461A/861A
8197C–AVR–05/11
ATtiny261A/461A/861A
f
OC1x
f
clkT1
21OCR1C+()⋅
------------------------------------------ -=
R
PWM
log2OCR1C1+()=
The counter value (TCNT1) that is shown as a histo gram in F igure 12-11 is incremented until the
counter value matches the TOP value. The counter is then cleared at the following clock cycle
The diagram includes the Waveform Output (OCW1x) in toggle Compare Mode. The small horizontal line marks on the TCNT1 slopes represent Compare Matches between OCR1x and
TCNT1.
The Timer/Counter Overflow Flag (TOV1) is set in the same clock cycle as the TCNT1 becom es
zero. The TOV1 Flag in this case behaves like a 11th bit, except that it is only set, not cleared.
However, combined with the timer overflow interrupt, that automatically clears the TOV1 Flag,
the timer resolution can be increased by software. There are no special cases to consider in the
Normal mode, a new counter value can be written anytime.
The Output Compare Unit can be used to ge nerate int errupts at some given time . Using the Output Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time. For gen erati ng a wave form , the O CW1x ou tput can be set to
toggle its logical level on each Compare Match by setting the Compare Output mode bits to toggle mode (COM1x[1:0] = 1). The OC1x value will not be visible on the port pin unless th e data
direction for the pin is set to output. The waveform generated will have a maximum frequency of
f
= f
OC1x
equation:
/4 when OCR1C is set to zero. The waveform frequency is defined by the following
clkT1
12.8.2Fast PWM Mode
Resolution, R
, shows how many bit is required to express the value in the OCR1C register
PWM
and it can be calculated using the following equation:
The Output Compare Pin configurations in Normal Mode are descr ibed in Table 12-2.
Table 12-2. Output Compare Pin Configurations in Normal Mode
The fast Pulse Width Modulation or fast PWM mode (PWM1A/PWM1B = 1 and WGM1[1: 0] = 00)
provides a high frequency PWM waveform generation option. The fast PWM differs from the
other PWM option by its single-slope operation. The counter counts from BOTT OM to TOP
(defined as OCR1C) then restarts from BOTTOM. In non-inverting Compare Output mode the
Waveform Output (OCW1x) is cleared on the Compare Match between TCNT1 and OCR1x and
set at BOTTOM. In inverting Compare Output mode, the Waveform Output is set on Compare
Match and cleared at BOTTOM. In complementary Com pare Output mo de the Waveform Ou tput
is cleared on the Compare Match and set at BOTTO M.
8197C–AVR–05/11
Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice
as high as the Phase and Frequency Correct PWM m ode that use dual-slope op eration. This
high frequency makes the fast PWM mode well suited for power regulation, rectification, and
99
DAC applications. High frequency allows physically small sized external components (coils,
TCNTn
OCR nx Updat e and
TOVn Interru pt Flag Set
1
Period
23
OCWnx
OCWnx
(COMnx[1 : 0 ] = 2)
(COMnx[1 : 0 ] = 3)
OCR nx Interrupt Flag Set
4567
f
OCnxPWM
f
clkT1
N
------------ -=
capacitors), and therefore reduces total system cost.
The timing diagram for the fast PWM mode is shown in Figure 12-12. The counter is incre-
mented until the counter value matches the TOP value. The counter is then cleared at the
following timer clock cycle. The TCNT1 value is in the timing diagram shown as a histogram for
illustrating the single-slope operation. The diagram includes the Waveform Output in noninverted and inverted Compare Output modes. The small horizonta l line marks on the TCNT1
slopes represent Compare Matches between OCR1x and TCNT1.
Figure 12-12.Fast PWM Mode, Timing Diagram
100
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC1x pins.
Setting the COM1x[1:0] bits to two will produce a non-inverted PWM and setting the COM1x[1:0]
to three will produce an inverted PWM output. Setting the COM1x[1:0] bits to one will enable
complementary Compare Output mode and produce both the non-inverted (OC1x) and inverted
output (OC1x
). The actual value will only be visible on the port pin if the data direction for the
port pin is set as output. The PWM waveform is generated by setting (or clearing) the Waveforn
Output (OCW1x) at the Compare Match between OCR1x and TCNT1, and clearing (or setting)
the Waveform Output at the timer clock cycle the counter is cleared (changes from TOP to
BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the number of steps in single-slope operation. The value of N equals
either to the TOP value.
The extreme values for the OCR1C Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR1C is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR1C equal to MAX will result
ATtiny261A/461A/861A
8197C–AVR–05/11
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.