|
If you can't view the Datasheet, Please click here to try to view without PDF Reader . |
|
Datasheet File OCR Text: |
General Features * High Performance, Low Power AVR(R) 8-Bit Microcontroller * Advanced RISC Architecture - 132 Powerful Instructions - Most Single Clock Cycle Execution - 32 x 8 General Purpose Working Registers - Up to 16MIPS Throughput at 16Mhz - On-chip 2-cycle Multiplier Non-volatile Program and Data Memories - 64K Bytes of In-System Self-Programmable Flash * Endurance: 10,000 Write/Erase Cycles - 4K Bytes EEPROM * Contains 128 Bytes of One Time Programmable Memory * Endurance: 100,000 Write/Erase Cycles - 4K Bytes Internal SRAM - Optional Boot Code Section * In-System Programming by On-chip Bootloader program JTAG (IEEE std. 1149.1 compliant) Interface - Boundary-scan Capabilities According to the JTAG Standard - Extensive On-chip Debug Support - Programming of Flash, EEPROM, Fuses, and Locks Bits through JTAG Interface - Locking JTAG for Software Security (using OTP programmation) ISO7816 UART Interface Fully compliant with EMV, GIE-CB and WHQL Standards - Programmable ISO clock from 1 Mhz to 4.8, 6, 8 or 12Mhz - Card insertion/removal detection with automatic deactivation sequence - Programmable Baud Rate Generator from 372 to 3 clock cycles - Synchronous/Asynchronous Protocols T=0 and T=1 with Direct or Inverse Convention - Automatic character repetition on parity errors - 32 Bit Waiting Time Counter - 16 Bit Guard Time Counter/Block Guard Time Counter - Internal Step Up/Down Converter with Programmable Voltage Output if DC/DC embedded: * Class A: 5V +/-8% at 60mA, Vcc>2.85 (50mA if Vcc >2.7) * Class B: 3V +/-8% at 60mA, Vcc>2.85 (50mA if Vcc >2.7) * Class C: 1.8V +/-8% at 35mA - ISO7816-12 USB Host controller for card interface * Supports up to 60mA USB Smart Cards * Supports limited cable length to Smart Card Connector (~50cm) - 4 kV ESD (MIL/STD 833 Class 3) protection on whole Smart Card Interface USB 2.0 Full-speed Device Module - Complies fully with: * Universal Serial Bus Specification Rev 2.0 - Supports data transfer rates up to 12 Mbit/s - Endpoint 0 for Control Transfers : up to 64-bytes - 8 Programmable Endpoints with IN or OUT Directions and with Bulk, Interrupt or Isochronous Transfers * 3 Programmable Endpoints with double buffering of 64x2 bytes - Suspend/Resume Interrupts, and Remote Wake-up Support - Power-on Reset and USB Bus Reset * 8-bit Microcontroller for Smart Card Readers * AT90SCR100 Datasheet Preliminary * * TPR0327AY-SMS-30Jan09 * * * * * * * * * * * - 48 Mhz clock for Full-speed Bus Operation - USB Bus Disconnection on Microcontroller Request Peripheral Features - One 8-bit Timer/Counter with Separate Prescaler, Compare Mode and PWM Channel - One 8-bit Timer/Counter with Separate Prescaler, Compare Mode and Real Time Counter on Separate Oscillator - One 16-bit Timer/Counter with Separate Prescaler and Compare Mode - Hardware Watchdog - Hardware AES 128/256 Engine - Random Number Generator (RNG) Communication Peripherals - High Speed Master/Slave SPI Serial Interface (Up to 20Mhz) - 2-Wire Serial Interface - USART interface (up to 2Mbps) - Standard SPI Interface (to ease the communication with most RF front end chips) Special Microcontroller Feature - Power-on Reset and Brown-out Detection - Internal Callibrated Oscillator - External and Internal Interrupt Sources - Five Sleep Modes: Idle, Power-save, Power-down, Standby and Extended Standby - Supply Monitoring with Interrupt Generation below a fixed level. Keyboard Interface with up to 5x4 Matrix Management Capability with Interrupts and Wake-Up on Key Pressed Event Up to 4 x I/O Ports: Programmable I/O Port Up to 4 x LED Outputs with Programmable Current Sources: 2 or 4 mA (not usable in emulation mode) Specific and Unique Serial Number per IC in production. Operating Temperature - Industrial (-40C to +85C) Core Operating Voltages - 2.4 - 5.5V DC/DC Operating Voltages (See "Smart Card Interface Characteristics" for details) - 2.7 - 5.5V Maximum Frequency - 8MHz Clock Input 2 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 1. Block Diagram Figure 1-1. Block Diagram CP CCRES L CR K ST CI O CC 4 CC , D 8, P DM Vc c PA7, KbIN7, PCINT7 PA6, KbIN6, PCINT6 PA5, KbIN5, PCINT5 PA4, KbIN4, PCINT4 PA3, KbIN3, PCINT3 PA2, KbIN2, PCINT2 PA1, KbIN1, PCINT1 PA0, KbIN0, PCINT0 PE7, KbO7, PCINT31 PE6, KbO6, PCINT30 PE5, KbO5, PCINT29 PE4, KbO4, PCINT28 PE3, KbO3, PCINT27 PE2, KbO2, PCINT26 PE1, KbO1, PCINT25 PE0, KbO0, PCINT24 PC5, JTGTDI, LED3 PC4, JTGTDO, LED2 PC3, JTGTMS, LED1 PC2, JTGTCK, LED0 PC1, SDA, INT3b PC0, SCL, INT2b Smart Card Interface PORT A Standard ISO7816 USB Host Controller Supply Monitor Keyboard Interface USB DMA PORT E On-chip Debug Watchdog JTAG cpu Interrupt Controller Power Management PORT C LED port TWI SPI DMA PD7, HSMISO, PCINT23 PD6, HSMOSI, PCINT22 PD5, HSSCK, PCINT21 PD4, HSSS, PCINT20 PD3, INT1, PCINT19 PD2, INT0, OC1B, PCINT18 PD1, TXD, PCINT17 PD0, RXD, PCINT16 PB7, SCK, OC2A, PCINT15 PB6, MISO, OC2B, PCINT14 PB5, MOSI, OC1A, PCINT13 PB4, SS, OC0B, PCINT12 PB3, PWM, OC0A, PCINT11 PB2, ICP1, PCINT10 PB1, T1, CKO, PCINT9 PB0, T0, XCK, PCINT8 PORT D High-Speed SPI SRAM 4 KB USART FLASH 64 KB Code EEPROM 4 KB Data SPI PORT B AES 256 RNG USB 8bit T/C 0 16bit T/C 1 Timers/Counters 8bit T/C 2 48MHz PWM RTC Clock Management USB device TO TO Note Except for the PORTC, all the other ports are connected to a Pin Change Interrupt Controller. D UC ap SC D+ 1 SC 2 AL XT 1 AL XT 2 3 TPR0327AY-SMS-30Jan09 4 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 2. Pin List Configuration * 2 package configurations to answer different needs - 32pins: LowPinCount package: for small package size, useful for small embedded systems (AT90SCR100L and AT90SCR100LS) - 64pins: FullPinCount: For full performance advanced reader (AT90SCR100H) ! Caution On Full Pin Count (FPC) package, the only supported package type is QFN, and all the Vss signals are connected to the e-pad. It is important to have it fully soldered on groundplane of final PCB. * USBReg refers to 3.3V USB specific regulator Note * PCINTx refer to Pin Change Interrupts. See "External Interrupt Registers" on page 69. Beware of the multiple functionality supported on each port. All functionnality may be active at the same time. The only way to disable a feature is to deactive it inside the corresponding peripheral block. ! Caution Table 2-1. Portmap Pin List Configuration SCR100LHS SCR100LSD SCR100H Supply ID Vcc Vss1 AVss RST Unmapped, generic pins Xtal1 Xtal2 DVcc Vcc2 Vcc3 Vcc4 Vcc5 Vdcdc Vss2 Vss3 D+ DUCap Configuration, Role x e e (1) x x x x x x x x x x x x x x x x x x x x x x x x x x x x Vcc Vss1 AVss RST XTAL1 Vcc XTAL2 DVcc Vcc2 Vcc3 Vcc4 Vcc5 Vdcdc Vss2 Vss3 D+ USB Reg DUCap Voltage Supply Ground PLL Ground Reset signal: Drive low to reinitialize the chip Clock Input: Support up to 8 Mhz crystals Digital Vcc:Used for internal regulator decoupling Voltage Supply: To be tied to same supply voltage as Vcc Voltage Supply: To be tied to same supply voltage as Vcc Voltage Supply: To be tied to same supply voltage as Vcc Voltage Supply: To be tied to same supply voltage as Vcc Voltage Supply for DC/DC Converter. Second Vss: To be tied to Vss Third Vss: To be tied to Vss (1) x x x x x x x x x e e (1) (1) x x x USB Interface USB Decoupling: Used for specific USB regulator decoupling 5 TPR0327AY-SMS-30Jan09 Table 2-1. Portmap Pin List Configuration SCR100LHS SCR100LSD SCR100H Supply ID RTC1 RTC2 PA7 PA6 PA5 PORT A PA4 PA3 PA2 PA1 PA0 PB7 PB6 PB5 PORT B PB4 PB3 PB2 PB1 PB0 PC5 PC4 PORT C(3) PC3 PC2 PC1 PC0 PD7 PD6 PD5 PORT D PD4 PD3 PD2 PD1 PD0 Configuration, Role x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x Vcc Vcc INT3 INT2 JTGTDI JTGTDO JTGTMS JTGTCK SDA SCL HSMISO HSMOSI HSSCK HSSS INT1 INT0 TXD RXD OC1B Vcc Vcc KbIN7 KbIN6 KbIN5 KbIN4 KbIN3 KbIN2 KbIN1 KbIN0 SCK MISO MOSI SS PWM OC2A OC2B OC1A OC0B OC0A ICP1 T1 T0 LED3 LED2 LED1 LED0 INT3b INT2b PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 HSxxxx: "High-Speed SPI Controller" (MISO, MOSI, SCK, SS) INTx: "External Interrupts" , default configuration TXD, RXD: "USART" signals OCxB: Output Comparators: See "Timers" on page 87. JTGxxx: "JTAG Interface and On-chip Debug System" SDA, SCL: "2-wire Serial Interface _ TWI" signals LEDx: "LED" Outputs (IO driving current) INTxb: "External Interrupts" , bis configuration CLKO XCK Vcc TOSC1 TOSC2 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 PCINT8 KbINx: Input for "Keyboard Interface" TOSCx: 32.768 Khz crystals input for Real Time Clock. (Please note that these pins are not GPIO accessible). x x x x x x x x x x x x x x SS, MISO, MOSI, SCK: Standard "SPI - Serial Peripheral Interface" OCxx: Output Comparator outputs. See "Timers" on page 87. ICP1: Input Capture. See "16-bit Timer/Counter1 with PWM" PWM: Output from "8-bit Timer/Counter0 with PWM" Tx: Clock input for "Timers" 0 and 1 XCK: Clock input for synchronous "USART" INTx: "External Interrupts" , default configuration CLKO: System clock output. (only active if CKOUT fuse is enabled). "Fuse Low Byte" . 6 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 2-1. Portmap Pin List Configuration SCR100LHS SCR100LSD SCR100H Supply ID PE7 PE6 PE5 PORT E PE4 PE3 PE2 PE1 PE0 Configuration, Role x x x x x x x x x x x x x x x x e (1) (2) x x x Smart Card PORT x x x x x x x x x x x x x x x x x x x KbO7 KbO6 KbO5 Vcc KbO4 KbO3 KbO2 KbO1 KbO0 Vcc CPRES CCLK CVcc CRST CIO CC4, DP CC8, DM CVcc CVSense CVcc CVss LI LO PCINT31 PCINT30 PCINT29 PCINT28 PCINT27 PCINT26 PCINT25 PCINT24 KbOx: Output for "Keyboard Interface" Cx: "Smart Card Interface Block (SCIB)" : Standard ISO7816 port and "USB Host Controller" . Smart Card Interface: "DC/DC Converter" Supply Signals x x Notes: 1. Should be connected to e-pad underneath QFN package 2. According to the current configuration, these pins are supplied either by USB regulator or CVcc 3. PORT C is not complete, due to RTC pins, dedicated to oscillator pads 7 TPR0327AY-SMS-30Jan09 8 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 3. Resources A comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr. 9 TPR0327AY-SMS-30Jan09 10 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 4. About Code Examples This documentation contains simple code examples that briefly show how to use various parts of the device. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details. The code examples assume that the part specific header file is included before compilation. For I/O registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI" instructions must be replaced with instructions that allow access to extended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR". 11 TPR0327AY-SMS-30Jan09 12 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 5. AVR CPU Core 5.1 Introduction This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. 5.2 Architectural Overview Figure 5-1. Block Diagram of the AVR Architecture Data Bus 8-bit Flash Program Memory Program Counter Status and Control Instruction Register 32 x 8 General Purpose Registrers Interrupt Unit SPI Unit Watchdog Timer Instruction Decoder Indirect Addressing Direct Addressing ALU Control Lines I/O Module1 Data SRAM I/O Module 2 I/O Module n EEPROM I/O Lines In order to maximize performance and parallelism, the AVR uses a Harvard architecture - with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. The program memory is In-System Reprogrammable Flash memory. 13 TPR0327AY-SMS-30Jan09 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 pointers can also be used as an address pointer for look up tables in Flash program memory. These added function registers are the 16-bit X-, Y-, and Z-register, described later in this section. The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation. Program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every program memory address contains a 16- or 32-bit instruction. Program Flash memory space is divided in two sections, the Boot Program section and the Application Program section. Both sections have dedicated Lock bits for write and read/write protection. The SPM instruction that writes into the Flash memory must reside in the Boot Program section. During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority. The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or via the Data Space locations following those of the Register File, 0x20 - 0x5F. In addition, the AT90SCR100 has Extended I/O space from 0x60 - 0xFF in SRAM where only the ST/STS/STD and LD/LDS/LDD instructions can be used. 5.3 ALU - Arithmetic Logic Unit The high-performance AVR ALU operates in direct connection with all the 32 general purpose working registers. Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate operand are executed. The ALU operations are divided into three main categories - arithmetic, logical, and bit-functions. This implementation of the architecture also provides a powerful multiplier supporting both signed/unsigned multiplication and fractional format. See the "Instruction Set" section for a detailed description. 14 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 5.4 Status Register The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software. 5.4.1 SREG - Status Register The AVR Status Register - SREG - is defined as: Bit 0x3F (0x5F) Read/write Initial value 7 I R/W 0 6 T R/W 0 5 H R/W 0 4 S R/W 0 3 V R/W 0 2 N R/W 0 1 Z R/W 0 0 C R/W 0 0x00 SREG * Bit 7 - I: Global Interrupt Enable The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by the application with the SEI and CLI instructions, as described in the instruction set reference. * Bit 6 - T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. * Bit 5 - H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful in BCD arithmetic. See the "Instruction Set Description" for detailed information. * Bit 4 - S: Sign Bit, S = N V The S-bit is always an exclusive OR between the Negative Flag N and the Two's Complement Overflow Flag V. See the "Instruction Set Description" for detailed information. * Bit 3 - V: Two's Complement Overflow Flag The Two's Complement Overflow Flag V supports two's complement arithmetic. 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 15 TPR0327AY-SMS-30Jan09 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. 5.5 General Purpose Register File The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: * One 8-bit output operand and one 8-bit result input * Two 8-bit output operands and one 8-bit result input * Two 8-bit output operands and one 16-bit result input * One 16-bit output operand and one 16-bit result input Figure 5-2 shows the structure of the 32 general purpose working registers in the CPU. Figure 5-2. AVR CPU General Purpose Working Registers 7 R0 R1 R2 ... R13 General Purpose Working Registers R14 R15 R16 R17 ... R26 R27 R28 R29 R30 R31 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F X-register Low Byte X-register High Byte Y-register Low Byte Y-register High Byte Z-register Low Byte Z-register High Byte 0x0D 0x0E 0x0F 0x10 0x11 0 Addr. 0x00 0x01 0x02 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 5-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. 5.5.1 The X-register, Y-register, and Z-register The registers R26..R31 can also be used as 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 5-3. 16 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 5-3. The X-, Y-, and Z-registers 15 X-register 7 R27 (0x1B) 15 Y-register 7 R29 (0x1D) 15 Z-register 7 R31 (0x1F) ZH 0 7 R30 (0x1E) YH 0 7 R28 (0x1C) ZL 0 0 XH 0 7 R26 (0x1A) YL 0 0 XL 0 0 In the different addressing modes these address registers have fixed displacement, automatic increment, and automatic decrement functionality (see the instruction set reference for details). 5.6 Stack Pointer The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the Stack Pointer. The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to point above 0x0100. The initial value of the stack pointer is the highest address of the internal SRAM. The Stack Pointer is decremented by one when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when data is popped from the Stack with return from subroutine RET or return from interrupt RETI. The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is implementation dependent. Bit 0x3E (0x5E) 0x3D (0x5D) Read/write Initial value 15 SP7 7 R R/W 0 1 14 SP6 6 R R/W 0 1 13 SP5 5 R R/W 0 1 12 SP12 SP4 4 R/W R/W 1 1 11 SP11 SP3 3 R/W R/W 0 1 10 SP10 SP2 2 R/W R/W 0 1 9 SP9 SP1 1 R/W R/W 0 1 8 SP8 SP0 0 R/W R/W 0 1 0x10 0xFF SPH SPH 5.7 Instruction Execution Timing This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock division is used. 17 TPR0327AY-SMS-30Jan09 Figure 5-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast-access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. Figure 5-4. The Parallel Instruction Fetches and Instruction Executions T1 T2 T3 T4 clk CPU 1st Instruction Fetch 1st Instruction Execute 2nd Instruction Fetch 2nd Instruction Execute 3rd Instruction Fetch 3rd Instruction Execute 4th Instruction Fetch Figure 5-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using two register operands is executed, and the result is stored back to the destination register. Figure 5-5. Single Cycle ALU Operation T1 T2 T3 T4 clk CPU Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back 5.8 Reset and Interrupt Handling The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a separate program vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt. Depending on the Program Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12 are programmed. This feature improves software security. See the section "Memory Programming" on page 377 for details. The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors. The complete list of vectors is shown in "Interrupts" on page 63. The list also determines the priority levels of the different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next is INT0 - the External Interrupt Request 0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR). Refer to "Interrupts" on page 63 for more information. 18 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The Reset Vector can also be moved to the start of the Boot Flash section by programming the BOOTRST Fuse, see "Memory Programming" on page 377. When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction - RETI - is executed. There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority. The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software. When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example shows how this can be used to avoid interrupts during the timed EEPROM write sequence. Assembly Code Example in r16, SREG cli sbi EECR, EEMPE sbi EECR, EEPE out SREG, r16 ; restore SREG value (I-bit) ; store SREG value ; start EEPROM write ; disable interrupts during timed sequence C Code Example char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ __disable_interrupt(); EECR |= (1< 19 TPR0327AY-SMS-30Jan09 Assembly Code Example sei ; set Global Interrupt Enable sleep; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s) C Code Example __enable_interrupt(); /* set Global Interrupt Enable */ __sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */ 5.8.1 Interrupt Response Time The interrupt execution response for all the enabled AVR interrupts is five clock cycles minimum. After five clock cycles the program vector address for the actual interrupt handling routine is executed. During these five clock cycle periods, 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 five clock cycles. This increase comes in addition to the start-up time from the selected sleep mode. A return from an interrupt handling routine takes five clock cycles. During these five clock cycles, the Program Counter (three bytes) is popped back from the Stack, the Stack Pointer is incremented by three, and the I-bit in SREG is set. 20 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 6. AT90SCR100 Memories This section describes the different memories in the AT90SCR100. The AVR architecture has two main memory spaces: the Data Memory and the Program Memory spaces. In addition, the AT90SCR100 features an EEPROM Memory for data storage. All three memory spaces are linear and regular. 6.1 In-System Reprogrammable Flash Program Memory The AT90SCR100 contains 64K bytes On-chip In-System Reprogrammable Flash memory for program storage. As all AVR instructions are 16 or 32 bits wide, the Flash is organized as 32K x 16. For software security, the Flash Program memory space is divided into two sections, Boot Program section and Application Program section. See "Application and Boot Loader Flash Sections" on page 363. The Flash memory has an endurance of at least 10,000 write/erase cycles. The AT90SCR100 Program Counter (PC) is 15/16 bits wide, which permits to address the 32/64K program memory locations. The operation of Boot Program section and associated Boot Lock bits for software protection are described in detail in "Memory Programming" on page 377. "Memory Programming" on page 377 contains a detailed description of Flash data serial downloading using the SPI pins or the JTAG interface. Constant tables can be allocated within the entire program memory address space (see the LPM - Load Program Memory instruction description). Timing diagrams for instruction fetch and execution are presented in "Instruction Execution Timing" on page 17. 21 TPR0327AY-SMS-30Jan09 Figure 6-1. 0x7FFF Full Memory Map Program Memory EEPROM Memory 0x1000 Boot Flash Section 0x7000 0x6FFF EEPROM Data Memory 0x0000 Data Memory 0x10FF Application Flash Section SRAM Memory 0x0100 0x00FF 0x0060 0x005F 0x0020 0x001F 0x0000 Peripheral Registers IO Registers 32 General Purpose Working Registers 0x0000 16 bits 8 bits 6.2 SRAM Data Memory Figure 6-1 shows how the AT90SCR100 SRAM Memory is organized. The AT90SCR100 is a complex microcontroller with more peripheral units than can be supported within the 64 locations reserved in the Opcode of the IN and OUT instructions. For the Extended I/O space from 0x0060 - 0x00FF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used. The address range $00 - $10FF Data Memory address the Register File, the I/O Memory, Extended I/O Memory, and the internal data SRAM. The first 32 locations address the Register file, the next 64 location the standard I/O Memory, then 160 locations of Extended I/O memory and the next 4,096 locations address the internal data SRAM. The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register file, registers R26 to R31 feature the indirect addressing pointer registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register. 22 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented. The 32 general purpose working registers, 64 I/O registers, 160 Extended I/O Registers and the 4096 bytes of internal data SRAM in the AT90SCR100 are all accessible through all these addressing modes. The Register File is described in "General Purpose Register File" on page 16. 6.2.1 Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 6-2. Figure 6-2. On-chip Data SRAM Access Cycles T1 T2 T3 clk CPU Address Data WR Data RD Compute Address Address valid Memory Access Instruction Next Instruction 6.3 EEPROM Data Memory The AT90SCR100 contains 4K bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described in the following section, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register. For a detailed description of SPI and JTAG downloading to the EEPROM, see page 381, and page 385 respectively. 6.3.1 EEPROM Read/Write Access The EEPROM Access Registers are accessible in the I/O space. The write access time for the EEPROM is given in Table 6-2. This is a self-timing function, wich allows the user software to 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, VCC is likely to rise or fall slowly on power-up/down. This causes the device, for some period of time, to run at a voltage lower than specified as minimum, for the clock frequency used. For details on how to avoid problems in these situations, See "Preventing EEPROM Corruption" on page 28. 23 TPR0327AY-SMS-30Jan09 Read Write In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this. When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction is executed. 6.3.2 EEARH and EEARL - The EEPROM Address Register Bit 0x22 (0x42) 0x21 (0x41) Bit Read/write Initial value 7 R R/W 0 x 6 R R/W 0 x 5 R R/W 0 x 15 14 13 12 EEAR [7..0] 4 R R/W 0 x 3 R/W R/W x x 2 R/W R/W x x 1 R/W R/W x x 0 R/W R/W x x 11 10 9 8 EEARH EEARL EEAR [11..8] * Bits 15..12 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and will always read as zero. * Bits 11..0 - EEAR8..0 : EEPROM Address The EEPROM Address Registers - EEARH and EEARL specify the EEPROM address in the 4K bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 4096. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed. 6.3.3 EEDR - The EEPROM Data Register Bit 0x20 (0x40) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 EEDR R/W 0 0x00 EEDR [7..0] * Bits 7..0 - EEDR7..0 : EEPROM Data For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address specified by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address specified by EEAR. 6.3.4 EECR - The EEPROM Control Register Bit 0x1F (0x3F) Read/write Initial value 7 R 0 6 R 0 5 EEPM1 R/W x 4 EEPM0 R/W x 3 EERIE R/W 0 2 EEMPE R/W 0 1 EEPE R/W x 0 EERE R/W 0 EECR * Bits 7..6 - Res: Reserved Bits These bits are reserved bits in the AT90SCR100 and will always read as zero. 24 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bits 5..4 - EEPM1..0 : EEPROM Programming Mode Bits The EEPROM Programming mode bit setting defines which programming action will be triggered when writing EEPE. It is possible to program data in one atomic operation (erase the old value and program the new value) or to split the Erase and Write operations in two different operations. The Programming times for the different modes are shown in Table 6-1. While EEPE is set, any write to EEPMn will be ignored. During reset, the EEPMn bits will be reset to 00 unless the EEPROM is busy programming. Table 6-1. EEPM1 0 0 1 1 EEPROM Mode Bits EEPM0 0 1 0 1 Programming Time 3.4 ms TBC 1.8 ms TBC 1.8 ms TBC - Operation Erase and Write in one operation (Atomic Operation) Erase Only Write Only Reserved for future use * Bit 3 - EERIE: EEPROM Ready Interrupt Enable Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set. Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant interrupt when EEPE is cleared. * Bit 2 - EEMPE: EEPROM Master Programming Enable The EEMPE bit determines whether setting EEPE to one causes the EEPROM to be written or not. If EEMPE is set, setting EEPE within four clock cycles will write data to the EEPROM at the selected address. If EEMPE is clear, setting EEPE will have no effect. When EEMPE has been written to one by software, hardware clears the bit to zero after four clock cycles. See the description of the EEPE bit for the EEPROM write procedure. * Bit 1 - EEPE: EEPROM Programming Enable The EEPROM Write Enable Signal EEPE is the write strobe to the EEPROM. When address and data are correctly set up, the EEPE bit must be written to one to write the value into the EEPROM. The EEMPE bit must be written to one before a logical one is written to EEPE, otherwise no EEPROM write takes place. The following procedure should be followed when writing the EEPROM (the order of steps 3 and 4 is not essential): 1. Wait until EEPE becomes zero. 2. Wait until SELFPRGEN in SPMCSR becomes zero. 3. Write new EEPROM address to EEAR (optional). 4. Write new EEPROM data to EEDR (optional). 5. Write a logical one to the EEMPE bit while writing a zero to EEPE in EECR. 6. Within four clock cycles after setting EEMPE, write a logical one to EEPE. The EEPROM can not be programmed during a CPU write to the Flash memory. The software must check that the Flash programming is completed before initiating a new EEPROM write. This is performed by step 2. Step 2 is only relevant if the software contains a Boot Loader allow- 25 TPR0327AY-SMS-30Jan09 ing the CPU to program the Flash. If the Flash is never being updated by the CPU, step 2 can be omitted. See "Memory Programming" on page 377 for details about Boot programming. An interrupt between step 5 and step 6 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the interrupted EEPROM access to fail. It is recommended that the Global Interrupt Flag is cleared during all the steps to avoid these problems. ! Caution When the write access time has elapsed, the EEPE bit is cleared by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEPE has been set, the CPU is halted for two cycles before the next instruction is executed. * Bit 0 - EERE: EEPROM Read Enable The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately. When the EEPROM is read, the CPU is halted for four cycles before the next instruction is executed. The user should poll the EEPE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change the EEAR Register. The calibrated Oscillator is used to time the EEPROM accesses. Table 6-2 lists the typical programming time for EEPROM access from the CPU. Table 6-2. Symbol EEPROM write (from CPU) EEPROM Programming Time Number of Calibrated RC Oscillator Cycles 26,368 TBC Typ Programming Time 3.3 ms TBC 6.3.5 Code Examples for EEPROM manipulation The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash Boot Loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish. 26 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Assembly Code Example EEPROM_write: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to Data Register out EEDR,r16 ; Write logical one to EEMPE sbi EECR,EEMPE ; Start eeprom write by setting EEPE sbi EECR,EEPE ret C Code Example void EEPROM_write(unsigned int uiAddress, unsigned char ucData) { /* Wait for completion of previous write */ while(EECR & (1< TPR0327AY-SMS-30Jan09 The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. Assembly Code Example EEPROM_read: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_read ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Start eeprom read by writing EERE sbi EECR,EERE ; Read data from Data Register in ret r16,EEDR C Code Example unsigned char EEPROM_read(unsigned int uiAddress) { /* Wait for completion of previous write */ while(EECR & (1< Preventing EEPROM Corruption During periods of low VCC, the EEPROM data can be corrupted because the supply voltage is too low for the CPU and the EEPROM to operate properly. These issues are the same as for board level systems using 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. 1. A regular write sequence to the EEPROM requires a minimum voltage to operate correctly. 2. The CPU itself can execute instructions incorrectly, if the supply voltage is too low. 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 VCC reset Protection circuit can be used. If a reset occurs while a write operation is in progress, the write operation will be completed assuming that the power supply voltage is sufficient. 28 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 6.4 I/O Memory The I/O space definition of the AT90SCR100 is shown in "Register Summary" on page 417. All AT90SCR100 I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed by the LD/LDS/LDD and ST/STS/STD instructions, transferring data between the 32 general purpose working registers and the I/O space. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. Refer to the instruction set section for more details. When using the I/O specific commands IN and OUT, I/O addresses 0x00 - 0x3F must be used. When addressing I/O Registers as data space using LD and ST instructions, 0x20 must be added to these addresses. The AT90SCR100 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in the Opcode of the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI instructions will only operate on the specified bit, and can therefore be used on registers containing such Status Flags. The CBI and SBI instructions work with registers 0x00 to 0x1F only. The I/O and peripherals control registers are explained in later sections. 6.4.1 General Purpose I/O Registers The AT90SCR100 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 bitaccessible using the SBI, CBI, SBIS, and SBIC instructions. GPIOR2 - General Purpose I/O Register 2 Bit 0x2B (0x4B) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 GPIOR2 R/W 0 0x00 6.4.2 GPIOR2 [7..0] 6.4.3 GPIOR1 - General Purpose I/O Register 1 Bit 0x2A (0x4A) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 GPIOR1 R/W 0 0x00 GPIOR1 [7..0] 29 TPR0327AY-SMS-30Jan09 6.4.4 GPIOR0 - General Purpose I/O Register 0 Bit 0x1E (0x3E) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 GPIOR0 R/W 0 0x00 GPIOR0 [7..0] 30 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 7. Clock System 7.1 Overview The Clock system of AT90SCR100 is based on a 8Mhz Oscillator which feeds a Phase Lock Loop (PLL) providing a 96Mhz clock frequency. Then, dividers permit to calibrate the frequencies available for the different Peripherals, Core and Memories. All of the clocks do not need to be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be stopped by using different sleep modes, as described in "Power Management and Sleep Modes" on page 43. The clock systems are detailed below. Figure 7-1 presents the principal clock systems in the AT90SCR100 and their distribution. Figure 7-1. Clock Distribution TOSC1 T1 T0 clk ASY Tn Clock Controller (2) clk Tn (2) PRR0.PR (Tx) 1 0 (default) Tn (2) clk I/O clk XTAL IOx Clock Controller (1) PRR0.PR (IOx) 1 0 (default) IOx (1) clk PLL PLL Clock clkMUX Multi-plexer Glitches free Core Divider clk Core clk CPU CPU Core (by 1, 4, 5, 6, 8, 12, 24, 48, 96) (Divider by 1 Only for Clk XTAL) clk Flash clk Write_Flash Flash & Eeprom Internal RC Oscillator 96Mhz PLL HS SPI Divider clk HSSPI PRR1.PRHSSPI 1 0 (default) PRR1.PRSCI 1 0 (default) PRR1.PRUSB 1 0 (default) PRR1.PRSCUSB 1 0 (default) USB Host Controller USB High Speed SPI Block (by 4, 5, 6, 8, 12, 24, 48, 96) XTAL1 XTAL2 clk XTAL SCI Divider clk SCI Smart Card Interface Block (by 8, 12, 16, 20, 24, 48, ...) x 1/2 clk USB 48Mhz (1): IOx includes: SPI, USART, TWI, AES, Keyboard peripherals (2): Tn indicates: Timer0, Timer1 and Timer2. Only Timer2 can count using clk ASY 31 TPR0327AY-SMS-30Jan09 7.1.1 AVR Core Clock - clkCore The Core clock is providing clock to all the systems linked with the AVR Core. The CPU and some peripherals, such as Timers, USART, SPI, TWI, Keyboard interface and AES are directly connected to the clkCore. Clock divisions performed by the Core Divider will also affect clkI/O and clkTIM (depending on the Timer Controller Clock selection). Please see "CLKPR - Clock Prescale Register" on page 40 for Core Divider access descriptions. 7.1.2 CPU Clock - clkCPU The CPU clock is routed to parts of the system concerned with operation of the AVR core. Examples of such modules are the General Purpose Register File, the Status Register and the data memory holding the Stack Pointer. Halting the CPU clock inhibits the core from performing general operations and calculations. I/O Clock - clkI/O The I/O clock is used by the majority of the I/O modules, like Timer/Counters, SPI, and USART. 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. You can choose to disable a peripheral by cutting the clock supplying it. This will reduce the consumption of the AT90SCR100. Please refer to "PRR0 - Power Reduction Register 0" on page 45 and "PRR1 - Power Reduction Register 1" on page 46. 7.1.3 Note 7.1.4 Memory Clock - clkFlash and clkWrite_Flash The Memory clock controls operation of the Flash interface. The clkFlash is usually active simultaneously with the CPU clock, and is used to read and execute code from Flash, and read data from EEPROM. The clkWrite_Flash is generated independently, and is used for all Flash and EEPROM write procedures. The section "Internal RC Oscillator" on page 37 gives more information about this private clock. 7.1.5 Asynchronous Timer Clock - clkASY The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clocked directly from an external clock or an external 32 kHz clock crystal. The dedicated clock domain allows this Timer/Counter to be used as a real-time counter even when the device is in sleep mode. High-Speed SPI Clock - clkHSSPI The High-Speed SPI does not use the clkcpu. Using the clkMUX, through specific dividers, the High-Speed SPI can work to frequencies higher than CPU's one. Please see "HSSPIIER HSSPI Interrupt Enable Register" on page 289, for details about divider description. You can reduce AT90SCR100 consumption by disabling the clock input into HSSPI, if you don't need this peripheral. See "PRR1 - Power Reduction Register 1" on page 46 for details. 7.1.6 Note 32 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 7.1.7 Smart Card Interface Clock - clkSCI The Smart Card Interface clock is generated from clkMUX via a specific Divider described in the section "SCICLK - Smart Card Clock Register" on page 199. This means the SCIB is capable of operating at frequencies up to 12Mhz. You can reduce AT90SCR100 consumption by disabling the clock input into SCIB, if you don't need this peripheral. See "PRR1 - Power Reduction Register 1" on page 46 for details. Note 7.1.8 USB Clock - clkUSB The USB modules can only work if clkMUX = clkPLL. Then, an automatic divider by 2 is applied to reach the 48 Mhz. Both USB Device and USB Host Controller modules use clkUSB. You can reduce AT90SCR100 consumption by disabling the clock input into USB Device module and/or USB Host Module, if you don't need these peripherals. See "PRR1 - Power Reduction Register 1" on page 46 for details. Note 7.2 Clock Sources At chip startup, clkMUX = clkXTAL. The external clock must be a 8Mhz clock, and can be generated by either a crystal or an oscillator. The selection of the External Clock source is done by a fuse as shown below: Table 7-1. Device Clocking Options Select (1) CKSEL3 1 0 Device Clocking Option Low Power Crystal Oscillator External Clock Notes: 1. For all fuses "1" means unprogrammed while "0" means programmed. 7.2.1 Default Clock Source The device is shipped in "Low Power Crystal Oscillator" mode. The start-up time is set to maximum and the time-out period enabled. Even if the AT90SCR100 core has swtiched to clkPLL, it can switch to clkXTAL again by clearing the PLLCR.PLLMUX bit. See "PLLCR - Phase Lock Loop (PLL) Control Register" on page 40. 7.2.2 Clock Startup Sequence Any clock source needs a sufficient VCC to start oscillating and a minimum number of oscillating cycles before it can be considered stable. To ensure sufficient VCC, the device issues an internal reset with a time-out delay (tTOUT) after the device reset is released by all other reset sources. The "On-chip Debug System" on page 48 describes the start conditions for the internal reset. The delay (tTOUT) is timed from the Watchdog Oscillator and the number of cycles in the delay is set by the SUTx and CKSELx fuse bits. The 33 TPR0327AY-SMS-30Jan09 delay options are shown in Table 7-2. The frequency of the Watchdog Oscillator is voltage dependent. Table 7-2. Number of Watchdog Oscillator Cycles Typ Time-out (VCC = 3.0V) 0 ms 4.3 ms 69 ms Number of Cycles 0 512 8K (8,192) 0 ms 4.1 ms 65 ms Typ Time-out (VCC = 5.0V) The main purpose of the delay is to keep the AVR in reset until it is supplied with the minimum Vcc. The delay will not monitor the actual voltage thus it will be required to select a delay longer than the Vcc rise time. If this is not possible, an internal or external Brown-Out Detection circuit should be used. A BOD circuit will ensure sufficient Vcc before it releases the reset, thus the time-out delay can be disabled. Disabling the time-out delay without utilizing a Brown-Out Detection circuit is not recommended. The oscillator is required to oscillate for a minimum number of cycles before the clock is considered stable. An internal ripple counter monitors the oscillator output clock, and keeps the internal reset active for a given number of clock cycles. The reset is then released and the device will start to execute. The recommended oscillator start-up time is dependent on the clock type, and varies from 6 cycles for an externally applied clock to 32K cycles for a low frequency crystal. The start-up sequence for the clock includes both the time-out delay and the start-up time when the device starts up from reset. When starting up from Power-save or Power-down mode, Vcc is assumed to be at a sufficient level and only the start-up time is included. 7.2.3 Clock Source Connections The pins XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier which can be configured for use as an On-chip Oscillator, as shown in Figure 7-2. Either a quartz crystal or a ceramic resonator may be used. C1 and C2 should always be equal for both crystals and resonators. For ceramic resonators, the capacitor values given by the manufacturer should be used. Figure 7-2. Crystal Oscillator Connections 8Mhz C1 = 47pF C2 = 47pF 7.2.3.1 Low Power Crystal Oscillator This Crystal Oscillator is a low power oscillator, with reduced voltage swing on the XTAL2 output. It gives the lowest power consumption, but is not capable of driving other clock inputs. The only crystal supported by the AT90SCR100 is an 8Mhz crystal. 34 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The CKSEL0 Fuse together with the SUT1..0 Fuses select the start-up times as shown in Table 7-3. Table 7-3. Start-up Times for the Low Power Crystal Oscillator Clock Selection Start-up Time from Power-down and Power-save 258 CK 258 CK 1K CK 1K CK 1K CK 16K CK 16K CK 16K CK Additional Delay from Reset (VCC = 5.0V) 14CK + 4.1 ms(1) 14CK + 65 ms(1) 14CK(2) 14CK + 4.1 ms(2) 14CK + 65 ms(2) 14CK 14CK + 4.1 ms 14CK + 65 ms Oscillator Source / Power Conditions Ceramic resonator, fast rising power Ceramic resonator, slowly rising power Ceramic resonator, BOD enabled Ceramic resonator, fast rising power Ceramic resonator, slowly rising power Crystal Oscillator, BOD enabled Crystal Oscillator, fast rising power Crystal Oscillator, slowly rising power Notes: CKSEL0 0 0 0 0 1 1 1 1 SUT1..0 00 01 10 11 00 01 10 11 1. These options should only be used if frequency stability at start-up is not important for the application. These options are not suitable for crystals. 2. These options are intended to be used with ceramic resonators and will ensure frequency stability at start-up. 7.2.3.2 External Clock To drive the device from an external clock source, XTAL1 should be driven as shown in Figure 7-3. To run the device on an external clock, the CKSEL Fuses must be programmed to "0000". Figure 7-3. External Clock Drive Configuration NC XTAL2 EXTERNAL CLOCK SIGNAL XTAL1 GND When this clock source is selected, start-up times are determined by the SUT Fuses as shown in Table 7-4. 35 TPR0327AY-SMS-30Jan09 Table 7-4. Start-up Times for the External Clock Selection Start-up Time from Powerdown and Power-save 6 CK 6 CK 6 CK Reserved Additional Delay from Reset (VCC = 5.0V) 14CK 14CK + 4.1 ms 14CK + 65 ms SUT1..0 00 01 10 11 Power Conditions BOD enabled Fast rising power Slowly rising power When applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable operation of the MCU. A variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. If changes of more than 2% are required, ensure that the MCU is kept in Reset during the changes. The System Clock Prescaler can be used to implement run-time changes of the internal clock frequency while still ensuring stable operation. Refer to "CLKPR - Clock Prescale Register" on page 40 for details. Note 7.2.4 PLL Clock The AT90SCR100's PLL is used to generate internal high frequency clock synchronized by an external low-frequency clock of 8Mhz desribed in section "Clock Sources" on page 33. The PLL block combines Phase Frequency Comparator and Lock Detector. This block makes the comparison between a reference clock and a reverse clock and generates some pulses on the Up or Down signal depending on the edges of the reverse clock. Enabling the PLL by setting PLLCR.ON bit starts the stabilization process. As soon as the PLL is locked, which means that the clock generated is stable, supporting a duty cycle of 50%, the PLLCR.LOCK bit is set. When the PLL is locked, it is now possible to switch the PLL Clock Multiplexer to the PLL clock, by setting the PLLCR.PLLMUX bit. See "PLLCR - Phase Lock Loop (PLL) Control Register" on page 40. It is highly recommended that the clkCPU dividers are changed before switching to the clkPLL. 36 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 7-4. Programming PLL PLL Programming Enable PLL PLLCR.ON = 1 Is PLL Locked ? PLLCR.LOCK = 1 ? No Yes Configure CPU Divider CLKPR = xxxxb Switch clk MUX to clk PLL PLLCR.PLLMUX = 1 7.2.5 Internal RC Oscillator By default, the Internal RC Oscillator provides an approximate 8 MHz clock. Though voltage and temperature dependent, this clock can be very accurately calibrated by the user. See Table 31-2 on page 411 and "Internal RC Oscillator Speed" on page 38 for more details. This oscillator is used to time Eeprom and Flash write accesses. This is why its calibration is important. During reset, hardware loads the pre-programmed calibration value into the OSCCAL Register and thereby automatically calibrates the RC Oscillator. The accuracy of this calibration is shown as Factory calibration in Table 31-2 on page 411. By changing the OSCCAL register from SW, see "OSCCAL - Oscillator Calibration Register" on page 39, it is possible to get a higher calibration accuracy than by using the factory calibration. The accuracy of this calibration is shown as User calibration in Table 31-2 on page 411. 37 TPR0327AY-SMS-30Jan09 7.2.5.1 Internal RC Oscillator Speed The figures below are based on other AVR microcontrollers. ! Caution These values are preliminary values representing design targets, and will be updated after characterization of the silicon Calibrated 8 MHz RC Oscillator Frequency vs. Temperature CALIBRATED 8 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE 8,3 Figure 7-5. 8,2 5.5V 5.0V 4.5V 4.0V 3.3V 2.7V 8,1 FRC (MHz) 8 7,9 7,8 7,7 -60 -40 -20 0 20 40 60 80 100 Temperature Figure 7-6. Calibrated 8 MHz RC Oscillator Frequency vs. Operating Voltage CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. OPERATING VOLTAGE 8,5 8,4 8,3 8,2 85C 25C FRC (M Hz ) 8,1 8 7,9 7,8 7,7 7,6 7,5 1,5 2 2,5 3 3,5 4 4,5 5 5,5 -40C V CC (V) 38 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 7.2.5.2 OSCCAL - Oscillator Calibration Register Bit $000066 Read/write Initial value 7 CAL7 R/W 6 CAL6 R/W 5 CAL5 R/W 4 CAL4 R/W 3 CAL3 R/W 2 CAL2 R/W 1 CAL1 R/W 0 CAL0 R/W OSCCAL Device Specific Calibration Value * Bits 7:0 - CAL7:0: Oscillator Calibration Value The Oscillator Calibration Register is used to trim the Calibrated Internal RC 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 31-2 on page 411. The application software can write this register to change the oscillator frequency. The oscillator can be calibrated to frequencies as specified in Table 312 on page 411. Calibration outside that range is not guaranteed. Note that this oscillator is used to time EEPROM and Flash write accesses, and these write times will be affected accordingly. If the EEPROM or Flash are written, do not calibrate to more than 8.8 MHz. Otherwise, the EEPROM or Flash write may fail. The CAL7 bit determines the range of operation for the oscillator. Setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. The two frequency ranges are overlapping, in other words a setting of OSCCAL = 0x7F gives a higher frequency than OSCCAL = 0x80. The CAL6..0 bits are used to tune the frequency within the selected range. A setting of 0x00 gives the lowest frequency in that range, and a setting of 0x7F gives the highest frequency in the range. 7.2.6 RTC Clock AT90SCR100 supports a RTC counting feature by using Timer 2. The description of the Real Time Counter is described Section 13.3 "8-bit Timer/Counter2 with PWM and Asynchronous Operation (RTC)" on page 134. The external clock to connect to get a accurate RTC is a 32.768 KHz clock. Figure 7-7. RTC Clock Connection TOSC1 TOSC2 32.768 KHz C1 = 22pF C2 = 22pF 39 TPR0327AY-SMS-30Jan09 7.3 Clock Output Buffer The device can output the system clock clkCORE on the CLKO pin. To enable the output, the CKOUT Fuse has to be programmed. This mode is suitable when the chip clock is used to drive other circuits on the system. The clock will also be output during reset, and the normal operation of the I/O pin will be overriden when the fuse is programmed. 7.4 7.4.1 Clock System Registers PLLCR - Phase Lock Loop (PLL) Control Register Bit $000062 Read/write Initial value 7 PLLMUX R/W 0 6 R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 LOCK R 0 0 ON R/W 0 0x00 PLLCR * Bit 7 - PLLMUX : PLL Clock Multiplexer Control bit Set this bit (1) to switch Clock Multiplexer (clkMUX) to PLL clock (clkPLL). Clear this bit (0) to switch clkMUX to external clock (clkXTAL). * Bit 6..2 - Reserved Bits These bits are reserved for future use. * Bit 1 - LOCK : PLL Lock Bit Signal This bit is set by hardware as soon as the clock generated by the PLL (clkPLL) is stable. It is forbidden to switch clkMUX to clkPLL if the LOCK bit is not set. Wait for the PLLCR.LOCK bit to be set before switching to clkPLL using the PLLMUX bit. * Bit 0 - ON : PLL Start Bit Setting this bit (1) will start the PLL. As soon as LOCK bit is set, you can switch on clkPLL clock, not before. Clearing this bit (0) will stop the PLL. When the CPU runs on clkPLL, and the PLL is stopped, the CPU will be clcked no longer. This will freeze the CPU and only a reset will be able to start the CPU again. Before stopping the PLL, make sure that the CPU uses External Clock clkXTAL by using the PLLMUX register. 7.4.2 CLKPR - Clock Prescale Register Bit $000061 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 CLKPS3 R/W 0 2 CLKPS2 R/W 0 1 R/W 0 0 CLKPR 0x00 R/W 0 ! Caution CLKPS1 CLKPS0 * Bit 7..4 - Reserved Bits These bits are reserved for future use. 40 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bits 3..0 - CLKPS3..0 : Clock Prescaler Select Bits 3..0 These bits define the division factor between the selected clock source and the internal system clock. These bits can be written at run-time to vary the clock frequency to suit the application requirements. As the divider divides the master clock input to the MCU, the speed of all synchronous peripherals is reduced when a division factor is used. The division factors are given in Table 7-5. You can change the CLKPR on the fly. The divider will automatically be active. Default value of CLKPR is 0x00. Table 7-5. CLKPS3 Clock Prescaler Select (clkCPU) CLKPS2 CLKPS1 CLKPS0 CLKPR 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0X0F Clock Division Factor 1(3) 4 5 6 8 12 24 48 96 clkCPU (clkMUX = clkPLL)(1) 16Mhz(3) 24Mhz 19.2Mhz 16Mhz 12Mhz 8Mhz 4Mhz 2Mhz 1Mhz clkCPU (clkMUX = clkXTAL)(2) 8Mhz 2Mhz 1.60Mhz 1.33Mhz 1Mhz 0.67Mhz 0.33Mhz 0.17Mhz 0.08Mhz 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 Notes: 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Reserved 1. clkMUX=96Mhz, clock generated by the PLL 2. clkMUX=8Mhz, clock provided by external clock source XTAL. 3. It is impossible for the CPU core to support 96Mhz, thus, by default, the divide by one clock option generates a 16Mhz clock. 41 TPR0327AY-SMS-30Jan09 42 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 8. Power Management and Sleep Modes Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to the application's requirements. To enter any of the five sleep modes, the SE bit in the SMCR must be written to logic one and a SLEEP instruction must be executed. The SM2, SM1, and SM0 bits in the SMCR Register select which sleep mode (Idle, Power-down, Power-save, or Standby) will be activated by the SLEEP instruction. See Table 8-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 startup time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from sleep. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector. Figure 7-1 on page 31 presents the different clock systems in the AT90SCR100, and their distribution. The figure is helpful in selecting an appropriate sleep mode. 8.1 Power Modes Descriptions Please refer to the section entitled "Important note about: Entering and Leaving low consumption modes" on page 47, to read important remarks on achieving minimum consumption. When waking up from Power-down or Power-Save mode, there is a delay from when the wake-up condition occurs to when the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined by the same CKSEL Fuses that define the Reset Timeout period, as described in Table 7-3 on page 35. ! Caution Note 8.1.1 Idle Mode When the SM2:0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing the peripherals and the interrupt system to continue operating. This sleep mode basically halts clkCPU and clkFLASH, while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow and USART Transmit Complete interrupts, as shown in Table 8-1. 8.1.2 Power-down Mode When the SM2:0 bits are written to 010, the SLEEP instruction makes the MCU enter Powerdown mode. In this mode, the external Oscillator is stopped, while the external interrupts, the 2wire Serial Interface, and the Watchdog continue operating (if enabled). Only an External Reset, a coherent communication request on the different communication interface (TWI, USB, HSSPI, SPI, USART), a card insertion/removal, an external interrupt, a pin change interrupt or a keyboard pin pressed interrupt can wake up the MCU. This sleep mode basically halts all generated clocks, allowing operation of asynchronous modules only. To obtain a minimum consumption level, don't forget to stop the DCDC and PLL, as remarked in section "Important note about: Entering and Leaving low consumption modes" on page 47. ! Caution 43 TPR0327AY-SMS-30Jan09 Note that if a level triggered interrupt is used to wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU. Refer to "External Interrupts" on page 69 for details. When waking up from Power-down mode, there is a delay from when the wake-up condition occurs until when the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined in Table 7-3. 8.1.3 Power-save Mode When the SM2:0 bits are written to 011, the SLEEP instruction makes the MCU enter Powersave mode. This mode is identical to Power-down, with one exception: If Timer/Counter2 is enabled, it will keep running during sleep. The device can wake up from either Timer Overflow or Output Compare event from Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in TIMSK2, and the Global Interrupt Enable bit in SREG is set. If Timer/Counter2 is not running, Power-down mode is recommended instead of Power-save mode. The Timer/Counter2 can be clocked both synchronously and asynchronously in Power-save mode. If the Timer/Counter2 is not using the asynchronous clock, the Timer/Counter Oscillator is stopped during sleep. If the Timer/Counter2 is not using the synchronous clock, the clock source is stopped during sleep. Note that even if the synchronous clock is running in Power-save, this clock is only available for the Timer/Counter2. 8.1.4 Standby Mode When the SM2:0 bits are 110, 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. 8.1.5 Extended Standby Mode When the SM2:0 bits are 111, the SLEEP instruction makes the MCU enter Extended Standby mode. This mode is identical to Power-save mode with the exception that the Oscillator is kept running. From Extended Standby mode, the device wakes up in six clock cycles. Active Clock Domains and Wake-up Sources in the Different Sleep Modes. Active Clock Domains clkHSSPI, clkUSB clkFlash, clkSCI Table 8-1. Oscillators Communication Wake-up Sources SPM/ EEPROM Ready WDT Interrupt Keyboard Pin Pin Change Main Clock Source Enabled Timer Osc Enabled Coherent Sleep Mode Idle Power-down Power-save Standby Extended Standby Notes: X X X X X X(1) X(1) X X(2) X(2) X(2) X(2) X X X X X X X X X X X X X X X X X X X X(1) X X(1) X X 1. If Timer/Counter2 is running in asynchronous mode. 2. For INT3:0, only level interrupt. 44 AT90SCR100 TPR0327AY-SMS-30Jan09 Other I/O pressed request Timer2 INT3:0 clkCPU clkASY clkI/O AT90SCR100 8.2 Power Reduction Register The Power Reduction Register, PRR, provides a method to stop the clock to individual peripherals to reduce power consumption. The current state of the peripheral is frozen and the I/O registers can not be read or written. Resources used by the peripheral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock. Waking up a module, which is done by clearing the bit in PRR, puts the module in the same state as before shutdown. 8.2.1 SMCR - Sleep Mode Control Register The Sleep Mode Control Register contains control bits for power management. Bit 0x33 (0x53) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 SM2 R/W 0 2 SM1 R/W 0 1 SM0 R/W 0 0 SE R/W 0 0x00 SMCR * Bits 3..1 - SM2..0 : Sleep Mode Select Bits 2..0 These bits select between the five available sleep modes as shown in Table 8-2. Table 8-2. SM2 0 0 0 0 1 1 1 1 Note: Sleep Mode Select SM1 0 0 1 1 0 0 1 1 SM0 0 1 0 1 0 1 0 1 Sleep Mode Idle Reserved Power-down Power-save Reserved Reserved Standby(1) Extended Standby(1) 1. Standby modes are only recommended for use with external crystals or resonators. * Bit 0 - SE: Sleep Enable The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer's purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up. 8.2.2 PRR0 - Power Reduction Register 0 The Power Reduction Register allows the shut down of peripherals directly connected to CPU resources. These peripherals are activated by default and can be shut down for power consumption reasons if they are not used by an application. Bit $000064 Read/write Initial value 7 PRTWI R/W 0 6 PRTIM2 R/W 0 5 PRTIM0 R/W 0 4 R 0 3 PRTIM1 R/W 0 2 PRSPI R/W 0 1 PRUSART0 R/W 0 0 R 0 0x00 PRR0 45 TPR0327AY-SMS-30Jan09 * Bit 7 - PRTWI: Power Reduction TWI Writing a logic one to this bit shuts down the TWI by stopping the clock to the module. When waking up the TWI again, the TWI should be re initialized to ensure proper operation. * Bit 6 - PRTIM2: Power Reduction Timer/Counter2 Writing a logic one to this bit shuts down the Timer/Counter2 module in synchronous mode (AS2 is 0). When the Timer/Counter2 is enabled, operation will continue like before the shutdown. * Bit 5 - 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 as before the shutdown. * Bit 4 - Res: Reserved bit Reserved for future use and will always read as 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 - PRSPI: Power Reduction Serial Peripheral Interface Writing a logic one to this bit shuts down the Serial Peripheral Interface by stopping the clock to the module. When waking up the SPI again, the SPI should be re initialized to ensure proper operation. * Bit 1 - PRUSART0: Power Reduction USART0 Writing a logic one to this bit shuts down the USART0 by stopping the clock to the module. When waking up the USART0 again, the USART0 should be reinitialized to ensure proper operation. * Bit 0 - Res: Reserved bit Reserved for future use and will always read as zero. 8.2.3 PRR1 - Power Reduction Register 1 The Power Reduction Register allows the shut down of peripherals directly connected to CPU resources. These peripherals are activated by default and can be shut down for power consumption reasons if they are not used by an application. Bit $000065 Read/write Initial value 7 R/W 0 6 R/W 0 5 PRKB R/W 0 4 PRAES R 0 3 PRSCI R/W 0 2 PRHSSPI R/W 0 1 PRUSB R/W 0 0 PRUSBH R 0 0x00 PRR1 * Bit 7 - Res: Reserved bit Reserved for future use and will always read as zero. * Bit 6 - Res: Reserved bit Reserved for future use and will always read as zero. * Bit 5 - PRKB: Power Reduction Keyboard 46 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Writing a logic one to this bit shuts down the Keyboard module by stopping the clock to the module. When waking up the Keyboard again, the Keyboard should be re initialized to ensure proper operation. * Bit 4 - PRAES: Power Reduction AES Writing a logic one to this bit shuts down the AES module by stopping the clock to the module. When waking up the AES again, the AES should be re initialized to ensure proper operation. * Bit 3 - PRSCI: Power Reduction Smart Card Interface Writing a logic one to this bit shuts down the Smart Card Interface module by stopping the clock to the module. When waking up the SCIB again, the SCIB should be re initialized to ensure proper operation. * Bit 2 - PRHSSPI: Power Reduction High Speed SPI Writing a logic one to this bit shuts down the High Speed Serial Peripheral Interface by stopping the clock to the module. When waking up the HSSPI again, the HSSPI should be re initialized to ensure proper operation. * Bit 1 - PRUSB: Power Reduction USB Writing a logic one to this bit shuts down the USB by stopping the clock to the module. When waking up the USB again, the USB should be reinitialized to ensure proper operation. * Bit 0 - PRUSBH: Power Reduction USB Host Controller Writing a logic one to this bit shuts down the USB Host Controller by stopping the clock to the module. When waking up the USB Host Controller again, the USB Host module should be reinitialized to ensure proper operation. Enabling the `Power Reduction USB Host Controller' prevents the device from communicating with USB smart cards. Note However, if the Smart Card Interface is ON, communication with standard smart cards (ISO7816 1-3) is still possible. To optimize the power consumption, if the application does not target USB Smart Card, the USB Host Controller should be disabled this way. 8.3 8.3.1 Important note about: Entering and Leaving low consumption modes Entering Power Down It is very important to note that there is no automatic switch to a low consumption mode for the PLL Clock Multiplexer and for the DC/DC converter. * To lower the powerdown consumption, the PLL Clock Multiplexer must be switched to External Clock and the PLL must be stopped. To do so: - Switch from PLL to External Clock by clearing PLLCR.PLLMUX. - Turn the PLL off by clearing PLLCR.ON. - Wait until PLLCR.LOCK bit is cleared. * To lower the powerdown consumption, the DC/DC converter must also be switched off. To do so: - Clear DCCR.DCON bit. This will generate a deactivation sequence. 47 TPR0327AY-SMS-30Jan09 - Wait until DCCR.DCRDY is cleared. 8.3.2 Waking up from Power Down Do not forget to restore the PLL configuration and DC/DC converter when waking the chip up. Please refer to Figure 7-4 on page 37 and Figure 16-1 on page 202 to re-enable these peripherals. 8.4 Minimizing Power Consumption There are several issues to consider when trying to minimize the power consumption in an AVR controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possible of the device's functions are operating. All functions not needed should be disabled. In particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption. 8.4.1 Brown-out Detector If the Brown-out Detector is not needed by the application, this module should be turned off. If the Brown-out Detector is enabled by the BODENABLE 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 54 for details on how to configure the Brown-out Detector. Internal Voltage Reference The Internal Voltage Reference will be enabled when needed by the Brown-out Detection. If this module is 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 Voltage Reference" on page 55 for details on the start-up time. Watchdog Timer If the Watchdog Timer is not needed in the application, the module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this will contribute significantly to the total current consumption. Refer to "Interrupts" on page 63 for details on how to configure the Watchdog Timer. Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. It is most important to ensure that no pins drive resistive loads. This ensures that no power is consumed by the input logic when not needed. In some cases, the input logic is needed to detect wake-up conditions, and it will then be enabled. Refer to the section "Digital Input Enable and Sleep Modes" on page 81 for details on which pins are enabled. If the input buffer is enabled and the input signal is left floating or has an analog signal level close to VCC/2, the input buffer will use excessive power. 8.4.2 8.4.3 8.4.4 8.4.5 On-chip Debug System If the On-chip debug system is enabled by the OCDEN Fuse and the chip enters sleep mode, the main clock source is enabled, and hence, always consumes power. In the deeper sleep modes, this will contribute significantly to the total current consumption. There are three alternative ways to disable the OCD system: 48 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Disable the OCDEN Fuse. * Disable the JTAGEN Fuse. * Write one to the JTD bit in MCUCR. See "MCUCR - MCU Control Register" on page 356. 49 TPR0327AY-SMS-30Jan09 50 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 9. System Control and Reset 9.1 Resetting the AVR During reset, all I/O Registers are set to their initial values, and the program starts execution from the Reset Vector. The instruction placed at the Reset Vector must be a JMP - Absolute Jump - instruction to the reset handling routine. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. The circuit diagram in Figure 9-1 shows the reset logic. Table 9-1 defines the electrical parameters of the reset circuitry. The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not require any clock source to be running. After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the 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 Fuses. The different selections for the delay period are presented in Table 7-3. 9.2 Reset Sources The AT90SCR100 has five sources of reset: * Power-on Reset. The MCU is reset when the supply voltage is below the Power-on Reset threshold (VPOT). * External Reset. The MCU is reset when a low level is present on the RESET pin for longer than the minimum pulse length. * Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled. * Brown-out Reset. The MCU is reset when the supply voltage VCC is below the Brown-out Reset threshold (VBOT) and the Brown-out Detector is enabled. * JTAG AVR Reset. The MCU is reset as long as there is a logic one in the Reset Register, one of the scan chains of the JTAG system. Refer to the section "IEEE 1149.1 (JTAG) Boundary-scan" on page 353 for details. 51 TPR0327AY-SMS-30Jan09 Figure 9-1. Reset Logic DATA BUS MCU Status Register (MCUSR) PORF BORF EXTRF WDRF JTRF CK Delay Counters TIMEOUT Power-on Reset Circuit BODLEVEL Pull-up Resistor SPIKE FILTER Brown-out Reset Circuit JTAG Reset Register Watchdog Oscillator Clock Controller SUT[1:0] Table 9-1. Symbol Reset Characteristics(1) Parameter Power-on Reset Threshold Voltage (rising) Power-on Reset Threshold Voltage (falling)(2) RESET Pin ViL RESET Pin ViH Minimum pulse width on RESET Pin 0.85VCC 1.5 s Condition Min Typ 1.4 1.3 Max 1.8 1.8 0.2VCC Units V V V VPOT VRST tRST Notes: 1. Values are guidelines only. Actual values are TBC. 2. The Power-on Reset will not work unless the supply voltage has been below VPOT (falling) 9.2.1 Power-on Reset A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level is defined in Table 9-1. The POR is activated whenever VCC is below the detection level. The POR circuit can be used to trigger the start-up Reset, as well as to detect a failure in supply voltage. 52 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reaching the Power-on Reset threshold voltage invokes the delay counter, which determines how long the device is kept in RESET after VCC rise. The RESET signal is activated again, without any delay, when VCC decreases below the detection level. Figure 9-2. V CC MCU Start-up, RESET Tied to VCC V POT RESET V RST TIME-OUT tTOUT INTERNAL RESET Figure 9-3. V CC MCU Start-up, RESET Extended Externally V POT RESET V RST TIME-OUT tTOUT INTERNAL RESET 9.2.2 External Reset An External Reset is generated by a low level on the RESET pin. Reset pulses longer than the minimum pulse width (see Table 9-1) will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage - VRST - on its positive edge, the delay counter starts the MCU after the Time-out period - tTOUT - has expired. 53 TPR0327AY-SMS-30Jan09 Figure 9-4. CC External Reset During Operation 9.2.3 Brown-out Detection AT90SCR100 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VCC level during operation by comparing it to a fixed trigger level. The BOD can be activated or disabled by the BODENABLE Fuses. The trigger level has a hysteresis to ensure spike free Brown-out Detection. The hysteresis on the detection level should be interpreted as VBOT+ = VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2. Table 9-2. BODENABLE Fuse Coding Min VBOT Typ VBOT BOD Disabled 2.3 V Max VBOT 1 0 BODENABLE Fuse Table 9-3. Symbol VHYST tBOD Brown-out Characteristics Parameter Brown-out Detector Hysteresis Min Pulse Width on Brown-out Reset Min Typ 50 Max Units mV ns When the BOD is enabled, and VCC decreases to a value below the trigger level (VBOT- in Figure 9-5), the Brown-out Reset is immediately activated. When VCC increases above the trigger level (V BOT+ in Figure 9-5), the delay counter starts the MCU after the Time-out period tTOUT has expired. The BOD circuit will only detect a drop in VCC if the voltage stays below the trigger level for longer than tBOD given in Table 9-1. 54 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 9-5. Brown-out Reset During Operation VCC VBOTVBOT+ RESET TIME-OUT tTOUT INTERNAL RESET 9.2.4 Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period tTOUT. Refer to page 63 for details on operation of the Watchdog Timer. Figure 9-6. CC Watchdog Reset During Operation CK 9.3 Internal Voltage Reference AT90SCR100 features an internal bandgap reference. This reference is used for Brown-out Detection and supply monitor. 9.3.1 Voltage Reference Enable Signals and Start-up Time The voltage reference has a start-up time that may influence the way it should be used. The start-up time is given in Table 9-4. 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 BODENABLE Fuse). 2. Supply Monitor is enabled (by programming the SMONCR.SMONEN bit). 55 TPR0327AY-SMS-30Jan09 To reduce power consumption in Power-down mode, the user can avoid the two conditions above to ensure that the reference is turned off before entering Power-down mode. Table 9-4. Symbol tBG Notes: Internal Voltage Reference Characteristics(1) Parameter Reference start-up time Condition VCC = 2.7 TA = 25C Min Typ 40 Max 70 Units s 1. Values are guidelines only. Actual values are TBD. 9.4 Supply monitor This feature is designed to prevent the AT90SCR100 operating under conditions that don't guarantee a correct operation of its peripherals. Useful to detect battery low voltage, the supply monitor peripheral generate an interruption when Vcc drops below a level defined in Table 9-5. Table 9-5. Symbol VSMON VSMHYST tSMON Supply Monitor References Parameter Supply Monitor Level Supply Monitor Hysteresis Min Pulse Width on Brown-out Reset Min Typ 2.5 50 Max Units V mV ns Vcc shall be below Supply Monitor level for a minimum time before the interruption to be generated. In the same behavior than BOD, the Supply Monitor has an hysteresis to reach the level, interpreted as VSMON+ = VSMON + VSMHYST/2 and VSMON- = VSMON - VSMHYST/2 Figure 9-7. Supply Monitor description VCC VSMON- VSMON+ RESET INTERRUPT TRIGGER Please refer to section "SMONCR - Supply Monitor Control Register" on page 60 and section "Interrupts" on page 63 for Supply Monitor interruption management. 56 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 9.5 Watchdog Timer AT90SCR100 has an Enhanced Watchdog Timer (WDT). The main features are: * Clocked from separate On-chip Oscillator * 3 Operating modes - Interrupt - System Reset - Interrupt and System Reset * Selectable Time-out period from 16ms to 8s * Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode Figure 9-8. Watchdog Timer 125kHz OSCILLATOR OSC/2K OSC/4K OSC/8K OSC/16K OSC/32K OSC/64K OSC/128K OSC/256K OSC/512K OSC/1024K WATCHDOG RESET WDE WDP0 WDP1 WDP2 WDP3 MCU RESET WDIF INTERRUPT WDIE The Watchdog Timer (WDT) is a timer counting cycles of a separate on-chip 125 kHz oscillator. The WDT gives an interrupt or a system reset when the counter reaches a given time-out value. In normal operation mode, it is required that the system uses the WDR - Watchdog Timer Reset - instruction to restart the counter before the time-out value is reached. If the system doesn't restart the counter, an interrupt or system reset will be issued. In Interrupt mode, the WDT gives an interrupt when the timer expires. This interrupt can be used to wake the device from sleep-modes, and also as a general system timer. One example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. In System Reset mode, the WDT gives a reset when the timer expires. This is typically used to prevent system hang-up in case of runaway code. The third mode, Interrupt and System Reset mode, combines the other two modes by first giving an interrupt and then switch to System Reset mode. This mode will for instance allow a safe shutdown by saving critical parameters before a system reset. The Watchdog always on (WDTON) fuse, if programmed, will force the Watchdog Timer to System Reset mode. With the fuse programmed the System Reset mode bit (WDE) and Interrupt mode bit (WDIE) are locked to 1 and 0 respectively. To further ensure program security, alterations to the Watchdog set-up must follow timed sequences. The sequence for clearing the WDE and changing the time-out configuration is as follows: 57 TPR0327AY-SMS-30Jan09 1. In the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit. 2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as desired, but with the WDCE bit cleared. This must be done in one operation. The following code example shows one assembly and one C function for turning off the Watchdog Timer. The example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the execution of these functions. Assembly Code Example WDT_off: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Clear WDRF in MCUSR in andi out r16, MCUSR r16, (0xff & (0< ; Turn on global interrupt C Code Example void WDT_off(void) { __disable_interrupt(); __watchdog_reset(); /* Clear WDRF in MCUSR */ MCUSR &= ~(1< AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Note If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of time-out resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialisation routine, even if the Watchdog is not in use. The following code example shows one assembly and one C function for changing the time-out value of the Watchdog Timer. Assembly Code Example WDT_Prescaler_Change: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Start timed sequence in ori out ; -ldi out ; -sei ret r16, WDTCSR r16, (1< ; Turn on global interrupt C Code Example void WDT_Prescaler_Change(void) { __disable_interrupt(); __watchdog_reset(); /* Start timed Sequence */ WDTCSR |= (1< The Watchdog Timer should be reset before any change of the WDP bits, since a change in the WDP bits can result in a time-out when switching to a shorter timeout period. 59 TPR0327AY-SMS-30Jan09 9.6 9.6.1 Register Description MCUSR - MCU Status Register The MCU Status Register provides information on which reset source caused an MCU reset. Bit 0x34 (0x54) Read/write Initial value 7 R 6 R 5 R 4 JTRF R/W 3 WDRF R/W 2 BORF R/W 1 EXTRF R/W 0 PORF R/W MCUSR See Bit Description * Bit 4 - JTRF: JTAG Reset Flag This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 3 - WDRF: Watchdog Reset Flag This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 2 - 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 reset condition, the user should read and then Reset the MCUSR as early as possible in the program. If the register is cleared before another reset occurs, the source of the reset can be found by examining the Reset Flags. 9.6.2 SMONCR - Supply Monitor Control Register Bit 0x0063 Read/write Initial value 7 R/W 0 6 R/W 0 5 R 0 4 R 0 3 R 0 2 R 0 1 R 0 0 SMONEN SMONCR R/W 0 0x00 SMONIF SMONIE * Bit 7 - SMONIF: Supply Monitor Interrupt Flag This bit is set by hardware when the external voltage Vcc drops below a Supply Monitor level. If SMONIE and SREG.I bits are set, then an interrupt is triggered. This interrupt should allow time to save important information, or cancel critical exchanges. This bit must be cleared by software. * Bit 6 - SMONIE: Supply Monitor Interrupt Enable 60 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 This bit is set and cleared by software. Set this bit to enable interrupt generation as soon as Vcc drops below the Supply Monitor level. The global interrupt bit (SREG.I) should be set. Clear this bit to mask Supply Monitor Interruption generation. * Bit 5..1 - Reserved Bits These bits are reserved for future use. * Bit 0 - SMONEN: Supply Monitor Enable This bit is set and cleared by software. Setting this bit will activate the Supply Monitor system. Clearing this bit will disable the Supply Monitor system and reduce power consumption. 9.6.3 WDTCSR - Watchdog Timer Control Register Bit $000060 Read/write Initial value 7 WDIF R/W 0 6 WDIE R/W 0 5 WDP3 R/W 0 4 WDCE R/W 0 3 WDE R/W 0 2 WDP2 R/W 0 1 WDP1 R/W 0 0 WDP0 R/W 0 0x00 WDTCSR * Bit 7 - WDIF: Watchdog Interrupt Flag This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, WDIF is cleared by writing a logic one to the flag. When the I-bit in SREG and WDIE are set, the Watchdog Time-out Interrupt is executed. * Bit 6 - WDIE: Watchdog Interrupt Enable When this bit is written to one and the I-bit in the Status Register is set, the Watchdog Interrupt is enabled. If WDE is cleared in combination with this setting, the Watchdog Timer is in Interrupt Mode, and the corresponding interrupt is executed if a time-out in the Watchdog Timer occurs. If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the Watchdog goes to System Reset Mode). This is useful for keeping the Watchdog Timer security while using the interrupt. To stay in Interrupt and System Reset Mode, WDIE must be set after each interrupt. This should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the Watchdog System Reset mode. If the interrupt is not executed before the next time-out, a System Reset will be applied. Table 9-6. WDTON(1) 0 0 0 0 1 Notes: Watchdog Timer Configuration WDE 0 0 1 1 x WDIE 0 1 0 1 x Mode Stopped Interrupt Mode System Reset Mode Interrupt and System Reset Mode System Reset Mode Action on Time-out None Interrupt Reset Interrupt, then go to System Reset Mode Reset 1. WDTON is a fuse bit (see "Fuse High Byte" on page 379). 61 TPR0327AY-SMS-30Jan09 * Bit 4 - WDCE: Watchdog Change Enable This bit is used in timed sequences for changing WDE and prescaler bits. To clear the WDE bit, and/or change the prescaler bits, WDCE must be set. Once written to one, hardware will clear WDCE after four clock cycles. * Bit 3 - WDE: Watchdog System Reset Enable WDE is overridden by WDRF in MCUSR. This means that WDE is always set when WDRF is set. To clear WDE, WDRF must be cleared first. This feature ensures multiple resets during conditions causing failure, and a safe start-up after the failure. * Bit 5, 2..0 - WDP3..0: Watchdog Timer Prescaler 3..0 The WDP3:0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is running. The different prescaling values and their corresponding time-out periods are shown in Table 9-7 on page 62. Table 9-7. WDP3 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 Watchdog Timer Prescale Select WDP2 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 WDP1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 WDP0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Reserved Number of WDT Oscillator Cycles 2K (2048) cycles 4K (4096) cycles 8K (8192) cycles 16K (16384) cycles 32K (32768) cycles 64K (65536) cycles 128K (131072) cycles 256K (262144) cycles 512K (524288) cycles 1024K (1048576) cycles Typical Time-out at VCC = 5.0V 15.625 ms 31.25 ms 62.5 ms 0.122 s 0.24 s 0.48 s 0.97 s 1.95 s 3.9 s 7.81 s 62 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 10. Interrupts This section describes the specifics of the interrupt handling as performed in AT90SCR100. For a general explanation of the AVR interrupt handling, refer to "Reset and Interrupt Handling" on page 18. 10.1 Interrupt Vectors in AT90SCR100 Table 10-1. Vector No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Reset and Interrupt Vectors Program Address(1) $0000(2) $0002 $0004 $0006 $0008 $000A $000C $000E $0010 $0012 $0014 $0016 $0018 $001A $001C $001E $0020 $0022 $0024 $0026 $0028 $002A $002C $002E -$0032 $0034 $0036 Source RESET INT0 INT1 INT2 INT3 PCINT0 PCINT1 PCINT2 WDT TIMER2_COMPA TIMER2_COMPB TIMER2_OVF TIMER1_CAPT TIMER1_COMPA TIMER1_COMPB TIMER1_OVF TIMER0_COMPA TIMER0_COMPB TIMER0_OVF SPI_STC USART_RX USART_UDRE USART_TX SUPPLY_MON RFU EE_READY TWI SPM_READY Interrupt Definition External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, and JTAG AVR Reset External Interrupt Request 0 External Interrupt Request 1 External Interrupt Request 2 External Interrupt Request 3 Pin Change Interrupt Request 0 Pin Change Interrupt Request 1 Pin Change Interrupt Request 2 Watchdog Time-out Interrupt Timer/Counter2 Compare Match A Timer/Counter2 Compare Match B Timer/Counter2 Overflow Timer/Counter1 Capture Event Timer/Counter1 Compare Match A Timer/Counter1 Compare Match B Timer/Counter1 Overflow Timer/Counter0 Compare Match A Timer/Counter0 Compare Match B Timer/Counter0 Overflow SPI Serial Transfer Complete USART Rx Complete USART Data Register Empty USART Tx Complete Supply Monitor Interruption Reserved For Future Use EEPROM Ready 2-wire Serial Interface Store Program Memory Ready 63 TPR0327AY-SMS-30Jan09 Table 10-1. Vector No. 29 30 31 32 33 34 35 36 37 38 Notes: Reset and Interrupt Vectors (Continued) Program Address(1) $0038 $003A $003C $003E $0040 $0042 $0044 $0046 $0048 $004A Source KEYBOARD AES HSSPI USB Endpoint USB Protocol SCIB USB Host Control USB Host Pipe CPRES PCINT3 Interrupt Definition Keyboard Input Changed AES Block Operation Ended High-Speed SPI Interface USB Endpoint linked Interrupt USB Protocol Interrupt Smart Card Reader Interface USB Host Controller Interrupt USB Host Pipe Interrupt Card Presence Detection Pin Change Interrupt Request 3 1. When the IVSEL bit in MCUCR is set, Interrupt Vectors will be moved to the start of the Boot Flash Section. The address of each Interrupt Vector will then be the address in this table added to the start address of the Boot Flash Section. 2. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader address at reset, see "Memory Programming" on page 377. Table 10-2 shows reset and Interrupt Vectors placement for the various combinations of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. Table 10-2. BOOTRST 1 1 0 0 Note: Reset and Interrupt Vectors Placement(1) IVSEL 0 1 0 1 Reset Address 0x0000 0x0000 Boot Reset Address Boot Reset Address Interrupt Vectors Start Address 0x0002 Boot Reset Address + 0x0002 0x0002 Boot Reset Address + 0x0002 1. The Boot Reset Address is shown in Table 28-7 on page 376. For the BOOTRST Fuse "1" means unprogrammed while "0" means programmed. The most typical and general program setup for the Reset and Interrupt Vector Addresses in AT90SCR100 is: Addr ess 0x 0x02 0x04 0x06 0x08 0x0A 0x0C Labels Code jmp jmp jmp jmp jmp jmp jmp RESET INT0 INT1 INT2 INT3 PCINT0 PCINT1 Comments ; ; ; ; ; ; ; Reset Handler IRQ0 Handler IRQ1 Handler IRQ2 Handler IRQ3 Handler PCINT0 Handler PCINT1 Handler 64 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 0x0E 0x10 0x12 0x14 0x16 0x18 0x1A 0x1C 0x1E 0x20 0x22 0x24 0x26 0x28 0x2A 0x2C 0x2E 0x30 0x32 0x34 0x36 0x38 0x3A 0x3C 0x3E 0x40 0x42 0x44 0x46 0x48 0x4A ; 0x3E 0x3F 0x40 0x41 0x42 0x43 ... jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp RESET: ldi out ldi out sei ; Main program start ; Set Stack Pointer to top of RAM ... When the BOOTRST Fuse is unprogrammed, the Boot section size set to 8K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: Address Labels Code 0x00000 RESET: ldi 0x00001 out SPH,r16 Comments r16,high(RAMEND); Main program start ; Set Stack Pointer to top of RAM 65 TPR0327AY-SMS-30Jan09 0x00002 0x00003 0x00004 0x00005 ; .org 0x1F002 0x1F002 0x1F004 ... 0x1FO36 ldi out sei r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx jmp jmp ... jmp EXT_INT0 EXT_INT1 ... SPM_RDY ; IRQ0 Handler ; IRQ1 Handler ; ; SPM Ready Handler When the BOOTRST Fuse is programmed and the Boot section size set to 8K bytes, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: Address Labels Code .org 0x0002 0x00002 0x00004 ... 0x00036 ; .org 0x1F000 0x1F000 RESET: ldi 0x1F001 0x1F002 0x1F003 0x1F004 0x1F005 out ldi out sei r16,high(RAMEND); Main program start SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx ; Set Stack Pointer to top of RAM jmp jmp ... jmp EXT_INT0 EXT_INT1 ... SPM_RDY ; IRQ0 Handler ; IRQ1 Handler ; ; SPM Ready Handler Comments When the BOOTRST Fuse is programmed, the Boot section size set to 8K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: Address Labels Code ; .org 0x1F000 0x1F000 0x1F002 0x1F004 ... 0x1F036 ; 0x1F03E RESET: ldi 0x1F03F 0x1F040 0x1F041 0x1F042 0x1FO43 out ldi out sei r16,high(RAMEND); Main program start SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx ; Set Stack Pointer to top of RAM jmp jmp jmp ... jmp RESET EXT_INT0 EXT_INT1 ... SPM_RDY ; Reset handler ; IRQ0 Handler ; IRQ1 Handler ; ; SPM Ready Handler Comments 66 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 10.1.1 Moving Interrupts Between Application and Boot Space The General Interrupt Control Register controls the placement of the Interrupt Vector table. MCUCR - MCU Control Register Bit 0x35 (0x55) Read/write Initial value 7 JTD R/W 0 6 R 0 5 R 0 4 PUD R/W 0 3 R 0 2 R 0 1 IVSEL R/W 0 0 IVCE R/W 0 0x00 MCUCR 10.1.2 * Bit 7..2 - Different bits These bits are used by other functions of the AVR core, or are reserved bits. * Bit 1 - IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual address of the start of the Boot Flash Section is determined by the BOOTSZ Fuses. Refer to the section "Memory Programming" on page 377 for details. To avoid unintentional changes of Interrupt Vector tables, a special write procedure must be followed to change the IVSEL bit: 1. Write the Interrupt Vector Change Enable (IVCE) bit to one. 2. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE. Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE is set, and they remain disabled until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status Register is unaffected by the automatic disabling. If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed, interrupts are disabled while executing from the Application section. If Interrupt Vectors are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled while executing from the Boot Loader section. Refer to the section "Memory Programming" on page 377 for details on Boot Lock bits. Note * Bit 0 - IVCE: Interrupt Vector Change Enable The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the IVSEL description above. See Code Example below. 67 TPR0327AY-SMS-30Jan09 Assembly Code Example Move_interrupts: ; Get MCUCR in r16, MCUCR mov r17, r16 ; Enable change of Interrupt Vector ori r16, (1< void Move_interrupts(void) { uchar temp; /* Get MCUCR */ temp = MCUCR; /* Enable change of Interrupt Vectors */ MCUCR = temp|(1< AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 11. External Interrupts The External Interrupts are triggered by the INT3:0 pin or any of the PCINT31:0 pins. Observe that, if enabled, the interrupts will trigger even if the INT3:0 or PCINT31:0 pins are configured as outputs. This feature provides a way of generating a software interrupt. The Pin change interrupt PCI3 will trigger if any enabled PCINT31:24 pin toggles, Pin change interrupt PCI2 will trigger if any enabled PCINT23:16 pin toggles, Pin change interrupt PCI1 will trigger if any enabled PCINT15:8 pin toggles and Pin change interrupt PCI0 will trigger if any enabled PCINT7:0 toggles. PCMSK3, PCMSK2, PCMSK1 and PCMSK0 Registers control which pins contribute to the pin change interrupts. Pin change interrupts on PCINT31:0 are detected asynchronously. This implies that these interrupts can also be used for waking the part from sleep modes other than Idle mode. The External Interrupts can be triggered by a falling or rising edge or a low level. This is set up as indicated in the specification for the External Interrupt Control Registers - EICRA (INT3:0). When the external interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. Low level interrupts and the edge interrupt on INT3:0 are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle mode. 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 TBD. Note Finally, as the INT2 and INT3 pins, are configured to PB0 and PB1 respectively and these port bits are multiplexed with other outputs, there is a way to use other pins to trigger INT2 and INT3. These pins are identified INT2b and INT3b (pins PC0 and PC1). Refer to "EIRR - External Interrupt Redirection Register" on page 71 for more information. 11.1 11.1.1 External Interrupt Registers EICRA - External Interrupt Control Register A The External Interrupt Control Register A contains control bits for interrupt sense control. Bit $000069 Read/write Initial value 7 ISC31 R/W 0 6 ISC30 R/W 0 5 ISC21 R/W 0 4 ISC20 R/W 0 3 ISC11 R/W 0 2 ISC10 R/W 0 1 ISC01 R/W 0 0 ISC00 R/W 0 0x00 EICRA * Bits 7..0 - ISC31, ISC30 - ISC00, ISC00 : External Interrupt 3 - 0 Sense Control Bits The External Interrupts 3 - 0 are activated by the external pins INT3:0 if the SREG I-flag and the corresponding interrupt mask in the EIMSK is set. The level and edges on the external pins that activate the interrupts are defined in Table 11-1. Edges on INT3:0 are registered asynchronously. Pulses on INT3:0 pins wider than the minimum pulse width given in Table 11-2 will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If a low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. If enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. When changing the ISCn bit, an interrupt can occur. 69 TPR0327AY-SMS-30Jan09 Therefore, it is recommended to first disable INTn by clearing its Interrupt Enable bit in the EIMSK Register. Then, the ISCn bit can be changed. Finally, the INTn interrupt flag should be cleared by writing a logical one to its Interrupt Flag bit (INTFn) in the EIFR Register before the interrupt is re-enabled. Table 11-1. ISCn1 0 0 1 1 Note: 0 1 0 1 Interrupt Sense Control(1) ISCn0 Description The low level of INTn generates an interrupt request. Any edge of INTn generates asynchronously an interrupt request. The falling edge of INTn generates asynchronously an interrupt request. The rising edge of INTn generates asynchronously an interrupt request. 1. n = 3, 2, 1or 0. When changing the ISCn1/ISCn0 bits, the interrupt must be disabled by clearing its Interrupt Enable bit in the EIMSK Register. Otherwise an interrupt can occur when the bits are changed Table 11-2. Symbol tINT Asynchronous External Interrupt Characteristics Parameter Minimum pulse width for asynchronous external interrupt Condition Min Typ 50 Max Units ns 11.1.2 EIMSK - External Interrupt Mask Register Bit 0x1D (0x3D) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 INT3 R/W 0 2 INT2 R/W 0 1 INT1 R/W 0 0 INT0 R/W 0 0x00 EIMSK * Bits 3..0 - INT3..0 : External Interrupt Request 3 - 0 Enable When an INT3:0 bit is written to one and the I-bit in the Status Register (SREG) is set (one), the corresponding external pin interrupt is enabled. The Interrupt Sense Control bits in the External Interrupt Control Register, EICRA, defines whether the external interrupt is activated on rising or falling edge or level sensed. Activity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. This provides a way of generating a software interrupt. 11.1.3 EIFR - External Interrupt Flag Register Bit 0x1C (0x3C) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 INTF3 R/W 0 2 INTF2 R/W 0 1 INTF1 R/W 0 0 INTF0 R/W 0 0x00 EIFR * Bits 3..0 - INTF3..0 : External Interrupt Flags 3 - 0 When an edge or logic change on the INT3:0 pin triggers an interrupt request, INTF3:0 becomes set (one). If the I-bit in SREG and the corresponding interrupt enable bit, INT3:0 in EIMSK, are set (one), the MCU will jump to the interrupt vector. The flag is cleared when the interrupt routine 70 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 is executed. Alternatively, the flag can be cleared by writing a logical one to it. These flags are always cleared when INT3:0 are configured as level interrupt. When entering sleep mode with the INT3:0 interrupts disabled, the input buffers on these pins will be disabled. This may cause a logic change in internal signals which will set the INTF3:0 flags. See "Digital Input Enable and Sleep Modes" on page 81 for more information. Note 11.1.4 EIRR - External Interrupt Redirection Register Bit 0x1A (0x3A) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 INTD3 R/W 0 2 INTD2 R/W 0 1 R 0 0 R 0 0x00 EIRR * Bit 3 - INTD3 : External Interruption 3 Direction This bit is set and cleared by software. Please see the table below for bit description: Table 11-3. INTD3 0 1 External Interruption 3 Pad location Interruption 3 Pad PB1 PC1 Description INT3 active, INT3b inactive INT3 inactive, INT3b active * Bit 2 - INTD2 : External Interruption 2 Direction This bit is set and cleared by software. Table 11-4. INTD3 0 1 External Interruption 2 Pad location Interruption 3 Pad PB0 PC0 Description INT2 active, INT2b inactive INT2 inactive, INT2b active 11.1.5 PCICR - Pin Change Interrupt Control Register Bit 0x68 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 PCIE3 R/W 0 2 PCIE2 R/W 0 1 PCIE1 R/W 0 0 PCIE0 R/W 0 0x00 PCICR * Bit 3 - PCIE3 : Pin Change Interrupt Enable 3 When the PCIE3 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 3 is enabled. Any change on any enabled PCINT31:24 pin will cause an interrupt. The corresponding interrupt of the Pin Change Interrupt Request is executed from the PCI3 Interrupt Vector. PCINT31:24 pins are enabled individually by the PCMSK3 Register. * Bit 2 - PCIE2 : Pin Change Interrupt Enable 2 When the PCIE2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 2 is enabled. Any change on any enabled PCINT23:16 pin will cause an inter- 71 TPR0327AY-SMS-30Jan09 rupt. The corresponding interrupt of the Pin Change Interrupt Request is executed from the PCI2 Interrupt Vector. PCINT23:16 pins are enabled individually by the PCMSK2 Register. * Bit 1 - PCIE1 : Pin Change Interrupt Enable 1 When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 1 is enabled. Any change on any enabled PCINT15:8 pin will cause an interrupt. The corresponding interrupt of the Pin Change Interrupt Request is executed from the PCI1 Interrupt Vector. PCINT15:8 pins are enabled individually by the PCMSK1 Register. * Bit 0 - PCIE0 : Pin Change Interrupt Enable 0 When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 0 is enabled. Any change on any enabled PCINT7:0 pin will cause an interrupt. The corresponding interrupt of the Pin Change Interrupt Request is executed from the PCI0 Interrupt Vector. PCINT7:0 pins are enabled individually by the PCMSK0 Register. 11.1.6 PCIFR - Pin Change Interrupt Flag Register Bit 0x1B (0x3B) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 PCIF3 R 0 2 PCIF2 R/W 0 1 PCIF1 R/W 0 0 PCIF0 R/W 0 0x00 PCIFR * Bit 3- PCIF3 : Pin Change Interrupt Flag 3 When a logic change on any PCINT31:24 pin triggers an interrupt request, PCIF3 becomes set (one). If the I-bit in SREG and the PCIE3 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 2 - PCIF2 : Pin Change Interrupt Flag 2 When a logic change on any PCINT23:16 pin triggers an interrupt request, PCIF2 becomes set (one). If the I-bit in SREG and the PCIE2 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 1 - PCIF1 : Pin Change Interrupt Flag 1 When a logic change on any PCINT15:8 pin triggers an interrupt request, PCIF1 becomes set (one). If the I-bit in SREG and the PCIE1 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 0 - PCIF0 : Pin Change Interrupt Flag 0 When a logic change on any PCINT7:0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in SREG and the PCIE0 bit in PCICR 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. 72 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 11.1.7 PCMSK3 - Pin Change Mask Register 3 Bit 0x000073 Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PCMSK3 0x00 R/W 0 PCINT31 PCINT30 PCINT29 PCINT28 PCINT27 PCINT26 PCINT25 PCINT24 * Bit 7..0 - PCINT31..24 : Pin Change Enable Mask 31..24 Each PCINT31:24 bit selects whether the pin change interrupt is enabled on the corresponding I/O pin. If PCINT31:24 is set and the PCIE3 bit in PCICR is set, the pin change interrupt is enabled on the corresponding I/O pin. If PCINT31:24 is cleared, the pin change interrupt on the corresponding I/O pin is disabled. 11.1.8 PCMSK2 - Pin Change Mask Register 2 Bit 0x00006D Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PCMSK2 0x00 R/W 0 PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 * Bit 7..0 - PCINT23..16 : Pin Change Enable Mask 23..16 Each PCINT23:16-bit selects whether the pin change interrupt is enabled on the corresponding I/O pin. If PCINT23:16 is set and the PCIE2 bit in PCICR is set, the pin change interrupt is enabled on the corresponding I/O pin. If PCINT23:16 is cleared, the pin change interrupt on the corresponding I/O pin is disabled. 11.1.9 PCMSK1 - Pin Change Mask Register 1 Bit 0x00006C Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PCINT8 R/W 0 0x00 PCMSK1 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 * Bit 7..0 - PCINT15..8 : Pin Change Enable Mask 15..8 Each PCINT15:8-bit selects whether the pin change interrupt is enabled on the corresponding I/O pin. If PCINT15:8 is set and the PCIE1 bit in PCICR is set, the pin change interrupt is enabled on the corresponding I/O pin. If PCINT15:8 is cleared, the pin change interrupt on the corresponding I/O pin is disabled. 11.1.10 PCMSK0 - Pin Change Mask Register 0 Bit 0x00006B Read/write Initial value 7 PCINT7 R/W 0 6 PCINT6 R/W 0 5 PCINT5 R/W 0 4 PCINT4 R/W 0 3 PCINT3 R/W 0 2 PCINT2 R/W 0 1 PCINT1 R/W 0 0 PCINT0 R/W 0 0x00 PCMSK0 * Bit 7..0 - PCINT7..0: Pin Change Enable Mask 7..0 Each PCINT7:0 bit selects whether the pin change interrupt is enabled on the corresponding I/O pin. If PCINT7:0 is set and the PCIE0 bit in PCICR is set, the pin change interrupt is enabled on 73 TPR0327AY-SMS-30Jan09 the corresponding I/O pin. If PCINT7:0 is cleared, the pin change interrupt on the corresponding I/O pin is disabled. 74 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 12. I/O Ports 12.1 Standard IO Ports All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). Each output buffer has symmetrical drive characteristics with both high sink and source capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VCC and Ground as indicated in Figure 12-1. Refer to "Electrical Characteristics" on page 409 for a complete list of parameters. Figure 12-1. I/O Pin Equivalent Schematic R pu Pxn Logic C pin See Figure "General Digital I/O" for Details All registers and bit references in this section are written in general form. A lower case "x" represents the reference letter for the port, and a lower case "n" represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in "Register Description for I/O-Ports" on page 83. 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 77. Most port pins are multiplexed with alternate functions for the peripheral features on the device. To get a full description of the different pin configuration, refer to "Pin List Configuration" on page 5. 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. 75 TPR0327AY-SMS-30Jan09 12.2 Specific Low Speed Keyboard Output To avoid abusive EMC generation, AT90SCR100 embeds specific Low Speed Output Pads. Figure 12-2. Low-speed Output Schematic Weak KBOn N NMOS Port Latch Data N CTRL Power Management Control SMCR + CPU status The current limitation of the CTRL block requires a polarisation current of about 250A. This block is automatically disabled in power-down, power-save, standby and extended standby modes. These pads only concern KBOn pins located on port PE [0..7]. See "Pin List Configuration" on page 5. 12.3 LED AT90SCR100 supports specific ports driving current to allow easy control of LED displays. Figure 12-3. LED Source Current Pin NMOS N LEDn.0 LEDn.1 Port Latch Data N LEDCR 1. When switching a low level, LEDCR device has a permanent current of about N mA/15 (N is 2 or 4) Note 2. The port must be configured and driven as standard IO port. 76 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 12-1. 0 0 0 0 1 1 Notes: LED Configuration LEDx.0 0 0 1 1 0 0 Port Latch Data 0 1 0 1 0 1 NMOS 1 0 0 0 0 0 PIN 0 1 0 1 0 1 Comments LED control disabled(1) LEDx.1 LED mode 2 mA LED mode 4 mA 1. When LED control disabled, a current of ~8mA is provided on the port. 12.3.1 LEDCR - LED Control Register Bit $000075 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 R 0 0 LEDCR 0x00 R 0 LED3 [1..0] LED2 [1..0] LED1 [1..0] LED0 [1..0] * Bit 7..6, 5..4, 3..2, 1..0 - LEDn [1..0]: LED Port configuration bits Table 13-1 .LED Port Selection LEDn1 0 0 1 1 LEDn0 0 1 0 1 Description LED control disabled 2 mA Current Source 4 mA Current Source Reserved Configuration Note For implementation example, please see section "Typical Application" on page 400. 12.4 Ports as General Digital I/O The ports are bi-directional I/O ports with optional internal pull-ups. Figure 12-4 shows a functional description of one I/O-port pin, here generically called Pxn. 77 TPR0327AY-SMS-30Jan09 Figure 12-4. General Digital I/O PUD Q D DDxn Q CLR RESET WDx RDx 1 Pxn Q D PORTxn Q CLR 0 RESET WRx SLEEP RRx WPx SYNCHRONIZER D Q D Q RPx PINxn L Q Q clk I/O PUD: SLEEP: clk I/O : PULLUP DISABLE SLEEP CONTROL I/O CLOCK WDx: RDx: WRx: RRx: RPx: WPx: WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN WRITE PINx REGISTER Note WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, SLEEP, and PUD are common to all ports. 12.4.1 Configuring the Pin Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in "Register Description for I/O-Ports" on page 83, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address. The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin. If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the pin has to 78 AT90SCR100 TPR0327AY-SMS-30Jan09 DATA BUS AT90SCR100 be configured as an output pin. The port pins are tri-stated when reset condition becomes 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). 12.4.2 Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port. Switching Between Input and Output When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all pull-ups in all ports. Switching between input with pull-up and output low generates the same problem. The user must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn} = 0b11) as an intermediate step. Table 12-2 summarizes the control signals for the pin value. Table 12-2. DDxn 0 0 0 1 1 12.4.3 Port Pin Configurations PUD (in MCUCR) X 0 1 X X I/O Input Input Input Output Output Pull-up No Yes No No No Comment Tri-state (Hi-Z) Pxn will source current if ext. pulled low. Tri-state (Hi-Z) Output Low (Sink) Output High (Source) PORTxn 0 1 1 0 1 12.4.4 Reading the Pin Value Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As shown in Figure 12-4, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. Figure 12-5 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively. 79 TPR0327AY-SMS-30Jan09 Figure 12-5. Synchronization when Reading an Externally Applied Pin value SYSTEM CLK INSTRUCTIONS SYNC LATCH PINxn r17 0x00 t pd, max t pd, min 0xFF XXX XXX in r17, PINx 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 1/2 and 11/2 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 12-6. The out instruction sets the "SYNC LATCH" signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is 1 system clock period. Figure 12-6. Synchronization when Reading a Software Assigned Pin Value SYSTEM CLK r16 INSTRUCTIONS SYNC LATCH PINxn r17 0x00 t pd 0xFF out PORTx, r16 nop 0xFF in r17, PINx The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin 80 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. Assembly Code Example(1) ... ; Define pull-ups and set outputs high ; Define directions for port pins ldi ldi out out nop ; Read port pins in ... r16,PINB r16,(1< C Code Example(1) unsigned char i; ... /* Define pull-ups and set outputs high */ /* Define directions for port pins */ PORTB = (1< Digital Input Enable and Sleep Modes As shown in Figure 12-4, 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, Standby and Extended Stand-By mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2. SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled, SLEEP is active also for these pins. If a logic high level ("one") is present on an asynchronous external interrupt pin configured as "Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin" while the external interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned Sleep mode, as the clamping in these sleep mode produces the requested logic change. 81 TPR0327AY-SMS-30Jan09 12.4.6 Unconnected Pins If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. Connecting unused pins directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output. 12.4.7 MCUCR - MCU Control Register Bit 0x35 (0x55) Read/write Initial value 7 JTD R/W 0 6 R 0 5 R 0 4 PUD R/W 0 3 R 0 2 R 0 1 IVSEL R/W 0 0 IVCE R/W 0 0x00 MCUCR * Bit 4 - PUD: Pull-up Disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01). See "Configuring the Pin" on page 78 for more details about this feature. 82 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 12.5 12.5.1 Register Description for I/O-Ports PORTA - Port A Data Register Bit 0x02 (0x22) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PORTA R/W 0 0x00 PORTA [7..0] 12.5.2 DDRA - Port A Data Direction Register Bit 0x01 (0x21) Read/write Initial value R/W 0 R/W 0 R/W 0 0 7 6 5 4 R/W 3 DDA [7..0] R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 DDRA 12.5.3 PINA - Port A Input Pins Address Bit 0x00 (0x20) Read/write Initial value R/W N/A R/W N/A R/W N/A 7 6 5 4 R/W N/A 3 PINA [7..0] R/W N/A R/W N/A R/W N/A R/W N/A 2 1 0 PINA 12.5.4 PORTB - Port B Data Register Bit 0x05 (0x25) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PORTB R/W 0 0x00 PORTB [7..0] 12.5.5 DDRB - Port B Data Direction Register Bit 0x04 (0x24) Read/write Initial value R/W 0 R/W 0 R/W 0 0 7 6 5 4 R/W 3 DDB [7..0] R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 DDRB 12.5.6 PINB - Port B Input Pins Address Bit 0x03 (0x23) Read/write Initial value R/W N/A R/W N/A R/W N/A 7 6 5 4 R/W N/A 3 PINB [7..0] R/W N/A R/W N/A R/W N/A R/W N/A 2 1 0 PINB 83 TPR0327AY-SMS-30Jan09 12.5.7 PORTC - Port C Data Register Bit 0x08 (0x28) Read/write Initial value 7 R/W 0 6 R/W 0 R/W 0 R/W 0 5 4 3 R/W 0 2 R/W 0 1 R/W 0 0 PORTC R/W 0 0x00 PORTC [5..0] 12.5.8 DDRC - Port C Data Direction Register Bit 0x07 (0x27) Read/write Initial value 7 R/W 0 6 R/W 0 R/W 0 R/W 0 0 5 4 3 R/W 2 DDC [5..0] R/W 0 R/W 0 R/W 0 0x00 1 0 DDRC 12.5.9 PINC - Port C Input Pins Address Bit 0x06 (0x26) Read/write Initial value 7 R/W N/A 6 R/W N/A R/W N/A R/W N/A 5 4 3 R/W N/A 2 PINC [5..0] R/W N/A R/W N/A R/W N/A 1 0 PINC 12.5.10 PORTD - Port D Data Register Bit 0x0B (0x2B) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PORTD R/W 0 0x00 PORTD [7..0] 12.5.11 DDRD - Port D Data Direction Register Bit 0x0A (0x2A) Read/write Initial value R/W 0 R/W 0 R/W 0 0 7 6 5 4 R/W 3 DDD [7..0] R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 DDRD 12.5.12 PIND - Port D Input Pins Address Bit 0x09 (0x29) Read/write Initial value R/W N/A R/W N/A R/W N/A 7 6 5 4 R/W N/A 3 PIND [7..0] R/W N/A R/W N/A R/W N/A R/W N/A 2 1 0 PIND 12.5.13 PORTE - Port E Data Register Bit 0x0E (0x2E) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 PORTE R/W 0 0x00 PORTE [7..0] 84 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 12.5.14 DDRE - Port E Data Direction Register Bit 0x0D (0x2D) Read/write Initial value R/W 0 R/W 0 R/W 0 0 7 6 5 4 R/W 3 DDE [7..0] R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 DDRE 12.5.15 PINE - Port E Input Pins Address Bit 0x0C (0x2C) Read/write Initial value R/W N/A R/W N/A R/W N/A 7 6 5 4 R/W N/A 3 PINE [7..0] R/W N/A R/W N/A R/W N/A R/W N/A 2 1 0 PINE 85 TPR0327AY-SMS-30Jan09 86 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13. Timers This section contains the detailed description of all 3 timers embedded in the AT90SCR100. Finally, a global chapter describes the mechanism for prescaler reset used on all 3 registers. 13.1 8-bit Timer/Counter0 with PWM Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and with PWM support. It allows accurate program execution timing (event management) and wave generation. The main features are: * * * * * * * Two Independent Output Compare Units Double Buffered Output Compare Registers Clear Timer on Compare Match (Auto Reload) Glitch Free, Phase Correct Pulse Width Modulator (PWM) Variable PWM Period Frequency Generator Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B) 13.1.1 Overview A simplified block diagram of the 8-bit Timer/Counter0 is shown in Figure 13-1. For the actual placement of I/O pins, refer to "Pin List Configuration" on page 5. The device-specific I/O Register and bit locations are listed in the ""8-bit Timer/Counter0 Register Description" on page 98". 87 TPR0327AY-SMS-30Jan09 Figure 13-1. 8-bit Timer/Counter0 Block Diagram Count Clear Direction Control Logic TOVn (Int.Req.) clk T0 Clock Select Edge Detector TOP BOTTOM ( From Prescaler ) Timer/Counter TCNT0 T0 = =0 OC0A (Int.Req.) = OCR0A Fixed TOP Value Waveform Generation OC0A OC0B (Int.Req.) Waveform Generation OC0B DATA BUS = OCR0B TCCR0A TCCR0B 13.1.1.1 Registers The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure. The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkT0). The double buffered Output Compare Registers (OCR0A and OCR0B) are compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pins (OC0A and OC0B). See "Output Compare Unit" on page 90. for details. The Compare Match event will also set the Compare Flag (OCF0A or OCF0B) which can be used to generate an Output Compare interrupt request. 13.1.1.2 Definitions Many register and bit references in this section are written in general form. A A lower case "x" replaces the Output Compare Unit, in this case Compare Unit A or Compare Unit B. However, 88 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing Timer/Counter0 counter value and so on. The definitions in Table 13-1 are also used extensively throughout the document. Table 13-1. BOTTOM MAX Definitions The counter reaches the BOTTOM when it becomes 0x00. The counter reaches its MAXimum when it becomes 0xFF (decimal 255). The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0A Register. The assignment is dependent on the mode of operation. TOP 13.1.2 Timer/Counter Clock Sources The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS02:0) bits located in the Timer/Counter Control Register (TCCR0B). For details on clock sources and prescaler, see "Timer/Counter Prescaler" on page 154. Counter Unit The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 13-2 shows a block diagram of the counter and its surroundings. Figure 13-2. Counter Unit Block Diagram 13.1.3 DATA BUS TOV0 (Int.Req.) Clock Select count TCNT0 clear direction ( From Prescaler ) bottom top Control Logic clk Tn Edge Detector T0 Signal description (internal signals): count direction clear clkTn top bottom Increment or decrement TCNT0 by 1. Select between increment and decrement. Clear TCNT0 (set all bits to zero). Timer/Counter clock, referred to as clkT0 in the following. Signifies that TCNT0 has reached maximum value. Signifies that TCNT0 has reached minimum value (zero). Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0). clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of 89 TPR0327AY-SMS-30Jan09 whether clkT0 is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the Timer/Counter Control Register (TCCR0A) and the WGM02 bit located in the Timer/Counter Control Register B (TCCR0B). There are close connections between how the counter behaves (counts) and how waveforms are generated on the Output Compare outputs OC0A and OC0B. For more details about advanced counting sequences and waveform generation, see "Modes of Operation" on page 92. The Timer/Counter Overflow Flag (TOV0) is set according to the mode of operation selected by the WGM02:0 bits. TOV0 can be used for generating a CPU interrupt. 13.1.4 Output Compare Unit The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The TOP and BOTTOM signals are used by the Waveform Generator for handling the special cases that occur in some modes of operation when maximum and minimum values are reached ("Modes of Operation" on page 92). Figure 13-3 shows a block diagram of the Output Compare unit. Figure 13-3. Output Compare Unit, Block Diagram DATA BUS OCR0x TCNT0 = (8-bit Comparator ) OCF0x (Int.Req.) top bottom FOC0x Waveform Generator OC0x WGM02:0 COM0x1:0 The OCR0x Registers are double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the dou- 90 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 ble buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare Registers to either the top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. The OCR0x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is disabled the CPU will access the OCR0x directly. 13.1.4.1 Force 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 (FOC0x) bit. Forcing Compare Match will not set the OCF0x Flag or reload/clear the timer, but the OC0x pin will be updated as if a real Compare Match had occurred (the COM0x1:0 bits settings define whether the OC0x pin is set, cleared or toggled). Compare Match Blocking by TCNT0 Write All CPU write operations to the TCNT0 Register will block any Compare Match that occur in the next timer clock cycle, even when the timer is stopped. This feature allows OCR0x to be initialized to the same value as TCNT0 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT0 in any mode of operation will block all Compare Matches for one timer clock cycle, there are risks involved when changing TCNT0 when using the Output Compare Unit, independently of whether the Timer/Counter is running or not. If the value written to TCNT0 equals the OCR0x value, the Compare Match will be missed, resulting in incorrect waveform generation. Similarly, do not write the TCNT0 value equal to BOTTOM when the counter is down-counting. The setup of the OC0x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC0x value is to use the Force Output Compare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even when changing between Waveform Generation modes. Changing the COM0x1:0 bits will take effect immediately. 13.1.5 Compare Match Output Unit The Compare Output mode (COM0x1:0) bits have two functions. The Waveform Generator uses the COM0x1:0 bits for defining the Output Compare (OC0x) state at the next Compare Match. Also, the COM0x1:0 bits control the OC0x pin output source. Figure 13-4 shows a simplified schematic of the logic affected by the COM0x1:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by the COM0x1:0 bits are shown. When referring to the OC0x state, the reference is for the internal OC0x Register, not the OC0x pin. If a system reset occurs, the OC0x Register is reset to "0". 13.1.4.2 13.1.4.3 91 TPR0327AY-SMS-30Jan09 Figure 13-4. Compare Match Output Unit, Schematic COM0x1 COM0x0 FOC0n Waveform Generator D Q 1 OC0x Pin OC0x D Q 0 DATA BUS PORT D Q DDR clk I/O The general I/O port function is overridden by the Output Compare (OC0x) from the Waveform Generator if either of the COM0x1:0 bits are set. However, the OC0x pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register bit for the OC0x pin (DDR_OC0x) must be set as an output before the OC0x value is visible on the pin. The port override function is independent of the Waveform Generation mode. The design of the Output Compare pin logic allows the initialization of the OC0x state before the output is enabled. Note that some COM0x1:0 bit settings are reserved for certain modes of operation. See "8-bit Timer/Counter0 Register Description" on page 98. 13.1.6 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM0x1:0 bits differently in Normal, CTC, and PWM modes. For all modes, setting the COM0x1:0 = 0 instructs the Waveform Generator that no action on the OC0x Register is to be performed on the next Compare Match. For compare output actions in the non-PWM modes refer to Table 13-2 on page 99. For fast PWM mode, refer to Table 13-3 on page 99, and for phase correct PWM refer to Table 13-4 on page 99. A change of the COM0x1:0 bits state will have an effect at the first Compare Match after the bits are written. For non-PWM modes, the action can be forced to have an immediate effect by using the FOC0x strobe bits. 13.1.7 Modes 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 the Waveform Generation mode (WGM02:0) and the Compare Output mode (COM0x1:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM0x1:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted PWM). For nonPWM modes the COM0x1:0 bits control whether the output should be set, cleared, or toggled at a Compare Match (See "Compare Match Output Unit" on page 91.). For detailed timing information see "Timer/Counter Timing Diagrams" on page 97. 92 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.1.7.1 Normal Mode The simplest mode of operation is the Normal mode (WGM02:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare Unit can be used to generate interrupts at some given time. Using the Output Compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time. 13.1.7.2 Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM02:0 = 2), 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 13-5. The counter value (TCNT0) increases until a Compare Match occurs between TCNT0 and OCR0A, and then counter (TCNT0) is cleared. Figure 13-5. CTC Mode, Timing Diagram OC0x Interrupt Flag Set TCNT0 OC0x (Toggle) Period 1 2 3 4 (COM0x1:0 = 1) An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR0A is lower than the current value of TCNT0, the counter will miss the Compare Match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can occur. For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical level on each Compare Match by setting the Compare Output mode bits to toggle mode (COM0A1:0 = 1). The OC0A value will not be visible on the port pin unless the data direction for 93 TPR0327AY-SMS-30Jan09 the pin is set to output. The waveform generated will have a maximum frequency of f OC0 = fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following equation: f clk_I/O f OCnx = ------------------------------------------------2 N ( 1 + OCRnx ) The N variable represents the prescale factor (1, 8, 64, 256, or 1024). As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. 13.1.7.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM02:0 = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the Compare Match between TCNT0 and OCR0x, and set at BOTTOM. In inverting Compare Output mode, the output is set on Compare Match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 13-6. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0x and TCNT0. Figure 13-6. Fast PWM Mode, Timing Diagram OCR0x Interrupt Flag Set OCR0x Update and TOV0 Interrupt Flag Set TCNT0 OC0x OC0x (COM0x1:0 = 2) (COM0x1:0 = 3) Period 1 2 3 4 5 6 7 The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. 94 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A1:0 bits to one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (See Table 13-3 on page 99). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by setting (or clearing) the OC0x Register at the Compare Match between OCR0x and TCNT0, and clearing (or setting) the OC0x Register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ----------------N 256 The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0A Register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR0A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0A equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by the COM0A1:0 bits.) A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0x to toggle its logical level on each Compare Match (COM0x1:0 = 1). The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 13.1.7.4 Phase Correct PWM Mode The phase correct PWM mode (WGM02:0 = 1 or 5) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is based on a dual-slope operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM. TOP is defined as 0xFF when WGM2:0 = 1, and OCR0A when WGM2:0 = 5. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the Compare Match between TCNT0 and OCR0x while upcounting, and set on the Compare Match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. In phase correct PWM mode the counter is incremented until the counter value matches TOP. When the counter reaches TOP, it changes the count direction. The TCNT0 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 13-7. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0x and TCNT0. 95 TPR0327AY-SMS-30Jan09 Figure 13-7. Phase Correct PWM Mode, Timing Diagram OC0x Interrupt Flag Set OCR0x Update TOV0 Interrupt Flag Set TCNT0 OC0x OC0x (COM0x1:0 = 2) (COM0x1:0 = 3) Period 1 2 3 The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A0 bits to one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (See Table 13-4 on page 99). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC0x Register at the Compare Match between OCR0x and TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at Compare Match between OCR0x and TCNT0 when the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnxPCPWM = ----------------N 510 The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0A Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR0A is set equal to BOTTOM, the output will be continuously low and if set equal to MAX the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. At the very start of period 2 in Figure 13-7 OC0x has a transition from high to low even though there is no Compare Match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a transition without Compare Match. * OCR0A changes its value from MAX, like in Figure 13-7. When the OCR0A value is MAX the OC0 pin value is the same as the result of a down-counting Compare Match. To ensure 96 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 symmetry around BOTTOM the OC0 value at MAX must correspond to the result of an upcounting Compare Match. * The timer starts counting from a value higher than the one in OCR0A, and for that reason misses the Compare Match and hence the OC0 change that would have happened on the way up. 13.1.8 Timer/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. The figures include information on when Interrupt Flags are set. Figure 13-8 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value in all modes other than phase correct PWM mode. Figure 13-8. Timer/Counter Timing Diagram, no Prescaling clk I/O clk Tn (clk I/O /1) TCNT0 MAX - 1 MAX BOTTOM BOTTOM + 1 TOV0 Figure 13-9 shows the same timing data, but with the prescaler enabled. Figure 13-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT0 MAX - 1 MAX BOTTOM BOTTOM + 1 TOV0 Figure 13-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC mode and PWM mode, where OCR0A is TOP. 97 TPR0327AY-SMS-30Jan09 Figure 13-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT0 OCR0x - 1 OCR0x OCR0x + 1 OCR0x + 2 OCR0x OCR0x Value OCF0x Figure 13-11 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode and fast PWM mode where OCR0A is TOP. Figure 13-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT0 (CTC) OCR0x TOP - 1 TOP BOTTOM BOTTOM + 1 TOP OCF0x 13.1.9 13.1.9.1 8-bit Timer/Counter0 Register Description TCCR0A - Timer/Counter Control Register A Bit 0x24 (0x44) Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R 0 2 R 0 1 WGM01 R/W 0 0 WGM00 R/W 0 0x00 TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 * Bits 7..6 - COM0A1..0: Compare Match Output A Mode These bits control the Output Compare pin (OC0A) behavior. If one or both of the COM0A1:0 bits are set, the OC0A output overrides the normal port functionality of the I/O pin it is connected. However, note that the Data Direction Register (DDR) bit corresponding to which the OC0A pin must be set in order to enable the output driver. 98 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 When OC0A is connected to the pin, the function of the COM0A1:0 bits depends on the WGM02:0 bit setting. Table 13-2 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to a normal or CTC mode (non-PWM). Table 13-2. COM0A1 0 0 1 1 Compare Output Mode, non-PWM Mode COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. Toggle OC0A on Compare Match Clear OC0A on Compare Match Set OC0A on Compare Match Table 13-3 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM mode. Table 13-3. COM0A1 0 0 1 1 Note: Compare Output Mode, Fast PWM Mode(1) COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. Clear OC0A on Compare Match, set OC0A at BOTTOM (non-inverting mode) Set OC0A on Compare Match, clear OC0A at BOTTOM (inverting mode) 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at BOTTOM. See "Fast PWM Mode" on page 94 for more details. Table 13-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode. Table 13-4. COM0A1 0 0 1 1 Note: Compare Output Mode, Phase Correct PWM Mode(1) COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. Clear OC0A on Compare Match when up-counting. Set OC0A on Compare Match when down-counting. Set OC0A on Compare Match when up-counting. Clear OC0A on Compare Match when down-counting. 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 95 for more details. * Bits 5..4 - COM0B1..0: Compare Match Output B Mode These bits control the Output Compare pin (OC0B) behavior. If one or both of the COM0B1:0 bits are set, the OC0B output overrides the normal port functionality of the I/O pin to which it is 99 TPR0327AY-SMS-30Jan09 connected. However, note that the Data Direction Register (DDR) bit corresponding to the OC0B pin must be set in order to enable the output driver. When OC0B is connected to the pin, the function of the COM0B1:0 bits depends on the WGM02:0 bit setting. Table 13-5 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to a normal or CTC mode (non-PWM). Table 13-5. COM0B1 0 0 1 1 Compare Output Mode, non-PWM Mode COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Toggle OC0B on Compare Match Clear OC0B on Compare Match Set OC0B on Compare Match Table 13-6 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM mode. Table 13-6. COM0B1 0 0 1 1 Note: Compare Output Mode, Fast PWM Mode(1) COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match, set OC0B at BOTTOM (non-inverting mode) Set OC0B on Compare Match, clear OC0B at BOTTOM (inverting mode) 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at BOTTOM. See "Fast PWM Mode" on page 94 for more details. Table 13-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode. Table 13-7. COM0B1 0 0 1 1 Note: Compare Output Mode, Phase Correct PWM Mode(1) COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match when up-counting. Set OC0B on Compare Match when down-counting. Set OC0B on Compare Match when up-counting. Clear OC0B on Compare Match when down-counting. 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 95 for more details. * Bits 3..2 - Res: Reserved Bits These bits are reserved bits in the AT90SCR100 and will always read as zero. 100 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bits 1..0 - WGM01..0: Waveform Generation Mode When combined with the WGM02 bit found in the TCCR0B Register, these bits control the counting sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used, see Table 13-8. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes (see "Modes of Operation" on page 92). Table 13-8. Waveform Generation Mode Bit Description Timer/Counter Mode of Operation Normal PWM, Phase Correct CTC Fast PWM Reserved PWM, Phase Correct Reserved Fast PWM Update of OCRx at Immediate TOP Immediate TOP - TOP - TOP TOV Flag Set on(1) MAX BOTTOM MAX MAX - BOTTOM - TOP Mode 0 1 2 3 4 5 6 7 Note: WGM2 0 0 0 0 1 1 1 1 WGM1 0 0 1 1 0 0 1 1 WGM0 0 1 0 1 0 1 0 1 TOP 0xFF 0xFF OCRA 0xFF - OCRA - OCRA 1. MAX = 0xFF, BOTTOM = 0x00 13.1.9.2 TCCR0B - Timer/Counter Control Register B Bit 0x25 (0x45) Read/write Initial value 7 FOC0A W 0 6 FOC0B W 0 5 R 0 4 R 0 3 WGM02 R/W 0 2 CS02 R/W 0 1 CS01 R/W 0 0 CSO0 R/W 0 0x00 TCCR0B * Bit 7 - FOC0A: Force Output Compare A The FOC0A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0A bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC0A output is changed according to its COM0A1:0 bits setting. Note that the FOC0A bit is implemented as a strobe. Therefore it is the value present in the COM0A1:0 bits that determines the effect of the forced compare. A FOC0A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0A as TOP. The FOC0A bit is always read as zero. * Bit 6 - FOC0B: Force Output Compare B The FOC0B bit is only active when the WGM bits specify a non-PWM mode. 101 TPR0327AY-SMS-30Jan09 However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0B bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC0B output is changed according to its COM0B1:0 bits setting. Note that the FOC0B bit is implemented as a strobe. Therefore it is the value present in the COM0B1:0 bits that determines the effect of the forced compare. A FOC0B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0B as TOP. The FOC0B bit is always read as zero. * Bits 5..4 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 3 - WGM02: Waveform Generation Mode See the description in the "TCCR0A - Timer/Counter Control Register A" on page 98. * Bits 2..0 - CS02..0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter. Table 13-9. CS02 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 Clock Select Bit Description CS00 0 1 0 1 0 1 0 1 Description No clock source (Timer/Counter stopped) clkI/O/(No prescaling) clkI/O/8 (From prescaler) clkI/O/64 (From prescaler) clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler) External clock source on T0 pin. Clock on falling edge. External clock source on T0 pin. Clock on rising edge. CS01 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. 13.1.9.3 TCNT0 - Timer/Counter Register Bit 0x26 (0x46) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 TCNT0 R/W 0 0x00 TCNT0 [7..0] The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running, introduces a risk of missing a Compare Match between TCNT0 and the OCR0x Registers. 102 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.1.9.4 OCR0A - Output Compare Register A Bit 0x27 (0x47) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR0A R/W 0 0x00 OCR0A [7..0] The Output Compare Register A contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC0A pin. 13.1.9.5 OCR0B - Output Compare Register B Bit 0x26 (0x46) Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR0B R/W 0 0x00 OCR0B [7..0] The Output Compare Register B contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC0B pin. 13.1.9.6 TIMSK0 - Timer/Counter Interrupt Mask Register Bit 0x6E Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 OCIE0B R/W 0 1 OCIE0A R/W 0 0 TOIE0 R/W 0 0x00 TIMSK0 * Bits 7..3 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 2 - 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 corresponding interrupt is executed 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 - 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 Match A interrupt is enabled. The corresponding interrupt is executed 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 0 - 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 TOV0 bit is set in the Timer/Counter 0 Interrupt Flag Register - TIFR0. 103 TPR0327AY-SMS-30Jan09 13.1.9.7 TIFR0 - Timer/Counter 0 Interrupt Flag Register Bit 0x15 (0x35) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 OCF0B R/W 0 1 OCF0A R/W 0 0 TOV0 R/W 0 0x00 TIFR0 * Bits 7..3 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and will always read as zero. * Bit 2 - OCF0B: Timer/Counter 0 Output Compare B Match Flag The OCF0B bit is set when a Compare Match occurs between the Timer/Counter and the data in OCR0B - Output Compare Register0 B. OCF0B is cleared by hardware 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. * Bit 1 - OCF0A: Timer/Counter 0 Output Compare A Match Flag The OCF0A bit is set when a Compare Match occurs between the Timer/Counter0 and the data in OCR0A - Output Compare Register0. OCF0A is cleared by hardware when executing the corresponding 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. * Bit 0 - 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. The setting of this flag is dependent of the WGM02:0 bit setting. Refer to Table 13-8, "Waveform Generation Mode Bit Description" on page 101. 104 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.2 16-bit Timer/Counter1 with PWM The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are: * * * * * * * * * * * 13.2.1 Overview A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 13-12. For the actual placement of I/O pins, refer to "Pin List Configuration" on page 5. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in the "16-bit Timer/Counter Register Description" on page 126. The PRTIM1 bit in "PRR0 - Power Reduction Register 0" on page 45 must be written to zero to enable Timer/Counter1 module. Refer to "Pin List Configuration" on page 5 for Timer/Counter1 pin placement and description. True 16-bit Design (i.e., Allows 16-bit PWM) Two independent Output Compare Units Double Buffered Output Compare Registers One Input Capture Unit Input Capture Noise Canceler Clear Timer on Compare Match (Auto Reload) Glitch-free, Phase Correct Pulse Width Modulator (PWM) Variable PWM Period Frequency Generator External Event Counter Four independent interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1) 105 TPR0327AY-SMS-30Jan09 Figure 13-12. 16-bit Timer/Counter Block Diagram Count Clear Direction Control Logic TOV1 (Int.Req.) clk Tn Clock Select Edge Detector TOP BOTTOM ( From Prescaler ) Timer/Counter TCNT1 T1 = =0 OC1A (Int.Req.) = OCR1A Fixed TOP Values Waveform Generation OC1A OC1B (Int.Req.) Waveform Generation OC1B DATA BUS = OCR1B ICF1 (Int.Req.) Edge Detector ICR1 Noise Canceler ICP1 TCCR1A TCCR1B 13.2.1.1 Registers The Timer/Counter1 (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Register (ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16bit registers. These procedures are described in the section "Accessing 16-bit Registers" on page 107. The Timer/Counter Control Registers (TCCR1A/B/C) are 8-bit registers and have no CPU access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR1). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK1). TIFR1 and TIMSK1 are not shown in the figure. The Timer/Counter1 can be clocked internally, via the prescaler, or by an external clock source on the T1 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter1 is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkTn). The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Counter value at all time. The result of the compare can be used by the Waveform Generator to 106 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 generate a PWM or variable frequency output on the Output Compare pin (OCR1A/B). See "Output Compare Units" on page 114. The compare match event will also set the Compare Match Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request. The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered) event on either the Input Capture pin (ICP1). The Input Capture unit includes a digital filtering unit (Noise Canceler) for reducing the chance of capturing noise spikes. The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined by either the OCR1A Register, the ICR1 Register, or by a set of fixed values. When using OCR1A as TOP value in a PWM mode, the OCR1A Register can not be used for generating a PWM output. However, the TOP value will in this case be double buffered allowing the TOP value to be changed in run time. If a fixed TOP value is required, the ICR1 Register can be used as an alternative, freeing the OCR1A to be used as PWM output. 13.2.1.2 Definitions Most register and bit references in this section are written in general form. A lower case "x" replaces the Output Compare unit channel. The following definitions are used extensively throughout the section: Table 13-10. Definitions BOTTOM MAX The counter reaches the BOTTOM when it becomes 0x0000. The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535). The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be one of the fixed values: 0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCR1A or ICR1 Register. The assignment is dependent of the mode of operation. TOP 13.2.2 Accessing 16-bit Registers The TCNT1, OCR1A/B, and ICR1 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. Each 16-bit timer has a single 8-bit register for temporary storage of the high byte of the 16-bit access. The same temporary register is shared between all 16-bit registers within each 16-bit timer. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a 16-bit register is written by the CPU, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. Not all 16-bit accesses uses the temporary register for the high byte. Reading the OCR1A/B 16bit registers does not involve using 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. The following code examples show how to access the 16-bit Timer Registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCR1A/B and ICR1 Registers. Note that when using "C", the compiler handles the 16-bit access. 107 TPR0327AY-SMS-30Jan09 Assembly Code Examples(1) ... ; Set TCNT1 to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNT1H,r17 out TCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ... C Code Examples(1) unsigned int i; ... /* Set TCNT1 to 0x01FF */ TCNT1 = 0x1FF; /* Read TCNT1 into i */ i = TCNT1; ... Note: 1. The example code assumes that the part specific header file is included. For I/O Registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI" instructions must be replaced with instructions that allow access to extended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR". The assembly code example returns the TCNT1 value in the r17:r16 register pair. It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit Timer Registers, then the result of the access outside the interrupt will be corrupted. Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. The following code examples show how to do an atomic read of the TCNT1 Register contents. Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle 108 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 . Assembly Code Example(1) TIM16_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 ret C Code Example(1) unsigned int TIM16_ReadTCNT1( void ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNT1 into i */ i = TCNT1; /* Restore global interrupt flag */ SREG = sreg; return i; } Note: 1. The example code assumes that the part specific header file is included. For I/O Registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI" instructions must be replaced with instructions that allow access to extended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR". The assembly code example returns the TCNT1 value in the r17:r16 register pair. 109 TPR0327AY-SMS-30Jan09 The following code examples show how to do an atomic write of the TCNT1 Register contents. Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Assembly Code Example(1) TIM16_WriteTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Set TCNT1 to r17:r16 out TCNT1H,r17 out TCNT1L,r16 ; Restore global interrupt flag out SREG,r18 ret C Code Example(1) void TIM16_WriteTCNT1( unsigned int i ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNT1 to i */ TCNT1 = i; /* Restore global interrupt flag */ SREG = sreg; } Note: 1. The example code assumes that the part specific header file is included. For I/O Registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI" instructions must be replaced with instructions that allow access to extended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR". The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNT1. 13.2.2.1 Reusing the Temporary High Byte Register If writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. However, note that the same rule of atomic operation described previously also applies in this case. Timer/Counter Clock Sources The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS12:0) bits located in the Timer/Counter control Register B (TCCR1B). For details on clock sources and prescaler, see "Timer/Counter Prescaler" on page 154. 13.2.3 110 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.2.4 Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 13-13 shows a block diagram of the counter and its surroundings. Figure 13-13. Counter Unit Block Diagram DATA BUS (8-bit) TOV1 (Int.Req.) TEMP (8-bit) Clock Select Count TCNT1H (8-bit) TCNT1L (8-bit) Clear Direction Control Logic clk Tn Edge Detector T1 TCNT1 (16-bit Counter) ( From Prescaler ) TOP BOTTOM Signal description (internal signals): Count Direction Clear clkTn TOP BOTTOM Increment or decrement TCNT1 by 1. Select between increment and decrement. Clear TCNT1 (set all bits to zero). Timer/Counter clock. Signifies that TCNT1 has reached maximum value. Signifies that TCNT1 has reached minimum value (zero). The 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNT1H) containing the upper eight bits of the counter, and Counter Low (TCNT1L) containing the lower eight bits. The TCNT1H Register can only be indirectly accessed by the CPU. When the CPU does an access to the TCNT1H I/O location, the CPU accesses the high byte temporary register (TEMP). The temporary register is updated with the TCNT1H value when the TCNT1L is read, and TCNT1H is updated with the temporary register value when TCNT1L is written. This allows the CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. It is important to notice that there are special cases of writing to the TCNT1 Register when the counter is counting that will give unpredictable results. The special cases are described in the sections where they are of importance. Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkTn). The clkTn can be generated from an external or internal clock source, selected by the Clock Select bits (CS12:0). When no clock source is selected (CS12:0 = 0) the timer is stopped. However, the TCNT1 value can be accessed by the CPU, independent of whether clk Tn is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The counting sequence is determined by the setting of the Waveform Generation mode bits (WGM13:0) located in the Timer/Counter Control Registers A and B (TCCR1A and TCCR1B). There are close connections between how the counter behaves (counts) and how waveforms are generated on the Output Compare outputs OC1x. For more details about advanced counting sequences and waveform generation, see "Modes of Operation" on page 117. 111 TPR0327AY-SMS-30Jan09 The Timer/Counter Overflow Flag (TOV1) is set according to the mode of operation selected by the WGM13:0 bits. TOV1 can be used for generating a CPU interrupt. 13.2.5 Input Capture Unit The Timer/Counter incorporates an Input Capture unit that can capture external events and give them a time-stamp indicating the time of occurrence. The external signal indicating an event, or multiple events, can be applied via the ICP1 pin. 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 13-14. The elements of the block diagram that are not directly a part of the Input Capture unit are gray shaded. Figure 13-14. Input Capture Unit Block Diagram DATA BUS (8-bit) TEMP (8-bit) ICR1H (8-bit) WRITE ICR1L (8-bit) TCNT1H (8-bit) TCNT1L (8-bit) ICR1 (16-bit Register) TCNT1 (16-bit Counter) ICNC ICES ICP1 Noise Canceler Edge Detector ICF1 (Int.Req.) When a change of the logic level (an event) occurs on the Input Capture pin (ICP1) and this change conforms to the setting of the edge detector, a capture will be triggered. When a capture is triggered, the 16-bit value of the counter (TCNT1) is written to the Input Capture Register (ICR1). The Input Capture Flag (ICF1) is set at the same system clock as the TCNT1 value is copied into ICR1 Register. If enabled (ICIE1 = 1), the Input Capture Flag generates an Input Capture interrupt. The ICF1 Flag is automatically cleared when the interrupt is executed. Alternatively the ICF1 Flag can be cleared by software by writing a logical one to its I/O bit location. Reading the 16-bit value in the Input Capture Register (ICR1) is done by first reading the low byte (ICR1L) and then the high byte (ICR1H). When the low byte is read the high byte is copied into the high byte temporary register (TEMP). When the CPU reads the ICR1H I/O location it will access the TEMP Register. The ICR1 Register can only be written when using a Waveform Generation mode that utilizes the ICR1 Register for defining the counter's TOP value. In these cases the Waveform Generation mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1 112 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Register. When writing the ICR1 Register the high byte must be written to the ICR1H I/O location before the low byte is written to ICR1L. For more information on how to access the 16-bit registers refer to "Accessing 16-bit Registers" on page 107. 13.2.5.1 Input Capture Trigger Source The main trigger source for the Input Capture unit is the Input Capture pin (ICP1). The Input Capture pin (ICP1) is sampled using the same technique as for the Tn pin (Figure 1312 on page 106). The edge detector is also identical. However, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. The input of the noise canceler and edge detector is always enabled unless the Timer/Counter is set in a Waveform Generation mode that uses ICR1 to define TOP. Note An Input Capture can be triggered by software by controlling the port of the ICP1 pin. 13.2.5.2 Noise Canceler The noise canceler improves noise immunity by using a simple digital filtering scheme. The noise canceler input is monitored over four samples, and all four must be equal to change the output that in turn is used by the edge detector. The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNCn) bit in Timer/Counter Control Register B (TCCR1B). When enabled the noise canceler introduces additional four system clock cycles of delay from a change applied to the input, to the update of the ICR1 Register. The noise canceler uses the system clock and is therefore not affected by the prescaler. 13.2.5.3 Using the Input Capture Unit The main challenge when using the Input Capture unit is to assign enough processor capacity for handling the incoming events. The time between two events is critical. If the processor has not read the captured value in the ICR1 Register before the next event occurs, the ICR1 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 ICR1 Register should be read as early in the interrupt handler routine as possible. Even though the Input Capture interrupt has relatively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. Using the Input Capture unit in any mode of operation when the TOP value (resolution) is actively changed during operation, is not recommended. Measurement of an external signal's duty cycle requires that the trigger edge is changed after each capture. Changing the edge sensing must be done as early as possible after the ICR1 Register has been read. After a change of the edge, the Input Capture Flag (ICF1) must be cleared by software (writing a logical one to the I/O bit location). For measuring frequency only, the clearing of the ICF1 Flag is not required (if an interrupt handler is used). 113 TPR0327AY-SMS-30Jan09 13.2.6 Output Compare Units The 16-bit comparator continuously compares TCNT1 with the Output Compare Register (OCR1x). If TCNT equals OCR1x the comparator signals a match. A match will set the Output Compare Flag (OCF1x) at the next timer clock cycle. If enabled (OCIE1x = 1), the Output Compare Flag generates an Output Compare interrupt. The OCF1x Flag is automatically cleared when the interrupt is executed. Alternatively the OCF1x 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 the Waveform Generation mode (WGM13:0) bits and Compare Output mode (COM1x1:0) bits. The TOP and BOTTOM signals are used by the Waveform Generator for handling the special cases that occur in some modes of operation when maximum and minimum values are reached (See "Modes of Operation" on page 117.) A special feature of Output Compare unit A allows it to define the Timer/Counter TOP value (i.e., counter resolution). In addition to the counter resolution, the TOP value defines the period time for waveforms generated by the Waveform Generator. Figure 13-15 shows a block diagram of the Output Compare unit. The "x" indicates Output Compare unit (A/B/C). The elements of the block diagram that are not directly a part of the Output Compare unit are gray shaded. Figure 13-15. Output Compare Unit, Block Diagram DATA BUS (8-bit) TEMP (8-bit) OCR1xH Buf. (8-bit) OCR1x OCR1xL Buf. (8-bit) TCNT1H (8-bit) TCNT1L (8-bit) Buffer (16-bit Register) TCNT1 (16-bit Counter) OCR1xH (8-bit) OCR1xL (8-bit) OCR1x (16-bit Register) = (16-bit Comparator ) OCF1x (Int.Req.) TOP BOTTOM Waveform Generator OC1x WGM13:0 COM1x1:0 The OCR1x Register is double buffered when using any of the twelve Pulse Width Modulation (PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double buffering synchronizes the update of the OCR1x Compare Register to either TOP or BOTTOM of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. 114 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The OCR1x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR1x Buffer Register, and if double buffering is disabled the CPU will access the OCR1x directly. The content of the OCR1x (Buffer or Compare) Register is only changed by a write operation (the Timer/Counter does not update this register automatically as the TCNT1 and ICR1 Register). Therefore OCR1x is not read via the high byte temporary register (TEMP). However, it is a good practice to read the low byte first as when accessing other 16-bit registers. Writing the OCR1x Registers must be done via the TEMP Register since the compare of all 16 bits is done continuously. The high byte (OCR1xH) has to be written first. When the high byte I/O location is written by the CPU, the TEMP Register will be updated by the value written. Then when the low byte (OCR1xL) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the OCR1x buffer or OCR1x Compare Register in the same system clock cycle. For more information of how to access the 16-bit registers refer to "Accessing 16-bit Registers" on page 107. 13.2.6.1 Force 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 OC1x pin will be updated as if a real compare match had occurred (the COM11:0 bits settings define whether the OC1x pin is set, cleared or toggled). Compare Match Blocking by TCNT1 Write All CPU writes to the TCNT1 Register will block any compare match that occurs 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 interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT1 when using any of the Output Compare channels, independent of whether the Timer/Counter is running or not. If the value written to TCNT1 equals the OCR1x value, the compare match will be missed, resulting in incorrect waveform generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP values. The compare match for the TOP will be ignored and the counter will continue to 0xFFFF. Similarly, do not write the TCNT1 value equal to BOTTOM when the counter is downcounting. The setup of the OC1x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC1x value is to use the Force Output Compare (FOC1x) strobe bits in Normal mode. The OC1x Register keeps its value even when changing between Waveform Generation modes. Changing the COM1x1:0 bits will take effect immediately. 13.2.6.2 13.2.6.3 115 TPR0327AY-SMS-30Jan09 13.2.7 Compare Match Output Unit The Compare Output mode (COM1x1:0) bits have two functions. The Waveform Generator uses the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next compare match. Secondly the COM1x1:0 bits control the OC1x pin output source. Figure 13-16 shows a simplified schematic of the logic affected by the COM1x1:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by the COM1x1:0 bits are shown. When referring to the OC1x state, the reference is for the internal OC1x Register, not the OC1x pin. If a system reset occur, the OC1x Register is reset to "0". Figure 13-16. Compare Match Output Unit, Schematic COM1x1 COM1x0 FOC1x Waveform Generator D Q 1 OC1x Pin OC1x D Q 0 DATA BUS PORT D Q DDR clk I/O The general I/O port function is overridden by the Output Compare (OC1x) from the Waveform Generator if either of the COM1x1:0 bits are set. However, the OC1x pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register bit for the OC1x pin (DDR_OC1x) must be set as output before the OC1x value is visible on the pin. The port override function is generally independent of the Waveform Generation mode, but there are some exceptions. Refer to Table 13-11, Table 13-12 and Table 13-13 for details. The design of the Output Compare pin logic allows initialization of the OC1x state before the output is enabled. Note that some COM1x1:0 bit settings are reserved for certain modes of operation. See "16-bit Timer/Counter Register Description" on page 126. The COM1x1:0 bits have no effect on the Input Capture unit. 116 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.2.7.1 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM1x1:0 = 0 tells the Waveform Generator that no action on the OC1x Register is to be performed on the next compare match. For compare output actions in the non-PWM modes refer to Table 13-11 on page 126. For fast PWM mode refer to Table 13-12 on page 127, and for phase correct and phase and frequency correct PWM refer to Table 13-13 on page 127. A change of the COM1x1:0 bits state will have effect at the first compare match after the bits are written. For non-PWM modes, the action can be forced to have immediate effect by using the FOC1x strobe bits. 13.2.8 Modes 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 the Waveform Generation mode (WGM13:0) and Compare Output mode (COM1x1:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM1x1:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes the COM1x1:0 bits control whether the output should be set, cleared or toggle at a compare match (See "Compare Match Output Unit" on page 116.) For detailed timing information refer to "Timer/Counter Timing Diagrams" on page 124. 13.2.8.1 Normal Mode The simplest mode of operation is the Normal mode (WGM13:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOV1) will be set in the same timer clock cycle as the TCNT1 becomes zero. The TOV1 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 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 Input Capture unit is easy to use in Normal mode. However, observe that the maximum interval between the external events must not exceed the resolution of the counter. If the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. The Output Compare units can be used to generate interrupts at some given time. Using the Output Compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time. 13.2.8.2 Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register are used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT1) matches either the OCR1A (WGM13:0 = 4) or the ICR1 (WGM13:0 = 12). The OCR1A or ICR1 define 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. 117 TPR0327AY-SMS-30Jan09 The timing diagram for the CTC mode is shown in Figure 13-17. The counter value (TCNT1) increases until a compare match occurs with either OCR1A or ICR1, and then counter (TCNT1) is cleared. Figure 13-17. CTC Mode, Timing Diagram OC1A Interrupt Flag Set or ICF1 Interrupt Flag Set (Interrupt on TOP) TCNT1 OC1A (Toggle) Period 1 2 3 4 (COM1A1:0 = 1) An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag according to the register used to define the TOP value. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing the TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR1A or ICR1 is lower than the current value of TCNT1, the counter will miss the compare match. The counter will then have to count to its maximum value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur. In many cases this feature is not desirable. An alternative will then be to use the fast PWM mode using OCR1A for defining TOP (WGM13:0 = 15) since the OCR1A then will be double buffered. For generating a waveform output in CTC mode, the OC1A output can be set to toggle its logical level on each compare match by setting the Compare Output mode bits to toggle mode (COM1A1:0 = 1). The OC1A value will not be visible on the port pin unless the data direction for the pin is set to output (DDR_OC1A = 1). The waveform generated will have a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). The waveform frequency is defined by the following equation: f clk_I/O f OCnA = -------------------------------------------------2 N ( 1 + OCRnA ) The N variable represents the prescaler factor (1, 8, 64, 256, or 1024). As for the Normal mode of operation, the TOV1 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x0000. 13.2.8.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM13:0 = 5, 6, 7, 14, or 15) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x, and set at BOTTOM. In inverting Compare Output mode output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase cor- 118 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 rect and phase and frequency correct PWM modes that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), hence reduces total system cost. The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated by using the following equation: log ( TOP + 1 ) R FPWM = ---------------------------------log ( 2 ) In fast PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 = 14), or the value in OCR1A (WGM13:0 = 15). The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 13-18. The figure shows fast PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a compare match occurs. Figure 13-18. Fast PWM Mode, Timing Diagram OCR1x/TOP Update and TOV1 Interrupt Flag Set and OC1A Interrupt Flag Set or ICF1 Interrupt Flag Set (Interrupt on TOP) TCNT1 OC1x OC1x (COM1x1:0 = 2) (COM1x1:0 = 3) Period 1 2 3 4 5 6 7 8 The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches TOP. In addition the OC1A or ICF1 Flag is set at the same timer clock cycle as TOV1 is set when either OCR1A or ICR1 is used for defining the TOP value. If one of the interrupts are enabled, the interrupt handler routine can be used for updating the TOP and compare values. When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x. Note that when using fixed TOP values the unused bits are masked to zero when any of the OCR1x Registers are written. The procedure for updating ICR1 differs from updating OCR1A when used for defining the TOP value. The ICR1 Register is not double buffered. This means that if ICR1 is changed to a low 119 TPR0327AY-SMS-30Jan09 value when the counter is running with none or a low prescaler value, there is a risk that the new ICR1 value written is lower than the current value of TCNT1. The result will then be that the counter will miss the compare match at the TOP value. The counter will then have to count to the MAX value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur. The OCR1A Register however, is double buffered. This feature allows the OCR1A I/O location to be written anytime. When the OCR1A I/O location is written the value written will be put into the OCR1A Buffer Register. The OCR1A Compare Register will then be updated with the value in the Buffer Register at the next timer clock cycle the TCNT1 matches TOP. The update is done at the same timer clock cycle as the TCNT1 is cleared and the TOV1 Flag is set. Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively changed (by changing the TOP value), using the OCR1A as TOP is clearly a better choice due to its double buffer feature. In fast PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins. Setting the COM1x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM1x1:0 to three (see Table on page 127). The actual OC1x value will only be visible on the port pin if the data direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at the compare match between OCR1x and TCNT1, and clearing (or setting) the OC1x Register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ---------------------------------N ( 1 + TOP ) The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x Register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the output will be a narrow spike for each TOP+1 timer clock cycle. Setting the OCR1x equal to TOP will result in a constant high or low output (depending on the polarity of the output set by the COM1x1:0 bits.) A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC1A to toggle its logical level on each compare match (COM1A1:0 = 1). This applies only if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). This feature is similar to the OC1A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 13.2.8.4 Phase Correct PWM Mode The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is, like the phase and frequency correct PWM mode, based on a dualslope operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x while upcounting, and set on the compare match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope 120 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. The PWM resolution for the phase correct PWM mode can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated by using the following equation: log ( TOP + 1 ) R PCPWM = ---------------------------------log ( 2 ) In phase correct PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1 (WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11). The counter has then reached the TOP and changes the count direction. The TCNT1 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 13-19. The figure shows phase correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a compare match occurs. Figure 13-19. Phase Correct PWM Mode, Timing Diagram OCR1x/TOP Update and OC1A Interrupt Flag Set or ICF1 Interrupt Flag Set (Interrupt on TOP) TOV1 Interrupt Flag Set (Interrupt on Bottom) TCNT1 OC1x OC1x (COM1x1:0 = 2) (COM1x1:0 = 3) Period 1 2 3 4 The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is set accordingly at the same timer clock cycle as the OCR1x Registers are updated with the double buffer value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the counter reaches the TOP or BOTTOM value. When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x. Note that when using fixed TOP values, the unused bits are masked to zero when any of the 121 TPR0327AY-SMS-30Jan09 OCR1x Registers are written. As the third period shown in Figure 13-19 illustrates, changing the TOP actively while the Timer/Counter is running in the phase correct mode can result in an unsymmetrical output. The reason for this can be found in the time of update of the OCR1x Register. Since the OCR1x update occurs at TOP, the PWM period starts and ends at TOP. This implies that the length of the falling slope is determined by the previous TOP value, while the length of the rising slope is determined by the new TOP value. When these two values differ the two slopes of the period will differ in length. The difference in length gives the unsymmetrical result on the output. It is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the TOP value while the Timer/Counter is running. When using a static TOP value there are practically no differences between the two modes of operation. In phase correct PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins. Setting the COM1x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM1x1:0 to three (See Table on page 127). The actual OC1x value will only be visible on the port pin if the data direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at the compare match between OCR1x and TCNT1 when the counter increments, and clearing (or setting) the OC1x Register at compare match between OCR1x and TCNT1 when the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnxPCPWM = --------------------------2 N TOP The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the output will be continuously low and if set equal to TOP the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A is used to define the TOP value (WGM13:0 = 11) and COM1A1:0 = 1, the OC1A output will toggle with a 50% duty cycle. 13.2.8.5 Phase and Frequency Correct PWM Mode The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequency correct PWM waveform generation option. The phase and frequency correct PWM mode is, like the phase correct PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x while upcounting, and set on the compare match while downcounting. In inverting Compare Output mode, the operation is inverted. The dual-slope operation gives a lower maximum operation frequency compared to the single-slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. The main difference between the phase correct, and the phase and frequency correct PWM mode is the time the OCR1x Register is updated by the OCR1x Buffer Register, (see Figure 1319 and Figure 13-20). The PWM resolution for the phase and frequency correct PWM mode can be defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and 122 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated using the following equation: log ( TOP + 1 ) R PFCPWM = ---------------------------------log ( 2 ) In phase and frequency correct PWM mode the counter is incremented until the counter value matches either the value in ICR1 (WGM13:0 = 8), or the value in OCR1A (WGM13:0 = 9). The counter has then reached the TOP and changes the count direction. The TCNT1 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency correct PWM mode is shown on Figure 13-20. The figure shows phase and frequency correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes noninverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a compare match occurs. Figure 13-20. Phase and Frequency Correct PWM Mode, Timing Diagram OC1A Interrupt Flag Set or ICF1 Interrupt Flag Set (Interrupt on TOP) OCR1x/TOP Updateand TOV1 Interrupt Flag Set (Interrupt on Bottom) TCNT1 OC1x OC1x (COM1x1:0 = 2) (COM1x1:0 = 3) Period 1 2 3 4 The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x Registers are updated with the double buffer value (at BOTTOM). When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag set when TCNT1 has reached TOP. The Interrupt Flags can then be used to generate an interrupt each time the counter reaches the TOP or BOTTOM value. When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x. As Figure 13-20 shows the output generated is, in contrast to the phase correct mode, symmetrical in all periods. Since the OCR1x Registers are updated at BOTTOM, the length of the rising and the falling slopes will always be equal. This gives symmetrical output pulses and is therefore frequency correct. 123 TPR0327AY-SMS-30Jan09 Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively changed by changing the TOP value, using the OCR1A as TOP is clearly a better choice due to its double buffer feature. In phase and frequency correct PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins. Setting the COM1x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM1x1:0 to three (See Table on page 127). The actual OC1x value will only be visible on the port pin if the data direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at the compare match between OCR1x and TCNT1 when the counter increments, and clearing (or setting) the OC1x Register at compare match between OCR1x and TCNT1 when the counter decrements. The PWM frequency for the output when using phase and frequency correct PWM can be calculated by the following equation: f clk_I/O f OCnxPFCPWM = --------------------------2 N TOP The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x Register represents special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the output will be continuously low and if set equal to TOP the output will be set to high for noninverted PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A is used to define the TOP value (WGM13:0 = 9) and COM1A1:0 = 1, the OC1A output will toggle with a 50% duty cycle. 13.2.9 Timer/Counter Timing Diagrams The Timer/Counter is a synchronous design and the timer clock (clkTn) is therefore shown as a clock enable signal in the following figures. The figures include information on when Interrupt Flags are set, and when the OCR1x Register is updated with the OCR1x buffer value (only for modes utilizing double buffering). Figure 13-21 shows a timing diagram for the setting of OCF1x. Figure 13-21. Timer/Counter Timing Diagram, Setting of OCF1x, no Prescaling clk I/O clk Tn (clk I/O /1) TCNT1 OCR1x - 1 OCR1x OCR1x + 1 OCR1x + 2 OCR1x OCR1x Value OCF1x Figure 13-22 shows the same timing data, but with the prescaler enabled. 124 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 13-22. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT1 OCR1x - 1 OCR1x OCR1x + 1 OCR1x + 2 OCR1x OCR1x Value OCF1x Figure 13-23 shows the count sequence close to TOP in various modes. When using phase and frequency correct PWM mode the OCR1x Register is updated at BOTTOM. The timing diagrams will be the same, but TOP should be replaced by BOTTOM, TOP-1 by BOTTOM+1 and so on. The same renaming applies for modes that set the TOV1 Flag at BOTTOM. Figure 13-23. Timer/Counter Timing Diagram, no Prescaling clk I/O clk Tn (clk I/O /1) TCNT1 (CTC and FPWM) TOP - 1 TOP BOTTOM BOTTOM + 1 TCNT1 (PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2 TOV1 (FPWM) and ICF1 (if used as TOP) OCR1x (Update at TOP) Old OCR1x Value New OCR1x Value Figure 13-24 shows the same timing data, but with the prescaler enabled. 125 TPR0327AY-SMS-30Jan09 Figure 13-24. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk /8) I/O TCNT1 (CTC and FPWM) TOP - 1 TOP - 1 TOP BOTTOM BOTTOM + 1 TCNT1 (PC and PFC PWM) TOP TOP - 1 TOP - 2 TOV1 (FPWM) and ICF1 (if used as TOP) OCR1x (Update at TOP) Old OCR1x Value New OCR1x Value 13.2.10 13.2.10.1 16-bit Timer/Counter Register Description TCCR1A - Timer/Counter1 Control Register A Bit $000080 Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R 0 2 R 0 1 WGM11 R/W 0 0 WGM10 R/W 0 0x00 TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 * Bit 7..6 - COM1A1..0: Compare Output Mode for Channel A * Bit 5..4 - COM1B1..0: Compare Output Mode for Channel B The COM1A1:0 and COM1B1:0 control the Output Compare pins (OC1A and OC1B respectively) behavior. If one or both of the COM1A1:0 bits are written to one, the OC1A output overrides the normal port functionality of the I/O pin it is connected to. If one or both of the COM1B1:0 bit are written to one, the OC1B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC1A or OC1B pin must be set in order to enable the output driver. When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits is dependent of the WGM13:0 bits setting. Table 13-11 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to a Normal or a CTC mode (non-PWM). Table 13-11. Compare Output Mode, non-PWM COM1A1/COM1B1 0 0 1 1 COM1A0/COM1B0 0 1 0 1 Description Normal port operation, OC1A/OC1B disconnected. Toggle OC1A/OC1B on Compare Match. Clear OC1A/OC1B on Compare Match (Set output to low level). Set OC1A/OC1B on Compare Match (Set output to high level). 126 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 13-12 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the fast PWM mode. Table 13-12. Compare Output Mode, Fast PWM(1) COM1A1/COM1B1 0 COM1A0/COM1B0 0 Description Normal port operation, OC1A/OC1B disconnected. WGM13:0 = 14 or 15: Toggle OC1A on Compare Match, OC1B disconnected (normal port operation). For all other WGM1 settings, normal port operation, OC1A/OC1B disconnected. Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode) Set OC1A/OC1B on Compare Match, clear OC1A/OC1B at BOTTOM (inverting mode) 0 1 1 1 Note: 0 1 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. In this case the compare match is ignored, but the set or clear is done at TOP. See "Fast PWM Mode" on page 118. for more details. Table 13-13 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase correct or the phase and frequency correct, PWM mode. Table 13-13. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM(1) COM1A1/COM1B1 0 COM1A0/COM1B0 0 Description Normal port operation, OC1A/OC1B disconnected. WGM13:0 = 9 or 11: Toggle OC1A on Compare Match, OC1B disconnected (normal port operation). For all other WGM1 settings, normal port operation, OC1A/OC1B disconnected. Clear OC1A/OC1B on Compare Match when upcounting. Set OC1A/OC1B on Compare Match when downcounting. Set OC1A/OC1B on Compare Match when upcounting. Clear OC1A/OC1B on Compare Match when downcounting. 0 1 1 0 1 Note: 1 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. See "Phase Correct PWM Mode" on page 120. for more details. * Bit 1..0 - WGM11..0: Waveform Generation Mode Combined with the WGM13:2 bits found in the TCCR1B Register, these bits control the counting sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used, see Table 13-14. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare match (CTC) mode, and three types of Pulse Width Modulation (PWM) modes. (See "Modes of Operation" on page 117.). 127 TPR0327AY-SMS-30Jan09 Table 13-14. Waveform Generation Mode Bit Description(1) Mode 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Note: WGM13 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 WGM12 (CTCn) 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 WGM11 (PWMn1) 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 WGM10 (PWMn0) 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Timer/Counter Mode of Operation Normal PWM, Phase Correct, 8-bit PWM, Phase Correct, 9-bit PWM, Phase Correct, 10-bit CTC Fast PWM, 8-bit Fast PWM, 9-bit Fast PWM, 10-bit PWM, Phase and Frequency Correct PWM, Phase and Frequency Correct PWM, Phase Correct PWM, Phase Correct CTC (Reserved) Fast PWM Fast PWM TOP 0xFFFF 0x00FF 0x01FF 0x03FF OCR1A 0x00FF 0x01FF 0x03FF ICR1 OCR1A ICR1 OCR1A ICR1 - ICR1 OCR1A Update of OCR1x at Immediate TOP TOP TOP Immediate BOTTOM BOTTOM BOTTOM BOTTOM BOTTOM TOP TOP Immediate - BOTTOM BOTTOM TOV1 Flag Set on MAX BOTTOM BOTTOM BOTTOM MAX TOP TOP TOP BOTTOM BOTTOM BOTTOM BOTTOM MAX - TOP TOP 1. The CTCn and PWMn1:0 bit definition names are obsolete. Use the WGM12:0 definitions. However, the functionality and location of these bits are compatible with previous versions of the timer. 13.2.10.2 TCCR1B - Timer/Counter1 Control Register B Bit $000081 Read/write Initial value 7 ICNC1 R/W 0 6 ICES1 R/W 0 5 R 0 4 WGM13 R/W 0 3 WGM12 R/W 0 2 CS12 R/W 0 1 CS11 R/W 0 0 CS10 R/W 0 0x00 TCCR1B * Bit 7 - ICNCn: Input Capture Noise Canceler Setting this bit (to one) activates the Input Capture Noise Canceler. When the noise canceler is activated, the input from the Input Capture pin (ICP1) is filtered. The filter function requires four successive equal valued samples of the ICP1 pin for changing its output. The Input Capture is therefore delayed by four Oscillator cycles when the noise canceler is enabled. * Bit 6 - ICESn: Input Capture Edge Select This bit selects which edge on the Input Capture pin (ICP1) that is used to trigger a capture event. When the ICESn bit is written to zero, a falling (negative) edge is used as trigger, and when the ICESn bit is written to one, a rising (positive) edge will trigger the capture. 128 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 When a capture is triggered according to the ICESn setting, the counter value is copied into the Input Capture Register (ICR1). The event will also set the Input Capture Flag (ICF1), and this can be used to cause an Input Capture Interrupt, if this interrupt is enabled. When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequently the Input Capture function is disabled. * Bit 5 - Reserved Bit This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be written to zero when TCCR1B is written. * Bit 4..3 - WGM13..2: Waveform Generation Mode See TCCR1A Register description. * Bit 2..0 - CS12..0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter, see Figure 13-21 and Figure 13-22. Table 13-15. Clock Select Bit Description CS12 0 0 0 0 1 1 1 1 CS11 0 0 1 1 0 0 1 1 CS10 0 1 0 1 0 1 0 1 Description No clock source (Timer/Counter stopped). clkI/O/1 (No prescaling) clkI/O/8 (From prescaler) clkI/O/64 (From prescaler) clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler) External clock source on Tn pin. Clock on falling edge. External clock source on Tn pin. Clock on rising edge. If external pin modes are used for the Timer/Countern, transitions on the Tn pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 13.2.10.3 TCCR1C - Timer/Counter1 Control Register C Bit $000082 Read/write Initial value 7 FOC1A R/W 0 6 FOC1B R/W 0 5 R 0 4 R 0 3 R 0 2 R 0 1 R 0 0 R 0 0x00 TCCR1C * Bit 7 - FOC1A: Force Output Compare for Channel A * Bit 6 - FOC1B: Force Output Compare for Channel B The FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWM mode. However, for ensuring compatibility with future devices, these bits must be set to zero when TCCR1A is written when operating in a PWM mode. When writing a logical one to the FOC1A/FOC1B bit, an immediate compare match is forced on the Waveform Generation unit. 129 TPR0327AY-SMS-30Jan09 The OC1A/OC1B output is changed according to its COM1x1:0 bits setting. Note that the FOC1A/FOC1B bits are implemented as strobes. Therefore it is the value present in the COM1x1:0 bits that determine the effect of the forced compare. A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear Timer on Compare match (CTC) mode using OCR1A as TOP. The FOC1A/FOC1B bits are always read as zero. 13.2.10.4 TCNT1H and TCNT1L -Timer/Counter1 Bit $000085 $000084 Bit Read/write Initial value 7 R/W R/W 0 0 6 R/W R/W 0 0 5 R/W R/W 0 0 15 14 13 12 11 10 9 8 TCNT1H TCNT1L 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 0 0 0x00 0x00 TCNT[15..8] TCNT [7..0] 4 R/W R/W 0 0 3 R/W R/W 0 0 The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and low bytes are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing 16-bit Registers" on page 107. Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a compare match between TCNT1 and one of the OCR1x Registers. Writing to the TCNT1 Register blocks (removes) the compare match on the following timer clock for all compare units. 130 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.2.10.5 OCR1AH and OCR1AL - Output Compare Register 1 A Bit $000089 $000088 Bit Read/write Initial value 7 R/W R/W 0 0 6 R/W R/W 0 0 5 R/W R/W 0 0 15 14 13 12 11 10 9 8 OCR1AH OCR1AL 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 0 0 0x00 0x00 OCR1A[15..8] OCR1A [7..0] 4 R/W R/W 0 0 3 R/W R/W 0 0 13.2.10.6 OCR1BH and OCR1BL - Output Compare Register 1 B Bit $00008B $00008A Bit Read/write Initial value 7 R/W R/W 0 0 6 R/W R/W 0 0 5 R/W R/W 0 0 15 14 13 12 11 10 9 8 OCR1BH OCR1BL 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 0 0 0x00 0x00 OCR1B[15..8] OCR1B [7..0] 4 R/W R/W 0 0 3 R/W R/W 0 0 The Output Compare Registers contain a 16-bit value that is continuously compared with the counter value (TCNT1). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC1x pin. The Output Compare Registers are 16-bit in size. To ensure that both the high and low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing 16-bit Registers" on page 107. 13.2.10.7 ICR1H and ICR1L - Input Capture Register 1 Bit $000087 $000086 Bit Read/write Initial value 7 R/W R/W 0 0 6 R/W R/W 0 0 5 R/W R/W 0 0 15 14 13 12 11 10 9 8 ICR1H ICR1L 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 0 0 0x00 0x00 ICR1[15..8] ICR1 [7..0] 4 R/W R/W 0 0 3 R/W R/W 0 0 The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin. The Input Capture can be used for defining the counter TOP value. The Input Capture Register is 16-bit in size. To ensure that both the high and low bytes are read simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing 16-bit Registers" on page 107. 131 TPR0327AY-SMS-30Jan09 13.2.10.8 TIMSK1 - Timer/Counter1 Interrupt Mask Register Bit $00006F Read/write Initial value 7 R 0 6 R 0 5 ICIE1 R/W 0 4 R 0 3 R 0 2 OCIE1B R/W 0 1 OCIE1A R/W 0 0 TOIE1 R/W 0 0x00 TIMSK1 * Bit 7..6 - Res: Reserved Bits These bits are unused bits in the AT90SCR100, and will always read as zero. * Bit 5 - ICIE1: Timer/Counter1, 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 Input Capture interrupt is enabled. The corresponding Interrupt Vector (See "Interrupts" on page 63.) is executed when the ICF1 Flag, located in TIFR1, is set. * Bit 4..3 - Res: Reserved Bits These bits are unused bits in the AT90SCR100, and will always read as zero. * Bit 2 - OCIE1B: Timer/Counter1, Output Compare B Match 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 Output Compare B Match interrupt is enabled. The corresponding Interrupt Vector (See "Interrupts" on page 63.) is executed when the OCF1B Flag, located in TIFR1, is set. * Bit 1 - OCIE1A: Timer/Counter1, Output Compare A Match 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 Output Compare A Match interrupt is enabled. The corresponding Interrupt Vector (See "Interrupts" on page 63.) is executed when the OCF1A Flag, located in TIFR1, is set. * Bit 0 - TOIE1: Timer/Counter1, Overflow 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 Overflow interrupt is enabled. The corresponding Interrupt Vector (See "Watchdog Timer" on page 57.) is executed when the TOV1 Flag, located in TIFR1, is set. 13.2.10.9 TIFR1 - Timer/Counter1 Interrupt Flag Register Bit $000016 Read/write Initial value 7 R 0 6 R 0 5 ICF1 R/W 0 4 R 0 3 R 0 2 OCF1B R/W 0 1 OCF1A R/W 0 0 TOV1 R/W 0 0x00 TIFR1 * Bit 7..6 - Res: Reserved Bits These bits are unused bits in the AT90SCR100, and will always read as zero. * Bit 5 - ICF1: Timer/Counter1, Input Capture Flag This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register (ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 Flag is set when the counter reaches the TOP value. 132 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICF1 can be cleared by writing a logic one to its bit location. * Bit 4..3 - Res: Reserved Bits These bits are unused bits in the AT90SCR100, and will always read as zero. * Bit 2 - OCF1B: Timer/Counter1, Output Compare B Match Flag This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register B (OCR1B). Note that a Forced Output Compare (FOC1B) strobe will not set the OCF1B Flag. OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector is executed. Alternatively, OCF1B can be cleared by writing a logic one to its bit location. * Bit 1 - OCF1A: Timer/Counter1, Output Compare A Match Flag This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register A (OCR1A). Note that a Forced Output Compare (FOC1A) strobe will not set the OCF1A Flag. OCF1A is automatically cleared when the Output Compare Match A Interrupt Vector is executed. Alternatively, OCF1A can be cleared by writing a logic one to its bit location. * Bit 0 - TOV1: Timer/Counter1, Overflow Flag The setting of this flag is dependent of the WGM13:0 bits setting. In Normal and CTC modes, the TOV1 Flag is set when the timer overflows. Refer to Table 13-14 on page 128 for the TOV1 Flag behavior when using another WGM13:0 bit setting. TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed. Alternatively, TOV1 can be cleared by writing a logic one to its bit location. 133 TPR0327AY-SMS-30Jan09 13.3 8-bit Timer/Counter2 with PWM and Asynchronous Operation (RTC) Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. The main features are: * * * * * * * Single Channel Counter Clear Timer on Compare Match (Auto Reload) Glitch-free, Phase Correct Pulse Width Modulator (PWM) Frequency Generator 10-bit Clock Prescaler Overflow and Compare Match Interrupt Sources (TOV2, OCF2A and OCF2B) Allows Clocking from External 32 kHz Watch Crystal Independent of the I/O Clock 13.3.1 Overview A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 13-23. For the actual placement of I/O pins, see "Pin List Configuration" on page 5. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in the "8-bit Timer/Counter Register Description" on page 145. The Power Reduction Timer/Counter2 bit, PRTIM2, in "PRR0 - Power Reduction Register 0" on page 45 must be written to zero to enable Timer/Counter2 module. Figure 13-25. 8-bit Timer/Counter Block Diagram Count Clear Direction Control Logic TOV2 (Int.Req.) clk Tn T/C Oscillator TOP BOTTOM Prescaler clk I/O TOSC2 TOSC1 Timer/Counter TCNT2 = =0 OC2A (Int.Req.) = OCR2A Fixed TOP Value Waveform Generation OC2A OC2B (Int.Req.) Waveform Generation OC2B DATA BUS = OCR2B Synchronized Status flags Synchronization Unit clk I/O clk ASY Status flags ASSR asynchronous mode select (AS2) TCCR2A TCCR2B 134 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 13.3.1.1 Registers The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit registers. Interrupt request (abbreviated to Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK2). TIFR2 and TIMSK2 are not shown in the figure. The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from the TOSC1/2 pins, as detailed later in this section. The asynchronous operation is controlled by the Asynchronous Status Register (ASSR). The Clock Select logic block controls which clock source the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkT2). The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pins (OC2A and OC2B). See "Output Compare Unit" on page 136. for details. The compare match event will also set the Compare Flag (OCF2A or OCF2B) which can be used to generate an Output Compare interrupt request. 13.3.1.2 Definitions Most register and bit references in this section are written in general form. A lower case "x" replaces the Output Compare unit channel. The definitions in Table 13-16 are also used extensively throughout the section. Table 13-16. Definitions BOTTOM MAX The counter reaches the BOTTOM when it becomes zero (0x00). The counter reaches its MAXimum when it becomes 0xFF (decimal 255). The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR2A Register. The assignment is dependent on the mode of operation. TOP 13.3.2 Timer/Counter Clock Sources The Timer/Counter can be clocked by an internal synchronous or an external asynchronous clock source. The clock source clkT2 is by default equal to the MCU clock, clkI/O. When the AS2 bit in the ASSR Register is written to logic one, the clock source is taken from the Timer/Counter Oscillator connected to TOSC1 and TOSC2. For details on asynchronous operation, see "ASSR - Asynchronous Status Register" on page 150. For details on clock sources and prescaler, see "Timer/Counter Prescaler" on page 154. Counter Unit The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 13-26 shows a block diagram of the counter and its surrounding environment. 13.3.3 135 TPR0327AY-SMS-30Jan09 Figure 13-26. Counter Unit Block Diagram DATA BUS TOV2 (Int.Req.) TOSC1 count TCNT2 clear direction clk Control Logic Tn Prescaler T/C Oscillator TOSC2 bottom top clkI/O Signal description (internal signals): count direction clear clkTn top bottom Increment or decrement TCNT2 by 1. Selects between increment and decrement. Clear TCNT2 (set all bits to zero). Timer/Counter clock, referred to as clkT2 in the following. Signalizes that TCNT2 has reached maximum value. Signalizes that TCNT2 has reached minimum value (zero). Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source, selected by the Clock Select bits (CS22:0). When no clock source is selected (CS22:0 = 0) the timer is stopped. However, the TCNT2 value can be accessed by the CPU, regardless of whether clkT2 is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in the Timer/Counter Control Register (TCCR2A) and the WGM22 located in the Timer/Counter Control Register B (TCCR2B). There are close connections between how the counter behaves (counts) and how waveforms are generated on the Output Compare outputs OC2A and OC2B. For more details about advanced counting sequences and waveform generation, see "Modes of Operation" on page 139. The Timer/Counter Overflow Flag (TOV2) is set according to the mode of operation selected by the WGM22:0 bits. TOV2 can be used for generating a CPU interrupt. 13.3.4 Output Compare Unit The 8-bit comparator continuously compares TCNT2 with the Output Compare Register (OCR2A and OCR2B). Whenever TCNT2 equals OCR2A or OCR2B, the comparator signals a match. A match will set the Output Compare Flag (OCF2A or OCF2B) at the next timer clock cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the Output Compare 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 the WGM22:0 bits and Compare Output mode (COM2x1:0) bits. The max and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in some modes of operation ("Modes of Operation" on page 139). Figure 13-21 on page 124 shows a block diagram of the Output Compare unit. 136 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 13-27. Output Compare Unit, Block Diagram DATA BUS OCR2x TCNT2 = (8-bit Comparator ) OC2x (Int.Req.) top bottom FOC2 Waveform Generator OC2x WGM21:0 COM2X1:0 The OCR2x Register is double buffered when using any of the Pulse Width Modulation (PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double buffering synchronizes the update of the OCR2x Compare Register to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. The OCR2x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR2x Buffer Register, and if double buffering is disabled the CPU will access the OCR2x directly. 13.3.4.1 Force 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 (FOC2x) bit. Forcing compare match will not set the OCF2x Flag or reload/clear the timer, but the OC2x pin will be updated as if a real compare match had occurred (the COM2x1:0 bits settings define whether the OC2x pin is set, cleared or toggled). Compare Match Blocking by TCNT2 Write All CPU write operations to the TCNT2 Register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. This feature allows OCR2x to be initialized to the same value as TCNT2 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT2 when using the Output Compare channel, independently of whether the Timer/Counter is running or not. If the value written to TCNT2 equals the OCR2x value, the compare match will be missed, resulting in incorrect waveform generation. Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is downcounting. 13.3.4.2 13.3.4.3 137 TPR0327AY-SMS-30Jan09 The setup of the OC2x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC2x value is to use the Force Output Compare (FOC2x) strobe bit in Normal mode. The OC2x Register keeps its value even when changing between Waveform Generation modes. Changing the COM2x1:0 bits will take effect immediately. 13.3.5 Compare Match Output Unit The Compare Output mode (COM2x1:0) bits have two functions. The Waveform Generator uses the COM2x1:0 bits for defining the Output Compare (OC2x) state at the next compare match. Also, the COM2x1:0 bits control the OC2x pin output source. Figure 13-28 shows a simplified schematic of the logic affected by the COM2x1:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by the COM2x1:0 bits are shown. When referring to the OC2x state, the reference is for the internal OC2x Register, not the OC2x pin. Figure 13-28. Compare Match Output Unit, Schematic COM2x1 COM2x0 FOC2x Waveform Generator D Q 1 OC2x Pin OC2x D Q 0 DATA BUS PORT D Q DDR clk I/O The general I/O port function is overridden by the Output Compare (OC2x) from the Waveform Generator if either of the COM2x1:0 bits are set. However, the OC2x pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register bit for the OC2x pin must be set as output before the OC2x value is visible on the pin. The port override function is independent of the Waveform Generation mode. The design of the Output Compare pin logic allows initialization of the OC2x state before the output is enabled. Note that some COM2x1:0 bit settings are reserved for certain modes of operation. See "8-bit Timer/Counter Register Description" on page 145. 13.3.5.1 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM2x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM2x1:0 = 0 tells the Waveform Generator that no action on the 138 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 OC2x Register is to be performed on the next compare match. For compare output actions in the non-PWM modes refer to Table 13-20 on page 147. For fast PWM mode, refer to Table 13-21 on page 147, and for phase correct PWM refer to Table 13-22 on page 147. A change of the COM2x1: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 FOC2x strobe bits. 13.3.6 Modes 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 the Waveform Generation mode (WGM22:0) and Compare Output mode (COM2x1:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM2x1:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes the COM2x1:0 bits control whether the output should be set, cleared, or toggled at a compare match (See "Compare Match Output Unit" on page 138.). For detailed timing information refer to "Timer/Counter Timing Diagrams" on page 143. 13.3.6.1 Normal Mode The simplest mode of operation is the Normal mode (WGM22:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero. The TOV2 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 TOV2 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare unit can be used to generate interrupts at some given time. Using the Output Compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time. 13.3.6.2 Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A 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 Table 13-29. The counter value (TCNT2) increases until a compare match occurs between TCNT2 and OCR2A, and then counter (TCNT2) is cleared. 139 TPR0327AY-SMS-30Jan09 Figure 13-29. CTC Mode, Timing Diagram OC2x Interrupt Flag Set TCNT2 OC2x (Toggle) Period 1 2 3 4 (COM2x1:0 = 1) An interrupt can be generated each time the counter value reaches the TOP value by using the OCF2A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR2A is lower than the current value of TCNT2, the counter will miss the compare match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the compare match can occur. For generating a waveform output in CTC mode, the OC2A output can be set to toggle its logical level on each compare match by setting the Compare Output mode bits to toggle mode (COM2A1:0 = 1). The OC2A value will not be visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of fOC2A = fclk_I/O/2 when OCR2A is set to zero (0x00). The waveform frequency is defined by the following equation: f clk_I/O f OCnx = ------------------------------------------------2 N ( 1 + OCRnx ) The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). As for the Normal mode of operation, the TOV2 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. 13.3.6.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM22:0 = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM22:0 = 3, and OCR2A when MGM22:0 = 7. In noninverting Compare Output mode, the Output Compare (OC2x) is cleared on the compare match between TCNT2 and OCR2x, and set at BOTTOM. In inverting Compare Output mode, the output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that uses dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. 140 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 13-30 on page 141. The TCNT2 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes noninverted and inverted PWM outputs. The small horizontal line marks on the TCNT2 slopes represent compare matches between OCR2x and TCNT2. Figure 13-30. Fast PWM Mode, Timing Diagram OCR2x Interrupt Flag Set OCR2x Update and TOV2 Interrupt Flag Set TCNT2 OC2x OC2x (COM2x1:0 = 2) (COM2x1:0 = 3) Period 1 2 3 4 5 6 7 The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin. Setting the COM2x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when WGM2:0 = 7 (See Table 13-18 on page 146). The actual OC2x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by setting (or clearing) the OC2x Register at the compare match between OCR2x and TCNT2, and clearing (or setting) the OC2x Register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ----------------N 256 The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). The extreme values for the OCR2A Register represent special cases when generating a PWM waveform output in the fast PWM mode. If the OCR2A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR2A equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by the COM2A1:0 bits.) A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC2x to toggle its logical level on each compare match (COM2x1:0 = 1). The waveform 141 TPR0327AY-SMS-30Jan09 generated will have a maximum frequency of foc2 = fclk_I/O/2 when OCR2A is set to zero. This feature is similar to the OC2A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 13.3.6.4 Phase Correct PWM Mode The phase correct PWM mode (WGM22:0 = 1 or 5) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is based on a dual-slope operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM. TOP is defined as 0xFF when WGM22:0 = 1, and OCR2A when MGM22:0 = 5. In noninverting Compare Output mode, the Output Compare (OC2x) is cleared on the compare match between TCNT2 and OCR2x while upcounting, and set on the compare match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. In phase correct PWM mode the counter is incremented until the counter value matches TOP. When the counter reaches TOP, it changes the count direction. The TCNT2 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 13-31. The TCNT2 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT2 slopes represent compare matches between OCR2x and TCNT2. Figure 13-31. Phase Correct PWM Mode, Timing Diagram OC2x Interrupt Flag Set OCR2x Update TOV2 Interrupt Flag Set TCNT2 OC2x OC2x (COM2x1:0 = 2) (COM2x1:0 = 3) Period 1 2 3 The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin. Setting the COM2x1:0 bits to two will produce a non-inverted PWM. An inverted PWM 142 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 output can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7 (See Table 13-19 on page 146). The actual OC2x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC2x Register at the compare match between OCR2x and TCNT2 when the counter increments, and setting (or clearing) the OC2x Register at compare match between OCR2x and TCNT2 when the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnxPCPWM = ----------------N 510 The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). The extreme values for the OCR2A Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR2A is set equal to BOTTOM, the output will be continuously low and if set equal to MAX the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. At the very start of period 2 in Figure 13-31 OC2x has a transition from high to low even though there is no Compare Match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a transition without Compare Match. * OCR2A changes its value from MAX, like in Figure 13-31. When the OCR2A value is MAX the OC2 pin value is the same as the result of a down-counting compare match. To ensure symmetry around BOTTOM the OC2 value at MAX must correspond to the result of an upcounting Compare Match. * The timer starts counting from a value higher than the one in OCR2A, and for that reason misses the Compare Match and hence the OC2 change that would have happened on the way up. 13.3.7 Timer/Counter Timing Diagrams The following figures show the Timer/Counter in synchronous mode, and the timer clock (clkT2) is therefore shown as a clock enable signal. In asynchronous mode, clkI/O should be replaced by the Timer/Counter Oscillator clock. The figures include information on when Interrupt Flags are set. Figure 13-32 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value in all modes other than phase correct PWM mode. Figure 13-32. Timer/Counter Timing Diagram, no Prescaling clk I/O clk Tn (clk I/O /1) TCNT2 MAX - 1 MAX BOTTOM BOTTOM + 1 TOV2 143 TPR0327AY-SMS-30Jan09 Figure 13-33 shows the same timing data, but with the prescaler enabled. Figure 13-33. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT2 MAX - 1 MAX BOTTOM BOTTOM + 1 TOV2 Figure 13-34 shows the setting of OCF2A in all modes except CTC mode. Figure 13-34. Timer/Counter Timing Diagram, Setting of OCF2A, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT2 OCR2x - 1 OCR2x OCR2x + 1 OCR2x + 2 OCR2x OCR2x Value OCF2x Figure 13-35 shows the setting of OCF2A and the clearing of TCNT2 in CTC mode. 144 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 13-35. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler (fclk_I/O/8) clk I/O clk Tn (clk I/O /8) TCNT2 (CTC) OCR2x TOP - 1 TOP BOTTOM BOTTOM + 1 TOP OCF2x 13.3.8 13.3.8.1 8-bit Timer/Counter Register Description TCCR2A - Timer/Counter Control Register A Bit $0000B0 Read/write Initial value 7 COM2A1 R/W 0 6 COM2A0 R/W 0 5 COM2B1 R/W 0 4 COM2B0 R/W 0 3 R 0 2 R 0 1 WGM21 R/W 0 0 WGM20 R/W 0 0x00 TCCR2A * Bits 7..6 - COM2A1..0: Compare Match Output A Mode These bits control the Output Compare pin (OC2A) behavior. If one or both of the COM2A1:0 bits are set, the OC2A output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2A pin must be set in order to enable the output driver. When OC2A is connected to the pin, the function of the COM2A1:0 bits depends on the WGM22:0 bit setting. Table 13-17 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to a normal or CTC mode (non-PWM). Table 13-17. Compare Output Mode, non-PWM Mode COM2A1 0 0 1 1 COM2A0 0 1 0 1 Description Normal port operation, OC0A disconnected. Toggle OC2A on Compare Match Clear OC2A on Compare Match Set OC2A on Compare Match 145 TPR0327AY-SMS-30Jan09 Table 13-18 shows the COM2A1:0 bit functionality when the WGM21:0 bits are set to fast PWM mode. Table 13-18. Compare Output Mode, Fast PWM Mode(1) COM2A1 0 0 1 1 Note: COM2A0 0 1 0 1 Description Normal port operation, OC2A disconnected. WGM22 = 0: Normal Port Operation, OC0A Disconnected. WGM22 = 1: Toggle OC2A on Compare Match. Clear OC2A on Compare Match, set OC2A at BOTTOM (non-inverting mode) Set OC2A on Compare Match, clear OC2A at BOTTOM (inverting mode) 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at BOTTOM. See "Fast PWM Mode" on page 140 for more details. Table 13-19 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to phase correct PWM mode. Table 13-19. Compare Output Mode, Phase Correct PWM Mode(1) COM2A1 0 0 1 1 Note: COM2A0 0 1 0 1 Description Normal port operation, OC2A disconnected. WGM22 = 0: Normal Port Operation, OC2A Disconnected. WGM22 = 1: Toggle OC2A on Compare Match. Clear OC2A on Compare Match when up-counting. Set OC2A on Compare Match when down-counting. Set OC2A on Compare Match when up-counting. Clear OC2A on Compare Match when down-counting. 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 142 for more details. * Bits 5..4 - COM2B1..0: Compare Match Output B Mode These bits control the Output Compare pin (OC2B) behavior. If one or both of the COM2B1:0 bits are set, the OC2B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2B pin must be set in order to enable the output driver. When OC2B is connected to the pin, the function of the COM2B1:0 bits depends on the WGM22:0 bit setting. Table 13-20 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to a normal or CTC mode (non-PWM). 146 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 13-20. Compare Output Mode, non-PWM Mode COM2B1 0 0 1 1 COM2B0 0 1 0 1 Description Normal port operation, OC2B disconnected. Toggle OC2B on Compare Match Clear OC2B on Compare Match Set OC2B on Compare Match Table 13-21 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to fast PWM mode. Table 13-21. Compare Output Mode, Fast PWM Mode(1) COM2B1 0 0 1 1 Note: COM2B0 0 1 0 1 Description Normal port operation, OC2B disconnected. Reserved Clear OC2B on Compare Match, set OC2B at BOTTOM (non-inverting mode) Set OC2B on Compare Match, clear OC2B at BOTTOM (inverting mode) 1. A special case occurs when OCR2B equals TOP and COM2B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at BOTTOM. See "Fast PWM Mode" on page 140 for more details. Table 13-22 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to phase correct PWM mode. Table 13-22. Compare Output Mode, Phase Correct PWM Mode(1) COM2B1 0 0 1 1 Note: COM2B0 0 1 0 1 Description Normal port operation, OC2B disconnected. Reserved Clear OC2B on Compare Match when up-counting. Set OC2B on Compare Match when down-counting. Set OC2B on Compare Match when up-counting. Clear OC2B on Compare Match when down-counting. 1. A special case occurs when OCR2B equals TOP and COM2B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 142 for more details. * Bits 3..2 - Res: Reserved Bits These bits are reserved bits in the AT90SCR100 and will always read as zero. * Bits 1..0 - WGM21..0: Waveform Generation Mode 147 TPR0327AY-SMS-30Jan09 Combined with the WGM22 bit found in the TCCR2B Register, these bits control the counting sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used, see Table 13-23. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes (see "Modes of Operation" on page 139). Table 13-23. Waveform Generation Mode Bit Description Timer/Counter Mode of Operation Normal PWM, Phase Correct CTC Fast PWM Reserved PWM, Phase Correct Reserved Fast PWM Update of OCRx at Immediate TOP Immediate BOTTOM - TOP - BOTTOM TOV Flag Set on(1) MAX BOTTOM MAX MAX - BOTTOM - TOP Mode 0 1 2 3 4 5 6 7 Note: WGM22 0 0 0 0 1 1 1 1 WGM21 0 0 1 1 0 0 1 1 WGM20 0 1 0 1 0 1 0 1 TOP 0xFF 0xFF OCR2A 0xFF - OCR2A - OCR2A 1. MAX= 0xFF, BOTTOM= 0x00 13.3.8.2 TCCR2B - Timer/Counter Control Register B Bit $0000B1 Read/write Initial value 7 FOC2A W 0 6 FOC2B W 0 5 R 0 4 R 0 3 WGM22 R/W 0 2 CS22 R/W 0 1 CS21 R/W 0 0 CS20 R/W 0 0x00 TCCR2B * Bit 7 - FOC2A: Force Output Compare A The FOC2A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR2B is written when operating in PWM mode. When writing a logical one to the FOC2A bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC2A output is changed according to its COM2A1:0 bits setting. Note that the FOC2A bit is implemented as a strobe. Therefore it is the value present in the COM2A1:0 bits that determines the effect of the forced compare. A FOC2A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR2A as TOP. The FOC2A bit is always read as zero. * Bit 6 - FOC2B: Force Output Compare B The FOC2B bit is only active when the WGM bits specify a non-PWM mode. 148 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR2B is written when operating in PWM mode. When writing a logical one to the FOC2B bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC2B output is changed according to its COM2B1:0 bits setting. Note that the FOC2B bit is implemented as a strobe. Therefore it is the value present in the COM2B1:0 bits that determines the effect of the forced compare. A FOC2B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR2B as TOP. The FOC2B bit is always read as zero. * Bits 5..4 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 3 - WGM22: Waveform Generation Mode See the description in the "TCCR2A - Timer/Counter Control Register A" on page 145. * Bit 2..0 - CS22..0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter, see Table 13-24. Table 13-24. Clock Select Bit Description CS22 0 0 0 0 1 1 1 1 CS21 0 0 1 1 0 0 1 1 CS20 0 1 0 1 0 1 0 1 Description No clock source (Timer/Counter stopped). clkT2S/(No prescaling) clkT2S/8 (From prescaler) clkT2S/32 (From prescaler) clkT2S/64 (From prescaler) clkT2S/128 (From prescaler) clkT2S/256 (From prescaler) clkT2S/1024 (From prescaler) 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. 13.3.8.3 TCNT2 - Timer/Counter Register Bit $0000B2 Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 TCNT2 R/W 0 0x00 TCNT2 [7..0] The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT2 Register blocks (removes) the Compare Match on the following timer clock. Modifying the counter (TCNT2) while the counter is running, introduces a risk of missing a Compare Match between TCNT2 and the OCR2x Registers. 149 TPR0327AY-SMS-30Jan09 13.3.8.4 OCR2A - Output Compare Register A Bit $0000B3 Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR2A R/W 0 0x00 OCR2A [7..0] The Output Compare Register A contains an 8-bit value that is continuously compared with the counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC2A pin. 13.3.8.5 OCR2B - Output Compare Register B Bit $0000B4 Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR2B R/W 0 0x00 OCR2B [7..0] The Output Compare Register B contains an 8-bit value that is continuously compared with the counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC2B pin. 13.3.9 13.3.9.1 Bit $0000B6 Read/write Initial value Asynchronous operation of the Timer/Counter ASSR - Asynchronous Status Register 7 R 0 6 EXCLK R/W 0 5 AS2 R/W 0 4 TCN2UB R 0 3 R 0 2 R 0 1 R 0 0 ASSR 0x00 R 0 OCR2AUB OCR2BUB TCR2AUB TCR2BUB * Bit 6 - EXCLK: Enable External Clock Input When EXCLK is written to one, and asynchronous clock is selected, the external clock input buffer is enabled and an external clock can be input on Timer Oscillator 1 (TOSC1) pin instead of a 32 kHz crystal. Writing to EXCLK should be done before asynchronous operation is selected. Note that the crystal Oscillator will only run when this bit is zero. * Bit 5 - AS2: Asynchronous Timer/Counter2 When AS2 is written to zero, Timer/Counter2 is clocked from the I/O clock, clkI/O. When AS2 is written to one, Timer/Counter2 is clocked from a crystal Oscillator connected to the Timer Oscillator 1 (TOSC1) pin. When the value of AS2 is changed, the contents of TCNT2, OCR2A, OCR2B, TCCR2A and TCCR2B might be corrupted. * Bit 4 - TCN2UB: Timer/Counter2 Update Busy When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set. When TCNT2 has been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value. * Bit 3 - OCR2AUB: Output Compare Register2 Update Busy 150 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 When Timer/Counter2 operates asynchronously and OCR2A is written, this bit becomes set. When OCR2A has been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that OCR2A is ready to be updated with a new value. * Bit 2 - OCR2BUB: Output Compare Register2 Update Busy When Timer/Counter2 operates asynchronously and OCR2B is written, this bit becomes set. When OCR2B has been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that OCR2B is ready to be updated with a new value. * Bit 1 - TCR2AUB: Timer/Counter Control Register2 Update Busy When Timer/Counter2 operates asynchronously and TCCR2A is written, this bit becomes set. When TCCR2A has been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that TCCR2A is ready to be updated with a new value. * Bit 0 - TCR2BUB: Timer/Counter Control Register2 Update Busy When Timer/Counter2 operates asynchronously and TCCR2B is written, this bit becomes set. When TCCR2B has been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that TCCR2B is ready to be updated with a new value. If a write is performed to any of the five Timer/Counter2 Registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur. The mechanisms for reading TCNT2, OCR2A, OCR2B, TCCR2A and TCCR2B are different. When reading TCNT2, the actual timer value is read. When reading OCR2A, OCR2B, TCCR2A and TCCR2B the value in the temporary storage register is read. 13.3.9.2 Asynchronous Operation of Timer/Counter2 When Timer/Counter2 operates asynchronously, some considerations must be taken. * Warning: When switching between asynchronous and synchronous clocking of Timer/Counter2, the Timer Registers TCNT2, OCR2x, and TCCR2x might be corrupted. A safe procedure for switching clock source is: 1. Disable the Timer/Counter2 interrupts by clearing OCIE2x and TOIE2. 2. Select clock source by setting AS2 as appropriate. 3. Write new values to TCNT2, OCR2x, and TCCR2x. 4. To switch to asynchronous operation: Wait for TCN2UB, OCR2xUB, and TCR2xUB. 5. Clear the Timer/Counter2 Interrupt Flags. 6. Enable interrupts, if needed. * The CPU main clock frequency must be more than four times the Oscillator frequency. * When writing to one of the registers TCNT2, OCR2x, or TCCR2x, the value is transferred to a temporary register, and latched after two positive edges on TOSC1. The user should not write a new value before the contents of the temporary register have been transferred to its destination. Each of the five mentioned registers have their individual temporary register, which means that e.g. writing to TCNT2 does not disturb an OCR2x write in progress. To detect that a transfer to the destination register has taken place, the Asynchronous Status Register - ASSR has been implemented. 151 TPR0327AY-SMS-30Jan09 * When entering Power-save or ADC Noise Reduction mode after having written to TCNT2, OCR2x, or TCCR2x, the user must wait until the written register has been updated if Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode before the changes are effective. This is particularly important if any of the Output Compare2 interrupt is used to wake up the device, since the Output Compare function is disabled during writing to OCR2x or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode before the corresponding OCR2xUB bit returns to zero, the device will never receive a compare match interrupt, and the MCU will not wake up. * If Timer/Counter2 is used to wake the device up from Power-save or ADC Noise Reduction mode, precautions must be taken if the user wants to re-enter one of these modes: The interrupt logic needs one TOSC1 cycle to be reset. If the time between wake-up and reentering sleep mode is less than one TOSC1 cycle, the interrupt will not occur, and the device will fail to wake up. If the user is in doubt whether the time before re-entering Powersave or ADC Noise Reduction mode is sufficient, the following algorithm can be used to ensure that one TOSC1 cycle has elapsed: 1. Write a value to TCCR2x, TCNT2, or OCR2x. 2. Wait until the corresponding Update Busy Flag in ASSR returns to zero. 3. Enter Power-save or ADC Noise Reduction mode. * When the asynchronous operation is selected, the 32.768 kHz Oscillator for Timer/Counter2 is always running, except in Power-down and Standby modes. After a Power-up Reset or wake-up from Power-down or Standby mode, the user should be aware of the fact that this Oscillator might take as long as one second to stabilize. The user is advised to wait for at least one second before using Timer/Counter2 after power-up or wake-up from Power-down or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost after a wake-up from Power-down or Standby mode due to unstable clock signal upon start-up, no matter whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin. * Description of wake up from Power-save or ADC Noise Reduction mode when the timer is clocked asynchronously: When the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value. After wake-up, the MCU is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction following SLEEP. * Reading of the TCNT2 Register shortly after wake-up from Power-save may give an incorrect result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2 must be done through a register synchronized to the internal I/O clock domain. Synchronization takes place for every rising TOSC1 edge. When waking up from Power-save mode, and the I/O clock (clkI/O) again becomes active, TCNT2 will read as the previous value (before entering sleep) until the next rising TOSC1 edge. The phase of the TOSC clock after waking up from Power-save mode is essentially unpredictable, as it depends on the wake-up time. The recommended procedure for reading TCNT2 is thus as follows: 1. Write any value to either of the registers OCR2x or TCCR2x. 2. Wait for the corresponding Update Busy Flag to be cleared. 3. Read TCNT2. * During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous timer takes 3 processor cycles plus one timer cycle. The timer is therefore 152 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 advanced by at least one before the processor can read the timer value causing the setting of the Interrupt Flag. The Output Compare pin is changed on the timer clock and is not synchronized to the processor clock. 13.3.9.3 TIMSK2 - Timer/Counter2 Interrupt Mask Register Bit $000070 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 OCIE2B R/W 0 1 OCIE2A R/W 0 0 TOIE2 R/W 0 0x00 TIMSK2 * Bit 2 - OCIE2B : Timer/Counter2 Output Compare Match B Interrupt Enable When the OCIE2B bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare Match B interrupt is enabled. The corresponding interrupt is executed if a compare match in Timer/Counter2 occurs, i.e., when the OCF2B bit is set in the Timer/Counter 2 Interrupt Flag Register - TIFR2. * Bit 1 - OCIE2A : Timer/Counter2 Output Compare Match A Interrupt Enable When the OCIE2A bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare Match A interrupt is enabled. The corresponding interrupt is executed if a compare match in Timer/Counter2 occurs, i.e., when the OCF2A bit is set in the Timer/Counter 2 Interrupt Flag Register - TIFR2. * Bit 0 - TOIE2 : Timer/Counter2 Overflow Interrupt Enable When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter2 occurs, i.e., when the TOV2 bit is set in the Timer/Counter2 Interrupt Flag Register - TIFR2. 13.3.9.4 TIFR2 - Timer/Counter2 Interrupt Flag Register Bit 0x17 (0x37) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 OCF2B R/W 0 1 OCF2A R/W 0 0 TOV2 R/W 0 0x00 TIFR2 * Bit 2 - OCF2B : Output Compare Flag 2 B The OCF2B bit is set (one) when a compare match occurs between the Timer/Counter2 and the data in OCR2B - Output Compare Register2. OCF2B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF2B is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE2B (Timer/Counter2 Compare match Interrupt Enable), and OCF2B are set (one), the Timer/Counter2 Compare match Interrupt is executed. * Bit 1 - OCF2A : Output Compare Flag 2 A The OCF2A bit is set (one) when a compare match occurs between the Timer/Counter2 and the data in OCR2A - Output Compare Register2. OCF2A is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF2A is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE2A (Timer/Counter2 Compare match Interrupt Enable), and OCF2A are set (one), the Timer/Counter2 Compare match Interrupt is executed. 153 TPR0327AY-SMS-30Jan09 * Bit 0 - TOV2 : Timer/Counter2 Overflow Flag The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV2 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE2A (Timer/Counter2 Overflow Interrupt Enable), and TOV2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In PWM mode, this bit is set when Timer/Counter2 changes counting direction at 0x00. 13.4 Timer/Counter Prescaler Figure 13-36. Prescaler for Timer/Counter2 clkI/O TOSC1 clkT2S Clear 10-BIT T/C PRESCALER clkT2S/8 clkT2S/32 clkT2S/64 clkT2S/128 clkT2S/256 AS2 PSRASY 0 CS20 CS21 CS22 TIMER/COUNTER2 CLOCK SOURCE clkT2 The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main system I/O clock clk IO . By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously clocked from the TOSC1 pin. This enables use of Timer/Counter2 as a Real Time Counter (RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port C. A crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock source for Timer/Counter2. The Oscillator is optimized for use with a 32.768 kHz crystal. By setting the EXCLK bit in the ASSR, a 32 kHz external clock can be applied. See "ASSR - Asynchronous Status Register" on page 150 for details. For Timer/Counter2, the possible prescaled selections are: clk T2S /8, clk T2S/32, clk T2S /64, clkT2S/128, clkT2S/256, and clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected. Setting the PSRASY bit in GTCCR resets the prescaler. This allows the user to operate with a predictable prescaler. 154 AT90SCR100 TPR0327AY-SMS-30Jan09 clkT2S/1024 AT90SCR100 13.4.1 GTCCR - General Timer/Counter Control Register Bit 0x23 (0x43) Read/write Initial value 7 TSM R/W 0 6 R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 R/W 0 0 GTCCR 0x00 R/W 0 PSRASY PSRSYNC * Bit 7 - TSM : Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the value that is written to the PSRASY and PSRSYNC bits is kept, hence keeping the corresponding prescaler reset signals asserted. This ensures that the corresponding Timer/Counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. When the TSM bit is written to zero, the PSRASY and PSRSYNC bits are cleared by hardware, and the Timer/Counters start counting simultaneously. * Bit 1 - PSRASY : Prescaler Reset Timer/Counter2 When this bit is one, the Timer/Counter2 prescaler will be reset. This bit is normally cleared immediately by hardware. If the bit is written when Timer/Counter2 is operating in asynchronous mode, the bit will remain one until the prescaler has been reset. The bit will not be cleared by hardware if the TSM bit is set. Refer to the description of the "Bit 7 - TSM: Timer/Counter Synchronization Mode" on page 136 for a description of the Timer/Counter Synchronization mode. * Bit 0 - PSRSYNC : Prescaler Reset Timer/Counter0, Timer/Counter1 When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is normally cleared immediately by hardware, except if the TSM bit is set. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both timers. 155 TPR0327AY-SMS-30Jan09 156 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 14. USB Device Interface This section contains an overview of the USB module and the description of the registers design to interface this USB module. It also details the USB interrupt, the Suspend and Resume modes, the double buffering, the mode detection and the attachment procedure. This section assumes the reader of this document is comfortable with the USB Specifications V2.0, available on the www.usb.org website. He may also refer to the USB register summary, located at the end of this document to have a complete overview of the registers available. See "Register Summary" on page 417. 14.1 Features * USB 2.0 FullSpeed compliant * Data transfer rates up to 12Mbit/s * 8 Programmable Endpoints bi-directionnals - Endpoint 0 for control: 64bytes - Endpoints 1 to 3 support double buffers of 64bytes each - Endpoints 4 to 7: 8 bytes each Suspend/Resume Interrupts Resume Wake Up Capabilities Automatic NACK if USB not ready to transmit/receive Specific USBDMA connected for fast and easy copy from Endpoint to RAM * * * * 14.2 Overview The following diagram represents the USB module that contains the necessary logic to communicate via a Full-Speed USB port. In Register configuration, you may see `X' suffix at the end of some register. This value is to be changed into 0, 1, 2, 3, 4, 5, 6 and 7 according to the endpoint targeted. The USBENUM is designed to target choose the endpoint to target. Note 157 TPR0327AY-SMS-30Jan09 Figure 14-1. USB Module Diagram USB MODULE USBDM (D-) USB Transceiver USBDP (D+) Clock and Suspend / Resume Manager USB SIE (Serial Interface Engine) XIN XOUT USB Control and Status, USB Interrupt, ... Data Exchanges USB UFI (Universal Function Interface) USBDMA Controller Endpoint 0 Endpoint 1 Endpoint 2 Endpoint 3 Endpoint 4 Endpoint 5 Endpoint 6 Endpoint 7 DPRAM 64 Bytes 2x64 Bytes 2x64 Bytes 2x64 Bytes 8 Bytes 8 Bytes 8 Bytes 8 Bytes The USB module of the AT90SCR100 is made up of the following elements: * The USB Transceiver: it is the electrical and physical interface between the USB Bus and the internal logic of the AT90SCR100. * The USB Serial Interface Engine: this logical part manages the NRZI coding/decoding, the bit stuffing/unstuffing, the CRC generation/checking and the serial-parallel data conversion as requested by the USB specifications. * The Universal Function Interface: this block is the interface between the data flow and the internal Dual Port RAM of the USB module that contains the endpoints. * The DPRAM block: the Dual Port RAM is an internal block of the USB module. It contains the seven available endpoints and can be accessed either by the SIE or the UFI. It is intended to be used as a buffer between the USB bus and the internal data bus of the AT90SCR100. * The USBDMA Controller: the Direct Memory Access logical module allows fast data transfers from the DPRAM to the RAM of the AT90SCR100. See "USBDMA Controller" on page 172. 158 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The USB interface of the AT90SCR100 is a module supporting one USB device address with eight configurable endpoints, managed by an embedded firmware running on the AVR. This firmware is responsible for handling the enumeration (particularly the SETUP packets management), executing the Suspend and Resume mode entries, filling and emptying the endpoints through the USBDMA Controller, sending STALL packets. The device is characterized by a full-speed (12Mb/s) bus-powered interface supporting Suspend and Resume modes and fully compliant with the USB V2.0 specifications. The endpoints 1, 2 and 3 have a double-buffering capability (double DPRAM size). This feature is particularly suitable for Bulk data transfers and is totally managed by the hardware. See "Double Buffering" on page 163. In order to communicate via the USB interface, the chip operates with at 48MHz clock. The chip internally de-activates and activates its oscillator when necessary in order to be compliant with the power consumption of the Suspend mode. 14.3 Endpoints Description The USB module contains eight endpoints. They are fully configurable through their corresponding register USBFCEX (for further details, please refer to "USBFCEX - USB Function Control Registers for Endpoint X" on page 169). The table below indicates the size (in Bytes) of each endpoint and also shows possible configurations for the USB device. Table 14-1. Endpoint Number EP0 EP1 EP2 EP3 EP4 EP5 EP6 EP7 Notes: Endpoints Description Size in Bytes 64 2x64 2x64 2x64 8 8 8 8 Double- Buffering Capability NO YES YES YES NO NO NO NO Recommended Data Transfer Type CONTROL BULK(1) BULK (1) BULK (1) CONTROL, BULK, INTERRUPT(2) CONTROL, BULK, INTERRUPT(2) CONTROL, BULK, INTERRUPT(2) CONTROL, BULK, INTERRUPT(2) 1. Can also be INTERRUPT or ISOCHRONOUS, not CONTROL 2. Can also be ISOCHRONOUS An endpoint featuring the double-buffering capability is allocated on two banks of DPRAM, each bank equal to the endpoint size. Endpoints 1, 2 and 3 support these double buffer of 64 Bytes. See "Double Buffering" on page 163. The hardware is responsible for handling the internal data toggle bit for each endpoint. This mechanism guarantees data sequence synchronisation between data transmitter and receiver across multiple transactions. Synchronisation is achieved via use of the DATA0 and DATA1 159 TPR0327AY-SMS-30Jan09 PIDs and separate data toggle sequence bits for the data transmitter and receiver. Receiver sequence bits toggle only when the receiver is able to accept data and receives an error-free data packet with the correct data PID. Transmitter sequence bits toggle only when the data transmitter receives a valid ACK handshake. Data toggle synchronization is not supported for isochronous transfers. 14.4 Attachment Procedure This procedure must be applied in order to connect the pull-up between the USB signal D+ and USBReg, thus identifying a Full-Speed USB device. The USB hardware module integrates the attachment pull-up resistors connected between the USB D+ differential data line and the internal 3.3 V USB regulator (USBReg). The serial resistors required by USB certification are not embedded in the USB hardware module. They must be added externally. Note Note Even after reset, the pull-up is not connected. This operation must be controlled by the software in order to attach the device. We can imagine two integration scenarios for AT90SCR100: * If the AT90SCR100 is standalone USB device Smart Card reader, then, connecting the USB cable into a computer, for instance, will power up the AT90SCR100. After chip initialization, PLL running, the USB module can be enabled using USBCR.USBE bit, set attachement pullup can also be set to make the host detect a full-speed peripheral. The host will then reset the communication, and the FEURI interruption will trigger. A enumeration procedure can finally go ahead naturally. * If the AT90SCR100 can be controlled by different hosts, for example by USART and USB, and if the host detection must be done dynamically, then a specific detection must be initiated. After chip power up, communication modules initialisation and PLL activation, the interruption on USART and USB (in the example) must be activated. The attachement pull-up must be enabled. Then, the first interruption (USBPI.FEURI or USART reception) will indicate the host communication mode. Please note that in this case, the D- line may be in High-Z state, making the USB module consumpts until the USB module is disabled or communication is runnning. To prevent consumption issue, a resistor or 1MegaOhm should be place as pull-up on USB D- line. 14.5 USB Interrupts The USB interrupt sources are split into two main families: * The USB Protocol Interrupts (Falling Edge on USB Reset, Start Of Frame, Resume, Suspend). They are included into the USBPI register (see "USBPI - USB Protocol Interrupt register" on page 165 for further details). * The USB Endpoint Interrupt (Endpoint0, 1, 2, 3, 4, 5, 6 and 7). They are included into the USBEI register (see "USBEI - USB Endpoint Interrupt Register" on page 166 for further details). This register only indicates which endpoint of the eight holds the source of the interruption. The source of the interruption can then be retrieved by checking the register USBCSEX corresponding to the endpoint (see "USBCSEX - USB Control And Status 160 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Register for Endpoint X" on page 167 for further details). These sources are Stall sent, Setup packet received, Data received, Data sent events. The AT90SCR100 has two interrupt vectors for both families. These vectors, called USB Endpoint and USB Protocol are only valid if the chip operates with the USB interface and are respectively located at addresses $003E and $0040. Every source can be enabled/disabled through bits of USBEIM or USBPIM registers. A USB interrupt is triggered assuming bits SREG.I is set (one) in order to enable the interrupt. Note The figure below shows the implications between the registers, the USB interrupt sources and the AVR interrupt logic. For further details about the AVR Interrupt Logic please refer to Section 10. "Interrupts" on page 63. Figure 14-2. USB Interrupt Hierarchy PROTOCOL INTERRUPT USBPI FEURI SOFI RMWUI RESI SUSI USBEI USBPIM LOGICAL OR AVR INTERRUPT LOGIC FEURIM SOFIM RMWUIM RESIM SUSIM USBEIM EP7I EP6I EP5I EP4I EP3I EP2I EP1I EP0I USB PROTOCOL UCSE7 UCSE6 UCSE5 UCSE4 UCSE3 UCSE2 UCSE1 UCSE3 UCSE0 UCSE3 ENDPOINT INTERRUPT EP7IM EP6IM EP5IM EP4IM EP3IM EP2IM EP1IM EP0IM USB ENDPOINT 14.6 Suspend and Resume Modes In order to be compliant with the USB specifications V2.0, a device has to support the low-power consumption state called Suspend and its associated resumption activity called Resume. The AT90SCR100 enters the Suspend mode only when requested by the host through bus inactivity for at least 3ms. 161 TPR0327AY-SMS-30Jan09 The USB module is able to detect this request and automatically sets the bit USBPI.SUSI. See "USBPI - USB Protocol Interrupt register" on page 165. This event generates a USB interruption if the Suspend Interrupt source is not masked and if the USB interrupt is enabled. In order to support the power consumption threshold fixed by the USB specifications, the oscillator is switched off by hardware. The POWER-DOWN mode must be entered by setting appropriate configuration in SMCR and followed by a SLEEP instruction. Note Once Suspend mode has been entered, the USB module is able to detect a Resume request. This event immediately and automatically makes the chip come out the POWER-DOWN mode and sets (one) bit USBPI.RESI. The fact that bit USBPI.RESI is set (one) triggers a new USB interrupt if the Resume Interrupt source is not masked and if the USB interrupt is enabled. The application software shall then clear the interrupt source in its interrupt service routine. When a Resume signal has been detected the USB module does not automatically restarts the internal oscillator. See "Important note about: Entering and Leaving low consumption modes" on page 47. Note 14.6.1 Remote Wake-up The USB Module is also able to generate a remote wake-up signal (K signal) to raise the communication with the host. To enable this feature, the USBGS.RMWUE bit must be set. The wake-up signal start to be generated by setting the bit USBCR.URMWU bit. As soon as this bit is set, a protocol interrupt is generated, if USBPIM.RMWUIM bit is set. through the raise of USBPI.RMWUI flag. The remote wake-up signal will be automatically stopped after ~13ms generation. As soon as the signal stops, the USBGS.RSMON bit is cleared. When the USBGS.RSMON bit is cleared, do not forget to clear USBCR.URMWU bit, for next Remote Wake Up sequence. Note Below is a scheme showing all the signal for Remote Wake Up management. Figure 14-3. Remote Wake Up State Sequence Description Enable the feature... USBGS.RMWUE ...Start the WakeUp Signal generation... USBCR.URMWU Control to be cleared by software ...and wait the end of the generation. USBGS.RMSON ~13ms USBPI.RMWUI Flag to be cleared by software 162 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 14.7 Double Buffering This special feature available on the endpoints 1, 2 and 3 allows the user to save time during USB transfers. It is specially recommended for BULK data transfers but is also suitable for ISOCHRONOUS or INTERRUPT. CONTROL is not possible on these double buffered endpoints. The double buffering uses two different data banks of the endpoint size. Its management remains transparent for the user. The advantages of the double buffering are the followings: * When receiving data from the host, the software can process the data received in one of the two banks while the second is being filled. The endpoints that do not have the double buffering capability must wait for their DPRAM to be emptied by the software before being ready to receive new data. * When sending data to the host, the software can fill the free bank while the USB module is sending data from the other one. The endpoints that do not have this feature must wait for the previous data to be sent before being allowed to fill again the single bank. The two following figures provide code algorithm for sending data to the host and receiving data from the host (respectively IN and OUT tokens). They are also valid for endpoints operating normally (without the double buffering capability). Figure 14-4. Sending Data Packets (Single Buffering) NO USBCSEX.TXPB = 0 ? YES FILL DPRAM SET bit USBCSEX.TXPB YES USBCSEX.TXPB = 0 ? NO NO USBCSEX.TXC = 1 ? (POLLING or INTERRUPT) YES CLEAR bit USBCSEX.TXC LAST DATA PACKET REACHED ? YES END NO Note The figure is correct if several data packets have to be sent. If only one packet is to be sent the testing of the bit USBCSE.TXPB must be ignored. 163 TPR0327AY-SMS-30Jan09 Figure 14-5. Receiving Data Packets USBCSEX.RCVD = 1 ? (POLLING or INTERRUPT) READ register USBDBCEX -> NbBytes NO READ DPRAM to get NbBytes Bytes of data CLEAR UCSEX.RCVD END 14.8 14.8.1 USB Device Registers Description USBCR - USB Control Register Bit $0000E0 Read/write Initial value 7 URMWU R/W 0 6 R 0 5 UPUC R/W 0 4 R 0 3 R 0 2 R 0 1 USBE R/W 0 0 R 0 0x00 USBCR * Bit 7 - URMWU : USB Remote Wake up bit When in suspend mode, setting this bit to one generates a wake-up command to the host, according to USB2.0 specifications. This bit must be cleared by software when USBGS.RSMON is cleared. See "Remote Wake-up" on page 162. * Bit 6 - Res : Reserved Bit This bit is reserved bits in the AT90SCR100 and is always read as zero. * Bit 5 - UPUC : USB Pull-Up Connection Bit This bit is set (one) and cleared (zero) by software. It directly acts on the connection of the USB pull-up attachment resistors between USB bus signal D+ and VREG. If set (one) the pull-up is connected. If cleared (zero) the pull-up is not connected. * Bit 4..2 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. 164 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 1 - USBE : USB Enable Bit You must clear this bit before using it, even if the USB module has not been used previously. Set this bit to enable the USB controller. Clear this bit to disable and reset the USB controller, to disable the USB transceiver and to disable the USB controller clock inputs. Clearing the USBE bit will freeze the USB macro the same way as PRR1.PRUSB. Anyway, these two bits are independant, and for the USB macro to run, USBE must be set and PRUSB must be cleared. See "PRR1 - Power Reduction Register 1" on page 46. Note * Bit 0 - Res : Reserved Bit This bit is reserved and will always be read as zero. 14.8.2 USBPI - USB Protocol Interrupt register The following interrupt sources are all sources for the USB Protocol interruption Bit $0000E1 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 FEURI R/W 0 3 SOFI R/W 0 2 RMWUI R/W 0 1 RESI R/W 0 0 SUSI R/W 0 0x00 USBPI * Bits 7..5 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bit 4 - FEURI : Falling Edge on USB Reset Interrupt Bit Set (one) by hardware when a falling edge on the USB Reset has occurred. This bit indicates the end of the USB bus Reset signaling. This interruption is not maskable at the USBPIM register level (see "USBPIM - USB Protocol Interrupt Mask Register" on page 166). Cleared (zero) by software. * Bit 3 - SOFI : Start Of Frame Interrupt Bit Set (one) by hardware when a Start Of Frame PID has been detected on the USB bus. Cleared (zero) by software. * Bit 2 - RMWUI :Remote WakeUp Interrupt Bit Set (one) byt hardware when the USBCR.URMWU bit is set. Cleared (zero) by software. * Bit 1 - RESI : Resume Interrupt Bit Set (one) by hardware when a USB Resume signal has been detected on the USB bus. Cleared (zero) by software. * Bit 0 - SUSI : Suspend Interrupt Bit Set (one) by hardware when a USB Suspend signal has been detected on the USB bus. 165 TPR0327AY-SMS-30Jan09 Cleared (zero) by software. These bits can also be set (one) by software. Note 14.8.3 USBPIM - USB Protocol Interrupt Mask Register Bit $0000E2 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 SOFIM R/W 0 2 RMWUIM R/W 0 1 RESIM R/W 1 0 SUSIM R/W 0 0x02 USBPIM See "USBPI - USB Protocol Interrupt register" on page 165. * Bits 7..4 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bit 3 - SOFIM : Start Of Frame Interrupt Mask Bit When SOFIM is set (one) the Start Of Frame interrupt is enabled. When SOFIM is cleared (zero) the Start Of Frame interrupt is masked. * Bit 2 - RMWUIM : Remote Wake-Up Interrupt Mask Bit When RMWUIM is set (one), the Remote WakeUp interrupt is enabled. When RMWUIM is cleared (zero), the Remote WakeUp interrupt is disabled. * Bit 1 - RESIM : Resume Interrupt Mask Bit When RESIM is set (one) the Resume interrupt is enabled. When RESIM is cleared (zero) the Resume interrupt is masked. * Bit 0 - SUSIM : Suspend Interrupt Mask Bit When SUSIM is set (one) the Suspend interrupt is enabled. When SUSIM is cleared (zero) the Suspend interrupt is masked. 14.8.4 USBEI - USB Endpoint Interrupt Register The following interrupt sources are all sources for the USB Endpoint interruption. Bit $0000E3 Read/write Initial value 7 EP7I R 0 6 EP6I R 0 5 EP5I R 0 4 EP4I R 0 3 EP3I R 0 2 EP2I R 0 1 EP1I R 0 0 EP0I R 0 0x00 USBEI * Bit n - EPnI : Endpoint n Interrupt Bit (n=0..7) This bit is set (one) by hardware when an endpoint interrupt condition has occurred on the endpoint n. 166 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 This bit is cleared (zero) by hardware when the endpoint interrupt source has been cleared (zero) by the software (see "USBCSEX - USB Control And Status Register for Endpoint X" on page 167). The endpoint interrupt conditions are listed below and further detailed in "USBCSEX - USB Control And Status Register for Endpoint X" on page 167. They are the same for the seven endpoints ( 0 n 7): * USBCSEn.TXC bit is set in Bulk In, Interrupt In or Control mode. * USBCSEn.RCVD bit is set in Bulk Out, Interrupt Out, Isochronous Out or Control mode. * USBCSEn.RXSETUP is set in Control mode. * USBCSEn.STSENT bit is set in Bulk, Interrupt or Control mode. 14.8.5 USBEIM - USB Endpoint Interrupt Mask Register Bit $0000E5 Read/write Initial value 7 EP7IM R/W 0 6 EP6IM R/W 0 5 EP5IM R/W 0 4 EP4IM R/W 0 3 EP3IM R/W 0 2 EP2IM R/W 0 1 EP1IM R/W 0 0 EP0IM R/W 0 0x00 USBEIM Note See "USBEI - USB Endpoint Interrupt Register" on page 166. * Bit n - EPnIM : Endpoint n Interrupt Mask Bit (n=0..7) When EPnIM is set (one) the Endpoint n interrupt is enabled. When EPnIM is cleared (zero) the Endpoint n interrupt is masked. 14.8.6 USBENUM - USB Endpoint Number Register Bit $0000CA Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 R/W 0 2 1 ENUM [2..0] R/W 0 R/W 0 0x00 0 USBENUM * Bit 7..3 - Res : Reserved Bits These bits are reserved and are always read as zero. * Bit 2..0 - ENUM2..0 : Endpoint Number Use this register to select an endpoint. The USB Device registers ended by a X correspond then to this number. 14.8.7 USBCSEX - USB Control And Status Register for Endpoint X Set USBENUM register to point to the relevant Endpoint before using the USBCEX register. Bit $0000CB Read/write Initial value 7 R 0 6 IERR R 0 5 FSTALL R/W 0 4 TXPB R/W 0 3 R/W 0 2 R/W 0 1 RCVD R/W 0 0 TXC R/W 0 0x00 USBCSEX STSENT RXSETUP 167 TPR0327AY-SMS-30Jan09 * Bit 7 - Res : Reserved Bit This bit is a reserved bit in the AT90SCR100 and is always read as zero. * Bit 6 - IERR : Isochronous Error Bit This bit is a status bit. It is set (one) by hardware when the CRC of a packet received in an Isochronous transfer is incorrect or corrupted. If the CRC is correct the bit is cleared (zero) by hardware. This bit is not a source for the Endpoint interrupt. * Bit 5 - FSTALL : Force Stall Bit This bit is a control bit. It is set (one) and cleared (zero) by software. If it is set (one) the corresponding endpoint is stalled and the host immediately receives a STALL as response to the IN or OUT tokens sent to this endpoint (see procedure on next page). If it is cleared (zero) the corresponding endpoint is not stalled. This bit is not a source for the Endpoint interrupt. * Bit 4 - TXPB : Tx Packet Busy Bit This bit is a control bit. It is set (one) by software and cleared (zero) by hardware. If it is cleared (zero), the DPRAM bank corresponding to the endpoint is empty. It can then be filled with data to be sent. If it is set (one), the data present in the DPRAM bank is sent. This bit is not a source for the Endpoint interrupt. * Bit 3 - STSENT : Stall Sent Bit This bit is a status bit. It is set (one) by hardware and cleared (zero) by software. If it is set (one), a STALL has been sent from the corresponding endpoint to the host through the USB bus. This bit is a source for the Endpoint interrupt and must be cleared to acknowledge the interruption. * Bit 2 - RXSETUP : Rx Setup Bit This bit is a status bit. It is set (one) by hardware and cleared (zero) by software. If it is set (one) and if the corresponding endpoint operates with Control mode transfers, a valid Setup packet has been received from the host through the USB bus. This bit is a source for the Endpoint interrupt and must be cleared to acknowledge the interruption. 168 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 1 - RCVD : Received Data Bit This bit is a status bit. It is set (one) by hardware and cleared (zero) by software. If it is set (one), the DPRAM of the corresponding endpoint is filled with data coming from the host through the USB bus. This bit is a source for the Endpoint interrupt and must be cleared to acknowledge the interruption. * Bit 0 - TXC : Tx Complete Bit This bit is a status bit. It is set (one) by hardware and cleared (zero) by software. If it is set (one), an ACK handshake from the host has been received on the corresponding endpoint through the USB bus. This bit is a source for the Endpoint interrupt and must be cleared to acknowledge the interruption. 14.8.8 USBDBCEX - USB Data Byte Count Registers for Endpoint X Set USBENUM register to point to the relevant Endpoint before using the USBDBCEX register. If a packet of data has been received from the host in the corresponding endpoint through the USB bus, these registers indicate the amount of data bytes available in the DPRAM. The value is considered valid if the bit USBCSEX.RCVD has been previously set by hardware. Bit $0000CC Read/write Initial value 7 BCT7 R/W 0 6 BCT6 R/W 0 5 BCT5 R/W 0 4 BCT4 R/W 0 3 BCT3 R/W 0 2 BCT2 R/W 0 1 BCT1 R/W 0 0 BCT0 R/W 0 0x00 USBDBCEX * Bits 7..0 - BCT7..0 : Bytes Count Bits These bits are set (one) and cleared (zero) by hardware. 14.8.9 USBFCEX - USB Function Control Registers for Endpoint X Set USBENUM register to point to the relevant Endpoint before using the USBFCEX register. Bit $0000CD Read/write Initial value 7 EPE R/W 0 6 R 0 5 R 0 4 R 0 3 R 0 2 EPDIR R/W 0 1 R/W 0 0 R/W 0 0x00 EPTYP1 EPTYP0 USBFCEX * Bits 7 - EPE : Endpoint Enable Bit This bit is set (one) and cleared (zero) by software. When it is set (one) the corresponding endpoint is enabled. When it is cleared (zero) the corresponding endpoint is disabled. A disabled endpoint does not respond when addressed (read or written) by the host. 169 TPR0327AY-SMS-30Jan09 At USB reset, EPE for endpoint 0 (USBFCEX.EPE for USBENUM=0) is automatically set by hardware. * Bits 6..3 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bit 2- EPDIR : Endpoint Direction Bit This bit is set (one) and cleared (zero) by software. This bit indicates the direction of the endpoint and is not valid for endpoints operating in Control transfer mode as this type of transfer occurs in both direction. If it is set (one), the endpoint direction is IN. If it is cleared (zero), the endpoint direction is OUT. * Bits 1..0 - EPTYP0 EPTYP1 : Endpoint Type Bits These bits are set (one) and cleared (zero) by software. These bit indicate the type of USB data transfer of the corresponding endpoint. See table below for the values available: Table 15-1 .Endpoint Types Selection EPTYP1 0 0 1 1 EPTYP0 0 1 0 1 Transfer Control Isochronous Bulk Interrupt 14.8.10 USBRSTE - USB Reset Endpoint Register Bit $0000E5 Read/write Initial value 7 RSTE7 R/W 0 6 RSTE6 R/W 0 5 RSTE5 R/W 0 4 RSTE4 R/W 0 3 RSTE3 R/W 0 2 RSTE2 R/W 0 1 RSTE1 R/W 0 0 RSTE0 USBRSTE R/W 0 0x00 * Bits 7..0 - RSTE7..0 : Reset Endpoint 7..0 Bits These bits are set (one) by software and cleared (zero) by hardware. Each endpoint has its corresponding bit (e.g RSTE3 corresponds to the endpoint 3) which is used to reset the endpoint. When resetting an endpoint, the following actions are performed: * Reset the DPRAM address pointers. * Set the internal data toggle bit to zero. To reset endpoint n (n=0..7), which is necessary when changing the device configuration and recommended when receiving a USB bus Reset signaling (before starting the enumeration operations), the following procedure shall be applied: 1. Clear (zero) USBRSTE.RSTEn. 2. Set (one) bit USBRSTE.RSTEn. 170 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 3. Wait for USBRSE.RSTEn to be cleared (zero) by hardware (polling). 14.8.11 USBGS - USB Global State Register Bit $0000E6 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 RSMON R 0 2 RMWUE R/W 0 1 FCF R/W 0 0 FAF R/W 0 0x00 USBGS * Bits 7..4 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bits 3 - RSMON : Resume Signal ON This bit is set and cleared by hardware. Set by hardware when a resume is sent to the USB host during remote wake-up sequence. Automatically cleared when the resume signal emission is halted (last ~13ms). * Bits 2 - RMWUE : Remote Wake-Up Enable This bit is set and cleared by software. Set this bit to enable the remote wake-up feature. * Bit 1 - FCF : Function Configured Flag Bit This bit is cleared (zero) by the hardware when a USB Reset signaling is received. The software must set (one) this bit after receiving a valid SET_CONFIGURATION request from the host unless it is equal to zero. The software must clear (zero) this bit after receiving a valid SET_CONFIGURATION request from the host with a zero value. * Bit 0 - FAF : Function Addressed Flag Bit This bit is cleared (zero) by the hardware when a USB Reset signaling is received. The software must set (one) this bit after receiving a valid SET_ADDRESS request from the host. 14.8.12 USBFA - USB Function Address Register Bit $0000E7 Read/write Initial value 7 R 0 6 FADD6 R/W 0 5 FADD5 R/W 0 4 FADD4 R/W 0 3 FADD3 R/W 0 2 FADD2 R/W 0 1 FADD1 R/W 0 0 FADD0 R/W 0 0x00 USBFA * Bit 7 - Res : Reserved Bit : This bit is reserved bit in the AT90SCR100 and is always read as zero. * Bits 6..0 - FADD6..0 : Function Address Register 6..0 Bits These bits are cleared (zero) by the hardware when a USB Reset is received. 171 TPR0327AY-SMS-30Jan09 The software must update these bits with the address value received during a valid SET_ADDRESS request. It must then set (one) the bit USBGS.FAF (see "USBGS - USB Global State Register" on page 171). 14.8.13 USBFN - USB Frame Number Registers Bit $0000E9 $0000E8 Bit Read/write Initial value 15 FN7 7 R R 0 0 14 FN6 6 R R 0 0 13 FN5 5 R R 0 0 12 FNEND FN4 4 R R 0 0 11 FNERR FN3 3 R R 0 0 10 FN10 FN2 2 R R 0 0 9 FN9 FN1 1 R R 0 0 8 FN8 FN0 0 R R 0 0 0x00 0x00 USBFNH USBFNL * Bits 15..13 - Res: Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bit 12 - FNEND : Frame Number End Bit This bit is set (one) and cleared (zero) by hardware. This bit is set (one) when an End Of Packet Start Of Frame (SOF) transaction has occurred. This bit is cleared (zero) by the next detected SOF. * Bit 11 - FNERR : Frame Number Error Bit This bit is set (one) and cleared (zero) by hardware. This bit is set (one) if the last Frame Number Field received is corrupted. Otherwise it is cleared (zero). * Bits 10..0 - FN10..0 : Frame Number Bits These bits are set (one) and cleared (zero) by hardware. These bits represent the Frame Number value. The Frame Number value represented by the eleven bits USBFNH.FN2..0 and USBFNL.FN7..0 should only be read when bit USBFNH.FNEND is set (one). Note 14.9 USBDMA Controller The USBDMA controller, implemented on the AT90SCR100, is intended to be used for executing fast transfers between the RAM memory and the DPRAM (Dual Port RAM) which is dedicated to the USB endpoints. This feature allows the application software of the AT90SCR100 to manage the exchanges imposed by the USB protocol. All the USB registers described in this section cannot be accessed if the USB module is not enabled. ! Caution 172 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The USBDMA controller basically requires four I/O registers to run and can be configured either to send or to receive data through the USB bus. Actually, its main purpose is to transfer data between the RAM of the AT90SCR100 and the DPRAM of the USB module. Very easy to use, it just requires the application software to select an endpoint (which can be the source or the destination), to set a valid base address in RAM (which can be the source or the destination), to fix the amount of data to be exchanged and the direction of the transfer. One USBDMA operation can transfer up to N bytes in (N+1) AVR cycles. Figure 14-6. USBDMA Controller Diagram USBDMACS.DMADIR USBDMACS.EPS2:0 USBDMACS.DMAERR RAM $10FF 000 USBDMACS.DMAR 0 1 DMAD DMAB 0 1 001 010 011 $100 100 101 110 DMA Controller Diagram 111 DPRAM Endpoint 0 (64 Bytes) Endpoint 1 (2x64 Bytes) Endpoint 2 (2x64 Bytes) Endpoint 3 (2x64 Bytes) Endpoint 4 (8 Bytes) Endpoint 5 (8 Bytes) Endpoint 6 (8 Bytes) Endpoint 7 (8 Bytes) Even if not represented above, the exchanges between the RAM and the DPRAM are controlled by the USB USBFI (see "USB Module Diagram" on page 34). Note When a USBDMA operation is started, the AVR is automatically stopped. At the end of the USBDMA operation, the application software automatically restarts where it left (actually with the instruction following the launching of the USBDMA operation). Thus the application software does not need to wait for an interruption or to poll the end of the USBDMA operation. 14.9.1 USBDMACS - USBDMA Control and Status Register This is the control and status register of the USBDMA controller. Bit $0000EA Read/write Initial value 7 R 0 6 EPS2 R/W 0 5 EPS1 R/W 0 4 EPS0 R/W 0 3 R 0 2 R/W 0 1 R/W 0 0 R/W 0 0x00 USBDMAERR USBDMAIR USBDMAR USBDMACS * Bit 7 - Res : Reserved Bit This bit is reserved in the AT90SCR100 and is always read as zero. * Bit 6..4 - EPS2..0 : Endpoint Selection Bits 173 TPR0327AY-SMS-30Jan09 These bits are set (one) and cleared (zero) by software. They are used to select the source or destination endpoint for the next USBDMA operation. A violation is triggered if a USBDMA operation is launched with 0 byte to transfer or when USBMACS.EPS2:0 value is more than 4. Endpoint Selection Bits EPS1 0 0 1 1 0 0 1 1 EPS0 0 1 0 1 0 1 0 1 Endpoint Selected Endpoint 0 Endpoint 1 Endpoint 2 Endpoint 3 Endpoint 4 Endpoint 5 Endpoint 6 Endpoint 7 Endpoint Size (Bytes) 64 2x64 2x64 64 8 8 8 8 Note Table 14-2. EPS2 0 0 0 0 1 1 1 1 * Bit 3 - Res : Reserved Bit This bit is reserved in the AT90SCR100 and is always read as zero. * Bit 2 - USBDMAERR : USB DMA Error Bit When launching the USBDMA controller, this bit is cleared (zero) by the hardware if the values into USBDMADH, USBDMADL and USBDMAB registers are suitable for the USBDMA operation requested. This bit can also be cleared(zero) by software. This bit is set (one) by hardware when starting a USBDMA operation and whenever one of these following cases occurs: * The base address contained in the registers USBDMADH and USBDMADL is incorrect (out of the allowed range). * According to the values of the registers USBDMADH, USBDMADL and USBDMAB and even if the base address is correct, an address out of the allowed range is going to be reached. * The value in the register USBDMAB is greater than the size of the selected endpoint for the USBDMA operation (see bits USBDMACS.EPS2:0 below). When this bit is set, and if the USB unterruptions are enabled, a USB interruption is generated. Don't forget to clear the USBDMACS.DMAERR bit before leaving the interruption routine to avoid repetitive and endless interruptions. ! Caution * Bit 1 - USBDMADIR : USB DMA Direction Bit This bit is set (one) and cleared (zero) by software. It indicates the direction of the next USBDMA operation transfer between the RAM memory and the selected endpoint (represented by the bits USBDMACS.EPS2:0): 174 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * If the bit is set (one), the transfer will be from the RAM memory to the selected endpoint (emission mode). * If the bit is cleared (zero), the transfer will be from the selected endpoint to the RAM memory (receiving mode). * Bit 0 - USBDMAR : USB DMA Run Bit This bit is set (one) by software and cleared (zero) by hardware. This bit controls the USBDMA operation launching. It is set (one) by software when a USBDMA operation is to be performed. It is cleared (zero) by hardware at the end of the operation. The software does not need to poll this bit in order to detect the end of the USBDMA operation. Indeed, when the USBDMACS.DMAR bit is set by the software, the AVR is automatically stopped. When the end of the USBDMA operation is reached, the AVR then automatically executes the instructions following the setting of the bit USBDMACS.DMAR. A USBDMA operation can not be interrupted because the CPU is not available during this time. Note Note 14.9.2 USBDMAD - USBDMA ADdress Registers Bit $0000EC $0000EB Bit Read/write Initial value 7 R R/W 0 0 6 R R/W 0 0 5 R/W R/W 0 0 15 14 4 R/W R/W 0 0 13 12 11 10 9 8 USBDMADH USBDMADL 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 1 0 0x01 0x00 USBDMAD [13..8] USBDMAD [7..0] 3 R/W R/W 0 0 * Bits 15..14 - Res : Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bits 13..0 - USBDMAD13..0 : DMA Address These bits represents the 14-bit USBDMA Address. These two registers set the base address in RAM. This address represents the source of the data to be sent if the USBDMA controller is configured in the emission mode. It represents the destination to store the data if the USBDMA controller is configured in the receiving mode. The initial value corresponds to RAM address $000100. You can address the whole RAM with this parameter. Values in RAM that must not be dumped, shall be stored out of the USBDMA RAM accessible range. When starting a USBDMA operation, the hardware will check if the values of USBDMADH, USBDMADL and USBDMAB registers does not exceed the specific RAM area ($000100 to $0010FF). If an error is detected, USBDMACS.DMAERR bit is automatically set (one). A Super- 175 TPR0327AY-SMS-30Jan09 visor RAM Illegal Access Attempt Violation security interrupt (if not masked) is so triggered. USBDMADH, USBDMADL and USBDMAB registers keep their previous value. After a USBDMA operation, USBDMADH and USBDMADL are set to the last value reached in RAM and incremented by one. For instance, after a 64-byte transfer started from base address $000100, USBDMAD equals to $000140 (USBDMADH = $01 and USBDMADL = $40). This feature allows to simplify registers and bits handlings when several USBDMA operations are to be successively performed, which can be the case when getting or sending several packets. Note 14.9.3 USBDMAB - USBDMA Amount of Bytes Register This register is dedicated to the amount of bytes to be transferred during the next USBDMA operation setting. Bit $0000ED Read/write Initial value 7 R 0 R/W 0 R/W 0 R/W 0 6 5 4 3 USBDMAB [6..0] R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 USBDMAB * Bit 7 - Res : Reserved Bit This bit is reserved bit in the AT90SCR100 and is always read as zero. * Bits 6..0 - USBDMAB6..0 : DMA Amount of Bytes Bits These bits are the (6..0) bits of the 7-bit USBDMA Amount of Bytes value. When starting a USBDMA operation, the hardware will check if the values of USBDMADH, USBDMADL and USBDMAB registers does not exceed the specific RAM area ($000100 to $0010FF). If an error is detected, USBDMACS.DMAERR bit is automatically set (one). A Supervisor RAM Illegal Access Attempt Violation security interrupt (if not masked) is so triggered. USBDMADH, USBDMADL and USBDMAB registers keep their previous value. After a USBDMA operation completion, the value of this register is not reset. Note The maximum value allowed for USBDMAB depends on the endpoint selected. 176 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 15. Smart Card Interface Block (SCIB) The SCIB provides all signals to interface directly with a smart card. The compliance with the ISO7816, EMV'2000 and GSM standards has been certified. Also, the WHQL standard can be achieved with an appropriate software. 15.1 Features * * * * * * * * * * * * Support of ISO/IEC 7816 Performances: Up to 3 cycles per etu, and ISO clock up to 4.8Mhz Frequency up to 12Mhz Character mode One transmit/receive buffer 11 bits ETU counter 9 bits guard time counter 32 bits waiting time counter Auto character repetition on error signal detection in transmit mode Auto error signal generation on parity error detection in receive mode Power off sequence generation Manual mode to drive directly the card I/O 15.2 Overview All synchronous (e.g. memory card), asynchronous and USB smart cards (e.g. microprocessor card) are supported. The component supplies the different voltages requested by the smart card. The power_on and power_off sequence is directly managed by the SCIB. To enable the communication on CC4/CC8 with USB smart cards, the USB Host Controller must be enabled. The card presence switch of the smart card connector is used to detect card insertion or card removal. In the case of card removal, the SCIB deactivates the smart card using the deactivation sequence. An interrupt can be generated when a card is inserted or removed. Any malfunction is reported to the microcontroller (interrupt + control register). The different operating modes are configured by internal registers. 15.3 Block Diagram The Smart Card Interface Block diagram is shown Figure 15-1: 177 TPR0327AY-SMS-30Jan09 Figure 15-1. SCIB Block Diagram Barrel Shifter CIO (in) clk SCI CIO (out) Etu Counter CCLK Guard Time Counter Scart fsm I/O Mux CRST CC4 (out) CC8 (out) Waiting Time Counter SCI Registers CC4 (in) CC8 (in) INT Interrupt Generator Power_on Power_off fsm VCARD 15.4 Definitions This paragraph introduces some of the terms used in ISO 7816-3 and EMV standards. Please refer to the full standards for a complete list of terms. Terminal and ICC Terminal is the reader, ICC is the Integrated Circuit Card ETU Elementary Timing Unit (Bit time) T=0 Character oriented half duplex protocol T=0 T=1 Block oriented half duplex protocol T=1 Activation: Cold Reset Reset initiated by the Terminal with Vcc power-up. The card will answer with ATR (see below) Activation: Warm Reset Reset initiated by the Terminal with Vcc already powered-up, and after a prior ATR or Warm Reset 178 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 De-Activation Deactivation by the Terminal as a result of : unresponsive ICC, or ICC removal. ATR Answer To Reset. Response from the ICC to a Reset initiated by the Terminal F and D F = Clock Rate Conversion Factor, D = Bit rate adjustment factor. ETU is defined as : ETU = F/(D*f) with f = Card Clock frequency. If f is in Hertz, ETU is in second. F and D are available in the ATR (byte TA1). The default values are F=372, D=1. Guard Time The time between 2 leading edges of the start bit of 2 consecutive characters is comprised of the character duration (10) plus the guard time. Be aware that the Guard Time counter and the Guard Time registers in the AT90SCR100 consider the time between 2 consecutive characters. So the equation is Guard Time Counter = Guard Time + 10. In other words, the Guard Time is the number of Stop Bits between 2 characters sent in the same direction. Extra Guard Time ISO IEC 7816-3 and EMV introduce the Extra Guard time to be added to the minimum Guard Time. Extra Guard Time only apply to consecutive characters sent by the terminal to the ICC. The TC1 byte in the ATR define the number N. For N=0 the character to character duration is 12 ETUs. For N=254 the character to character duration is 266. For N=255 (special case) The minimum character to character duration is to be used : 12 for T=0 protocol and 11 for T=1 protocol. Block Guard Time The time between the leading edges of 2 consecutive characters sent in opposit direction. ISO IEC 7816-3 and EMV recommend a fixed Block Guard Time of 22 ETUs. Work Waiting Time (WWT) In T=0 protocol WWT is the interval between the leading edge of any character sent by the ICC, and the leading edge of the previous character sent either by the ICC or the Terminal. If no character is received by the terminal after WWTmax time, the Terminal initiates a deactivation sequence. Character Waiting Time (CWT) In T=1 protocol CWT is the interval between the leading edge of 2 consecutive characters sent by the ICC. If the next character is not received by the Terminal after CWTmax time, the Terminal initiates a deactivation sequence. Block Waiting Time (BWT) In T=1 protocol BWT is the interval between the leading edge of the start bit of the last character sent by the Terminal that gives the right to sent to the ICC, and the leading edge of the start bit of the first character sent by the ICC. If the first character from the ICC is not received by the Terminal after BWTmax time, the Terminal initiates a deactivation sequence. Waiting Time Extention (WTX) In T=1 protocol the ICC can request a Waiting Time Extension with a S(WTX request) request. The Terminal should acknowlege it. The Waiting time between the leading edge of the start bit of 179 TPR0327AY-SMS-30Jan09 the last character sent by the Terminal that gives the right to sent to the ICC, and the leading edge of the start bit of the first character sent by the ICC will be BWT*WTX ETUs. Parity error in T=0 protocol In T=0 protocol, a Terminal (respectively an ICC) detecting a parity error while receiving a character shall force the Card IO line at 0 starting at 10.5 ETUs, thus reducing the first Guard bit by half the time. The Terminal (respectively an ICC) shall maintain a 0 for 1 ETU min and 2 ETUs max (according to ISO IEC) or to 2 ETUs (according to EMV). The ICC (respectively a Terminal) shall monitor the Card IO to detect this error signal then attempt to repeat the character. According to EMV, following a parity error the character can be repeated one time, if parity error is detected again this procedure can be repeated 3 more times. The same character can be transmitted 5 times in total. ISO IEC7816-3 says this procedure is mandatory in ATR for card supporting T=0 while EMV says this procedure is mandatory for T=0 but does not apply for ATR. 15.5 15.5.1 Functional Description The architecture of the Smart Card Interface Block can be detailed as follows: Barrel Shifter The Barrel Shifter performs the translation between 1 bit serial data and 8-bit parallel data. The barrel function is useful for character repetition as the character is still present in the shifter at the end of the character transmission. This shifter is able to shift the data in both directions and to invert the input or output value in order to manage both direct and inverse ISO7816-3 convention. Coupled with the barrel shifter is a parity checker and generator. There are 2 registers connected to this barrel shifter, one for the transmission and one for the reception. They act as buffers to relieve the CPU of timing constraints. 15.5.2 SCART FSM (Smart Card Asynchronous Receiver Transmitter Finite State Machine) This is the core of the block. Its purpose is to control the barrel shifter. To sequence correctly the barrel shifter for a reception or a transmission, it uses the signals issued by the different counters. One of the most important counters is the guard time counter that gives time slots corresponding to the character frame. The SCART FSM is enabled only in UART mode. See "SCICR - Smart Card Interface Control Register" on page 190. The transition from reception mode to the transmission mode is done automatically. Priority is given to the transmission. Transmission refers to Terminal transmission to the ICC. Reception refers to reception by the Terminal from the ICC. 15.5.3 ETU Counter The ETU (Elementary Timing Unit) counter controls the operating frequency of the barrel shifter, in fact it generates the enable signal of the barrel shifter. It receives the Card Clock, and generates the ETU clock. The Card Clock frequency is called "f" below. The ETU counter is 11 bit wide. A special compensation mode can be activated. It accomodates situations where the ETU is not an integer number of Card Clock (clkSCI). The compensation mode is controlled by the COMP bit 180 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 in SCETUH register bit position 7. With COMP=1 the ETU of every character even bits is reduced by 1 Card Clock period. As a result, the average ETU is : ETU_average = (ETU - 0.5). One should bear in mind that the ETU counter should be programmed to deliver a faster ETU which will be reduced by the COMP mechanism, not the other way around. This allows to reach the required precision of the character duration specified by the ISO7816-3 standard. Example1 : F=372, D=32 => ETU= F/D = 11.625 clock cycles. We select ETU[10-0] = 12 , COMP=1. ETUaverage= 12 - (0.5*COMP) = 11.5 The result will be a full character duration (10 bit) = (10 - 0.107)*ETU. The EMV specification is (10 +/- 0.2)*ETU 15.5.4 Guard Time Counter The minimum time between the leading edge of the start bits of 2 consecutive characters transmitted by the Terminal is controlled by the Guard Time counter, as described in Figure 15-4. The Guard Time counter is an 9 bit counter. It is initialized to 001h at the start of a transmission by the Terminal. It then increments itself at each ETU until it reaches the 9 bit value loaded into the SCGT register. At this time a new Terminal transmission is enabled and the Guard Time Counter stops incrementing. As soon as a new transmission starts, the Guard Time Counter is re-initialized to 1. The value of the Guard Time Counter cannot be read. Reading SCGT only gives the minimum time between 2 characters that the Guard Time Counter allows. Note Care must be taken with the Guard Time Counter which counts the duration between the leading edges of 2 consecutive characters. This corresponds to the character duration (10 ETU) plus the Guard Time as defined by the ISO and EMV recommendations. To program Guard Time = 2 : 2 stop bits between 2 characters which is equivalent to the minimum delay of 12 ETUs between the leading edges of 2 consecutive characters, SCGT should be loaded with the value 12 decimal. See Figure 15-2. Figure 15-2. Guard Time Transmission to ICC CHAR n+1 CHAR n+2 >= SCGT 15.5.5 Block Guard Time Counter The Block Guard Time counter provides a way to program a minimum time between the leading edge of the start bit of a character received from the ICC and the leading edge of the start bit of a character sent by the terminal. ISO IEC 7816-3 and EMV recommend a fixed Block Guard Time of 22 ETUs. The AT90SCR100 offers the possibility to extend this delay up to 512 ETUs. The Block Guard Time is a 9 bit counter. When the Block Guard Time mode is enabled (BGTEN=1 in SCSR register) the Block Guard Time counter is initialized to 000h at the start of a 181 TPR0327AY-SMS-30Jan09 character receptions from the ICC. It then increments at each ETU until it reaches the 9 bit value loaded into shadow SCGT registers, or until it is re-initialized by the start of an new transmission from the ICC. If the Block Guard Time counter reaches the 9 bit value loaded into shadow SCGT registers, a transmission by the TERMINAL is enabled, and the Block Guard Time counter stops incrementing. The Block Guard Time counter is re-initialized at the start of each terminal transmission. The SCGT shadow registers are loaded with the content of GT[8-0] contained in the registers SCGT with the rising edge of the bit BGTEN in the SCSR register. See Figure 15-4. Figure 15-3. Block Guard Time Reception from ICC CHAR 1 CHAR 2 CHAR n Transmission to ICC Write SCGT with a value for Guard Time CHAR 1 CHAR 2 >= Block Guard Time >= SCGT Write "Block Guard Time" in SCGT register and set the BGTEN to transfer the value to the shadow SCGT register Figure 15-4. Guard Time and Block Guard Time counters ETU Counter Guard Time Counter 9 bits Comparator Transmit Enable 9 bits Shadow SCGTH 9 bits Shadow SCGTL GT[8..0] SCGTH SCGTL Block Guard Time Counter 9 bits Comparator Transmit Enable To illustrate the use of Guard Time and Block Guard Time, consider the ISO/IEC7816-3 recommendation : Guard Time = 2 (minimum delay between 2 consecutive characters sent by the Terminal = 12 ETUs), and Block Guard Time = 22 ETUs. After a smart Card Reset * Write `00' decimal in SCGTH, Write `22' decimal in SCGTL * Set BGTEN in SCSR (BGTEN was 0 before as a result of the smart card reset) * Write `12' decimal in SCGTL Now the Guard Time and Block Guard Time are properly initialized. The TERMINAL will insure a minimun 12 ETUs between 2 leading edges of 2 consecutive characters transmitted. The TERMINAL will also insure a minimum of 22 ETUs between the leading edge of a character sent by 182 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 the ICC, and the leading edge of a character sent by the TERMINAL. There is no need to write SCGT again and again. 15.5.6 Waiting Time (WT) Counter The WT counter is a 32 bits down counter which can be loaded with the value contained in the SCWT3, SCWT2, SCWT1, SCWT0 registers. Its main purpose is timeout signal generation. It is 32 bits wide and is decremented at the ETU rate. see Figure 15-5. When the WT counter times out, an interrupt is generated and the SCIB function is locked: reception and emission are disabled. It can be enabled by resetting the macro or reloading the counter. The Waiting Time Counter can be used in T=0 protocol for the Work Waiting Time. It can be used in T=1 protocol for the Character Waiting Time and for the Block Waiting Time. See the detailed explanation below. Figure 15-5. Waiting Time Counter ETU Counter WTEN Guard Time Counter Timeout Load Write SCWT2 WT [31..0] Uart Start Bit SCWT3 SCWT2 SCWT1 SCWT0 In the so called manual mode, the counter is loaded, if WTEN = 0, during the write of SCWT2 register. The counter is loaded with a 32 bit word built with SCWT3 SCWT2 SCWT1 SCWT0 registers (SCWT0 contains WT[7-0] bytes. WTEN is located in the SCICR register. When WTEN=1 and in UART mode, the counter is re-loaded at each start bit. This mode will be detailed below in T=0 protocol and T=1 protocol. In manual mode, the WTEN signal controls the start of the counter (rising edge) and the stop of the counter (falling edge). After a timeout of the counter, a falling edge on WTEN, a reload of SCWT2 and a rising edge of WTEN are necessary to start again the counter and to release the SCIB macro. The reload of SCWT2 transfers all SCWT0, SCWT1, SCWT2 and SCWT3 registers to the WT counter. In UART mode there is an automatic load on the start bit detection. This automatic load is very useful for changing on-the-fly the timeout value since there is a register to hold the load value. This is the case for T=1 protocol. In T=0 protocol the maximun interval between the start leading edge of any character sent by the ICC and the start of the previous character sent by either the ICC or the Terminal is the maximum Work Waiting Time. The Work Waiting Time shall not exceed 960*D*WI ETUs with D and WI parameters are returned by the field TA1 and TC2 respectively in the Answer To Reset (ATR). This is the value the user shall write in the SCWT0,1,2,3 register. This value will be reloaded in the Waiting Time counter every start bit. 183 TPR0327AY-SMS-30Jan09 Figure 15-6. T=0 mode > GT CHAR 1 CHAR 2 < WT In T=1 protocol : The maximum interval between the leading edge of the start bit of 2 consecutive characters sent by the ICC is called maximum Character Waiting Time. The Character Waiting Time shall not exceed (2*CWI + 11) ETUs with 0 =< BWI =< 5. Consequently 12 ETUs =< CWT =< 43 ETUs. T=1 protocol also specify the maximum Block Waiting Time. This is the time between the leading edge of the last character sent by the Terminal giving the right to send to the ICC, and the leading edge of the start bit of the first character sent by the ICC. The Block Waiting Time shall not exceed (2*BWI*960 + 11) ETUs with 0 =< BWI =< 4. Consequently 971 ETUs =< BWT =< 15371 ETUs. In T=1 protocol it is possible to extend the Block Waiting Time with the Waiting Time Extension (WTX). When selected the waiting time becomes BWT*WTX ETUs. The Waiting Time counter is 32 bit wide to accomodate this feature. It is possible to take advantage of the automatic reload of the Waiting Time counter with a start bit in UART mode (T=1 protocol use UART mode) . If the Terminal sends a block of N characters, and the ICC is supposed to answer immediately after, then the following sequence can be used. While sending the (N-1)th character of the block, the Terminal can write the SCWT0,1,2,3 with BWImax. At the start bit of the Nth character, the BWImax is loaded in the Waiting Time counter During the transmission of the Nth character, the Terminal can write SCWT0,1,2,3 with the CWImax. At the start bit of the first character sent by the ICC, the CWImax will be loaded in the Waiting Time counter. Figure 15-7. T=1 Mode TRANSMISSION Bloc 1 RECEPTION Bloc n CHAR 1 CHAR 2 CHAR n CHAR 1 CHAR 2 CHAR n < BWT < CWT 184 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 15.5.7 Power-on and Power-off FSM The Power-on Power-off Finite State Machine (FSM) applies the signals on the smart card in accordance with ISO7816-3 standard. It drives the Activation (Cold Reset and Warm Reset as well as De-Activation) it also manages the exception conditions such as overcurrent (see DC/DC Converter) To be able to power on the SCIB, the card must be present. After the detection of a card presence, the Terminal initiate a Cold Reset Activation. The Cold Reset Activation Terminal procedure is as follow and the Figure 15-8. Timing indications are given according to ISO IEC 7816: * RESET= Low , I/O in the receive state * Power Vcc (see DC/DC Converter) * Once Vcc is established, apply Clock at time Ta * Maintain Reset Low until time Ta+tb (tb< 400 clocks) * Monitor The I/O line for the Answer To Reset (ATR) between 400 and 40000 clock cycles after Tb. ( 400 clocks < tc < 40000clocks) Figure 15-8. SCIB Activation Cold Reset Sequence after a Card Insertion CVcc CRST CCLK CIO Undefined Ta Ta + tb Tb + tc Data The Warm Reset Activation Terminal procedure is as follow and the Figure 15-9 * Vcc active, Reset = High, CLK active * Terminal drives Reset low at time T to initiate the warm Reset. Reset=0 maintained for at least 400 clocks until time Td = T+te (400 clocks < te) * Terminal keeps the IO line in receive state * Terminal drives Reset high after at least 400 clocks at time Td * ICC shall respond with an ATR within 40000 clocks (tf<40000 clocks) 185 TPR0327AY-SMS-30Jan09 Figure 15-9. SCIB Activation Warm Reset Sequence CVcc CRST CCLK CIO Undefined Td=T + te Td + Tf Data The removal of the smart card will automatically start the power off sequence as described in Figure 15-10. The SCIB deactivation sequence after a reset of the CPU or after a lost of power supply is ISO7816-3 compliant. The switch order of the signals is the same as in Figure 15-10 but the delay between signals is analog and not clock dependant. Figure 15-10. SCIB Deactivation Sequence after a Card Extraction CVcc CRST CCLK CIO Undefined 8 Clock Cycles 15.5.8 Interrupt Generator There are several sources of interruption issued by the SCIB. All these interrupts generate the signal: SCIB interruption. See "Interrupts" on page 63. 186 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 15-11. SCIB Interrupt Sources Transmit buffer copied to shift register ESCTBI Output voltage out of range Timer on WT counter ESCWTI SCIB Interrupt SCTI ESCTI Reception complete ESCRI Parity error detected ESCPI SCPI SCRI VCARDERR EVCARDER SCWTI SCTBI Transmission complete This signal is high level active. Each of the sources is able to activate the SCIB interruption which is cleared by software by clearing the corresponding bits in the Smart Card Interrupt register. If another interrupt occurs during the read of the Smart Card Interrupt register, the activation of the corresponding bit in the Smart Card Interrupt register and the new SCIB interruption is delayed until the interrupt register is read by the microcontroller. Each bit of the SCIIR register is irrelevant while the corresponding interruption is disabled in SCIER register. When the interruption mode is not used, the bits of the SCISR register must be used instead of the bits of the SCIIR register. ! Caution 15.6 15.6.1 Additional Features Clock The clkSCI input must be in the range 1 - 5 MHz according to ISO 7816. The clkSCI can be programmed up to 12 MHz. In this case, the timing specification of the output buffer will not be ISO 7816 compliant. Please refer to section "Clock System" on page 31 for the description of the input clock. The dividers values are designed to access most common frequencies of ISO7816 norm. See section "SCICLK - Smart Card Clock Register" on page 199, for the clock frequency available in output of the Smart Card interface. 15.6.2 Card Presence Input The CPRES input can generate an interrupt. To do so, global interrupt must be enabled and SCIER.CARDINE must be set. The CPRES interrupt is generated by an event on CPRES (i.e. a high or low edge depending on the setting of SCICR.CARDDET). 187 TPR0327AY-SMS-30Jan09 As soon as the program executes the CPRES interrupt routine, the CPRES interrupt is automatically cleared. See "Interrupts" on page 63 for CPRES interrupt vector address." If Card Presence interruption is enabled, the AT90SCR100 wakes up from low power mode as soon as an event on CPRES is detected. Note An internal pull-up on Card Presence input can be disconnected in order to reduce the consumption (SCSR.CPRESRES). In this case, an external resistor (typically 1 M) must be externally tied to Vcc. 15.6.3 Transmit / Receive Buffer The contents of the SCIBUF Transmit / Receive Buffer is transferred or received into / from the Shift Register. The Shift Register is not accessible by the microcontroller. Its role is to prepare the byte to be copied on the I/O pin for a transmission or in the SCIBUF buffer after a reception. During a character transmission process, as soon as the contents of the SCIBUF buffer is transferred to the shift register, the SCTBE bit is set in SCISR register to indicate that the SCIBUF buffer is empty and ready to accept a new byte. This mechanism avoids to wait for the complete transmission of the previous byte before writing a new byte in the buffer and enables to speed up the transmission. * If the Character repetition mode is not selected (bit CREP=0 in SCICR), as soon as the contents of the Shift Register is transferred to I/O pin, the SCTC bit is set in SCISR register to indicate that the byte has been transmitted. * If the Character repetition mode is selected (bit CREP=1 in SCICR) The terminal will be able to repeat characters as requested by the ICC (See the Parity Error in T=0 protocol description in the definition paragraph above). The SCTC bit in SCISR register will be set after a successful transmission (no retry or no further retry requested by the ICC). If the number of retries is exhausted (up to 4 retries depending on CREPSEL bit in SCSR) and the last attempt is still unsuccessful, the SCTC bit in SCISR will not be set and the SCPE bit in SCISR register will be set instead. During a character reception process, the contents of the Shift Register is transferred in the SCIBUF buffer. * If the Character repetition mode is not selected (bit CREP=0 in SCICR), as soon as the contents of the Shift Register is transferred to the SCIBUF the SCRC bit is set in SCISR register to indicate that the byte has been received, and the SCIBUF contains a valid character ready to be read by the microcontroller. * If the Character repetition mode is selected (bit CREP=1 in SCICR) The terminal will be able to request repetition if the received character exhibit a parity error. Up to 4 retries can be requested depending on CREPSEL bit in SCSR. The SCRC bit will be set in SCISR register after a successful reception, first reception or after retry(ies). If the number of retries is exhausted (up to 4 retries depending on CREPSEL bit in SCSR) and the last retry is still 188 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 unsuccessful, the SCRC bit and the SCPE bit in SCISR register will be set. It will be possible to read the erroneous character. The SCTBI, SCTI, SCRI and SCPI bits have the same functions as SCTBE, SCTC, SCRC and SCPE bits. The first ones are able to generate interruptions if the interruptions are enabled in SCIER register while the second ones are only status bits to be used in polling mode. If the interruption mode is not used, the status bits must be used. The SCTBI, SCTI and SCRI bits do not contain valid information while their respective interrupt enable bits ESCTBI, EXCTI, ESCRI are cleared. ! Caution Figure 15-12. Character Transmission Diagram SCISR Register SCTBE SCTC SCPE Parity Error SCIBUF Transmitted Character Shift Register I/O Pin SCIER.ESCTBI SCIER.ESCTI Parity Error SCTBI SCIIR Register SCTI SCPI 189 TPR0327AY-SMS-30Jan09 Figure 15-13. Character Reception Diagram SCISR Register SCTBE SCRC SCPE Shift Register I/O Pin SCIBUF Received Character SCIER.ESCRI SCTBI SCIIR Register SCRI SCPI 15.6.4 SCIB Reset The SCICR register contains a reset bit. If set, this bit generates a reset of the SCIB and its registers. All default values will be set into the SCIB registers. 15.7 15.7.1 Smart Card Interface Block Registers SCICR - Smart Card Interface Control Register Bit $0000FF Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 UART R/W 0 2 WTEN R/W 0 1 CREP R/W 0 0 CONV R/W 0 0x00 SCICR SCIRESET CARDDET VCARD [1..0] * Bit 7 - SCIRESET: Smart Card Interface Reset Bit Set this bit to reset and deactivate the Smart Card interface. This bit acts as an active high software reset. Clear this bit to activate the Smart Card interface. The read back value becomes 0 only when the card interface is completely activated and ready. When clearing this bit by software, it is required to wait till this bit is cleared before using the interface. Note * Bit 6 - CARDDET: Card Presence Detector Sense Clear this bit to indicate the card presence detector is open when no card is inserted (CPRES is high and will go low when a card is inserted). 190 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Set this bit to indicate the card presence detector is closed when no card is inserted (CPRES is low and will go high when a card is inserted). Switching the value of CARDDET parameter can generate interruption if SCIER.CARDINIE is set. SCIER.CARDINIE must be set only when CARDDET bit is correctly configured. ! Caution * Bit 5..4 - VCARD[1..0]: Card Voltage Selection Table 15-1. 0 0 1 1 Card Voltage Selection VCARD0 0 1 0 1 CVcc 1.8V 3.0V 5.0V VCARD1 Note The DCDC peripheral must be ON and the SCCON.CARDVCC bit must be high to generate the programmed card voltage. Changing VCARD while DC/DC is workding and CVcc is already ON could generate unexpected behavior. Please power_off the CVcc, and take care DC/DC is not busy before changing these bits and reapplying new voltage. See Figure 16-2 on page 203. ! Caution * Bit 3 - UART: Card UART Selection Clear this bit to use the CARDIO bit to drive the Card I/O (CIO) pin. Set this bit to use the Smart Card UART to drive the Card I/O (CIO) pin. Controls also the Waiting Time Counter as described in "Waiting Time (WT) Counter" on page 183 * Bit 2 - WTEN: Waiting Time Counter Enable Clear this bit to stop the counter and enable the load of the Waiting Time counter hold registers. The hold registers are loaded with SCWT0, SCWT1, SCWT2, SCWT3 values when SCWT2 is written. Set this bit to start the Waiting Time Counter. The counters stop when it reaches the timeout value. If the UART bit is set, the Waiting Time Counter automatically reloads with the hold registers whenever a start bit is sent or received. * Bit 1 - CREP: Character Repetition Clear this bit to disable parity error detection and indication on the Card I/O pin in receive mode and to disable character repetition in transmit mode. Set this bit to enable parity error indication on the Card I/O pin in receive mode and to set automatic character repetition when a parity error is indicated in transmit mode. 191 TPR0327AY-SMS-30Jan09 Depending upon CREPSET bit is SCSR register, the receiver can indicate parity error up to 4times (3 repetitions) or up to 5times (4 repetitions) after which it will raise the parity error bit SCPE bit in the SCISR register. If parity interrupt is enabled, the SCPI bit in SCIIR register will be set too. Alternately, the transmitter will detect ICC character repetition request. After 3 or 4 unsuccessful repetitions (depending on CREPSEL bit in SCSR register), the transmitter will raise the parity error bit SCPE bit in the SCISR register. If parity interrupt is enabled, the SCPI bit in SCIIR register will be set too. Character repetition mode is specified for T=0 protocol only and should not be used in T=1 protocol (block oriented protocol) Note * Bit 0 - CONV: ISO Convention Clear this bit to use the direct convention: b0 bit (LSB) is sent first, the parity bit is added after b7 bit and a low level on the Card I/O pin represents a'0'. Set this bit to use the inverse convention: b7 bit (LSB) is sent first, the parity bit is added after b0 bit and a low level on the Card I/O pin represents a'1'. 15.7.2 SCCON - Smart Card Contacts Register Bit $0000FE Read/write Initial value 7 CLK R/W 0 6 R 0 5 CARDC8 R/W 0 4 CARDC4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 SCCON 0x00 R/W 0 CARDIO CARDCLK CARDRST CARDVCC * Bit 7 - CLK: Card Clock Selection Clear this bit to use the SCCON.CARDCLK bit to drive Card CLK pin. Set this bit to use clkSCI signal to drive the Card CLK pin Internal synchronization avoids glitches on the CLK pin when switching this bit. Note * Bit 6 - Reserved Bit This bit is reserved for future use. * Bit 5 - CARDC8: Card C8 Clear this bit to drive a low level on the Card C8 pin (CC8 pin). Set this bit to set a high level on the Card C8 pin (CC8 pin). The CC8 pin can be used as a pseudo bi-directional I/O when this bit is set. VCARDOK=1 (SCISR.4 bit) condition must be true to change the state of CC8 pin. * Bit 4 - CARDC4: Card C4 Clear this bit to drive a low level on the Card C4 pin (CC4 pin). Set this bit to set a high level on the Card C4 pin (CC4 pin). 192 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The CC4 pin can be used as a pseudo bi-directional I/O when this bit is set. VCARDOK=1 (SCISR.4 bit) condition must be true to change the state of CC4 pin. * Bit 3 - CARDIO: Card I/O If UART bit is cleared in SCICR register, this bit enables the use of the Card IO pin (CIO pin) as a standard bi-directional port : * To read from CIO port pin : set CARDIO bit then read CARDIO bit to have the CIO port value * To write in CIO port pin : set CARDIO bit to write a 1 in CIO port pin , clear CARDIO bit to write a 0 in CIO port pin. VCARDOK=1 (SCISR.4 bit) condition must be true to change the state of CIO pin * Bit 2 - CARDCLK: Card CLK When the CLK bit is cleared in SCCON Register, the value of this bit is driven to the Card CLK pin. VCARDOK=1 (SCISR.4 bit) condition must be true to change the state of Card CLK pin. * Bit 1 - CARDRST: Card RST Clear this bit to drive a low level on the Card RST pin. Set this bit to set a high level on the Card RST pin. VCARDOK=1 (SCISR.4 bit) condition must be true to change the state of Card RST pin. * Bit 0 - CARDVCC: Card Vcc Control Clear this bit to deactivate the Card interface and set its power-off. The other bits of SCCON register have no effect while this bit is cleared. Set this bit to power-on the Card interface. The activation sequence should be handled by software. 15.7.3 SCISR - Smart Card UART Interface Status Register Bit $0000FD Read/write Initial value 7 SCTBE R 1 6 CARDIN R 0 5 R 0 4 VCARDOK R 0 3 SCWTO R 0 2 SCTC R/W 0 1 SCRC R/W 0 0 SCPE R/W 0 0x80 SCISR * Bit 7 - SCTBE: UART Transmit Buffer Empty Status This bit is set by hardware when the Transmit Buffer is copied to the transmit shift register of the Smart Card UART. It is cleared by hardware when SCIBUF register is written. This bit can only be used if the Guardtime parameter is lesser or equal to 11etu. The meaning of this bit if guardtime is higher than 11etu is not reliable; In this case, using SCTC is mandatory. ! Caution * Bit 6 - CARDIN: Card Presence Status This bit is set by hardware if there is a card presence (debouncing filter has to be done by software). 193 TPR0327AY-SMS-30Jan09 This bit is cleared by hardware if there is no card presence. If global interrupts are activated and SCIER.CARDINE is set (one), and Card Presence goes high, an interrupt is generated. See "Card Presence Input" on page 187. * Bit 5 - Res: Reserved Bit This bit is reserved and will always be read as `0'. * Bit 4 - VCARDOK: Card Voltage Correct Status This bit is set when the output voltage is within the voltage range specified by VCARD[1:0] in SCICR register. It is cleared otherwise. To modify the bits CARDC8, CARDC4, CARDIO, CARDCLK and CARDRST in register SCCON, the bit VCAROK must be equal to 1. Note * Bit 3 - SCWTO: Waiting Time Counter Timeout Status This bit is set by hardware when the Waiting Time Counter has expired. It is cleared by reloading the counter or by reseting the SCIB. * Bit 2 - SCTC: UART Transmitted Character Status This bit is set by hardware when the Smart Card UART has transmitted a character. If character repetition mode is selected, this bit will be set only after a successful transmission. If the last allowed repetition is not successful, this bit will not be set. This bit must be cleared by software. * Bit 1 - SCRC: UART Received Character Status This bit is set by hardware when the Smart Card UART has received a character. This bit must be cleared by software. If character repetition mode is selected, this bit will be set only after a successful reception. If the last allowed repetition is still unsuccessful, this bit will be set to let the user read the erroneous value if necessary. * Bit 0 - SCPE: Character Reception Parity Error Status This bit is set when a parity error is detected on the received character. This bit must be cleared by software. If character repetition mode is selected, this bit will be set only if the ICC report an error on the last allowed repetition of a TERMINAL transmission, or if a reception parity error is found on the last allowed ICC character repetition. 194 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 15.7.4 SCIIR - Smart Card UART Interrupt Identification Register Bit $0000FC Read/write Initial value 7 SCTBI R 0 6 R 0 5 R 0 4 VCARDERR R 0 3 SCWTI R 0 2 SCTI R 0 1 SCRI R 0 0 SCPI R 0 0x00 SCIIR * Bit 7 - SCTBI: UART Transmit Buffer Empty Interrupt This bit is set by hardware when the Transmit Buffer is copied into the transmit shift register of the Smart Card UART. It generates an interrupt if ESCTBI bit is set in SCIER register otherwise this bit is irrelevant. This bit must be cleared by software. * Bit 5..6 - Res: Reserved Bits Those bits arereserved and will always be read as `0'. * Bit 4 - VCARDERR: Card Voltage Error Interrupt This bit is set when the output voltage goes out of the voltage range specified by VCARD field. It generates an interrupt if EVCARDER bit is set in SCIER register otherwise this bit is irrelevant. This bit must be cleared by software. * Bit 3 - SCWTI: Waiting Time Counter Timeout Interrupt This bit is set by hardware when the Waiting Time Counter has expired. It generates an interrupt if ESCWTI bit is set in SCIER register otherwise this bit is irrelevant. This bit must be cleared by software. * Bit 2 - SCTI: UART Transmitted Character Interrupt This bit is set by hardware when the Smart Card UART has completed the character transmission. It generates an interrupt if ESCTI bit is set in SCIER register otherwise this bit is irrelevant. This bit must be cleared by software. * Bit 1 - SCRI: UART Received Character Interrupt This bit is set by hardware when the Smart Card UART has completed the character reception. It generates an interrupt if ESCRI bit is set in SCIER register otherwise this bit is irrelevant. This bit must be cleared by software. * Bit 0 - SCPI: Character Reception Parity Error Interrupt This bit is set at the same time as SCTI or SCRI if a parity error is detected on the received character. It generates an interrupt if ESCPI bit is set in SCIER register otherwise this bit is irrelevant. This bit must be cleared by software. It is recommended that the application saves the SCIIR register after reading it in order to avoid the loss of pending interruptions as the SCIIR register is cleared when it is read by the MCU. Note 195 TPR0327AY-SMS-30Jan09 15.7.5 SCIER - Smart Card UART Interrupt Enable Register Bit $0000FD Read/write Initial value 7 R/W 0 6 R 0 5 R 0 4 R/W 0 3 R/W 0 2 ESCTI R/W 0 1 ESCRI R/W 0 0 ESCPI R/W 0 0x00 SCIER ESCTBI CARDINE EVCARDER ESCWTI * Bit 7 - ESCTBI: UART Transmit Buffer Empty Interrupt Enable Clear this bit to disable the Smart Card UART Transmit Buffer Empty interrupt. Set this bit to enable the Smart Card UART Transmit Buffer Empty interrupt. * Bit 6 - CARDINE: Card In Interrupt Enable Clear this bit to disable te Smart Card Card Presence Detection interrupt generation. Set this bit to enable te Smart Card Card Presence Detection interrupt generation. * Bit 5 - Res: Reserved Bits Those bits arereserved and will always be read as `0'. * Bit 4 - EVCARDER: Card Voltage Error Interrupt Enable Clear this bit to disable the Card Voltage Error interrupt. Set this bit to enable the Card Voltage Error interrupt. * Bit 3 - ESCWTI: Waiting Time Counter Timeout Interrupt Enable Clear this bit to disable the Waiting Time Counter timeout interrupt. Set this bit to enable the Waiting Time Counter timeout interrupt. * Bit 2 - ESCTI: UART Transmitted Character Interrupt Enable Clear this bit to disable the Smart Card UART Transmitted Character interrupt. Set this bit to enable the Smart Card UART Transmitted Character interrupt. * Bit 1 - ESCRI: UART Received Character Interrupt Enable Clear this bit to disable the Smart Card UART Received Character interrupt. Set this bit to enable the Smart Card UART Received Character interrupt. * Bit 0 - ESCPI: Character Reception Parity Error Interrupt Enable Clear this bit to disable the Smart Card Character Reception Parity Error interrupt. Set this bit to enable the Smart Card Character Reception Parity Error interrupt. 15.7.6 SCSR - Smart Card Selection Register Bit $0000FA Read/write Initial value 7 R 0 6 BGTEN R/W 0 5 R 0 4 R/W 0 3 R/W 0 2 R 0 1 R 0 0 R 0 0x00 SCSR CREPSEL CPRESRES * Bit 7 - Reserved Bit 196 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 This bit is reserved for future use. * Bit 6 - BGTEN: Block Guard Time Enable Set this bit to select the minimum interval between the leading edge of the start bits of the last character received from the ICC and the first character sent by the Terminal. The transfer of GT[8-0] value to the BGT counter is done on the rising edge of the BGTEN. Clear this bit to suppress the minimum time between reception and transmission. * Bit 5 - Reserved Bit This bit is reserved for future use. * Bit 4 - CREPSEL: Character Repetition Selection Clear this bit to select 5 times transmission (1 original + 4 repetitions) before parity error indication (conform to EMV). Set this bit to select 4 times transmission (1 original + 3 repetitions) before parity error indication. * Bit 3 - CPRESRES: Card Presence Pull-up Resistor Clear this bit to connect the internal 100K Pull-up on CPRES pin. Set this bit to disconnect the internal pull-up from this pin. * Bit 2..0 - Reserved Bits These bits are reserved for future use. Writing these reserved bits can have side effects. Take care of not writing them. 15.7.7 SCIBUF - Smart Card Transmit/Receive Buffer Bit $0000F9 Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 SCIBUF R/W 0 0x00 SCIBUFD [7..0] * Bit 7..0 - SCIBUFD7..0: Smart Card Transmit/Receive Buffer A new byte can be written in the buffer to be transmitted on the I/O pin when SCTBE bit is set. The bits are sorted and copied on the I/O pin according to the active convention. A new byte received from I/O pin is ready to be read when SCRI bit is set. The bits are sorted according to the active convention. 197 TPR0327AY-SMS-30Jan09 15.7.8 SCETU - Smart Card ETU Register Bit $0000F8 $0000F7 Bit Read/write Initial value 7 R/W R/W 0 0 6 R R/W 0 1 5 R R/W 0 1 4 R R/W 0 1 15 COMP 14 13 12 11 ETU [7..0] 3 R R/W 0 0 2 R/W R/W 0 1 1 R/W R/W 0 0 0 R/W R/W 1 0 0x01 0x74 10 9 ETU [10..8] 8 SCETUH SCETUL * Bit 15 - COMP: Compensation Clear this bit when no time compensation is needed (i.e. when the ETU to Card CLK period ratio is close to an integer with an error less than 1/4 of Card CLK period). Set this bit otherwise and reduce the ETU period by 1 Card CLK cycle for even bits. * Bit 14..11 - Reserved Bits These bits are reserved for future use. * Bit 10..0 - ETU: ETU Value The Elementary Time Unit is (ETU[10:0] - 0.5*COMP)/f, where f is the Card CLK frequency. According to ISO 7816, ETU[10:0] can be set between 11 and 2048. The default reset value of ETU[10:0] is 372 (F=372, D=1). The ETU counter is reloaded at each register's write operation. Note ! Caution Do not change this register during character reception or transmission or while Guard Time or Waiting Time Counters are running. 15.7.9 SCGT - Smart Card Guard Time Register Bit $0000F6 $0000F5 Bit Read/write Initial value 7 R R/W 0 0 6 R R/W 0 0 5 R R/W 0 0 4 R R/W 0 0 15 14 13 12 11 GT [7..0] 3 R R/W 0 1 2 R R/W 0 1 1 R R/W 0 0 0 R/W R/W 0 0 0x00 0x0C 10 9 8 GT8 SCGTH SCGTL * Bit 15..9 - Reserved Bits These bits are reserved for future use. 198 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 8..0 - GT8..0: Transmit Guard Time The minimum time between two consecutive start bits in transmit mode is GT[8:0] x ETU. This is equal to ISO IEC Guard Time +10. See "Block Guard Time Counter" on page 181. According to ISO IEC 7816, the time between 2 consecutive leading edge start bits can be set between 11 and 266 (11 to 254+12 ETUs). 15.7.10 SCWT - Smart Card Character/Block Waiting Time Register Bit $0000F4 $0000F3 $0000F2 $0000F1 R/W Initial value 0 0 0 1 R/W 0 0 0 0 R/W 0 0 1 0 0 0 0 0 7 6 5 4 3 2 1 0 SCWT3 SCWT2 SCWT1 SCWT0 R/W 0 0 1 0 R/W 0 0 0 0 R/W 0 0 1 0 0x00 0x00 0x25 0x80 WT [31..24] WT (23..16] WT [15..8] WT [7..0] R/W R/W 0 0 0 0 * Bit 31..0 - WT: Waiting Time Byte WT[31:0] is the reload value of the Waiting Time Counter (WTC). The WTC is a general-purpose timer. It uses the ETU clock and is controlled by the WTEN bit (See "SCICR - Smart Card Interface Control Register" on page 190. and See "Waiting Time (WT) Counter" on page 183.). When UART bit of "Smart Card Interface Block Registers" is set, the WTC is automatically reloaded at each start bit of the UART. It is used to check the maximum time between to consecutive start bits. If SCICR.WTEN=0, the Waiting Time Counter is loaded by writting SCWT2 and resetting SCICR.WTEN. ! Caution 15.7.11 SCICLK - Smart Card Clock Register Bit $0000F0 Read/write Initial value 7 R 0 6 R 0 R/W 1 R/W 0 5 4 3 R/W 1 2 R/W 1 1 R/W 1 0 SCICLK R/W 1 0x2F SCICLK [5..0] * Bit 7..6 - Reserved Bits These bits are reserved for future use. * Bit 5..0 - SCICLK5..0: Clock Bits Combination of SCICLK bits provide clock divider for Smart Card Interface output as follow: 199 TPR0327AY-SMS-30Jan09 Table 15-2. Clock Dividers For Smart Card Interface SCICLK [5-0] 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E SCIB Frequency (Mhz) 48 32 24 19.2 16 8 6 4.8 4 3 2.4 2 Reserved Reserved Reserved Divider 2 3 4 5 6 12 16 20 24 32 40 48 Reserved Reserved Reserved ClkPLL 96 96 96 96 96 96 96 96 96 96 96 96 96 96 96 200 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 16. DC/DC Converter 16.1 Overview The AT90SCR100 embeds a DC/DC converter to generate voltage to supply any kind of ISO7816 Smart Card, and to generate the VBUS voltage for USB Smart Cards. This peripheral is also controlled by "Smart Card Interface Block (SCIB)" . 16.2 Features * Operating Voltages : 2.7 - 5.5 V * Programmable Ouput Voltages : 1.8V, 3V or 5V * Automatic deactivation sequence when switched off 16.3 Description The Smart Card voltage (CVcc) is supplied by the integrated DC/DC converter which is controlled by several registers: * The DCCR register controls the start-up, shutdown of DC/DC peripheral. See "DCCR DC/DC Converter Register" on page 203. * The SCICR register controls the CVcc level by means of VCARD[1..0] bits. See "SCICR Smart Card Interface Control Register" on page 190. * The SCCON register controls the generation of by means of CARDVCC bit. See "SCCON Smart Card Contacts Register" on page 192. The CVcc cannot be generated while the CPRES pin remains inactive. If CPRES pin becomes inactive while the DC/DC converter is operating, an automatic power_off sequence of the DC/DC converter is initiated by the internal logic. It is mandatory to switch off the DC/DC Converter before entering in Power-down mode, by clearing DCCR.DCON. Note 16.3.1 Initialization Procedure To generate a specific voltage on CVcc, please follow at the following diagram: To generate a VBUS voltage to supply a USB Smart Card, the below process is mandatory, with SCICR.VCARD = b11, to generate 5V. The 3.3V of CC4/CC8 will be generate using a specific regulator. ! Caution 201 TPR0327AY-SMS-30Jan09 Figure 16-1. DC/DC initialization procedure: DC/DC Activation DCCR.DCON=1 Start the DC/DC Converter No Card Presence required DCCR.DCRDY=1? Yes Set SCICR.VCARD No Poll DC/DC Converter is ready Configure the Voltage to generate No Card Presence required This can be done either by polling or interruption. See Card Presence Input section Wait for Card Insertion SCCON.CARDVCC=1 Ask for CVcc generation SCISR.VCARDOK=1 ? Yes CVcc generated Need activation sequence No Poll to know when CVcc has reached the desired voltage As the DCDC voltage is now generated, the activation sequence can be processed ! Caution This procedure does not take into account any error signal. This should be added for full Smart Card Interface management. 16.3.2 Changing VCard Level Parameter It is forbidden to modify the voltage delivered by CVcc while DC/DC is loaded. The DCCR.DCBUSY bit permits to check the state of DC/DC load. While it is set, it is advised to not: * Shut the DC/DC Off (using DCCR.DCON bit) * Change SCICR.VCARD[0..1] parameter 16.4 Summary: State Machine The graph below permits to see how work the different signals of the DC/DC, and understand what is accepted, or not, regarding the moment of DC/DC use: 202 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 16-2. DC/DC State Machine Internal_Supply DCCR.RDY ~200s DCCR.BUSY CVcc Signal >20s (*) >20s (*) Modification of SCICR.VCARD OK DCCR.DCON =1 DCCR.DRDY SCCON.CARDVCC =1 DCCR.BUSY SCCON.CARDVCC =0 Modification of SCICR.VCARD OK SCCON.CARDVCC =1 DCCR.BUSY SCCON.CARDVCC =0 Shutdown procedure DCCR.DCON =0 (*): This timing depends on SCICR.VCARD configuration but is, at least, 20s 16.5 16.5.1 DC/DC Registers DCCR - DC/DC Converter Register Bit $0000EF Read/write Initial value 7 DCON R/W 0 6 DCRDY R 0 5 DCBUSY R 0 4 R 0 3 R 0 2 R 0 1 R 0 0 R 0 0x00 DCCR * Bit 7 - DCON : DC/DC ON bit Set (one) this bit to start the DC/DC up. The DC/DC must be started before trying to generate a Card Vcc using Smart Card Interface. DCCR.DCRDY bit will inform you when the DCDC is ready to use. Clear (zero) this bit to shut the DC/DC down. * Bit 6 - DCRDY : DC/DC Ready bit This bit is cleared and set by hardware. After having started the DC/DC using DCCR.DCON, this bit indicates when the DC/DC is ready to be used. This bit is cleared when the DC/DC is off. * Bit 5 - DCBUSY : DC/DC Busy bit This bit is cleared and set by hardware. This bit is set when the DC/DC is loaded and running. This means that it is advised to wait for its reset before changing parameters of DC/DC, shutting DC/DC down etc... See Figure 16-2 on page 203. 203 TPR0327AY-SMS-30Jan09 204 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 17. USB Host Controller The USB Smart Card Interface provides an efficient way to communicate to USB with smart cards. AT90SCR100 embeds a USB Host Controller designed to communicate with USB smart card the same way as another USB Host system, in addition to a USB Host Smart Card Interface, with some limitations. 17.1 Features * USB 2.0 Full Speed Peripheral with Host functions (low-speed compatbible) * Single Device Connection * * * * * - Device load: up to 60mA Supports USB2.0 Electrical Conditions Possibility to adapt USB IC Electrical Conditions Handle Suspend/Resume Requests 168 bytes of DPRAM 4 Pipes, configured in the DPRAM 17.2 USB Host Smart Card Interface Description The AT90SCR100 USB Host Interface is dedicated to USB Smart Card connection. As a consequence, only D+/D- are controlled by this block and must be connected to C4 and C8 pads of the Smart Card Interface pads (see Smart Card Port in section "Pin List Configuration" ). The USB Host Controller needs a 48Mhz clock. To do so, it needs the PLL running and PLL Multiplexer switched to clkPLL. See "Clock System" on page 31. Finally, to be compliant with any type of USB Smart Card, the USB Host smart card interface supports 2 different pads set: Standard USB 2.0 pads (with 15K pull-down) and USB-IC pads (Standard IO). For USB-IC requirements, please see section "USB-IC Design" on page 206. Please refer to USB norm and documentation to get information on these two standards. The USB serial resistors are not included inside USB Smart Card Interface hardware. To be fully USB compliant, 2 externals serial resistors of 22 must be placed on D+ and D-. ! Caution Finally, the AT90SCR100 can generate a VBUS 5V using the internal DC/DC. See "DC/DC Converter" on page 201. But the card consumption will be limited, in this case, to the capabilities of DC/DC converter. Anyway, the card may also be supplied by external supply voltage with more capabilities. 205 TPR0327AY-SMS-30Jan09 Figure 17-1. USB Smart Card Interface Block Diagram USB Smart Card Interface SCIB Controller CC4 CC8 DC/DC UHCR.UHEN=1 CC8 CC4 UHCR.UHEN=1 UHCR.PAD = '01' USB-IC Pad UHCR.PAD D+ DD+ D- = '01' clk USB Logical D+ Logical D- CC4 CC8 USB Host Controller = '00' = '00' 15K 15K CPU (SRAM) On-Chip USB DPRAM Pipe 0 Pipe 1 168 Bytes Pipe 2 Pipe 3 USB 2.0 Internal Vcc USB Regulator 17.3 USB-IC Design Regarding the USB-IC specifications, the AT90SCR100 pads are not exactly compliant, as they do not include pull-down resistors of 30-150 K. Designing a specific USB-IC system will thus require to connect 2 pull-down resistors on CC4 and CC8 pins. Another external component will also be mandatory, to control the attachement of these pulldown resistors, as described in the USB-IC specifications. That is why this design will require the use of another pin to control a commutator that will attach the pull-down resistors or not. Please refer to the USB-IC specification for details about the need of control. TBD: references of components to achieve such functionnalities. 206 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 17-2. USB-IC Design Recommendations AT90SCR100 CC4 CC8 D+ D- GPIO Can be any control pin Bidirectional Commutator RPDH RPDH 30K < RPDH < 150K 17.4 Memory Management The controller does only support the following memory allocation management: The reservation of a Pipe can only be made in the growing order (Pipe 0 to the last Pipe). The firmware shall thus configure them in the same order. The reservation of a Pipe "ki" is done when its ALLOC bit is set. Then, the hardware allocates the memory and insert it between the Pipe "ki-1" and "ki+1". The "ki+1" Pipe memory "slides" up and its data is lost. Note that the "ki+2" and upper Pipe memory does not slide. Clearing a Pipe enable (PEN) does not clear neither its ALLOC bit, nor its configuration (PSIZE, PBK). To free its memory, the firmware should clear ALLOC. Then, the "ki+1" Pipe memory automatically "slides" down. Note that the "ki+2" and upper Pipe memory does not slide. The following figure illustrates the allocation and reorganization of the USB memory in a typical example: 207 TPR0327AY-SMS-30Jan09 Figure 17-3. USB Smart Card Interface Block Diagram Free 3 2 1 0 PEN=1 ALLOC=1 Free 3 2 PEN=0 (ALLOC=1) Free 3 LOST MEMORY Free 3 2 1 (bigger size) 0 Pipe Activation Conflict 2 0 Free its memory (ALLOC=0) 0 Pipe Disable Pipe Activation * First, Pipe 0 to Pipe 3 are configured, in the growing order. The memory of each is reserved in the DPRAM. * Then, the Pipe 1 is disabled (EPEN=0), but its memory reservation is internally kept by the controller. * Its ALLOC bit is cleared: the Pipe 2 "slides" down, but the Pipe 3 does not "slide". * Finally, if the firmware chooses to reconfigure the Pipe 1 with a bigger size. The controller reserved the memory after the Pipe 0 memory and automatically "slide" the Pipe 2. The Pipe 3 does not move and a memory conflict appears, in that both Pipe 2 and 3 use a common area. The data of those pipes are potentially lost. * The data of Pipe/Endpoint 0 are never lost whatever the activation or deactivation of the higher Pipe. Its data is lost if it is deactivated. Note * Deactivate and reactivate the same Pipe with the same parameters does not lead to a "slide" of the higher endpoints. For those endpoints, the data are preserved. * CFGOK is set by hardware even in the case that there is a "conflict" in the memory allocation. 17.5 17.5.1 USB Host Controller Description Pipe description For the USB Host controller, the term of Pipe is used instead of Endpoint for the USB Device controller. A Host Pipe corresponds to a Device Endpoint, as described in the USB specification: 208 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 17-4. Pipes and Endpoints in a USB system In the USB Host controller, a Pipe will be associated to a Device Endpoint, considering the Device Configuration Descriptors. 17.5.2 Power-on and Reset The next diagram explains the USB host controller main states on power-on: Figure 17-5. USB SCI states after reset Clock stopped Macro off Device Disconnection Host Idle Device Connection Device Disconnection Host Ready UHCR.SOFEN=0 Host Suspend UHCR.SOFEN=1 USB Host controller state after an hardware reset is `Reset'. When the USB Host controller is enabled, the USB controller is in `Idle' state. In this state, the USB Host controller waits for the Device connection, with a minimum power consumption. The USB Pad should be in Idle mode. The macro does not need to have the PLL activated to enter in `Host Ready' state. The Host controller enters in Suspend state when the USB bus is in Suspend state, i.e. when the Host controller doesn't generate the Start of Frame. In this state, the USB consumption is minimum. The Host controller exits to the Suspend state when starting to generate the SOF over the USB line. 209 TPR0327AY-SMS-30Jan09 17.5.3 Device Detection A Device is detected by the USB controller when the USB bus if different from D+ and D- low. In other words, when the USB Host Controller detects the Device pull-up on the D+ line. To enable this detection, the Host Controller has to provide the Vbus power supply to the Device, thanks to CVcc pin. The Device Disconnection is detected by the USB Host controller when the USB Idle correspond to D+ and D- low on the USB line. When a Device Disconnection event has been detected, you must reset the USB Host module, to reset the internal parameters and be able to support a new connection. ! Caution 17.5.4 Pipe Selection Prior to any operation performed by the CPU, the Pipe must first be selected. This is done by: * Clearing PNUMS. * Setting PNUM with the Pipe number which will be managed by the CPU. The CPU can then access to the various Pipe registers and data. 17.5.5 Pipe Configuration The following flow must be respected in order to activate a Pipe: 210 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 17-6. Pipe activation flow: Pipe Activation UPNUM.PNUM=X Select the pipe to configure UPCRX.PEN=1 Update: UPCFG0X .PTYPE .PTOKEN .PEPNUM Select the pipe type: - Type (Control, Isochronous, Bulk, I - Token (IN, OUT, SETUP) - Endpoint Number Update: UPCFG1X .PSIZE .PBK .CFGMEM Configure the Pipe memory: - Pipesize - Number Of Banks UPSTAX.CFGOK=1 ? ERROR Update UPCFG2X .INTFRQ (interrupt only) Configure the polling interval for interrupt pipe Pipe activated and freezed Once the Pipe is activated (UPCRX.PEN set), the hardware is ready to send requests to the Device. When configured (UPSTAX.CFGOK=1), only the Pipe Token (UPCFG0X.PTOKEN) and the polling interval for Interrupt pipe can be modified. There are 4 pipes to configure. A Control type pipe supports only 1 bank (or data bank). Any other value will lead to a configuration error (UPSTAX.CFGOK=0). To guarantee a correct operation of the USB Host Controller: ! Caution * The pipe 0 size must not be greater than 32 bytes. * The pipe 1 size must not be greater than 64 bytes. * The pipe 2 size must not be greater than 64 bytes. * The pipe 3 size must not be greater than 8 bytes. 211 TPR0327AY-SMS-30Jan09 A clear of UPCRX.PEN will reset the configuration of the Pipe. All the corresponding Pipe registers are reset to there reset values. Please refer to "Memory Management" section for more details. To initialize the communication with the USB device, the firmware has to configure the Default Control Pipe with the following parameters: Note * Type: Control * Token: SETUP * Data Bank:1 * Size: 64 Bytes T he firmware will ask for 8 bytes of the Devic e Desc riptor sending a GET_DESCRIPTOR request. These bytes contains the MaxPacketSize of the Device default control endpoint and the firmware will then re-configure the size of the Default Control Pipe with this size parameter. 17.5.6 USB Reset The USB controller sends a USB Reset when the firmware set the UHCR.RESET bit. The UHINT.RSTI bit is set by hardware when the USB Reset has been sent. This triggers an interrupt if the UHIEN.RSTE has been set. When a USB Reset has been sent, all the Pipe configuration and the memory allocation are reset. The General Host interrupt enable register is left unchanged. If the bus was previously in suspend mode (UHCR.SOFEN = 0), the USB controller automatically switches to the resume mode (UHINT.HWUPI is set) and the UHCR.SOFEN bit is set by hardware in order to generate SOF immediately after the USB Reset. 17.5.7 Address Setup Once the Device has answer to the first Host requests with the default address (0), the Host assigns a new address to the device. The Host controller has to send a USB reset to the device and perform a SET ADDRESS control request, with the new address to be used by the Device. This control request ended, the firmware writes the new address into the UHADDR register. All following requests, on every Pipes, will be performed using this new address. When the Host controller sends a USB reset, the UHADDR register is reset by hardware and the following Host requests will be performed using the default address (0). 17.5.8 Remote Wake-Up detection The Host Controller enters in Suspend mode when clearing the UHCR.SOFEN bit. No more Start Of Frame is sent on the USB bus and the USB Device enters in Suspend mode 3ms later. The Device awakes the Host Controller by sending an Upstream Resume (Remote Wake-Up feature). The Host Controller detects a non-idle state on the USB bus and set the UHINT.HWUPI bit. If the non-Idle correspond to an Upstream Resume (K state), the UHINT.RXRSMI bit is set by hardware. The firmware has to generate a downstream resume within 1ms and for at least 20ms by setting the UHCR.RESUME bit. 212 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Once the downstream Resume has been generated, the UHCR.SOFE bit is automatically set by hardware in order to generate SOF immediately after the USB resume. Host Ready UHCR.SOFEN=0 Host Suspend UHCR.SOFE=1 or UHINT.HWUPI=1 17.5.9 USB Pipe Reset The firmware can reset a Pipe using the pipe reset register. The configuration of the pipe and the data toggle remains unchanged. Only the bank management and the status bits are reset to their initial values. To completely reset a Pipe, the firmware has to disable and then enable the pipe. 17.5.10 Pipe Data Access In order to read or to write into the Pipe Fifo, the CPU selects the Pipe number with the UPNUM register and performs read or write action on the UPDATX register. Control Pipe management A Control transaction is composed of 3 phases: * SETUP * Data (IN or OUT) * Status (OUT or IN) The firmware has to change the Token for each phase. The initial data toggle is set for the corresponding token (ONLY for Control Pipe): * SETUP: Data0 * OUT: Data1 * IN: Data1 (expected data toggle) 17.5.11 17.5.12 OUT Pipe management The Pipe must be configured and not frozen first. If the firmware decides to switch to suspend mode (clear UHCR.SOFEN) even if a bank is ready to be sent, the USB controller will automatically exit from Suspend mode and the bank will be sent. Note 17.5.12.1 "Manual" mode The UPINTX.TXOUTI bit is set by hardware when the current bank becomes free. This triggers an interrupt if the UPIENX.TXOUTE bit is set. The UPINTX.FIFOCON bit is set at the same time. The CPU writes into the FIFO and clears the UPINTX.FIFOCON bit to allow the USB controller to send the data. If the OUT Pipe is composed of multiple banks, this also switches to the next data bank. The UPINTX.TXOUTI and UPINTX.FIFOCON bits are automatically updated by hardware regarding the status of the next bank. 213 TPR0327AY-SMS-30Jan09 Figure 17-7. Example of OUT Data bank Management Example with 1 OUT data bank OUT DATA (Bank 0) ACK HW UPINTX.TXOUTI SW SW OUT UPINTX.FIFOCON SW Write data from CPU Bank 0 SW Write data from CPU Bank 0 Example with 2 OUT data banks OUT DATA (Bank 0) ACK HW UPINTX.TXOUTI SW SW SW OUT DATA (Bank 1) ACK UPINTX.FIFOCON SW Write data from CPU Bank 0 SW Write data from CPU Bank 1 Write data from CPU Bank 0 Example with 2 OUT data banks OUT DATA (Bank 0) ACK OUT DATA (Bank 1) ACK HW UPINTX.TXOUTI SW SW SW UPINTX.FIFOCON SW Write data from CPU Bank 0 Write data from CPU Bank 1 SW Write data from CPU Bank 0 17.5.12.2 "Autoswitch" mode In this mode, the clear of the UPINTX.FIFOCON bit is performed automatically by hardware each time the Pipe bank is full. The firmware has to check if the next bank is empty or not before writing the next data. On UPINTX.TXOUTI interrupt, the firmware fills a complete bank. A new interrupt will be generated each time the current bank becomes free. 214 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 17.5.13 IN Pipe management The Pipe must be configured first. Note 17.5.13.1 "Manual" mode When the Host requires data from the device, the firmware has to determine first the IN mode to use using the INMODE bit: * UPCRX.INMODE = 0. The UPINRQX register is taken in account. The Host controller will perform (UPINRQX+1) IN requests on the selected Pipe before freezing the Pipe. This mode avoids to have extra IN requests on a Pipe. * UPCRX.INMODE = 1. The USB controller will perform infinite IN request until the firmware freezes the Pipe. The IN request generation will start when the firmware clear the UPCRX.PFREEZE bit. Each time the current bank is full, the UPINTX.RXINI and the UPINTX.FIFOCON bits are set. This triggers an interrupt if the UPIENX.RXINE bit is set. The firmware can acknowledge the USB interrupt by clearing the UPINTX.RXINI bit. The Firmware reads the data and clears the UPINTX.FIFOCON bit in order to free the current bank. If the IN Pipeis composed of multiple banks, clearing the UPINTX.FIFOCON bit will switch to the next bank. The RXINI and FIFOCON bits are then updated by hardware in accordance with the status of the new bank. Figure 17-8. Example of IN Data bank Management Example with 1 IN data bank IN DATA (to Bank 0) ACK HW UPINTX.RXINI SW IN DATA (to Bank 0) ACK HW SW UPINTX.FIFOCON Read data from CPU Bank 0 SW Read data from CPU Bank 0 Example with 2 IN data banks IN DATA (to Bank 0) ACK HW UPINTX.RXINI SW IN DATA (to Bank 1) ACK HW SW UPINTX.FIFOCON Read data from CPU Bank 0 SW Read data from CPU Bank 1 215 TPR0327AY-SMS-30Jan09 17.5.13.2 "Autoswitch" mode In this mode, the clear of the UPINTX.FIFOCON bit is performed automatically by hardware each time the Pipe bank is empty. The firmware has to check if the next bank is empty or not before reading the next data. On UPINTX.RXINI interrupt, the firmware reads a complete bank. A new interrupt will be generated each time the current bank contains data to read. The acknowledge of the UPINTX.RXINI interrupt is always performed by software. 17.5.13.3 CRC Error (isochronous only) A CRC error can occur during IN stage if the USB controller detects a bad received packet. In this situation, the STALLEDI/CRCERRI interrupt is triggered. This does not prevent the RXINI interrupt from being triggered. 17.6 Interrupt system Figure 17-9. USB Host Controller Interrupt System HWUPI UHINT.6 HWUPE UHIEN.6 HSOFI UHINT.5 HSOFE UHIEN.5 RXRSMI UHINT.4 RXRSME UHIEN.4 RSMEDI UHINT.3 USB Host Interrupt RSMEDE UHIEN.3 RSTI UHINT.2 RSTE UHIEN.2 DDISCI UHINT.1 DDISCE UHIEN.1 DCONNI UHINT.0 DCONNE UHIEN.0 216 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 17-10. USB Host Controller Pipe Interrupt System PIPE 3 PIPE 2 PIPE 1 OVERFI UPSTAX.6 UNDERFI UPSTAX.5 NAKEDI UPINTX.6 FLERRE UPIEN.7 PIPE 0 NAKEDE UPIEN.6 PERRI UPINTX.4 PERRE UPIEN.4 FLERRE UPIEN.7 TXSTPI UPINTX.3 USB Host Pipe Interrupt TXSTPE UPIEN.3 TXOUTI UPINTX.2 TXOUTE UPIEN.2 RXSTALLI UPINTX.1 RXSTALLE UPIEN.1 RXINI UPINTX.0 RXINE UPIEN.0 17.6.1 Idle and Power-Down The CPU exits from Idle and Power-Down mode with any USB Interrupts. 17.7 17.7.1 USB Host Controller Registers UHCR - USB Host Control Register Bit $009E Read/write Initial value 7 UHEN R/W 0 6 R/W 0 5 R/W 0 4 FRZCLK R/W 1 3 R 0 2 RESUME R/W 0 1 RESET R/W 0 0 SOFEN R/W 0 0x00 UHCR PAD [1..0] * Bit 7 - UHEN : USB Host Enable Set this bit to enable the USB Host Controller. This will connect CC4 and CC8 to USB Host block output signals. Clear this bit to disable USB Host controller and reconnect CC4 and CC8 pads to standard SmartCard Interface Block pads. * Bit 6..5 - PAD1..0 : Pad Type These bits switch the D+/D- of the USB Host Controller outputs to specific pads as follow: * 00 : Pad electrically compliant to USB 2.0 (USB Host pads) * 01 : Pad electrically compliant to USB-IC (SCIB pads) * Others : Reserved for future use 217 TPR0327AY-SMS-30Jan09 * Bits 4 - FRZCLK : Freeze USB Clock Bit Set to disable the PLL clock input (the "Resume Detection" is still active). This reduces the power consumption. Clear to enable the clock inputs. This bit is different from PRR1.PRUSBH which avoid providing clock to the state machine of USB Host Controller, disabling the whole controller. Note * Bit 3 - Res : Reserved Bit This bit is a reserved bit. The value read from this bit is always 0. Do not set this bit. * Bit 2 - RESUME : Send USB Resume Set this bit to generate a USB Resume on the USB bus. Cleared by hardware when the USB Resume has been sent. Clearing by software has no effect. * Bit 1 - RESET : Send USB Reset Set this bit to generate a USB Reset on the USB bus. Cleared by hardware when the USB Reset has been sent. Clearing by software has no effect. Refer to the "USB Reset" section for more details. * Bit 0 - SOFEN : Start Of Frame Generation ENable Set this bit to generate SOF on the USB bus. Clear this bit to disable the SOF generation and to leave the USB bus in Idle state. 17.7.2 UHSR - USB Host Status Register Bit $0099 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 SPEED R 1 2 R 0 1 R 0 0 R 0 0x08 UHSR * Bits 7..4 - Res : Reserved Bits These bits are reserved bits. The value read from these bits is always 0. Do not set these bits. * Bit 3 - SPEED : Speed Status Flag Set by hardware when the controller is in FULL-SPEED mode. Cleared by hardware when the controller is in LOW-SPEED mode. * Bit 2..0 - Res : Reserved Bits These bits are reserved bits. The value read from these bits is always 0. Do not set these bits. 218 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 17.7.3 UHINT - USB Host INTerrupt Register Bit $009F Read/write Initial value 7 R 0 6 HWUPI R/W 0 5 HSOFI R/W 0 4 R/W 0 3 R/W 0 2 RSTI R/W 0 1 DDISCI R/W 0 0 DCONNI R/W 0 0x00 UHINT RXRSMI RSMEDI * Bit 7 - Res : Reserved Bit This bit is reserved for future use. The value read from these bits is always 0. Do not set these bits. * Bit 6 - HWUPI : Host Wake-Up Interrupt Set by hardware when a non-idle state is detected on the USB bus. Shall be clear by software to acknowledge the interrupt. Setting by software has no effect. * Bit 5 - HSOFI : Host Start Of Frame Interrupt Set by hardware when a SOF is issued by the Host controller. This triggers a USB interrupt when HSOFE is set. Shall be cleared by software to acknowledge the interrupt. Setting by software has no effect. * Bit 4 - RXRSMI : Upstream Resume Received Interrupt Set by hardware when an Upstream Resume has been received from the Device. Shall be cleared by software. Setting by software has no effect. * Bit 3 - RSMEDI : Downstream Resume Sent Interrupt Set by hardware when a Downstream Resume has been sent to the Device. Shall be cleared by software. Setting by software has no effect. * Bit 2 - RSTI : USB Reset Sent Interrupt Set by hardware when a USB Reset has been sent to the Device. Shall be cleared by software. Setting by software has no effect. * Bit 1 - DDISCI :Device Disconnection Interrupt Set by hardware when the device has been removed from the USB bus. Shall be cleared by software. Setting by software has no effect. After having detected a disconnection, please reset the USB Host. See "Device Detection" on page 210. * Bit 0 - DCONNI : Device Connection Interrupt Set by hardware when a new device has been connected to the USB bus. Shall be cleared by software. Setting by software has no effect. 219 TPR0327AY-SMS-30Jan09 17.7.4 UHIEN - USB Host Interrupt ENable Register Bit $00A0 Read/write Initial value 7 R 0 6 HWUPE R/W 0 5 HSOFE R/W 0 4 R/W 0 3 R/W 0 2 RSTE R/W 0 1 DDISCE R/W 0 0 DCONNE R/W 0 0x00 UHIEN RXRSME RSMEDE * Bit 7 - Res : Reserved Bit This bit is reserved for future use. The value read from these bits is always 0. Do not set these bits. * Bit 6 - HWUPE : Host Wake-Up Interrupt Enable Set this bit to enable HWUP interrupt. Clear this bit to disable HWUP interrupt. * Bit 5 - HSOFE : Host Start Of frame Interrupt Enable Set this bit to enable HSOF interrupt. Clear this bit to disable HSOF interrupt. * Bit 4 - RXRSME : Upstream Resume Received Interrupt Enable Set this bit to enable the RXRSMI interrupt. Clear this bit to disable the RXRSMI interrupt. * Bit 3 - RSMEDE : Downstream Resume Sent Interrupt Enable Set this bit to enable the RSMEDI interrupt. Clear this bit to disable the RSMEDI interrupt. * Bit 2 - RSTE : USB Reset Sent Interrupt Enable Set this bit to enable the RSTI interrupt. Clear this bit to disable the RSTI interrupt. * Bit 1 - DDISCE : Device Disconnection Interrupt Enable Set this bit to enable the DDISCI interrupt. Clear this bit to disable the DDISCI interrupt. After having detected a disconnection, please reset the USB Host. See "Device Detection" on page 210. * Bit 0 - DCONNE : Device Connection Interrupt Enable Set this bit to enable the DCONNI interrupt. Clear this bit to disable the DCONNI interrupt. 220 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 17.7.5 UHADDR - USB Host ADDRess Register Bit $00A1 Read/write Initial value 7 R 0 R/W 0 R/W 0 R/W 0 6 5 4 3 HADDR [6..0] R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 UHADDR * Bit 7 - Res : Reserved Bit This bit is reserved for future use. The value read from this bit is always 0. Do not set this bit. * Bits 6..0 - HADDR6..0 : USB Host Address These bits contains the address of the USB Device. 17.7.6 UHFNUM - USB Host Frame Number Registers Bit $00A3 $00A2 Bit Read/write Initial value 7 R R 0 0 6 R R 0 0 5 R R 0 0 15 14 13 12 4 R R 0 0 11 3 R R 0 0 2 R R 0 0 10 9 FNUM [10..8] 1 R R 0 0 0 R R 0 0 0x00 0x00 8 UHFNUMH UHFNUML FNUM [7..0] * Bits 15..11 - Res : Reserved Bits These bits are reserved for future use. The value read from these bits is always 0. Do not set these bits. * Bits 10..0 - FNUM10..0 - Frame Number The value contained in tis register is the current SOF number. This value can be modified by software. 17.7.7 UHFLEN - USB Host Frame Length Register Bit $00A4 Read/write Initial value R 0 R 0 R 0 7 6 5 4 R 0 3 R 0 2 R 0 1 R 0 0 UHFLEN R 0 0x00 FLEN [7..0] * Bits 7..0 - FLEN7..0 : Frame Length The value contained the data frame length transmitted 221 TPR0327AY-SMS-30Jan09 17.7.8 UPNUM - USB Pipe Number Register Bit $00A7 Read/write Initial value R 0 R 0 R 0 R 0 R 0 7 6 5 4 3 2 R 0 1 PNUM1 R/W 0 0 PNUM0 R/W 0 0x00 UPNUM * Bits 7..2 - Res : Reserved Bits The value read from these bits is always 0. Do not set these bits. * Bits 1..0 - PNUM1..0 : Pipe Number Select the pipe using this register. The USB Host registers ended by a X correspond then to this number. This number is used for the USB controller following the value of the PNUMD bit. 17.7.9 UPRST - USB Pipe Reset Register Bit $00A8 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 P3RST R/W 0 2 P2RST R/W 0 1 P1RST R/W 0 0 P0RST R/W 0 0x00 UPRST * Bits 7..4 - Res : Reserved Bits The value read from these bits is always 0. Do not set these bits. * Bit 3 - P3RST : Pipe 3 Reset Set this bit to 1 and reset this bit to 0 to reset the Pipe 3. * Bit 2 - P2RST : Pipe 2 Reset Set this bit to 1 and reset this bit to 0 to reset the Pipe 2. * Bit 1 - P1RST : Pipe 1 Reset Set this bit to 1 and reset this bit to 0 to reset the Pipe 1. * Bit 0 - P0RST : Pipe 0 Reset Set this bit to 1 and reset this bit to 0 to reset the Pipe 0. 17.7.10 UPCRX - USB Pipe Control Register for Pipe X Set UPNUM register to point to the relevant Pipe before updating the UPCRX register. Bit $00A9 Read/write Initial value 7 R 0 6 R/W 0 5 R/W 0 4 R 0 3 RSTDT R/W 0 2 R 0 1 R 0 0 PEN R/W 0 0x00 UPCRX PFREEZE INMODE * Bit 7 - Res : Reserved This bit is reserved. The value read from these bits is always 0. Do not set these bits. 222 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 6 - PFREEZE : Pipe Freeze Set this bit to Freeze the Pipe requests generation. Clear this bit to enable the Pipe request generation. This bit is set by hardware when: * The pipe is not configured * A STALL handshake has been received on this Pipe * An error occurs on the Pipe (PERR = 1) * (INRQ+1) In requests have been processed This bit is set at 1 by hardware after a Pipe reset or a Pipe enable. * Bit 5 - INMODE : IN Request mode Set this bit to allow the USB controller to perform infinite IN requests when the Pipe is not frozen. Clear this bit to perform a pre-defined number of IN requests. This number is stored in the UINRQX register. * Bit 4 - Res : Reserved Bit This bit is reserved. The value read from these bits is always 0. Do not set these bits. * Bit 3 - RSTDT : Reset Data Toggle Set this bit to reset the Data Toggle to its initial value for the current Pipe. Cleared by hardware when proceed. Clearing by software has no effect. * Bits 2..1 -Res : Reserved Bits The value read from these bits is always 0. Do not set these bits. * Bit 0 - PEN : Pipe Enable Set to enable the Pipe. Clear to disable and reset the Pipe. 17.7.11 UPCFG0X - USB Pipe Configuration Register 0 for Pipe X Set UPNUM register to point to the relevant Pipe before updating the UPCFG0X register. Bit $00AA Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 UPCFG0X R/W 0 0x00 PTYPE [1..0] PTOKEN [1..0] PEPNUM [3..0] * Bits 7..6 - PTYPE1..0 : Pipe Type Select the type of the Pipe: * 00: Control * 01: Isochronous * 10: Bulk * 11: Interrupt 223 TPR0327AY-SMS-30Jan09 * Bits 5..4 - PTOKEN1..0 : Pipe Token Select the Token to associate to the Pipe * 00: SETUP * 01: IN * 10: OUT * 11: reserved * Bits 3..0 - PEPNUM3..0 : Pipe Endpoint Number Set this field according to the Pipe configuration. Set the number of the Endpoint targeted by the Pipe. This value is from 0 and 15. 17.7.12 UPCFG1X - USB Pipe Configuration Register 1 for Pipe X Set UPNUM register to point to the relevant Pipe before updating the UPCFG1X register. Bit $00AB Read/write Initial value 7 R 0 R/W 0 6 5 PSIZE [0..2] R/W 0 R/W 0 0 4 3 R/W 2 PBK [0..1] R/W 0 1 ALLOC R/W 0 R 0 0x00 0 UPCFG1X * Bit 7 - Res : Reserved This bit is reserved. The value read from these bits is always 0. Do not set these bits. * Bits 6..4 - PSIZE0..2 : Pipe Size Select the size of the Pipe: * 000: 8 * 001: 16 * 010: 32 * 011: 64 * Other: Reserved * Bits 3..2 - PBK0..1 : Pipe Bank Select the number of banks to declare for the current pipe! * 00: 1bank * 01: 2banks * Others: reserved * Bit 1 - ALLOC : Configure Pipe Memory Set to configure the pipe memory with the characteristics. Clear to update the memory allocation. Refer to the "Memory Management" chapter for more details. * Bit 0 - Res : Reserved This bit is reserved. The value read from these bits is always 0. Do not set these bits. 224 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 17.7.13 UPCFG2X - USB Pipe Configuration Register 2 for Pipe X Set UPNUM register to point to the relevant Pipe before updating the UPCFG2X register. Bit $00AD Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 UPCFG2X R/W 0 0x00 INTFRQ [7..0] * Bits 7..0 - INTFRQ7..0 : Interrupt Pipe Request Frequency These bits are the maximum value in millisecond of the pulling period for an Interrupt Pipe. This value has no effect for a non-Interrupt Pipe. Note 17.7.14 UPSTAX - USB Pipe Status Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPSTAX register. Bit $00AC Read/write Initial value 7 CFGOK R 0 6 R/W 0 5 R/W 0 4 R 0 3 R 0 2 R 0 1 R 0 0 UPSTAX 0x00 R 0 OVERFI UNDERFI DTSEQ [1..0] NBUSYBK [1..0] * Bit 7 - CFGOK : Configure Pipe Memory OK Set by hardware if the required memory configuration has been successfully performed. Cleared by hardware when the pipe is disabled. The USB reset and the reset pipe have no effect on the configuration of the pipe. * Bit 6 - OVERFI : Overflow Set by hardware when a the current Pipe has received more data than the maximum length of the current Pipe. An interrupt is triggered if the FLERRE bit is set. Shall be cleared by software. Setting by software has no effect. * Bit 5 - UNDERFI : Underflow Set by hardware when a transaction underflow occurs in the current isochronous or interrupt Pipe. The Pipe can't send the data flow required by the device. A ZLP will be sent instead. An interrupt is triggered if the FLERRE bit is set. Shall be cleared by software. Setting by software has no effect. The Host controller has to send a OUT packet, but the bank is empty. A ZLP will be sent and the UNDERFI bit is set underflow for interrupt Pipe. Note * Bit 4 - Res : Reserved The value read from these bits is always 0. Do not set these bits. * Bits 3..2 - DTSEQ1..0 : Toggle Sequencing Flag 225 TPR0327AY-SMS-30Jan09 Set by hardware to indicate the PID data of the current bank: * 00: Data0 * 01: Data1 * 1x: Reserved. For OUT Pipe, this value indicates the next data toggle that will be sent. This is not relative to the current bank. For IN Pipe, this value indicates the last data toggle received on the current bank. * Bit 0..1 - NBUSYBK0..1 : Busy Bank Flag Set by hardware to indicate that the number of busy banks. For OUT Pipe, it indicates the number of busy bank(s), filled by the user, ready for OUT transfer. For IN Pipe, it indicates the number of busy bank(s) filled by IN transaction from the Device. * 00: All banks are free * 01: 1 busy bank * 10: 2 busy banks * 11: Reserved 17.7.15 UPINRQX - USB Pipe IN Request Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPINRQX register. Bit $00A5 Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 UPINRQX R/W 0 0x00 INRQ [7..0] * Bits 7..0 - INRQ7..0 : IN Request Number Before Freeze Enter the number of IN transactions before the USB controller freezes the pipe. The USB controller will perform (INRQ+1) IN requests before to freeze the Pipe. This counter is automatically decreased by 1 each time a IN request has been successfully performed. 17.7.16 UPERRX - USB Pipe Error Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPERRX register. Bit $009D Read/write Initial value R 0 7 6 R/W 0 5 R/W 0 4 CRC16 R/W 0 3 PTIMEOUT R/W 0 2 PID R/W 0 1 R/W 0 0 R/W 0 0x00 COUNTER [1..0] DATAPID DATATGL UPERRX * Bit 7 - Res : Reserved The value read from these bits is always 0. Do not set these bits. * Bits 6..5 - COUNTER1..0 : Error counter This counter is increased by the USB controller each time an error occurs on the Pipe. When this value reaches 3, the Pipe is automatically frozen. Clear these bits by software. 226 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 4 - CRC16 : CRC16 Error Set by hardware when a CRC16 error has been detected. Shall be cleared by software. Setting by software has no effect. * Bit 3 - PTIMEOUT - Pipe Time-out Error Set by hardware when a time-out error has been detected. Shall be cleared by software. Setting by software has no effect. * Bit 2 - PID - PID Error Set by hardware when a PID error has been detected. Shall be cleared by software. Setting by software has no effect. * Bit 1 - DATAPID - Data PID Error Set by hardware when a data PID error has been detected. Shall be cleared by software. Setting by software has no effect. * Bit 0 - DATATGL - Bad Data Toggle Set by hardware when a data toggle error has been detected. Shall be cleared by software. Setting by software has no effect. 17.7.17 UPINTX - USB Pipe INTerrupt Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPINTX register. Bit $00A6 Read/write Initial value 7 FIFOCON R/W 0 6 NAKEDI R/W 0 5 RWAL R/W 0 4 PERRI R/W 0 3 TXSTPI R/W 0 2 R/W 0 1 R/W 0 0 RXINI R/W 0 0x00 UPINTX TXOUTI RXSTALLI * Bit 7 - FIFOCON : FIFO Control For OUT and SETUP Pipe: Set by hardware when the current bank is free, at the same time than TXOUT or TXSTP. Clear to send the FIFO data. Setting by software has no effect. For IN Pipe: Set by hardware when a new IN message is stored in the current bank, at the same time than RXIN. Clear to free the current bank and to switch to the following bank. Setting by software has no effect. * Bit 6 - NAKEDI : NAK Handshake received Set by hardware when a NAK has been received on the current bank of the Pipe. This triggers an interrupt if the NAKEDE bit is set in the UPIENX register. Shall be clear to handshake the interrupt. Setting by software has no effect. * Bit 5 - RWAL : Read/Write Allowed 227 TPR0327AY-SMS-30Jan09 OUT Pipe: Set by hardware when the firmware can write a new data into the Pipe FIFO. Cleared by hardware when the current Pipe FIFO is full. IN Pipe: Set by hardware when the firmware can read a new data into the Pipe FIFO. Cleared by hardware when the current Pipe FIFO is empty. This bit is also cleared by hardware when the RXSTALL or the PERR bit is set * Bit 4 - PERRI : PIPE Error Set by hardware when an error occurs on the current bank of the Pipe. This triggers an interrupt if the PERRE bit is set in the UPIENX register. Refers to the UPERRX register to determine the source of the error. Automatically cleared by hardware when the error source bit is cleared. * Bit 3 - TXSTPI : SETUP Bank ready Set by hardware when the current SETUP bank is free and can be filled. This triggers an interrupt if the TXSTPE bit is set in the UPIENX register. Shall be cleared to handshake the interrupt. Setting by software has no effect. * Bit 2 - TXOUTI : OUT Bank ready Set by hardware when the current OUT bank is free and can be filled. This triggers an interrupt if the TXOUTE bit is set in the UPIENX register. Shall be cleared to handshake the interrupt. Setting by software has no effect. * Bit 1 - RXSTALLI / CRCERR : STALL Received / Isochronous CRC Error Set by hardware when a STALL handshake has been received on the current bank of the Pipe. The Pipe is automatically frozen. This triggers an interrupt if the RXSTALLE bit is set in the UPIENX register. Shall be cleared to handshake the interrupt. Setting by software has no effect. For Isochronous Pipe: Set by hardware when a CRC error occurs on the current bank of the Pipe. This triggers an interrupt if the TXSTPE bit is set in the UPIENX register. Shall be cleared to handshake the interrupt. Setting by software has no effect. * Bit 0 - RXINI : IN Data received Set by hardware when a new USB message is stored in the current bank of the Pipe. This triggers an interrupt if the RXINE bit is set in the UPIENX register. Shall be cleared to handshake the interrupt. Setting by software has no effect. 228 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 17.7.18 UPIENX - USB Pipe Interrupt ENable Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPIENX register. Bit $00AE Read/write Initial value 7 FLERRE R/W 0 6 NAKEDE R/W 0 5 R 0 4 PERRE R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 RXINE R/W 0 0x00 UPIENX TXSTPE TXOUTE RXSTALLE * Bit 7 - FLERRE : Flow Error Interrupt enable Set to enable the OVERFI and UNDERFI interrupts. Clear to disable the OVERFI and UNDERFI interrupts. * Bit 6 - NAKEDE : NAK Handshake Received Interrupt Enable Set to enable the NAKEDI interrupt. Clear to disable the NAKEDI interrupt. * Bit 5 - Res : Reserved The value read from these bits is always 0. Do not set these bits. * Bit 4 - PERRE : PIPE Error Interrupt Enable Set to enable the PERRI interrupt. Clear to disable the PERRI interrupt. * Bit 3 - TXSTPE : SETUP Bank ready Interrupt Enable Set to enable the TXSTPI interrupt. Clear to disable the TXSTPI interrupt. * Bit 2 - TXOUTE : OUT Bank ready Interrupt Enable Set to enable the TXOUTI interrupt. Clear to disable the TXOUTI interrupt. * Bit 1 - RXSTALLE : STALL Received Interrupt Enable Set to enable the RXSTALLI interrupt. Clear to disable the RXSTALLI interrupt. * Bit 0 - RXINE : IN Data received Interrupt Enable Set to enable the RXINI interrupt. Clear to disable the RXINI interrupt. 17.7.19 UPDATX - USB Pipe Data Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPDATX register. Bit $00AF Read/write Initial value R/W 0 R/W 0 R 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 UPDATX R/W 0 0x00 PDAT [7..0] 229 TPR0327AY-SMS-30Jan09 * Bits 7..0 - PDAT7..0 : Pipe Data Bits Set by the software to read/write a byte from/to the Pipe FIFO selected by PNUM. 17.7.20 UPBCX - USB Pipe Byte Count Register for Pipe X Set UPNUM register to point to the relevant Pipe before using the UPBCXH and UPBCXL registers. Bit $009C $009B Bit Read/write Initial value 7 R R/W 0 0 6 R R/W 0 0 5 R R/W 0 0 15 14 13 12 4 R R/W 0 0 11 3 R R/W 0 0 2 R/W R/W 0 0 10 9 PBYTCT [10..8] 1 R/W R/W 0 0 0 R/W R/W 0 0 0x00 0x00 8 UPBCXH UPBCXL PBYTCT [7..0] * Bits 15..11 - Res : Reserved The value read from these bits is always 0. Do not set these bits. * Bits 10..0 - PBYCT10..0 : Byte count Bits Set by hardware. PBYCT10:0 is: * (for OUT Pipe) increased after each writing into the Pipe and decremented after each byte sent, * (for IN Pipe) increased after each byte received by the host, and decremented after each byte read by the software. 17.7.21 UPINT - USB Pipe Interrupt Register Bit $009A Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 PINT3 R 0 2 PINT2 R 0 1 PINT1 R 0 0 PINT0 R 0 0x00 UPINT * Bits 7..4 - Res : Reserved The value read from these bits is always 0. Do not set these bits. * Bits 3..0 - PINT3..0 : Pipe Interrupts Bits Set by hardware when an interrupt is triggered by the UPINTX register and if the corresponding endpoint interrupt enable bit is set. Cleared by hardware when the interrupt source is served. 230 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 18. USART The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a highly flexible serial communication device. 18.1 Features * * * * * * * * * * * * Full Duplex Operation (Independent Serial Receive and Transmit Registers) Asynchronous or Synchronous Operation Master or Slave Clocked Synchronous Operation High Resolution Baud Rate Generator Supports Serial Frames with 5, 6, 7, 8, or 9 Data Bits and 1 or 2 Stop Bits Odd or Even Parity Generation and Parity Check Supported by Hardware Data OverRun Detection Framing Error Detection Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete Multi-processor Communication Mode Double Speed Asynchronous Communication Mode 18.2 USART0 The AT90SCR100 has one USART, USART0. 18.3 Overview A simplified block diagram of the USART Transmitter is shown in Figure 18-1 on page 232. CPU accessible I/O Registers and I/O pins are shown in bold. The Power Reducion USART0 bit, PRUSART0, in TBC must be disabled by writing a logical zero to it. 231 TPR0327AY-SMS-30Jan09 Figure 18-1. USART Block Diagram Clock Generator UBRR[H:L] OSC BAUD RATE GENERATOR SYNC LOGIC PIN CONTROL XCK Transmitter UDR (Transmit) PARITY GENERATOR TRANSMIT SHIFT REGISTER PIN CONTROL TxD TX CONTROL DATA BUS Receiver CLOCK RECOVERY RX CONTROL RECEIVE SHIFT REGISTER DATA RECOVERY PIN CONTROL RxD UDR (Receive) PARITY CHECKER UCSRA UCSRB UCSRC The dashed boxes in the block diagram separate the three main parts of the USART (listed from the top): Clock Generator, Transmitter and Receiver. Control Registers are shared by all units. The Clock Generation logic consists of synchronization logic for external clock input used by synchronous slave operation, and the baud rate generator. The XCK (Transfer Clock) pin is only used by synchronous transfer mode. The Transmitter consists of a single write buffer, a serial Shift Register, Parity Generator and Control logic for handling different serial frame formats. The write buffer allows a continuous transfer of data without any delay between frames. The Receiver is the most complex part of the USART module due to its clock and data recovery units. The recovery units are used for asynchronous data reception. In addition to the recovery units, the Receiver includes a Parity Checker, Control logic, a Shift Register and a two level receive buffer (UDR0). The Receiver supports the same frame formats as the Transmitter, and can detect Frame Error, Data OverRun and Parity Errors. 18.4 Clock Generation The Clock Generation logic generates the base clock for the Transmitter and Receiver. The USART0 supports four modes of clock operation: Normal asynchronous, Double Speed asyn- 232 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 chronous, Master synchronous and Slave synchronous mode. The UMSEL0 bit in USART Control and Status Register C (UCSR0C) selects between asynchronous and synchronous operation. Double Speed (asynchronous mode only) is controlled by the U2X0 found in the UCSR0A Register. When using synchronous mode (UMSEL0 = 1), the Data Direction Register for the XCK pin (DDR_XCK) controls whether the clock source is internal (Master mode) or external (Slave mode). The XCK pin is only active when using synchronous mode. Figure 18-2. Clock Generation Logic, Block Diagram UBRR fosc Prescaling Down-Counter UBRR+1 /2 /4 /2 U2X 0 1 Clk io or XCK DDR_XCK Sync Register Edge Detector 0 1 txclk xcki XCK Pin xcko 0 1 UMSEL DDR_XCK UCPOL 1 0 rxclk Signal description: txclk rxclk xcki operation. xcko fOSC 18.4.1 Transmitter clock (Internal Signal). Receiver base clock (Internal Signal). Input from XCK pin (internal Signal). Used for synchronous slave Clock output to XCK pin (Internal Signal). Used for synchronous master operation. UART Block clock: clkIO Internal Clock Generation - The Baud Rate Generator Internal clock generation is used for the asynchronous and the synchronous master modes of operation. The description in this section refers to Figure 18-2. The USART Baud Rate Register (UBRR0) and the down-counter connected to it function as a programmable prescaler or baud rate generator. The down-counter, running at system clock (fosc), is loaded with the UBRR0 value each time the counter has counted down to zero or when the UBRRL0 Register is written. A clock is generated each time the counter reaches zero. This clock is the baud rate generator clock output (= fosc/(UBRR0+1)). The Transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. The baud rate generator output is used directly by the Receiver's clock and data recovery units. However, the recovery units use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the UMSEL0, U2X0 and DDR_XCK bits. 233 TPR0327AY-SMS-30Jan09 Table 18-1 contains equations for calculating the baud rate (in bits per second) and for calculating the UBRR0 value for each mode of operation using an internally generated clock source. Table 18-1. Equations for Calculating Baud Rate Register Setting Equation for Calculating Baud Rate (1) Equation for Calculating UBRR Value Operating Mode Asynchronous Normal mode (U2X0 = 0) f OSC BAUD = ----------------------------------------16 ( UBRR0 + 1 ) f OSC UBRR0 = ----------------------- - 1 16BAUD Asynchronous Double Speed mode (U2X0 = 1) f OSC BAUD = -------------------------------------8 ( UBRR0 + 1 ) f OSC UBRR0 = ------------------- - 1 8BAUD Synchronous Master mode f OSC BAUD = -------------------------------------2 ( UBRR0 + 1 ) f OSC UBRR0 = ------------------- - 1 2BAUD 1. The baud rate is defined to be the transfer rate in bit per second (bps) BAUDBaud rate (in bits per second, bps) fOSCSystem Oscillator clock frequency injected in UART block: clkIO UBRRnContents of the UBRRH0 and UBRRL0 Registers, (0-4095) Some examples of UBRR0 values for some system clock frequencies are found in Table 18-9 on page 254. 18.4.2 Double Speed Operation (U2X0) The transfer rate can be doubled by setting the U2X0 bit in UCSR0A. Setting this bit only has effect for the asynchronous operation. Set this bit to zero when using synchronous operation. Setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. Note however that the Receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. For the Transmitter, there are no downsides. 234 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 18.4.3 External Clock External clocking is used by the synchronous slave modes of operation. The description in this section refers to Figure 18-2 for details. External clock input from the XCK pin is sampled by a synchronization register to minimize the chance of meta-stability. The output from the synchronization register must then pass through an edge detector before it can be used by the Transmitter and Receiver. This process introduces a two CPU clock period delay and therefore the maximum external XCK clock frequency is limited by the following equation: f OSC f XCK < ---------4 18.4.4 Synchronous Clock Operation When synchronous mode is used (UMSEL0 = 1), the XCK pin will be used as either clock input (Slave) or clock output (Master). The dependency between the clock edges and data sampling or data change is the same. The basic principle is that data input (on RxD0) is sampled at the opposite XCK clock edge of the edge the data output (TxD0) is changed. Figure 18-3. Synchronous Mode XCK Timing. UCPOL = 1 XCK RxD / TxD Sample UCPOL = 0 XCK RxD / TxD Sample The UCPOL0 bit UCRSC selects which XCK clock edge is used for data sampling and which is used for data change. As Figure 18-3 shows, when UCPOL0 is zero the data will be changed at rising XCK edge and sampled at falling XCK edge. If UCPOL0 is set, the data will be changed at falling XCK edge and sampled at rising XCK edge. 18.5 Frame Formats A serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a parity bit for error checking. The USART accepts all 30 combinations of the following as valid frame formats: * 1 start bit * 5, 6, 7, 8, or 9 data bits * no, even or odd parity bit * 1 or 2 stop bits A frame starts with the start bit followed by the least significant data bit. Then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit 235 TPR0327AY-SMS-30Jan09 is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. Figure 18-4 illustrates the possible combinations of the frame formats. Bits inside brackets are optional. Figure 18-4. Frame Formats FRAME (IDLE) St 0 1 2 3 4 [5] [6] [7] [8] [P] Sp1 [Sp2] (St / IDLE) St (n) P Sp IDLE must be Start bit, always low. Data bits (0 to 8). Parity bit. Can be odd or even. Stop bit, always high. No transfers on the communication line (RxD0 or TxD0). An IDLE line high. The frame format used by the USART is set by the UCSZ02:0, UPM01:0 and USBS0 bits in UCSR0B and UCSR0C. The Receiver and Transmitter use the same setting. Note that changing the setting of any of these bits will corrupt all ongoing communication for both the Receiver and Transmitter. The USART Character SiZe (UCSZ02:0) bits select the number of data bits in the frame. The USART Parity mode (UPM01:0) bits enable and set the type of parity bit. The selection between one or two stop bits is done by the USART Stop Bit Select (USBS0) bit. The Receiver ignores the second stop bit. An FE (Frame Error) will therefore only be detected in the cases where the first stop bit is zero. 18.5.1 Parity Bit Calculation The parity bit is calculated by doing an exclusive-or of all the data bits. If odd parity is used, the result of the exclusive or is inverted. The relation between the parity bit and data bits is as follows:: P even = d n - 1 ... d 3 d 2 d 1 d 0 0 P odd = d n - 1 ... d 3 d 2 d 1 d 0 1 Peven Podd dn Parity bit using even parity Parity bit using odd parity Data bit n of the character If used, the parity bit is located between the last data bit and first stop bit of a serial frame. 18.6 USART Initialization The USART has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. For interrupt driven by USART operation, 236 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the initialization. Before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. The TXC0 Flag can be used to check that the Transmitter has completed all transfers, and the RXC Flag can be used to check that there are no unread data in the receive buffer. The TXC0 Flag must be cleared before each transmission (before UDR0 is written) if it is used for this purpose. Note The following simple USART initialization code examples show one assembly and one C function that are equal in functionality. The examples assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. The baud rate is given as a function parameter. For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 Registers. Assembly Code Example(1) USART_Init: ; Set baud rate out out ldi out ldi out ret UBRRH0, r17 UBRRLn0 r16 r16, (1< ; Set frame format: 8data, 2stop bit C Code Example (1) void USART_Init( unsigned int baud ) { /* Set baud rate */ UBRRH0 = (unsigned char)(baud>>8); UBRRL0 = (unsigned char)baud; /* Enable receiver and transmitter */ UCSR0B = (1< 237 TPR0327AY-SMS-30Jan09 18.7 Data Transmission - The USART Transmitter The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSR0B Register. When the Transmitter is enabled, the normal port operation of the TxD0 pin is overridden by the USART and given the function as the Transmitter's serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions. If synchronous operation is used, the clock on the XCK pin will be overridden and used as transmission clock. 18.7.1 Sending Frames with 5 to 8 Data Bit A data transmission is initiated by loading the transmit buffer with the data to be transmitted. The CPU can load the transmit buffer by writing to the UDR0 I/O location. The buffered data in the transmit buffer will be moved to the Shift Register when the Shift Register is ready to send a new frame. The Shift Register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. When the Shift Register is loaded with new data, it will transfer one complete frame at the rate given by the Baud Register, U2X0 bit or by XCK depending on mode of operation. The following code examples show a simple USART transmit function based on polling of the Data Register Empty (UDRE0) Flag. When using frames with less than eight bits, the most significant bits written to the UDR0 are ignored. The USART has to be initialized before the function can be used. For the assembly code, the data to be sent is assumed to be stored in Register R16 Assembly Code Example(1) USART_Transmit: ; Wait for empty transmit buffer sbis UCSR0A,UDRE0 rjmp USART_Transmit ; Put data (r16) into buffer, sends the data out ret UDR0,r16 C Code Example (1) void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSR0A & (1< 238 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 18.7.2 Sending Frames with 9 Data Bit If 9-bit characters are used (UCSZ0 = 7), the ninth bit must be written to the TXB8 bit in UCSR0B before the low byte of the character is written to UDR0. The following code examples show a transmit function that handles 9-bit characters. For the assembly code, the data to be sent is assumed to be stored in registers R17:R16. Assembly Code Example(1) USART_Transmit: ; Wait for empty transmit buffer sbis UCSR0A,UDRE0 rjmp USART_Transmit ; Copy 9th bit from r17 to TXB8 cbi sbi out ret UCSR0B,TXB8 UCSR0B,TXB8 UDR0,r16 sbrc r17,0 ; Put LSB data (r16) into buffer, sends the data C Code Example (1) void USART_Transmit( unsigned int data ) { /* Wait for empty transmit buffer */ while ( !( UCSR0A & (1< 239 TPR0327AY-SMS-30Jan09 When the Data Register Empty Interrupt Enable (UDRIE0) bit in UCSR0B is written to one, the USART Data Register Empty Interrupt will be executed as long as UDRE0 is set (assuming that global interrupts are enabled). UDRE0 is cleared by writing UDR0. When interrupt-driven data transmission is used, the Data Register Empty interrupt routine must either write new data to UDR0 in order to clear UDRE0 or disable the Data Register Empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. The Transmit Complete (TXC0) Flag bit is set when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer. The TXC0 Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC0 Flag is useful in half-duplex communication interfaces (like the RS-485 standard), where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. When the Transmit Compete Interrupt Enable (TXCIE0) bit in UCSR0B is set, the USART Transmit Complete Interrupt will be executed when the TXC0 Flag becomes set (provided that global interrupts are enabled). When the transmit complete interrupt is used, the interrupt handling routine does not have to clear the TXC0 Flag, this is done automatically when the interrupt is executed. 18.7.4 Parity Generator The Parity Generator calculates the parity bit for the serial frame data. When parity bit is enabled (UPM01 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. Disabling the Transmitter The disabling of the Transmitter (setting the TXEN to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD0 pin. 18.7.5 18.8 Data Reception - The USART Receiver The USART Receiver is enabled by writing the Receive Enable (RXEN0) bit in the UCSR0B Register to one. When the Receiver is enabled, the normal pin operation of the RxD0 pin is overridden by the USART and given the function as the Receiver's serial input. The baud rate, mode of operation and frame format must be set up once before any serial reception can be done. If synchronous operation is used, the clock on the XCK pin will be used as transfer clock. 18.8.1 Receiving Frames with 5 to 8 Data Bits The Receiver starts data reception when it detects a valid start bit. Each bit that follows the start bit will be sampled at the baud rate or XCK clock, and shifted into the Receive Shift Register until the first stop bit of a frame is received. A second stop bit will be ignored by the Receiver. When the first stop bit is received, i.e., a complete serial frame is present in the Receive Shift Register, the contents of the Shift Register will be moved into the receive buffer. The receive buffer can then be read by reading the UDR0 I/O location. The following code example shows a simple USART receive function based on polling of the Receive Complete (RXC0) Flag. When using frames with less than eight bits the most significant 240 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 bits of the data read from the UDR0 will be masked to zero. The USART has to be initialized before the function can be used. Assembly Code Example(1) USART_Receive: ; Wait for data to be received sbis UCSR0A, RXC0 rjmp USART_Receive ; Get and return received data from buffer in ret r16, UDR0 C Code Example(1) unsigned char USART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSR0A & (1< 241 TPR0327AY-SMS-30Jan09 Assembly Code Example(1) USART_Receive: ; Wait for data to be received sbis UCSR0A, RXC0 rjmp USART_Receive ; Get status and 9th bit, then data from buffer in in in r18, UCSR0A r17, UCSR0B r16, UDR0 ; If error, return -1 andi r18,(1< C Code Example(1) unsigned int USART_Receive( void ) { unsigned char status, resh, resl; /* Wait for data to be received */ while ( !(UCSR0A & (1< The receive function example reads all the I/O Registers into the Register File before any computation is done. This gives an optimal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. 242 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 18.8.3 Receive Compete Flag and Interrupt The USART Receiver has one flag that indicates the Receiver state. The Receive Complete (RXC0) Flag indicates if there are unread data present in the receive buffer. This flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled (RXEN0 = 0), the receive buffer will be flushed and consequently the RXC0 bit will become zero. When the Receive Complete Interrupt Enable (RXCIE0) in UCSR0B is set, the USART Receive Complete interrupt will be executed as long as the RXC0 Flag is set (provided that global interrupts are enabled). When interrupt-driven data reception is used, the receive complete routine must read the received data from UDR0 in order to clear the RXC0 Flag, otherwise a new interrupt will occur once the interrupt routine terminates. 18.8.4 Receiver Error Flags The USART Receiver has three Error Flags: Frame Error (FE0), Data OverRun (DOR0) and Parity Error (UPE0). All can be accessed by reading UCSR0A. Common for the Error Flags is that they are located in the receive buffer together with the frame for which they indicate the error status. Due to the buffering of the Error Flags, the UCSR0A must be read before the receive buffer (UDR0), since reading the UDR0 I/O location changes the buffer read location. Another equality for the Error Flags is that they can not be altered by software doing a write to the flag location. However, all flags must be set to zero when the UCSR0A is written for upward compatibility of future USART implementations. None of the Error Flags can generate interrupts. The Frame Error (FE0) Flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. The FE0 Flag is zero when the stop bit was correctly read (as one), and the FE0 Flag will be one when the stop bit was incorrect (zero). This flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. The FE0 Flag is not affected by the setting of the USBS0 bit in UCSR0C since the Receiver ignores all, except for the first, stop bits. For compatibility with future devices, always set this bit to zero when writing to UCSR0A. The Data OverRun (DOR0) Flag indicates data loss due to a receiver buffer full condition. A Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a new start bit is detected. If the DOR0 Flag is set there was one or more serial frame lost between the frame last read from UDR0, and the next frame read from UDR0. For compatibility with future devices, always write this bit to zero when writing to UCSR0A. The DOR0 Flag is cleared when the frame received was successfully moved from the Shift Register to the receive buffer. The Parity Error (UPE0) Flag indicates that the next frame in the receive buffer had a Parity Error when received. If Parity Check is not enabled the UPE0 bit will always be read zero. For compatibility with future devices, always set this bit to zero when writing to UCSR0A. For more details see "Parity Bit Calculation" on page 236 and "Parity Checker" on page 243. 18.8.5 Parity Checker The Parity Checker is active when the high USART Parity mode (UPM01) bit is set. Type of Parity Check to be performed (odd or even) is selected by the UPM00 bit. When enabled, the Parity Checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. The result of the check is stored in the receive buffer together 243 TPR0327AY-SMS-30Jan09 with the received data and stop bits. The Parity Error (UPE0) Flag can then be read by software to check if the frame had a Parity Error. The UPE0 bit is set if the next character that can be read from the receive buffer had a Parity Error when received and the Parity Checking was enabled at that point (UPM01 = 1). This bit is valid until the receive buffer (UDR0) is read. 18.8.6 Disabling the Receiver In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing receptions will therefore be lost. When disabled (i.e., the RXEN0 is set to zero) the Receiver will no longer override the normal function of the RxD0 port pin. The Receiver buffer FIFO will be flushed when the Receiver is disabled. Remaining data in the buffer will be lost Flushing the Receive Buffer The receiver buffer FIFO will be flushed when the Receiver is disabled, i.e., the buffer will be emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal operation, due to for instance an error condition, read the UDR0 I/O location until the RXC0 Flag is cleared. The following code example shows how to flush the receive buffer. Assembly Code Example(1) USART_Flush: sbis UCSR0A, RXC0 ret in r16, UDR0 rjmp USART_Flush 18.8.7 C Code Example(1) void USART_Flush( void ) { unsigned char dummy; while ( UCSR0A & (1< Asynchronous Data Reception The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the RxD0 pin. The data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the Receiver. The asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 18.9.1 Asynchronous Clock Recovery The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 18-5 illustrates the sampling process of the start bit of an incoming frame. The sample rate is 16 times the baud rate for Normal mode, and eight times the baud rate for Double Speed mode. The horizontal arrows illustrate the synchronization variation due to the sampling process. Note the larger time variation is obtained when using the Double Speed mode (U2X0 = 1) of operation. 244 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Samples denoted zero are samples done when the RxD0 line is idle (i.e., no communication activity). Figure 18-5. Start Bit Sampling RxD IDLE START BIT 0 Sample (U2X = 0) 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 Sample (U2X = 1) 0 1 2 3 4 5 6 7 8 1 2 When the clock recovery logic detects a high (idle) to low (start) transition on the RxD0 line, the start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in the figure. The clock recovery logic then uses samples 8, 9, and 10 for Normal mode, and samples 4, 5, and 6 for Double Speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. If two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the Receiver starts looking for the next high to low-transition. If however, a valid start bit is detected, the clock recovery logic is synchronized and the data recovery can begin. The synchronization process is repeated for each start bit. 18.9.2 Asynchronous Data Recovery When the receiver clock is synchronized to the start bit, the data recovery can begin. The data recovery unit uses a state machine that has 16 states for each bit in Normal mode and eight states for each bit in Double Speed mode. Figure 18-6 shows the sampling of the data bits and the parity bit. Each of the samples is given a number that is equal to the state of the recovery unit. Figure 18-6. Sampling of Data and Parity Bit RxD BIT n Sample (U2X = 0) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 Sample (U2X = 1) 1 2 3 4 5 6 7 8 1 The decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. The center samples are emphasized on the figure by having the sample number inside boxes. The majority voting process is done as follows: If two or all three samples have high levels, the received bit is registered to be a logic 1. If two or all three samples have low levels, the received bit is registered to be a logic 0. This majority voting process acts as a low pass filter for the incoming signal on the RxD0 pin. The recovery process is then repeated until a complete frame is received. Including the first stop bit. Note that the Receiver only uses the first stop bit of a frame. Figure 18-7 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. 245 TPR0327AY-SMS-30Jan09 Figure 18-7. Stop Bit Sampling and Next Start Bit Sampling RxD STOP 1 (A) (B) (C) Sample (U2X = 0) 1 2 3 4 5 6 7 8 9 10 0/1 0/1 0/1 Sample (U2X = 1) 1 2 3 4 5 6 0/1 The same majority voting is done to the stop bit as done for the other bits in the frame. If the stop bit is registered to have a logic 0 value, the Frame Error (FE0) Flag will be set. A new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. For Normal Speed mode, the first low level sample can be at point marked (A) in Figure 18-7. For Double Speed mode the first low level must be delayed to (B). (C) marks a stop bit of full length. The early start bit detection influences the operational range of the Receiver. 18.9.3 Asynchronous Operational Range The operational range of the Receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. If the Transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the Receiver does not have a similar (see Table 18-2) base frequency, the Receiver will not be able to synchronize the frames to the start bit. The following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. Table 19-1 . ( D + 1 )S R slow = -----------------------------------------S - 1 + D S + SF D S SF SM Rslow ( D + 2 )S R fast = ----------------------------------( D + 1 )S + S M Sum of character size and parity size (D = 5 to 10 bit) Samples per bit. S = 16 for Normal Speed mode and S = 8 for Double Speed mode. First sample number used for majority voting. SF = 8 for normal speed and SF = 4 for Double Speed mode. Middle sample number used for majority voting. SM = 9 for normal speed and SM = 5 for Double Speed mode. is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. Rfast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. Table 18-2 and Table 18-3 list the maximum receiver baud rate error that can be tolerated. Note that Normal Speed mode has higher toleration of baud rate variations. 246 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 18-2. Recommended Maximum Receiver Baud Rate Error for Normal Speed Mode (U2Xn = 0) Rslow (%) 93.20 94.12 94.81 95.36 95.81 96.17 Rfast (%) 106.67 105.79 105.11 104.58 104.14 103.78 Max Total Error (%) +6.67/-6.8 +5.79/-5.88 +5.11/-5.19 +4.58/-4.54 +4.14/-4.19 +3.78/-3.83 Recommended Max Receiver Error (%) 3.0 2.5 2.0 2.0 1.5 1.5 D # (Data+Parity Bit) 5 6 7 8 9 10 Table 18-3. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode (U2Xn = 1) Rslow (%) 94.12 94.92 95.52 96.00 96.39 96.70 Rfast (%) 105.66 104.92 104,35 103.90 103.53 103.23 Max Total Error (%) +5.66/-5.88 +4.92/-5.08 +4.35/-4.48 +3.90/-4.00 +3.53/-3.61 +3.23/-3.30 Recommended Max Receiver Error (%) 2.5 2.0 1.5 1.5 1.5 1.0 D # (Data+Parity Bit) 5 6 7 8 9 10 The recommendations of the maximum receiver baud rate error was made under the assumption that the Receiver and Transmitter equally divides the maximum total error. There are two possible sources for the receivers baud rate error. The Receiver's system clock (XTAL) will always have some minor instability over the supply voltage range and the temperature range. When using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. The second source for the error is more controllable. The baud rate generator can not always do an exact division of the system frequency to get the baud rate wanted. In this case an UBRR value that gives an acceptable low error can be used if possible. 18.10 Multi-processor Communication Mode Setting the Multi-processor Communication mode (MPCM0) bit in UCSR0A enables a filtering function of incoming frames received by the USART Receiver. Frames that do not contain address information will be ignored and not put into the receive buffer. This effectively reduces the number of incoming frames that has to be handled by the CPU, in a system with multiple MCUs that communicate via the same serial bus. The Transmitter is unaffected by the MPCM0 setting, but has to be used differently when it is a part of a system utilizing the Multi-processor Communication mode. If the Receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indicates if the frame contains data or address information. If the Receiver is set up for frames with 247 TPR0327AY-SMS-30Jan09 nine data bits, then the ninth bit (RXB8n) is used for identifying address and data frames. When the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. When the frame type bit is zero the frame is a data frame. The Multi-processor Communication mode enables several slave MCUs to receive data from a master MCU. This is done by first decoding an address frame to find out which MCU has been addressed. If a particular slave MCU has been addressed, it will receive the following data frames as normal, while the other slave MCUs will ignore the received frames until another address frame is received. 18.10.1 Using MPCM0 For an MCU to act as a master MCU, it can use a 9-bit character frame format (UCSZ0 = 7). The ninth bit (TXB80) must be set when an address frame (TXB80 = 1) or cleared when a data frame (TXB = 0) is being transmitted. The slave MCUs must in this case be set to use a 9-bit character frame format. The following procedure should be used to exchange data in Multi-processor Communication mode: 1. All Slave MCUs are in Multi-processor Communication mode (MPCM0 in UCSR0A is set). 2. The Master MCU sends an address frame, and all slaves receive and read this frame. In the Slave MCUs, the RXC0 Flag in UCSR0A will be set as normal. 3. Each Slave MCU reads the UDR0 Register and determines if it has been selected. If so, it clears the MPCM0 bit in UCSR0A, otherwise it waits for the next address byte and keeps the MPCM0 setting. 4. The addressed MCU will receive all data frames until a new address frame is received. The other Slave MCUs, which still have the MPCM0 bit set, will ignore the data frames. 5. When the last data frame is received by the addressed MCU, the addressed MCU sets the MPCM0 bit and waits for a new address frame from master. The process then repeats from 2. Using any of the 5- to 8-bit character frame formats is possible, but impractical since the Receiver must change between using n and n+1 character frame formats. This makes fullduplex operation difficult since the Transmitter and Receiver uses the same character size setting. If 5- to 8-bit character frames are used, the Transmitter must be set to use two stop bit (USBS0 = 1) since the first stop bit is used for indicating the frame type. Do not use Read-Modify-Write instructions (SBI and CBI) to set or clear the MPCM0 bit. The MPCM0 bit shares the same I/O location as the TXC0 Flag and this might accidentally be cleared when using SBI or CBI instructions. 248 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 18.11 USART Register Description 18.11.1 UDR0 - USART I/O Data Register n Bit $0000C6 $0000C6 Read/write Initial value R/W 0 R/W 0 R/W 0 0 7 6 5 4 3 RXB[7..0] TXB[7..0] R/W R/W 0 R/W 0 R/W 0 R/W 0 0x00 2 1 0 UDR0 (Read) (Write) The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address referred to as USART Data Register or UDR0. The Transmit Data Buffer Register (TXB) will be the destination for data written to the UDR0 Register location. Reading the UDR0 Register location will return the contents of the Receive Data Buffer Register (RXB). For 5-, 6-, or 7-bit characters the upper unused bits will be ignored by the Transmitter and set to zero by the Receiver. The transmit buffer can only be written when the UDRE0 Flag in the UCSR0A Register is set. Data written to UDR0 when the UDRE0 Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the Shift Register is empty. Then the data will be serially transmitted on the TxD0 pin. The receive buffer consists of a two level FIFO. The FIFO will change its state whenever the receive buffer is accessed. Due to this behavior of the receive buffer, do not use Read-ModifyWrite instructions (SBI and CBI) on this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of the FIFO. 18.11.2 UCSR0A - USART Control and Status Register A Bit $0000C0 Read/write Initial value 7 RXC0 R 0 6 TXC0 R/W 0 5 UDRE0 R 1 4 FE0 R 0 3 DOR0 R 0 2 UPE0 R 0 1 U2X0 R/W 0 0 MPCM0 R/W 0 0x20 UCSR0A * Bit 7 - RXC0: USART Receive Complete This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXC0 bit will become zero. The RXC0 Flag can be used to generate a Receive Complete interrupt (see description of the RXCIE0 bit). * Bit 6 - TXC0: USART Transmit Complete This flag bit is set when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer (UDR0). The TXC0 Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC0 Flag can generate a Transmit Complete interrupt (see description of the TXCIE0 bit). * Bit 5 - UDRE0: USART Data Register Empty 249 TPR0327AY-SMS-30Jan09 The UDRE0 flag indicates if the transmit buffer (UDR0) is ready to receive new data. If UDRE0 is one, the buffer is empty, and therefore ready to be written. The UDRE0 Flag can generate a Data Register Empty interrupt (see description of the UDRIE0 bit). UDRE0 is set after a reset to indicate that the Transmitter is ready. * Bit 4 - FE0: Frame Error This bit is set if the next character in the receive buffer had a Frame Error when received. I.e., when the first stop bit of the next character in the receive buffer is zero. This bit is valid until the receive buffer (UDR0) is read. The FE0 bit is zero when the stop bit of received data is one. Always set this bit to zero when writing to UCSR0A. * Bit 3 - DOR0: Data OverRun This bit is set if a Data OverRun condition is detected. A Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a new start bit is detected. This bit is valid until the receive buffer (UDR0) is read. Always set this bit to zero when writing to UCSR0A. * Bit 2 - UPE0: USART Parity Error This bit is set if the next character in the receive buffer had a Parity Error when received and the Parity Checking was enabled at that point (UPM01 = 1). This bit is valid until the receive buffer (UDR0) is read. Always set this bit to zero when writing to UCSR0A. * Bit 1 - U2X0: Double the USART Transmission Speed This bit only has effect for the asynchronous operation. Write this bit to zero when using synchronous operation. Writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively doubling the transfer rate for asynchronous communication. * Bit 0 - MPCM0: Multi-processor Communication Mode This bit enables the Multi-processor Communication mode. When the MPCM0 bit is written to one, all the incoming frames received by the USART Receiver that do not contain address information will be ignored. The Transmitter is unaffected by the MPCM0 setting. For more detailed information see "Multi-processor Communication Mode" on page 247. 18.11.3 UCSR0B - USART Control and Status Register B Bit $0000C1 Read/write Initial value 7 RXCIE0 R/W 0 6 TXCIE0 R/W 0 5 UDRIE0 R/W 0 4 RXEN0 R/W 0 3 TXEN0 R/W 0 2 UCSZ02 R/W 0 1 RXB80 R 0 0 TXB80 R/W 0 0x00 UCSR0B * Bit 7 - RXCIE0: RX Complete Interrupt Enable 0 Writing this bit to one enables interrupt on the RXC0 Flag. A USART Receive Complete interrupt will be generated only if the RXCIE0 bit is written to one, the Global Interrupt Flag in SREG is written to one and the RXC0 bit in UCSR0A is set. * Bit 6 - TXCIE0: TX Complete Interrupt Enable 0 250 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Writing this bit to one enables interrupt on the TXC0 Flag. A USART Transmit Complete interrupt will be generated only if the TXCIE0 bit is written to one, the Global Interrupt Flag in SREG is written to one and the TXC0 bit in UCSR0A is set. * Bit 5 - UDRIE0: USART Data Register Empty Interrupt Enable 0 Writing this bit to one enables interrupt on the UDRE0 Flag. A Data Register Empty interrupt will be generated only if the UDRIE0 bit is written to one, the Global Interrupt Flag in SREG is written to one and the UDRE0 bit in UCSR0A is set. * Bit 4 - RXEN0: Receiver Enable 0 Writing this bit to one enables the USART Receiver. The Receiver will override normal port operation for the RxD0 pin when enabled. Disabling the Receiver will flush the receive buffer invalidating the FE0, DOR0, and UPE0 Flags. * Bit 3 - TXEN0: Transmitter Enable 0 Writing this bit to one enables the USART Transmitter. The Transmitter will override normal port operation for the TxD0 pin when enabled. The disabling of the Transmitter (writing TXENn0to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD0 port. * Bit 2 - UCSZ02: Character Size 0 The UCSZ02 bits combined with the UCSZ01:0 bit in UCSR0C sets the number of data bits (Character size) in a frame the Receiver and Transmitter use. * Bit 1 - RXB80: Receive Data Bit 8 0 RXB80 is the ninth data bit of the received character when operating with serial frames with nine data bits. Must be read before reading the low bits from UDR0. * Bit 0 - TXB80: Transmit Data Bit 8 0 TXB80 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. Must be written before writing the low bits to UDR0. 18.11.4 UCSR0C - USART Control and Status Register C Bit $0000C2 Read/write Initial value 7 UMSEL01 R/W 0 6 UMSEL00 R/W 0 5 UPM01 R/W 0 4 UPM00 R/W 0 3 USBS0 R/W 0 2 UCSZ01 R/W 1 1 UCSZ00 R/W 1 0 UCPOL0 R/W 0 0x06 UCSR0C * Bits 7..6 - UMSEL01..0 USART Mode Select These bits select the mode of operation of the USART0 as shown in Table 18-4.. Table 18-4. 0 UMSEL0 Bits Settings UMSEL00 0 Mode Asynchronous USART UMSEL01 251 TPR0327AY-SMS-30Jan09 Table 18-4. 0 1 1 Note: UMSEL0 Bits Settings UMSEL00 1 0 1 Mode Synchronous USART (Reserved) Master SPI (MSPIM)(1) UMSEL01 1. See "USART in SPI Mode" on page 257 for full description of the Master SPI Mode (MSPIM) operation * Bits 5..4 - UPM01..0: Parity Mode These bits enable and set type of parity generation and check. If enabled, the Transmitter will automatically generate and send the parity of the transmitted data bits within each frame. The Receiver will generate a parity value for the incoming data and compare it to the UPM0 setting. If a mismatch is detected, the UPE0 Flag in UCSR0A will be set. Table 18-5. UPM01 0 0 1 1 UPM0 Bits Settings UPM00 0 1 0 1 Parity Mode Disabled Reserved Enabled, Even Parity Enabled, Odd Parity * Bit 3 - USBS0: Stop Bit Select This bit selects the number of stop bits to be inserted by the Transmitter. The Receiver ignores this setting. Table 18-6. USBS Bit Settings USBS0 0 1 Stop Bit(s) 1-bit 2-bit * Bit 2:1 - UCSZ01:0: Character Size The UCSZ01:0 bits combined with the UCSZ02 bit in UCSR0B sets the number of data bits (Character size) in a frame the Receiver and Transmitter use. Table 18-7. UCSZ02 0 0 0 0 1 UCSZ0 Bits Settings UCSZ01 0 0 1 1 0 UCSZ00 0 1 0 1 0 Character Size 5-bit 6-bit 7-bit 8-bit Reserved 252 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 18-7. UCSZ02 1 1 1 UCSZ0 Bits Settings UCSZ01 0 1 1 UCSZ00 1 0 1 Character Size Reserved Reserved 9-bit * Bit 0 - UCPOL0: Clock Polarity This bit is used for synchronous mode only. Write this bit to zero when asynchronous mode is used. The UCPOL0 bit sets the relationship between data output change and data input sample, and the synchronous clock (XCK). Table 18-8. UCPOL0 0 1 UCPOLn Bit Settings Transmitted Data Changed (Output of TxD0 Pin) Rising XCK Edge Falling XCK Edge Received Data Sampled (Input on RxD0 Pin) Falling XCK Edge Rising XCK Edge 18.11.5 UBRR0L and UBRR0H - USART Baud Rate Registers Bit $0000C5 $0000C4 Read/write Initial value R R/W 0 0 R R/W 0 0 R R/W 0 0 7 6 5 4 UBRR[7..0] R R/W 0 0 R/W R/W 0 0 R/W R/W 0 0 R/W R/W 0 0 R/W R/W 0 0 0x00 0x00 3 2 1 0 UBRRH0 UBRRL0 UBRR[11..8] * Bit 15..12 - Reserved Bits These bits are reserved for future use. For compatibility with future devices, these bit must be written to zero when UBRRH is written. * Bit 11..0 - UBRR11..0: USART Baud Rate Register This is a 12-bit register which contains the USART baud rate. The UBRRH contains the four most significant bits, and the UBRRL contains the eight least significant bits of the USART baud rate. Ongoing transmissions by the Transmitter and Receiver will be corrupted if the baud rate is changed. Writing UBRRL will trigger an immediate update of the baud rate prescaler. 253 TPR0327AY-SMS-30Jan09 18.12 Examples of Baud Rate Setting For AT90SCR100 frequencies, the most commonly used baud rates for asynchronous operation can be generated by using the UBRR settings in Table 18-9 and Table 18-10. UBRR values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the table. Higher error ratings are acceptable, but the Receiver will have less noise resistance when the error ratings are high, especially for large serial frames (see "Asynchronous Operational Range" on page 246). The error values are calculated using the following equation: BaudRate Closest Match Error[%] = ------------------------------------------------------- - 1 * 100% BaudRate Table 18-9. Baud Rate (bps) 2400 4800 9600 14.4k 19.2k 28.8k 38.4k 57.6k 76.8k 115.2k 230.4k 250k 500k 1M 1.5M 2M Max. Note: (1) Examples of UBRR0 Settings accessible Oscillator Frequencies fosc = 8.0000 MHz U2X0 = 0 U2X0 = 1 UBRR 416 207 103 68 51 34 25 16 12 8 3 3 1 0 1Mbps Error -0.1% 0.2% 0.2% 0.6% 0.2% -0.8% 0.2% 2.1% 0.2% -3.5% 8.5% 0% 0% 0% fosc = 16 MHz U2X0 = 0 UBRR 416 207 103 68 51 34 25 16 12 8 3 3 1 0 1Mbps Error -0.1% 0.2% 0.2% 0.6% 0.2% -0.8% 0.2% 2.1% 0.2% -3.5% 8.5% 0% 0% 0% U2X0 = 1 UBRR 832 416 207 138 103 68 51 34 25 16 8 7 3 1 0 0 2Mbps Error 0% -0.1% 0.2% -0.1% 0.2% 0.6% 0.2% -0.8% 0.2% 2.1% -3.5% 0% 0% 0% 33.3% 0% UBRR 499 249 124 82 62 41 30 20 15 9 4 4 1 0 fosc = 19.2 MHz U2X0 = 0 Error 0% 0% 0% 0.4% -0.8% -0.8% 0.8% -0.8% 2.3% 4.2% 4.2% -4% 20% 20% -% -% 1.2Mbps U2X0 = 1 UBRR 999 499 249 166 124 82 62 41 30 20 9 9 4 1 1 0 Error 0% 0% 0% -0.2% 0% 0.4% -0.8% -0.8% 0.8% -0.8% 4.2% -4% -4% 20% -20% 20% 2.4Mbps UBRR 207 103 51 34 25 16 12 8 6 3 1 1 0 - Error 0.2% 0.2% 0.2% -0.8% 0.2% 2.1% 0.2% -3.5% -7% 8.5% 8.5% 0% 0% - 500kbps 1. UBRR = 0, Error = 0.0% 254 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 18-10. Examples of UBRR0 Settings accessible Oscillator Frequencies (Continued) fosc = 20 MHz Baud Rate (bps) 2400 4800 9600 14.4k 19.2k 28.8k 38.4k 57.6k 76.8k 115.2k 230.4k 250k 500k 1M 1.5M 2M Max.(1) 1.25Mbps U2X0 = 0 UBRR 520 259 129 86 64 42 32 21 15 10 4 4 2 0 Error 0% 0.2% 0.2% -0.2% 0.2% 0.9% -1.4% -1.4% 1.7% -1.4% 8.5% 0% -16.7% 25% U2X0 = 1 UBRR 1041 520 259 173 129 86 64 42 32 21 10 9 4 2 1 0 Error 0% 0% 0.2% -0.2% 0.2% -0.2% 0.2% 0.9% -1.4% -1.4% -1.4% 0% 0% -16.7% -16.7% 25% 2.5Mbps Note: 1. UBRR = 0, Error = 0.0% 255 TPR0327AY-SMS-30Jan09 256 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 19. USART in SPI Mode The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) can be set to a master SPI compliant mode of operation. The Master SPI Mode (MSPIM) has the following features: 19.1 Features * * * * * * * * Full Duplex, Three-wire Synchronous Data Transfer Master Operation Supports all four SPI Modes of Operation (Mode 0, 1, 2, and 3) LSB First or MSB First Data Transfer (Configurable Data Order) Queued Operation (Double Buffered) High Resolution Baud Rate Generator High Speed Operation (fXCKmax = fCK/2) Flexible Interrupt Generation 19.2 Overview Setting both UMSEL01:0 bits to one enables the USART in MSPIM logic. In this mode of operation the SPI master control logic takes direct control over the USART resources. These resources include the transmitter and receiver shift register and buffers, and the baud rate generator. The parity generator and checker, the data and clock recovery logic, and the RX and TX control logic is disabled. The USART RX and TX control logic is replaced by a common SPI transfer control logic. However, the pin control logic and interrupt generation logic is identical in both modes of operation. The I/O register locations are the same in both modes. However, some of the functionality of the control registers changes when using MSPIM. 19.3 Clock Generation The Clock Generation logic generates the base clock for the Transmitter and Receiver. For USART MSPIM mode of operation only internal clock generation (i.e. master operation) is supported. The Data Direction Register for the XCK0 pin (DDR_XCK0) must therefore be set to one (i.e. as output) for the USART in MSPIM to operate correctly. Preferably the DDR_XCK0 should be set up before the USART in MSPIM is enabled (i.e. TXEN0 and RXEN0 bit set to one). The internal clock generation used in MSPIM mode is identical to the USART synchronous master mode. The baud rate or UBRR0 setting can therefore be calculated using the same equations, see Table 19-1: 257 TPR0327AY-SMS-30Jan09 Table 19-1. Equations for Calculating Baud Rate Register Setting Equation for Calculating Baud Rate (1) Equation for Calculating UBRR0 Value Operating Mode Synchronous Master mode f OSC BAUD = -------------------------------------2 ( UBRRn + 1 ) f OSC UBRRn = ------------------- - 1 2BAUD 1. The baud rate is defined to be the transfer rate in bit per second (bps) BAUD fOSC UBRR0 Baud rate (in bits per second, bps) System Oscillator clock frequency: clkIO Contents of the UBRR0H and UBRR0L Registers, (0-4095) 19.4 SPI Data Modes and Timing There are four combinations of XCK0 (SCK) phase and polarity with respect to serial data, which are determined by control bits UCPHA0 and UCPOL0. The data transfer timing diagrams are shown in Figure 19-1. Data bits are shifted out and latched in on opposite edges of the XCK0 signal, ensuring sufficient time for data signals to stabilize. The UCPOL0 and UCPHA0 functionality is summarized in Table 19-2. Note that changing the setting of any of these bits will corrupt all ongoing communication for both the Receiver and Transmitter. Table 19-2. UCPOL0 0 0 1 1 UCPOL0 and UCPHA0 FunctionalityUCPHA0 0 1 0 1 SPI Mode 0 1 2 3 Leading Edge Sample (Rising) Setup (Rising) Sample (Falling) Setup (Falling) Trailing Edge Setup (Falling) Sample (Falling) Setup (Rising) Sample (Rising) 258 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 19-1. UCPHA0 and UCPOL0 data transfer timing diagrams. UCPOL=0 UCPHA=1 XCK Data setup (TXD) Data sample (RXD) XCK Data setup (TXD) Data sample (RXD) UCPOL=1 UCPHA=0 XCK Data setup (TXD) Data sample (RXD) XCK Data setup (TXD) Data sample (RXD) 19.5 Frame Formats A serial frame for the MSPIM is defined to be one character of 8 data bits. The USART in MSPIM mode has two valid frame formats: * 8-bit data with MSB first * 8-bit data with LSB first A frame starts with the least or most significant data bit. Then the next data bits, up to a total of eight, are succeeding, ending with the most or least significant bit accordingly. When a complete frame is transmitted, a new frame can directly follow it, or the communication line can be set to an idle (high) state. The UDORD0 bit in UCSR0C sets the frame format used by the USART in MSPIM mode. The Receiver and Transmitter use the same setting. Note that changing the setting of any of these bits will corrupt all ongoing communication for both the Receiver and Transmitter. 16-bit data transfer can be achieved by writing two data bytes to UDR0. A UART transmit complete interrupt will then signal that the 16-bit value has been shifted out. 19.5.1 USART MSPIM Initialization The USART in MSPIM mode has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting master mode of operation (by setting DDR_XCK0 to one), setting frame format and enabling the Transmitter and the Receiver. Only the transmitter can operate independently. For interrupt driven USART operation, the Global Interrupt Flag should be cleared (and thus interrupts globally disabled) when doing the initialization. To ensure immediate initialization of the XCK0 output the baud-rate register (UBRR0) must be zero at the time the transmitter is enabled. Contrary to the normal mode USART operation the UBRR0 must then be written to the desired value after the transmitter is enabled, but before the first transmission is started. Setting UBRR0 to zero before enabling the transmitter is not necessary if the initialization is done immediately after a reset since UBRR0 is reset to zero. Note Before doing a re-initialization with changed baud rate, data mode, or frame format, be sure that there is no ongoing transmissions during the period the registers are changed. The TXC0 Flag 259 TPR0327AY-SMS-30Jan09 can be used to check that the Transmitter has completed all transfers, and the RXC0 Flag can be used to check that there are no unread data in the receive buffer. Note that the TXC0 Flag must be cleared before each transmission (before UDR0 is written) if it is used for this purpose. The following simple USART initialization code examples show one assembly and one C function that are equal in functionality. The examples assume polling (no interrupts enabled). The baud rate is given as a function parameter. For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. Assembly Code Example USART_Init: clr r18 out UBRR0H,r18 out UBRR0L,r18 ; Setting the XCK0 port pin as output, enables master mode. sbi XCK0_DDR, XCK0 ; Set MSPI mode of operation and SPI data mode 0. ldi r18, (1< void USART_Init( unsigned int baud ) { UBRR0 = 0; /* Setting the XCK0 port pin as output, enables master mode. */ XCK0_DDR |= (1< Data Transfer Using the USART in MSPI mode requires the Transmitter to be enabled, i.e. the TXEN0 bit in the UCSR0B register is set to one. When the Transmitter is enabled, the normal port operation of the TxD0 pin is overridden and given the function as the Transmitter's serial output. Enabling 260 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 the receiver is optional and is done by setting the RXEN0 bit in the UCSR0B register to one. When the receiver is enabled, the normal pin operation of the RxD0 pin is overridden and given the function as the Receiver's serial input. The XCK0 will in both cases be used as the transfer clock. After initialization the USART is ready for doing data transfers. A data transfer is initiated by writing to the UDR0 I/O location. This is the case for both sending and receiving data since the transmitter controls the transfer clock. The data written to UDR0 is moved from the transmit buffer to the shift register when the shift register is ready to send a new frame. To keep the input buffer in sync with the number of data bytes transmitted, the UDR0 register must be read once for each byte transmitted. The input buffer operation is identical to normal USART mode, i.e. if an overflow occurs the character last received will be lost, not the first data in the buffer. This means that if four bytes are transferred, byte 1 first, then byte 2, 3, and 4, and the UDR0 is not read before all transfers are completed, then byte 3 to be received will be lost, and not byte 1. Note The following code examples show a simple USART in MSPIM mode transfer function based on polling of the Data Register Empty (UDRE0) Flag and the Receive Complete (RXC0) Flag. The USART has to be initialized before the function can be used. For the assembly code, the data to be sent is assumed to be stored in Register R16 and the data received will be available in the same register (R16) after the function returns. The function simply waits for the transmit buffer to be empty by checking the UDRE0 Flag, before loading it with new data to be transmitted. The function then waits for data to be present in the receive buffer by checking the RXC0 Flag, before reading the buffer and returning the value.. 261 TPR0327AY-SMS-30Jan09 Assembly Code Example USART_MSPIM_Transfer: ; Wait for empty transmit buffer sbis UCSR0A, UDRE0 rjmp USART_MSPIM_Transfer ; Put data (r16) into buffer, sends the data out UDR0,r16 ; Wait for data to be received USART_MSPIM_Wait_RXC0: sbis UCSR0A, RXC0 rjmp USART_MSPIM_Wait_RXC0 ; Get and return received data from buffer in r16, UDR0 ret C Code Example unsigned char USART_Receive( void ) { /* Wait for empty transmit buffer */ while ( !( UCSR0A & (1< Transmitter and Receiver Flags and Interrupts The RXC0, TXC0, and UDRE0 flags and corresponding interrupts in USART in MSPIM mode are identical in function to the normal USART operation. However, the receiver error status flags (FE, DOR, and PE) are not in use and is always read as zero. Disabling the Transmitter or Receiver The disabling of the transmitter or receiver in USART in MSPIM mode is identical in function to the normal USART operation. 19.6.2 19.7 19.7.1 USART MSPIM Register Description The following section describes the registers used for SPI operation using the USART. UDR0 - USART MSPIM I/O Data Register The function and bit description of the USART data register (UDR0) in MSPI mode is identical to normal USART operation. See "UDR0 - USART I/O Data Register n" on page 249. 262 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 19.7.2 UCSR0A - USART MSPIM Control and Status Register 0 A Bit $0000C0 Read/write Initial value 7 RXC0 R 0 6 TXC0 R/W 0 5 UDRE0 R 1 4 R 0 3 R 0 2 R 0 1 R/W 0 0 R/W 0 0x20 UCSR0A * Bit 7 - RXC0: USART Receive Complete This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXC0 bit will become zero. The RXC0 Flag can be used to generate a Receive Complete interrupt (see description of the RXCIE0 bit). * Bit 6 - TXC0: USART Transmit Complete This flag bit is set when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer (UDR0). The TXC0 Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC0 Flag can generate a Transmit Complete interrupt (see description of the TXCIE0 bit). * Bit 5 - UDRE0: USART Data Register Empty The UDRE0 flag indicates if the transmit buffer (UDR0) is ready to receive new data. If UDRE0 is one, the buffer is empty, and therefore ready to be written. The UDRE0 Flag can generate a Data Register Empty interrupt (see description of the UDRIE0 bit). UDRE0 is set after a reset to indicate that the Transmitter is ready. * Bit 4..0 - Reserved Bits in MSPI mode When in MSPI mode, these bits are reserved for future use. For compatibility with future devices, these bits must be written to zero when UCSR0A is written. 19.7.3 UCSR0B - USART MSPIM Control and Status Register 0 B Bit $0000C1 Read/write Initial value 7 RXCIE0 R/W 0 6 TXCIE0 R/W 0 5 UDRIE0 R/W 0 4 RXE0 R/W 0 3 TXE0 R/W 0 2 R/W 0 1 R 0 0 R/W 0 0x00 UCSR0B * Bit 7 - RXCIE0: RX Complete Interrupt Enable 0 Writing this bit to one enables interrupt on the RXC0 Flag. A USART Receive Complete interrupt will be generated only if the RXCIE0 bit is written to one, the Global Interrupt Flag in SREG is written to one and the RXC0 bit in UCSR0A is set. * Bit 6 - TXCIE0: TX Complete Interrupt Enable 0 Writing this bit to one enables interrupt on the TXC0 Flag. A USART Transmit Complete interrupt will be generated only if the TXCIE0 bit is written to one, the Global Interrupt Flag in SREG is written to one and the TXC0 bit in UCSR0A is set. * Bit 5 - UDRIE0: USART Data Register Empty Interrupt Enable 0 263 TPR0327AY-SMS-30Jan09 Writing this bit to one enables interrupt on the UDRE0 Flag. A Data Register Empty interrupt will be generated only if the UDRIE0 bit is written to one, the Global Interrupt Flag in SREG is written to one and the UDRE0 bit in UCSR0A is set. * Bit 4 - RXEN0: Receiver Enable 0 Writing this bit to one enables the USART Receiver. The Receiver will override normal port operation for the RxD0 pin when enabled. Disabling the Receiver will flush the receive buffer invalidating the FE0, DOR0, and UPE0 Flags. * Bit 3 - TXEN0: Transmitter Enable 0 Writing this bit to one enables the USART Transmitter. The Transmitter will override normal port operation for the TxD0 pin when enabled. The disabling of the Transmitter (writing TXENn0to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD0 port * Bit 2..0 - Reserved Bits in MSPI mode When in MSPI mode, these bits are reserved for future use. For compatibility with future devices, these bits must be written to zero when UCSR0B is written. 19.7.4 UCSR0C - USART MSPIM Control and Status Register 0 C Bit $0000C2 Read/write Initial value 7 UMSEL01 R/W 0 6 UMSEL00 R/W 0 5 R/W 0 4 R/W 0 3 R/W 0 2 UDORD0 R/W 1 1 UCPHA R/W 1 0 UCPOL0 R/W 0 0x06 UCSR0C * Bit 7..6 - UMSEL01..0: USART Mode Select These bits select the mode of operation of the USART as shown in Table 19-3. See "UCSR0C - USART Control and Status Register C" on page 251 for full description of the normal USART operation. The MSPIM is enabled when both UMSEL0 bits are set to one. The UDORD0, UCPHA0, and UCPOL0 can be set in the same write operation where the MSPIM is enabled. Table 19-3. 0 0 1 1 UMSEL0 Bits Settings UMSEL00 0 1 0 1 Asynchronous USART Synchronous USART (Reserved) Master SPI (MSPIM) Mode UMSEL01 * Bit 5..3 - Reserved Bits in MSPI mode When in MSPI mode, these bits are reserved for future use. For compatibility with future devices, these bits must be written to zero when UCSR0C is written. * Bit 2 - UDORD0: Data Order When set to one the LSB of the data word is transmitted first. When set to zero the MSB of the data word is transmitted first. Refer to the Frame Formats section page 4 for details. 264 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 1 - UCPHA0: Clock Phase The UCPHA0 bit setting determine if data is sampled on the leasing edge (first) or tailing (last) edge of XCK0. Refer to the SPI Data Modes and Timing section page 4 for details. * Bit 0 - UCPOL0: Clock Polarity The UCPOL0 bit sets the polarity of the XCK0 clock. The combination of the UCPOL0 and UCPHA0 bit settings determine the timing of the data transfer. Refer to the SPI Data Modes and Timing section page 4 for details. 19.7.5 UBRR0L and UBRR0H -USART MSPIM Baud Rate Registers The function and bit description of the baud rate registers in MSPI mode is identical to normal USART operation. See "UBRR0L and UBRR0H - USART Baud Rate Registers" on page 253. 19.8 AVR USART MSPIM vs. AVR SPI The USART in MSPIM mode is fully compatible with the AVR SPI regarding: * Master mode timing diagram. * The UCPOL0 bit functionality is identical to the SPI CPOL bit. * The UCPHA0 bit functionality is identical to the SPI CPHA bit. * The UDORD0 bit functionality is identical to the SPI DORD bit. However, since the USART in MSPIM mode reuses the USART resources, the use of the USART in MSPIM mode is somewhat different compared to the SPI. In addition to differences of the control register bits, and that only master operation is supported by the USART in MSPIM mode, the following features differ between the two modules: * The USART in MSPIM mode includes (double) buffering of the transmitter. The SPI has no buffer. * The USART in MSPIM mode receiver includes an additional buffer level. * The SPI WCOL (Write Collision) bit is not included in USART in MSPIM mode. * The SPI double speed mode (SPI2X) bit is not included. However, the same effect is achieved by setting UBRR0 accordingly. * Interrupt timing is not compatible. * Pin control differs due to the master only operation of the USART in MSPIM mode. A comparison of the USART in MSPIM mode and the SPI pins is shown in Table 19-4 on page 265. Table 19-4. Comparison of USART in MSPIM mode and SPI pins. SPI MOSI MISO SCK SS Master Out only Master In only (Functionally identical) Not supported by USART in MSPIM Comment USART_MSPIM TxD0 RxD0 XCK0 (N/A) 265 TPR0327AY-SMS-30Jan09 266 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 20. SPI - Serial Peripheral Interface The Serial Peripheral Interface (SPI) allows synchronous data transfer between the AT90SCR100 and peripheral devices such as RF front-end chip. The AT90SCR100 SPI includes the following features: 20.1 Features * * * * * * * * Full-duplex, Three-wire Synchronous Data Transfer Master or Slave Operation LSB First or MSB First Data Transfer Seven Programmable Bit Rates End of Transmission Interrupt Flag Write Collision Flag Protection Wake-up from Idle Mode Double Speed (CK/2) Master SPI Mode 20.2 Description USART can also be used in Master SPI mode. See "USART in SPI Mode" on page 257. The Power Reduction SPI bit, PRSPI, in "PRR0 - Power Reduction Register 0" on page 45 on page 50 must be written to zero to enable SPI module. Please Refer to Section 2. "Pin List Configuration" on page 5 for SPI pin placement. Figure 20-1. SPI Block Diagram Clk IO DIVIDER /2/4/8/16/32/64/128 SPI2X SPI2X 267 TPR0327AY-SMS-30Jan09 The interconnection between Master and Slave CPUs with SPI is shown in Figure 20-2. The system consists of two shift Registers, and a Master clock generator. The SPI Master initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and Slave prepare the data to be sent in their respective shift Registers, and the Master generates the required clock pulses on the SCK line to interchange data. Data is always shifted from Master to Slave on the Master Out - Slave In, MOSI, line, and from Slave to Master on the Master In - Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling high the Slave Select, SS, line. When configured as a Master, the SPI interface has no automatic control of the SS line. This must be handled by user software before communication can start. When this is done, writing a byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer Register for later use. When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the SPI Data Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before reading the incoming data. The last incoming byte will be kept in the Buffer Register for later use. Figure 20-2. SPI Master-slave Interconnection SHIFT ENABLE The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When receiving data, however, a received character must be read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost. In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of the clock signal, the minimum low and high periods should be: Low period: longer than 2 CPU clock cycles. High period: longer than 2 CPU clock cycles. 268 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 20-1. Table 20-1. Pin MOSI MISO SCK SS SPI Pin Overrides Direction, Master SPI User Defined Input User Defined User Defined Direction, Slave SPI Input User Defined Input Input 269 TPR0327AY-SMS-30Jan09 The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. E.g. if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB. Assembly Code Example SPI_MasterInit: ; Set MOSI and SCK output, all others input ldi out ldi out ret SPI_MasterTransmit: ; Start transmission of data (r16) out SPDR,r16 Wait_Transmit: ; Wait for transmission complete sbis SPSR,SPIF rjmp Wait_Transmit ret r17,(1< C Code Example void SPI_MasterInit(void) { /* Set MOSI and SCK output, all others input */ DDR_SPI = (1< AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example SPI_SlaveInit: ; Set MISO output, all others input ldi out ldi out ret SPI_SlaveReceive: ; Wait for reception complete sbis SPSR,SPIF rjmp SPI_SlaveReceive ; Read received data and return in ret r16,SPDR r17,(1< C Code Example void SPI_SlaveInit(void) { /* Set MISO output, all others input */ DDR_SPI = (1< TPR0327AY-SMS-30Jan09 20.3 20.3.1 SS Pin Functionality Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high. The SS pin is useful for packet/byte synchronization to keep the slave bit counter synchronous with the master clock generator. When the SS pin is driven high, the SPI slave will immediately reset the send and receive logic, and drop any partially received data in the Shift Register. 20.3.2 Master Mode When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI Slave. If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin defined as an input, the SPI system interprets this as another master selecting the SPI as a slave and starting to send data to it. To avoid bus contention, the SPI system takes the following actions: 1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs. 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed. Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by a slave select, it must be set by the user to re-enable SPI Master mode. 20.4 20.4.1 SPI Registers SPCR - SPI Control Register Bit 0x2C (0x4C) Read/write Initial value 7 SPIE R/W 0 6 SPE R/W 0 5 DORD R/W 0 4 MSTR R/W 0 3 CPOL R/W 0 2 CPHA R/W 0 1 SPR1 R/W 0 0 SPR0 R/W 0 0x00 SPCR * Bit 7 - SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and the if the Global Interrupt Enable bit in SREG is set. * Bit 6 - SPE: SPI Enable 272 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. * Bit 5 - DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted first. * Bit 4 - MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode. * Bit 3 - CPOL: Clock Polarity When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low when idle. Refer to Figure 20-3 and Figure 20-4 for an example. The CPOL functionality is summarized below: Table 20-2. CPOL Functionality CPOL 0 1 Leading Edge Rising Falling Trailing Edge Falling Rising * Bit 2 - CPHA: Clock Phase The settings of the Clock Phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK. Refer to Figure 20-3 and Figure 20-4 for an example. The CPOL functionality is summarized below: Table 20-3. CPHA Functionality CPHA 0 1 Leading Edge Sample Setup Trailing Edge Setup Sample * Bits 1:0 - SPR1, SPR0: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have no effect on the Slave. The relationship between SCK and the Oscillator Clock frequency clkIO is shown in the following table: Table 20-4. SPI2X 0 0 0 0 1 Relationship Between SCK and the Oscillator Frequency SPR1 0 0 1 1 0 SPR0 0 1 0 1 0 SCK Frequency clkIO/4 clkIO/16 clkIO/64 clkIO/128 clkIO/2 273 TPR0327AY-SMS-30Jan09 Table 20-4. SPI2X 1 1 1 Relationship Between SCK and the Oscillator Frequency SPR1 0 1 1 SPR0 1 0 1 SCK Frequency clkIO/8 clkIO/32 clkIO/64 20.4.2 SPSR - SPI Status Register Bit 0x2D (0x4D) Read/write Initial value 7 SPIF R 0 6 WCOL R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 R 0 0 SPI2X R/W 0 0x00 SPSR * Bit 7 - SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). * Bit 6 - WCOL: Write COLlision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. * Bit 5:1 - Res: Reserved Bits These bits are reserved bits in the AT90SCR100 and will always read as zero. * Bit 0 - SPI2X: Double SPI Speed Bit When this bit is written logic one the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode (see Table 20-4). This means that the minimum SCK period will be two CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at clkIO/4 or lower. The SPI interface on the AT90SCR100 is also used for program memory and EEPROM downloading or uploading. See page 381 for serial programming and verification. 20.4.3 SPDR - SPI Data Register Bit 0x2E (0x4E) Read/write Initial value R/W x R/W x R/W x 7 6 5 4 R/W x 3 R/W x 2 R/W x 1 R/W x 0 SPDR R/W x SPDR [7:0] The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read. 274 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 20.5 Data Modes There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure 20-3 and Figure 20-4. Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient time for data signals to stabilize. This is clearly seen by summarizing Table 20-2 and Table 20-3, as done below: Table 20-5. CPOL Functionality Leading Edge CPOL=0, CPHA=0 CPOL=0, CPHA=1 CPOL=1, CPHA=0 CPOL=1, CPHA=1 Sample (Rising) Setup (Rising) Sample (Falling) Setup (Falling) Trailing eDge Setup (Falling) Sample (Falling) Setup (Rising) Sample (Rising) SPI Mode 0 1 2 3 Figure 20-3. SPI Transfer Format with CPHA = 0 SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) LSB first (DORD = 1) MSB LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB Figure 20-4. SPI Transfer Format with CPHA = 1 SCK (CPOL = 0) mode 1 SCK (CPOL = 1) mode 3 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) LSB first (DORD = 1) MSB LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB 275 TPR0327AY-SMS-30Jan09 276 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 21. High-Speed SPI Controller This High Speed SPI (HSSPI) Interface comes with 4 dedicated pads (HSMISO, HSMOSI, HSSCK, HSSS). 21.1 Features * * * * * * * * * Support clock up to 20Mhz in Master and Slave Mode Full-duplex, 4-wire Synchronous Data Transfer Master or Slave Operation Transmission / Reception Three sources of Interrupt: Byte Transmitted, Time-out and Reception Overflow Specific DMA for fast copy from internal DPRAM to RAM 4 DPRAM buffers of 16 bytes each: 2 for Reception and 2 for Transmission Internal Double Buffering for high performance Programmable clock and inter-bytes (guardtime) delays Figure 21-1. HSSPI Block Diagram S Msb Lsb Msb Lsb HSMISO M Tx 8-Bit Shift Register Buffer DPRAM Rx 8-Bit Shift Register M HSMOSI S clk HSSPI Clock HSSPI Clock (Master) S HSSPI Controller M HSSCK S HSSS M SPICKRDY SPIEN CPHA 32 HSSPI Status Register 32 32 HSSPI Control Register HSSPI Interrupt Internal Request Data Bus 21.2 Description The interconnection between Master and Slave CPUs with HSSPI is shown in Figure 21-2. The HSSPI Controller is enabled by setting the HSSPICFG.SPIEN bit (by default, the HSSPI Controller is in Slave mode) and fully operational when the HSSPISR.SPICKRDY bit is set. To select the frequency of the HSSPI clock, the HSSPICFG.SPICKDIV bits (described in page 287) 277 TPR0327AY-SMS-30Jan09 MSTR CPOL BTD must be configured before enabling the HSSPI Controller. Any attempt at modifying the HSSPI Clock frequency once the HSSPI Controller is enabled will not affect it. The HSSPICFG.MSTR bit selects either Master or Slave operations. The HSSPI Master initiates the communication cycle after pulling low the HSSS line of the desired Slave. The Master and Slave prepare the data to be sent using their respective shift registers or using the internal DPRAM (according to the HSSPICFG.DPRAM bit), and the Master generates the required clock pulses on the HSSCK line to exchange data. Data is always shifted from Master to Slave on the Master Out - Slave In, HSMOSI line, and from Slave to Master on the Master In Slave Out, HSMISO line, simultaneously. Figure 21-2. HSSPI Master - Slave Interconnection Msb Master Lsb Msb Slave Lsb 8 Bit Shift Register HSMISO HSMOSI 8 Bit Shift Register Master HSSPI Clock Generator HSSCK Chip as Master Chip as Slave The DPRAM stores two 16 Bytes buffers for transmission and two 16 Bytes buffers for reception. 21.2.1 HSSPI Controller Configured as a Master When configured as a Master, the HSSPI interface has no automatic control of the HSSS line. This must be handled by software before starting the communication. One byte sending using shift register (without DPRAM) When the DPRAM is not activated (HSSPICFG.DPRAM bit cleared) and a byte is written to the HSSPI Transmit Data Register (HSSPITDR register), the hardware shifts the 8 bits (MSB first) into the Slave and receives a byte from the Slave simultaneously. After shifting one byte, the Byte Transfer Done flag (HSSPIIR.BTD) is set. If global interrupt and the HSSPIIER.BTDIE bit have been previously set, an interrupt is generated. At this stage, the Master can read the HSSPIRDR register to retrieve the byte sent by the other device. The HSSPIIR.BTD flag must then be cleared by software. The figure below illustrates the way the HSSPI works when configured as a Master without DPRAM mode. 21.2.1.1 278 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 21-3. HSSPI - Master without DPRAM operation Configure SPICK frequency (HSSPIFG) Configure SPI Guard Time (HSSPIGTR) Configure CPOL, CPHA, MSTR=1, SPIEN, DPRAM=0, BTDIE (if IRQ mode) Wait HSSPICKRDY Write data to send into HSSPITDR Wait BTD (HSSPIIR) Data to receive? YES Read data from HSSPIRDR NO Clear BTD (HSSPIIR) (mandatory if IRQ mode) 21.2.1.2 Buffer sending with DPRAM and HSSPIDMA (DPRAM mode) When the DPRAM is activated (HSSPICFG.DPRAM bit set), the data to be sent must be written to one of the internal DPRAM buffers using the HSSPIDMA. To do so, use the HSSPIDMA mechanism to copy HSSPIDMAB bytes from RAM to DPRAM. It is not possible to copy more than 16 bytes per copy. The DPRAM targeted by the copy is totally transparent to the user. Once this is done, the number of bytes to be transmitted is written to the HSSPICNT register. The HSSPI interface will start to shift this number of bytes from the master to the slave and from the slave to the master simultaneously. If the HSSPISR.TXBUFE = 1, new data can be copied in the second buffer using HSSPIDMA again. After shifting all the bytes of one buffer, the Byte Transfer Done flag (HSSPIIR.BTD) is set. If the HSSPI interrupt enable bit and the HSSPIIER.BTDIE bit have been previously set, an interrupt is generated. 279 TPR0327AY-SMS-30Jan09 At this point, the Master can copy the received data from reception DPRAM into RAM, using HSSPIDMA. The HSSPIIR.BTD flag must then be cleared by software. If the HSSPIIR.BTD is set and the next buffer becomes full, the HSSPIIR.RCVOF is set. If the HSSPI interrupt enable bit and the HSSPIIER.RCVOFIE bit have been previously set, an interrupt is generated. The figure below illustrates the way the HSSPI works when configured as a Master with DPRAM/HSSPIDMA. Figure 21-4. SPI - Master with DPRAM/HSSPIDMA activated Configure SPICK frequency (HSSPICFG) Configure SPI Guard Time (HSSPIGTR) Configure CPOL, CPHA, MSTR=1, SPIEN, DPRAM=1, BTDIE (if IRQ mode) Wait SPICKRDY (HSSPISR) YES nb_data to send or receive>16? NO Prepare RAM and HSSPIDMA Copy nb_data left data into DPRAM. Write nb_data left in HSSPICNT TXBUFE? (HSSPISR) YES Init RAM data and HSSPIDMA Copy data into DPRAM Write 16 in HSSPICNT NO Init RAM data and HSSPIDMA Copy data into DPRAM Write 16 in HSSPICNT Prepare RAM and HSSPIDMA Copy 16 or nb_data left data into DPRAM. Write 16 or nb_data left in HSSPICNT Wait BTD (HSSPIIR) YES Data to receive? Read SPICNT Start copy of received data into RAM using HSSPIDMA. Read received data directly in RAM NO Clear BTD (HSSPIIR) 280 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 21.2.2 21.2.2.1 SPI Controller Configured as a Slave One byte sending using shift register (without DPRAM) If the DPRAM is not activated (HSSPICFG.DPRAM bit cleared), the software may update the contents of the HSSPI Transmit Data Register, SPITDR, that will be shifted out by incoming clock pulses on the clock pin. As soon as the byte has been completely shifted, the Byte transfer Done flag (HSSPIIR.BTD) is set. If global interrupt and the HSSPIIER.BTDIE bit have been previously set, an interrupt is generated. At this stage, the Slave can read the HSSPIRDR register to retrieve the byte sent by the other device. The HSSPICFG.BTD flag must then be cleared by software. Figure 21-5. HSSPI - Slave without DPRAM activated Configure CPOL, CPHA, MSTR=0, SPIEN, DPRAM=0, BTDIE (if IRQ mode) Wait SPICKRDY (HSSPISR) Data to send? NO YES Write data to send into HSSPITDR Wait BTD (HSSPIIR) Wait BTD (HSSPIIR) Data to receive? YES Read data from HSSPIRDR NO Clear BTD (HSSPIIR) (mandatory if IRQ mode) 281 TPR0327AY-SMS-30Jan09 21.2.2.2 Buffer sending with DPRAM and HSSPIDMA (DPRAM mode) When the DPRAM is activated (HSSPICFG.DPRAM bit set), the data to be sent must be written to one of the internal DPRAM buffers using HSSPIDMA. Once this is done, the number of bytes to be transmitted is written to the HSSPICNT register. When the master applies the clock, this number of bytes is shifted from the master to the slave and from the slave to the master simultaneously. At this point, new data can be stored in the second buffer if the HSSPISR.TXBUFE = 1. Each time all the data in one of the buffers is sent, the Byte Transfer Done flag (HSSPIIR.BTD) is set. If global interrupt and the HSSPIIER.BTDIE bit have been previously set, an interrupt is generated. At this stage, the incoming data can be copied from internal DPRAM to RAM using HSSPIDMA. The HSSPIIR.BTD flag must then be cleared by software. If the HSSPIIR.BTD is set and the next buffer becomes full, the HSSPIIR.RCVOF is set. If global interrupt and the HSSPIIER.RCVOFIE bit have been previously set, an interrupt is generated. The figures below (Figure 21-6, Figure 21-7 & Figure 21-8) illustrate the way the SPI works when configured as a Slave with DPRAM mode. 282 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 21-6. SPI - Slave with DPRAM operation - First part NO Use the timeout? YES Configure SPICK frequency (HSSPICFG) Configure HSSPITIMEOUT Configure CPOL, CPHA, MSTR=0, SPIEN, DPRAM=1, BTDIE Wait SPICKRDY (HSSPISR) Data to send? NO GOTO LABEL "RECEIVE DATA" YES YES nb_data to send or receive>16? NO Prepare RAM and HSSPIDMA Copy nb_data left data into DPRAM. Write nb_data left in HSSPICNT TXBUFE? (HSSPISR) YES Init RAM data and HSSPIDMA Copy data into DPRAM Write 16 in HSSPICNT NO Init RAM data and HSSPIDMA Copy data into DPRAM Write 16 in HSSPICNT Prepare RAM and HSSPIDMA Copy 16 or nb_data left data into DPRAM. Write 16 or nb_data left in HSSPICNT Wait BTD (HSSPIIR) YES Data to receive? Read SPICNT Start copy of received data into RAM using HSSPIDMA. Read received data directly in RAM NO Clear BTD (HSSPIIR) 283 TPR0327AY-SMS-30Jan09 Figure 21-7. SPI - Slave with DPRAM operation - Second part LABEL "RECEIVE DATA" nb_data to receive known? NO GOTO LABEL "RECEIVE DATA UK" YES YES Write 16 in HSSPICNT nb_data to receive >16? Write 16 in HSSPICNT NO Write nb_data to receive in HSSPICNT NO Write nb_data left in HSSPICNT YES nb_data to receive >16? Wait BTD (HSSPIIR) YES rx_buf_full? Read HSSPICNT Start copy of received data into RAM using HSSPIDMA. Read received data directly in RAM NO Clear BTD (HSSPIIR) Read HSSPICNT Start copy of received data into RAM using HSSPIDMA. Read received data directly in RAM Clear BTD (HSSPIIR) If the number of bytes to be received or sent is not known, a timeout can be used. It can be activated by entering a time bit value in the HSSPITIMEOUT and setting the HSSPICR.STTTO bit. As the amount of data is unknown, the two registers (HSSPICNT) have to be set to the maximum value, 16. When the timeout occurs, the HSSPIIR.TIMEOUT bit is set. If the HSSPI interrupt enable bit and the HSSPIIER.TIMEOUTIE bit have been previously set, an interrupt is generated. The number of byte received is available in the HSSPICNT register. Clearing the HSSPIIR.TIMEOUT bit by soft or by setting the HSSPICR.STTTO bit will update the internal DPRAM 284 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 21-8. SPI - Slave with DPRAM operation - Third part LABEL "RECEIVE DATA UK" Write 16 in HSSPICNT Write 16 in HSSPICNT Set bit HSSPICR.STTO Wait BTD or TIMEOUT NO BTD? then TIMEOUT YES Copy 16 into RAM using HSSPIDMA. Read received data directly into RAM Read nb_data in HSSPICNT Copy nb_data into RAM using HSSPIDMA. Read received data directly into RAM Clear TIMEOUT (HSSPIIR) Disable DMA (Clear HSSPICFG.DPRAM) Clear BTD (HSSPIIR) Enable DMA (Set HSSPICFG.DPRAM) Wait DMA ready (HSSPISR.DPRAMRDY) Set bit HSSPICR.STTO End of reception. Next loop In SPI slave mode, the control logic will sample the incoming signal of the HSSCK pin. To ensure correct sampling of the clock signal, the frequency of the HSSPI clock should never exceed f SCKmax (f SCKmax=24 Mbits/s). When the HSSPI is enabled, the data direction of the HSMOSI, HSMISO, HSSCK, and HSSS pins is overridden according to Table 21-1 . Table 21-1. Pin MOSI MISO SCK NSS SPI Pin Overrides Direction, Master SPI Output Input Output Output Direction, Slave SPI Input Output Input Input 285 TPR0327AY-SMS-30Jan09 21.3 21.3.1 HSSS line Functionality Slave Mode When the HSSPI is configured as a Slave (HSSPICFG.MSTR bit cleared), the Slave Select (HSSS) line is driven by the master device. The HSSS has no effect on the HSSPI logic. It is the software's responsibility to manage the HSSS level. 21.3.2 Master Mode When the HSSPI is configured as a Master (HSSPICFG.MSTR bit set), the HSSS line is used to select the slave. 21.4 Data Modes There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure 21-9 and Figure 21-10. Figure 21-9. SPI Transfer Format with CPHA = 0 Figure 21-10. SPI Transfer Format with CPHA = 1 286 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 21.5 21.5.1 HSSPI Interface Registers HSSPICFG - HSSPI Config Register Bit $0000D9 Read/write Initial value 1 7 R/W 6 SPICKDIV [2..0] R/W 0 R/W 0 5 4 DPRAM R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 HSSPICFG 0x80 R/W 0 HSCPHA HSCPOL HSMSTR HSSPIEN * Bits 7..5 - SPICKDIV2..0: SPI Clock Divider Ratio Bits Defines the HSSPI Clock divider ratio. The following table gives, for each combination of SPICKDIV2, SPICKDIV1 and SPICKDIV0, the division applied to the clock. Figure 7-1 on page 31 gives information about the clock tree and base frequency for HSSPI. Table 21-2. SPICKDIV2 0 0 0 0 1 1 1 1 Note: HSSPI dividers(1) SCKCKDIV1 0 0 1 1 0 0 1 1 SCKCKDIV0 0 1 0 1 0 1 0 1 Divider 4 5 6 8 12 24 48 96 External clock divider ratio(1) 24 Mhz 19.2 Mhz 16 Mhz 12 Mhz 8 Mhz 4 Mhz 2 Mhz 1 Mhz 1. Base frequency is clkIO = 96Mhz Note Any attempt at modifying the HSSPICFG.SPICKDIV value once the HSSPI Controller is enabled will not affect the HSSPI Clock frequency. * Bit 4 - DPRAM: DPRAM Bit When set (one), this bit enables the DPRAM/HSSPIDMA systems. When cleared (zero), this bit disables the DPRAM/HSSPIDMA systems. After a DPRAM is disabled, the DPRAM is reset. This reset is active for two clock cycles of the DPRAM clock. It is recommended to do nothing on the DPRAM during these two clock cycles. Note * Bit 3 - HSCPHA: High Speed Clock PHAse Bit The settings of the clock phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of HSSCK. Refer to Figure 21-9 and Figure 21-10. 287 TPR0327AY-SMS-30Jan09 The CPHA functionality is summarized below: Table 21-3. CPHA 0 1 CPHA Configuration Leading edge Sample Setup Trailing edge Setup Sample * Bit 2 - HSCPOL: High Speed Clock POLarity Bit When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low when idle. Refer to Figure 21-9 and Figure 21-10. The CPOL functionality is summarized below: Table 21-4. CPOL 0 1 CPOL Configuration Leading edge Rising Falling Trailing edge Falling Rising * Bit 1 - HSMSTR: High Speed Master/Slave Select Bit This bit selects the Master HSSPI mode when set (one), and Slave HSSPI mode when cleared (zero). This bit is cleared by software or by hardware when the HSSPICFG.SPIEN gets cleared (disabling the HSSPI). * Bit 0 - HSSPIEN: High Speed SPI Enable Bit When this bit is set (one), the HSSPI Controller is enabled with the predefined configuration. When this bit is cleared (zero), the HSSPI Controller is disabled and HSSPICFG.HSMSTR is driven low. Configuring and activating the HSSPI peripheral with the same instruction is a valid action. Note 21.5.2 HSSPIIR - HSSPI Interrupt Register Bit $0000DA Read/write Initial value 7 TIMEOUT R/W 0 6 BTD R/W 0 5 RCVOF R/W 0 4 NSSRE R/W 0 3 NSSFE R/W 0 2 R 0 1 R 0 0 R 0 0x00 HSSPIIR * Bit 7 - TIMEOUT: Timeout Interrupt Bit This bit is set (one) when a Timeout occurs. An interrupt is generated if HSSPIIER.TIMEOUTIE is set and global interrupt is enabled. This bit is cleared by software or by hardware when the HSSPICFG.SPIEN is toggled (enabling or disabling the HSSPI). * Bit 6 - BTD: Byte Transfer Done Bit 288 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 This bit is set (one) when a serial transfer of the number of bytes specified in HSSPICNT is completed. An interrupt is generated if HSSPIIER.BTDIE is set and global interrupt is enabled. This bit is cleared by software or by hardware when the HSSPICFG.SPIEN is toggled (enabling or disabling the HSSPI). * Bit 5 - RCVOF: Receive Overflow Bit This bit is set by hardware, when the DPRAM mode is set and the two 16 bytes receive buffers are full. An interrupt is generated if HSSPIIER.RCVOFIE is set and global interrupt is enabled. * Bit 4 - NSSRE: NSS Rising Edge Set (one) by hardware on a rising edge on HSSS Cleared (zero) by software * Bit 3 - NSSFE: NSS Falling edge Bit Set (one) by hardware on a falling edge on HSSS Cleared (zero) by software 21.5.3 HSSPIIER - HSSPI Interrupt Enable Register Bit $0000D4 Read/write Initial value 7 R/W 0 6 R/W 0 5 R/W 0 4 R/W 0 3 R 0 2 R 0 1 R 0 0 R 0 0x00 HSSPIIER TIMEOUTIE BTDIE RCVOFIE NSSIE * Bit 7 - TIMEOUTIE: Timeout Interrupt Enable Bit When set (one), this bit enables the Timeout event as the source of the HSSPI interrupt. When cleared (zero), this bit disables the Timeout source of the HSSPI interrupt. * Bit 6 - BTDIE: Byte Transfer Done Interrupt Enable Bit When set (one), this bit enables the Byte Transfer Done event as the source of the HSSPI interrupt. When cleared (zero), this bit disables the Byte Transfer Done source of the HSSPI interrupt. * Bit 5 - RCVOFIE: Receive Overflow Interrupt Enable Bit When set (one), this bit enables the Receive Overflow event as the source of the HSSPI interrupt. When cleared (zero), this bit disables the Receive Overflow source of the HSSPI interrupt. * Bit 4 - NSSIE: NSS Interrupt Enable When set (one), the HSSS interrupt is enabled on falling and rising edges When cleared (zero), the HSSS interrrupt is disabled 289 TPR0327AY-SMS-30Jan09 21.5.4 HSSPICR - HSSPI Control Register Bit $0000DB Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 STTTO W 0 1 RETTO W 0 0 CS W 0 0x00 HSSPICR * Bit 2 - STTTO: Start Time-Out When set (one), this will rearm the time-out timer and start it once the first byte is received When cleared (zero), no action is performed. * Bit 1 - RETTO: Rearm Timeout Interrupt Enable Bit When set (one), this will rearm the time-out timer, giving more time to receive the next byte. When cleared (zero), no action is performed. * Bit 0 - CS: SPI CS Bit When set (one), the HSSPI HSSS pin is set (one). When cleared (zero), the SPI HSSS pin is cleared (zero). 21.5.5 HSSPISR - HSSPI Status Register Bit $0000D8 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 DPRAMRDY R 0 3 NSS R 0 2 RXBUFF R 0 1 R 0 0 HSSPISR 0x00 R 0 TXBUFE SPICKRDY * Bit 4 - DPRAMRDY: DPRAM Ready Bit When this bit is set (one), the DPRAM is running and operational. When this bit is cleared (zero), the DPRAM is not available. * Bit 3 - NSS: NSS Bit Status of the HSSS pin * Bit 2 - RXBUFF: Reception Buffer Full Bit When this bit is set (one), all reception buffers are full. * Bit 1 - TXBUFE: Transmission Buffer Empty Bit When this bit is set (one), all transmission buffers are empty. * Bit 0 - SPICKRDY: SPI Clock Ready Bit When this bit is set (one), the HSSPI Controller is running and operational. When this bit is cleared (zero), the HSSPI Controller is not available. 290 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 21.5.6 HSSPITDR - HSSPI Transmit Data Register Bit $0000D7 Read/write Initial value W 0 W 0 W 0 7 6 5 4 W 0 3 W 0 2 W 0 1 W 0 0 HSSPITDR W 0 0x00 HSSPITDD [7..0] * Bits 7..0 - HSSPITDD7..0: Transmit Data value This register is used only when the DPRAM mode is disabled. The HSSPI Transmit Data register is a write register used for data transmission from the register file to the HSSPI Shift register. Writing to the register initiates data transmission. 21.5.7 HSSPIRDR - HSSPI Received Data Register Bit $0000D6 Read/write Initial value R 0 R 0 R 0 7 6 5 4 R 0 3 R 0 2 R 0 1 R 0 0 HSSPIRDR R 0 0x00 HSSPIRDD [7..0] * Bits 7..0 - HSSPIRDD7..0: Receive Data value This register is used only when the DPRAM mode is disabled. The HSSPI Receive Data register is a read register used for data reception to the register file from the HSSPI Shift register. Reading this register causes the Shift Register holding the first received data to be read. 21.5.8 HSSPIGTR - HSSPI Guard Time Register Bit $0000D5 Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 HSSPIGTR R/W 0 0x00 HSSPIGTD [7..0] * Bits 7..0 - HSSPIGTD7..0: Guard Time value The HSSPI Guard Time register value is the number of HSSPI clock cycles to be inserted between characters, in master mode only. 21.5.9 HSSPICNT - HSSPI Byte Count Register Bit $0000D3 Read/write Initial value 7 R 0 6 R 0 5 R 0 R/W 0 0 4 3 R/W 2 HSSPICNTD [4..0] R/W 0 R/W 0 R/W 0 0x00 1 0 HSSPICNT * Bits 4..0 - HSSPICNTD4..0 : Number of byte received or to send This register is used only when DPRAM mode is activated. Writing this register specifies the number of bytes to be sent and received for the current received and transmit buffers. 291 TPR0327AY-SMS-30Jan09 Reading this register gives the amount of data received for the current received buffer (In this case, the current received buffer means that this buffer received the expected number of data or had a timeout). Writing HSSPICNT register will internally switch the DPRAM buffers. Note Thus, the DMA controller will point to the other DPRAM buffer. 21.5.10 HSSPITIMEOUT - HSSPI Timeout Register Bit $0000D2 $0000D1 Bit Read/write Initial value 7 R/W R/W 0 0 6 R/W R/W 0 0 5 R/W R/W 0 0 15 14 13 12 11 10 9 8 HSSPITOH HSSPITOL 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 0 0 0x00 0x00 SPITIMEOUT[15..8] SPITIMEOUT [7..0] 4 R/W R/W 0 0 3 R/W R/W 0 0 * Bits 15..0 - SPITIMEOUT15..0 : Communication Timeout This register is used only when DPRAM mode is activated. It specifies the number of clock cycles before a timeout occurs (bit HSSPIIR.TIMEOUT is set). See "HSSPIIR - HSSPI Interrupt Register" on page 288. The clock is defined by HSSPICFG.SPICKDIV bits. See "HSSPICFG HSSPI Config Register" on page 287. 21.6 HSSPIDMA Controller The HSSPIDMA controller, implemented on the AT90SCR100, is intended to execute fast transfers between the RAM memory and the internal HSSPI DPRAM. This feature allows the application software of the AT90SCR100 to manage the exchanges imposed by the SPI communication at high frequency. All the registers described in this section cannot be accessed if the HSSPI module is not enabled. ! Caution The HSSPIDMA is enabled as soon as DPRAM mode is activated ( by setting bit HSSPICFG.DPRAM). One HSSPIDMA operation can transfer up to N bytes in (N+1) AVR cycles. 292 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 21-11. HSSPIDMA Controller Diagram HSSPIDMACS.DMADIR HSSPIDMACS.DMAERR Automatic Switch RAM $10FF DMAB Reception DPRAM HSSPIDMACS.DMAR 0 1 1 0 HSSPIDMACS.DMAR $100 16 bytes DMA Controller Diagram Transmission DPRAM Automatic Switch 16 bytes 16 bytes 0 1 DMAD 16 bytes Note When a HSSPIDMA operation is started, the AVR is automatically stopped. At the end of the HSSPIDMA operation, the application software automatically restarts where it left (actually with the instruction following the launching of the HSSPIDMA operation). Thus the application software does not need to wait for an interrupt or to need poll the end of the HSSPIDMA operation. 21.6.1 HSSPIDMACS - HSSPIDMA Control and Status register This is the control and status register of the HSSPIDMA controller. 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 HSSPIDMAERR R/W 0 1 HSSPIDMADIR R/W 0 0 HSSPIDMAR R/W 0 0x00 HSSPIDMACS Bit $0000DC Read/write Initial value * Bit 2 - HSSPIDMAERR : DMA Error Bit When starting the HSSPIDMA controller, this bit is cleared (zero) by the hardware if the values in HSSPIDMADH, HSSPIDMADL and HSSPIDMAB registers are suitable for the HSSPIDMA operation requested. This bit can also be cleared(zero) by software. This bit is set (one) by hardware when starting a HSSPIDMA operation and whenever one of these following cases occurs: * The base address contained in the registers HSSPIDMADH and HSSPIDMADL is incorrect (out of the allowed range). * According to the values of the registers HSSPIDMADH, HSSPIDMADL and HSSPIDMAB and even if the base address is correct, an address out of the allowed range is going to be reached. 293 TPR0327AY-SMS-30Jan09 * The value in the register HSSPIDMAB is greater than the size of the DPRAM (16bytes) for the HSSPIDMA operation. When this bit is set, and if the HSSPI interruptions are enabled, an HSSPI interruption is generated. Don't forget to clear the HSSPIDMACS.DMAERR bit before leaving the interruption routine to avoid repetitive and endless interruptions. ! Caution * Bit 1- HSSPIDMADIR: DMA Direction Bit: This bit is set (one) and cleared (zero) by software. It indicates the direction of the next HSSPIDMA operation transfer between the RAM memory and the internal DPRAM of HSSPI block. * If the bit is set (one), the transfer will be from the RAM memory to the current transmission DPRAM (emission mode). The empty transmission DPRAM will be automatically selected. * If the bit is cleared (zero), the transfer will be from the current reception DPRAM to the RAM memory (receiving mode). The firstly filled DPRAM will be selected before the other (more recently modified). * Bit 0 - HSSPIDMAR: DMA Run Bit: This bit is set (one) by software and cleared (zero) by hardware. This bit controls the HSSPIDMA operation launching. It is set (one) by software when a HSSPIDMA operation is to be performed. It is cleared (zero) by hardware at the end of the operation. The software does not need to poll this bit in order to detect the end of the HSSPIDMA operation. Indeed, when the HSSPIDMACS.DMAR bit is set by the software, the AVR is automatically stopped. When the end of the HSSSPIDMA operation is reached, the AVR then automatically executes the instructions following the setting of the bit HSSPIDMACS.DMAR. A HSSPIDMA operation can not be interrupted because the CPU is not available during this time. Note Note 294 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 21.6.2 HSSPIDMAD - HSSPIDMA ADdress registers Bit $0000DE $0000DD Bit Read/write Initial value 7 R R/W 0 0 6 R R/W 0 0 5 R/W R/W 0 0 15 14 4 R/W R/W 0 0 13 12 11 10 9 8 HSSPIDMADH HSSPIDMADL 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 1 0 0x01 0x00 HSSPIDMAD [13..8] HSSPIDMAD [8..0] 3 R/W R/W 0 0 * Bits 7..6 - Res: Reserved Bits These bits are reserved bits in the AT90SCR100 and are always read as zero. * Bits 13..0 - HSSPIDMAD13..0 : HS SPI DMA Address These bits represents the 14-bit HSSPIDMA Address. These two registers set the base address in RAM. This address represents the source of the data to be sent if the HSSPIDMA controller is configured in the emission mode. It represents the destination to store the data if the HSSPIDMA controller is configured in the receiving mode. The initial value corresponds to RAM address $000100. You can address the whole RAM with this parameter. Values in RAM that must not be dumped, shall be stored out of the HSSPIDMA RAM accessible range. When starting a HSSPIDMA operation, the hardware will check if the values of HSSPIDMADH, HSSPIDMADL and HSSPIDMAB registers does not exceed the specific RAM area ($000100 to $0010FF). If an error is detected, HSSPIDMACS.DMAERR bit is automatically set (one). A Supervisor RAM Illegal Access Attempt Violation security interrupt (if not masked) is so triggered. HSSPIDMADH, HSSPIDMADL and HSSPIDMAB registers keep their previous value. After a HSSPIDMA operation, HSSPIDMADH and HSSPIDMADL are set to the last value reached in RAM and incremented by one. For instance, after a 64-byte transfer started from base address $000100, HSSPIDMAD equals to $000140 (HSSPIDMADH = $01 and HSSPIDMADL = $40). This feature allows to simplify registers and bits handlings when several HSSPIDMA operations are to be successively performed, which can be the case when getting or sending several packets. Note 21.6.3 HSSPIDMAB - DMA Amount of Bytes Register This register is dedicated to the amount of bytes to be transferred during the next HSSPIDMA operation setting. Bit $00DF Read/write Initial value 7 R 0 6 R 0 5 R 0 R/W 0 0 4 3 R/W 2 HSSPIDMAB [4..0] R/W 0 R/W 0 R/W 0 0x00 1 0 HSSPIDMAB * Bit 7..5 - Res : Reserved Bits This bit is reserved bit in the AT90SCR100 and is always read as zero. 295 TPR0327AY-SMS-30Jan09 * Bits 4..0 - HSSPIDMAB4..0 : HS SPI DMA Amount of Bytes Bits These bits are the (4..0) bits of the 7-bit HSSPIDMA Amount of Bytes value. When starting a HSSPIDMA operation, the hardware will check if the values of HSSPIDMADH, HSSPIDMADL and HSSPIDMAB registers does not exceed the specific RAM area ($000100 to $0010FF). If an error is detected, HSSPIDMACS.DMAERR bit is automatically set (one). A Supervisor RAM Illegal Access Attempt Violation security interrupt (if not masked) is so triggered. HSSPIDMADH, HSSPIDMADL and HSSPIDMAB registers keep their previous value. After a HSSPIDMA operation completion, the value of this register is not reset. Note The maximum value allowed for HSSPIDMAB is 16. 296 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 22. 2-wire Serial Interface _ TWI 22.1 Features * * * * * * * * * * Simple Yet Powerful and Flexible Communication Interface, only two Bus Lines Needed Both Master and Slave Operation Supported Device can Operate as Transmitter or Receiver 7-bit Address Space Allows up to 128 Different Slave Addresses Multi-master Arbitration Support Up to 400 kHz Data Transfer Speed Slew-rate Limited Output Drivers Noise Suppression Circuitry Rejects Spikes on Bus Lines Fully Programmable Slave Address with General Call Support Address Recognition Causes Wake-up When AVR is in Sleep Mode 22.2 TWI Serial Interface Bus Definition The 2-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The TWI protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the TWI protocol. Figure 22-1. TWI Bus Interconnection V CC Device 1 Device 2 Device 3 ........ Device n R1 R2 SDA SCL 22.2.1 TWI Terminology The following definitions are frequently encountered in this section. Table 22-1. Term Master TWI Terminology Description The device that initiates and terminates a transmission. The Master also generates the SCL clock. 297 TPR0327AY-SMS-30Jan09 Table 22-1. Term Slave Transmitter Receiver TWI Terminology Description The device addressed by a Master. The device placing data on the bus. The device reading data from the bus. The Power Reduction TWI bit, PRTWI bit in PRR0 must be written to zero to enable the TWI Serial Interface. 22.2.2 Electrical Interconnection The number of devices that can be connected to the bus is only limited by the bus capacitancelimit of 400 pF and the 7-bit slave address space. A detailed specification of the electrical characteristics of the TWI is given in section "2-wire Serial Interface Characteristics TBC/TBD" on page 411. Two different sets of specifications are presented there, one relevant for bus speeds below 100 kHz, and one valid for bus speeds up to 400 kHz. 22.3 22.3.1 Data Transfer and Frame Format Transferring Bits Each data bit transferred on the TWI bus is accompanied by a pulse on the clock line. The level of the data line must be stable when the clock line is high. The only exception to this rule is for generating start and stop conditions. Figure 22-2. Data Validity SDA SCL Data Stable Data Stable Data Change 22.3.2 START and STOP Conditions The Master initiates and terminates a data transmission. The transmission is initiated when the Master issues a START condition on the bus, and it is terminated when the Master issues a STOP condition. Between a START and a STOP condition, the bus is considered busy, and no other master should try to seize control of the bus. A special case occurs when a new START condition is issued between a START and STOP condition. This is referred to as a REPEATED START condition, and is used when the Master wishes to initiate a new transfer without relinquishing control of the bus. After a REPEATED START, the bus is considered busy until the next STOP. This is identical to the START behavior, and therefore START is used to describe both START and REPEATED START for the remainder of this datasheet, unless otherwise noted. As 298 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 depicted below, START and STOP conditions are signalled by changing the level of the SDA line when the SCL line is high. Figure 22-3. START, REPEATED START and STOP conditions SDA SCL START STOP START REPEATED START STOP 22.3.3 Address Packet Format All address packets transmitted on the TWI bus are 9 bits long, consisting of 7 address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed. When a Slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle. If the addressed Slave is busy, or for some other reason can not service the Master's request, the SDA line should be left high in the ACK clock cycle. The Master can then transmit a STOP condition, or a REPEATED START condition to initiate a new transmission. An address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or SLA+W, respectively. The MSB of the address byte is transmitted first. Slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. When a general call is issued, all slaves should respond by pulling the SDA line low in the ACK cycle. A general call is used when a Master wishes to transmit the same message to several slaves in the system. When the general call address followed by a Write bit is transmitted on the bus, all slaves set up to acknowledge the general call will pull the SDA line low in the ack cycle. The following data packets will then be received by all the slaves that acknowledged the general call. Note that transmitting the general call address followed by a Read bit is meaningless, as this would cause contention if several slaves started transmitting different data. All addresses of the format 1111 xxx should be reserved for future purposes. Figure 22-4. Address Packet Format Addr MSB SDA Addr LSB R/W ACK SCL 1 START 2 7 8 9 299 TPR0327AY-SMS-30Jan09 22.3.4 Data Packet Format All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the Master generates the clock and the START and STOP conditions, while the Receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signalled by the Receiver pulling the SDA line low during the ninth SCL cycle. If the Receiver leaves the SDA line high, a NACK is signalled. When the Receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the Transmitter by sending a NACK after the final byte. The MSB of the data byte is transmitted first. Figure 22-5. Data Packet Format Data MSB Aggregate SDA SDA from Transmitter SDA from Receiver SCL from Master 1 SLA+R/W 2 7 Data Byte 8 9 STOP, REPEATED START or Next Data Byte Data LSB ACK 22.3.5 Combining Address and Data Packets into a Transmission A transmission basically consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition. An empty message, consisting of a START followed by a STOP condition, is illegal. Note that the Wired-ANDing of the SCL line can be used to implement handshaking between the Master and the Slave. The Slave can extend the SCL low period by pulling the SCL line low. This is useful if the clock speed set up by the Master is too fast for the Slave, or the Slave needs extra time for processing between the data transmissions. The Slave extending the SCL low period will not affect the SCL high period, which is determined by the Master. As a consequence, the Slave can reduce the TWI data transfer speed by prolonging the SCL duty cycle. Figure 22-6 shows a typical data transmission. Note that several data bytes can be transmitted between the SLA+R/W and the STOP condition, depending on the software protocol implemented by the application software. Figure 22-6. Typical Data Transmission Addr MSB Addr LSB R/W ACK Data MSB Data LSB ACK 1 START 2 7 SLA+R/W 8 9 1 2 Data Byte 7 8 9 ST 300 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 22.4 Multi-master Bus Systems, Arbitration and Synchronization The TWI protocol allows bus systems with several masters. Special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more masters initiate a transmission at the same time. Two problems arise in multi-master systems: * An algorithm must be implemented allowing only one of the masters to complete the transmission. All other masters should cease transmission when they discover that they have lost the selection process. This selection process is called arbitration. When a contending master discovers that it has lost the arbitration process, it should immediately switch to Slave mode to check whether it is being addressed by the winning master. The fact that multiple masters have started transmission at the same time should not be detectable to the slaves, i.e. the data being transferred on the bus must not be corrupted. * Different masters may use different SCL frequencies. A scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. This will facilitate the arbitration process. The wired-ANDing of the bus lines is used to solve both these problems. The serial clocks from all masters will be wired-ANDed, yielding a combined clock with a high period equal to the one from the Master with the shortest high period. The low period of the combined clock is equal to the low period of the Master with the longest low period. Note that all masters listen to the SCL line, effectively starting to count their SCL high and low time-out periods when the combined SCL line goes high or low, respectively. Figure 22-7. SCL Synchronization Between Multiple Masters TA low TA high SCL from Master A SCL from Master B SCL Bus Line TB low Masters Start Counting Low Period TB high Masters Start Counting High Period Arbitration is carried out by all masters continuously monitoring the SDA line after outputting data. If the value read from the SDA line does not match the value the Master had output, it has lost the arbitration. Note that a Master can only lose arbitration when it outputs a high SDA value while another Master outputs a low value. The losing Master should immediately go to Slave mode, checking if it is being addressed by the winning Master. The SDA line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or 301 TPR0327AY-SMS-30Jan09 address packet. Arbitration will continue until only one Master remains, and this may take many bits. If several masters are trying to address the same Slave, arbitration will continue into the data packet. Figure 22-8. Arbitration Between Two Masters START SDA from Master A Master A Loses Arbitration, SDA A SDA SDA from Master B SDA Line Synchronized SCL Line Note that arbitration is not allowed between: * A REPEATED START condition and a data bit. * A STOP condition and a data bit. * A REPEATED START and a STOP condition. It is the user software's responsibility to ensure that these illegal arbitration conditions never occur. This implies that in multi-master systems, all data transfers must use the same composition of SLA+R/W and data packets. In other words: All transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined. 22.5 Overview of the TWI Module The TWI module is comprised of several submodules, as shown in Figure 22-9. All registers drawn in a thick line are accessible through the AVR data bus. 302 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 22-9. Overview of the TWI Module SCL Slew-rate Control Spike Filter SDA Slew-rate Control Spike Filter Bus Interface Unit START / STOP Control Spike Suppression Bit Rate Generator Prescaler Arbitration detection Address/Data Shift Register (TWDR) Ack Bit Rate Register (TWBR) Address Match Unit Address Register (TWAR) Status Register (TWSR) Control Unit Control Register (TWCR) Address Comparator State Machine and Status control 22.5.1 SCL and SDA Pins These pins interface the AVR TWI with the rest of the MCU system. The output drivers contain a slew-rate limiter in order to conform to the TWI specification. The input stages contain a spike suppression unit removing spikes shorter than 50 ns. Note that SDA and SCL pads supports internal pull-ups. The internal pull-ups can in some systems eliminate the need for external ones. Bit Rate Generator Unit This unit controls the period of SCL when operating in a Master mode. The SCL period is controlled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but the CPU clock frequency in the Slave must be at least 16 times higher than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period. The SCL frequency is generated according to the following equation: 22.5.2 CPU Clock frequency SCL frequency = ---------------------------------------------------------TWPS 16 + 2(TWBR) 4 * TWBR = Value of the TWI Bit Rate Register. TWI Unit 303 TPR0327AY-SMS-30Jan09 * TWPS = Value of the prescaler bits in the TWI Status Register Pull-up resistor values should be selected according to the SCL frequency and the capacitive bus line load. Note 22.5.3 Bus Interface Unit This unit contains the Data and Address Shift Register (TWDR), a START/STOP Controller and Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted, or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also contains a register containing the (N)ACK bit to be transmitted or received. This (N)ACK Register is not directly accessible by the application software. However, when receiving, it can be set or cleared by manipulating the TWI Control Register (TWCR). When in Transmitter mode, the value of the received (N)ACK bit can be determined by the value in the TWSR. The START/STOP Controller is responsible for generation and detection of START, REPEATED START, and STOP conditions. The START/STOP controller is able to detect START and STOP conditions even when the AVR MCU is in one of the sleep modes, enabling the MCU to wake up if addressed by a Master. If the TWI has initiated a transmission as Master, the Arbitration Detection hardware continuously monitors the transmission trying to determine if arbitration is in process. If the TWI has lost an arbitration, the Control Unit is informed. Correct action can then be taken and appropriate status codes generated. 22.5.4 Address Match Unit The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the TWAR is written to one, all incoming address bits will also be compared against the General Call address. Upon an address match, the Control Unit is informed, allowing correct action to be taken. The TWI may or may not acknowledge its address, depending on settings in the TWCR. The Address Match unit is able to compare addresses even when the AVR MCU is in sleep mode, enabling the MCU to wake up if addressed by a Master. If another interrupt (e.g., INT0) occurs during TWI Power-down address match and wakes up the CPU, the TWI aborts operation and return to its idle state. If this causes any problems, ensure that TWI Address Match is the only enabled interrupt when entering Power-down. Control Unit The Control unit monitors the TWI bus and generates responses corresponding to settings in the TWI Control Register (TWCR). When an event requiring the attention of the application occurs on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Status Register (TWSR) is updated with a status code identifying the event. The TWSR only contains relevant status information when the TWI Interrupt Flag is asserted. At all other times, the TWSR contains a special status code indicating that no relevant status information is available. As long as the TWINT Flag is set, the SCL line is held low. This allows the application software to complete its tasks before allowing the TWI transmission to continue. The TWINT Flag is set in the following situations: * After the TWI has transmitted a START/REPEATED START condition. * After the TWI has transmitted SLA+R/W. 22.5.5 304 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * After the TWI has transmitted an address byte. * After the TWI has lost arbitration. * After the TWI has been addressed by own slave address or general call. * After the TWI has received a data byte. * After a STOP or REPEATED START has been received while still addressed as a Slave. * When a bus error has occurred due to an illegal START or STOP condition. 22.6 Using the TWI The AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all bus events, like reception of a byte or transmission of a START condition. Because the TWI is interrupt-based, the application software is free to carry on other operations during a TWI byte transfer. Note that the TWI Interrupt Enable (TWIE) bit in TWCR together with the Global Interrupt Enable bit in SREG allow the application to decide whether or not assertion of the TWINT Flag should generate an interrupt request. If the TWIE bit is cleared, the application must poll the TWINT Flag in order to detect actions on the TWI bus. When the TWINT Flag is asserted, the TWI has finished an operation and awaits application response. In this case, the TWI Status Register (TWSR) contains a value indicating the current state of the TWI bus. The application software can then decide how the TWI should behave in the next TWI bus cycle by manipulating the TWCR and TWDR Registers. Figure 22-10 is a simple example of how the application can interface to the TWI hardware. In this example, a Master wishes to transmit a single data byte to a Slave. This description is quite abstract, a more detailed explanation follows later in this section. A simple code example implementing the desired behavior is also presented. Figure 22-10. Interfacing the Application to the TWI in a Typical Transmission 1. Application writes to TWCR to initiate transmission of START 3. Check TWSR to see if START was sent. Application loads SLA+W into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one, and TWSTA is written to zero. 5. Check TWSR to see if SLA+W was sent and ACK received. Application loads data into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one 7. Check TWSR to see if data was sent and ACK received. Application loads appropriate control signals to send STOP into TWCR, making sure that TWINT is written to one Application Action TWI bus START SLA+W A Data A STOP 2. TWINT set. Status code indicates START condition sent 4. TWINT set. Status code indicates SLA+W sent, ACK received TWI Hardware Action 6. TWINT set. Status code indicates data sent, ACK received Indicates TWINT set 1. The first step in a TWI transmission is to transmit a START condition. This is done by writing a specific value into TWCR, instructing the TWI hardware to transmit a START condition. The value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after 305 TPR0327AY-SMS-30Jan09 the application has cleared TWINT, the TWI will initiate transmission of the START condition. 2. When the START condition has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the START condition has successfully been sent. 3. The application software should now examine the value of TWSR, to make sure that the START condition was successfully transmitted. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load SLA+W into TWDR. Remember that TWDR is used both for address and data. After TWDR has been loaded with the desired SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the address packet. 4. When the address packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the address packet has successfully been sent. The status code will also reflect whether a Slave acknowledged the packet or not. 5. The application software should now examine the value of TWSR, to make sure that the address packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load a data packet into TWDR. Subsequently, a specific value must be written to TWCR, instructing the TWI hardware to transmit the data packet present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet. 6. When the data packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a Slave acknowledged the packet or not. 7. The application software should now examine the value of TWSR, to make sure that the data packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOP condition. Note that TWINT is NOT set after a STOP condition has been sent. Even though this example is simple, it shows the principles involved in all TWI transmissions. These can be summarized as follows: * When the TWI has finished an operation and expects application response, the TWINT Flag is set. The SCL line is pulled low until TWINT is cleared. 306 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * When the TWINT Flag is set, the user must update all TWI Registers with the value relevant for the next TWI bus cycle. As an example, TWDR must be loaded with the value to be transmitted in the next bus cycle. * After all TWI Register updates and other pending application software tasks have been completed, TWCR is written. When writing TWCR, the TWINT bit should be set. Writing a one to TWINT clears the flag. The TWI will then start executing whatever operation was specified by the TWCR setting. In the following an assembly and C implementation of the example is given. Note that the code below assumes that several definitions have been made, for example by using include-files. Assembly Code Example ldi r16, (1< while (!(TWCR & (1< TPR0327AY-SMS-30Jan09 Assembly Code Example wait3: 6 in r16,TWCR sbrs r16,TWINT rjmp wait3 in r16,TWSR andi r16, 0xF8 cpi 7 r16, MT_DATA_ACK brne ERROR ldi r16, (1< if ((TWSR & 0xF8) != MT_DATA_ACK) ERROR(); TWCR = (1< Transmission Modes The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As an example, the TWI can use MT mode to write data into a TWI EEPROM, MR mode to read the data back from the EEPROM. If other masters are present in the system, some of these might transmit data to the TWI, and then SR mode would be used. It is the application software that decides which modes are legal. The following sections describe each of these modes. Possible status codes are described along with figures detailing data transmission in each of the modes. These figures contain the following abbreviations: S: START condition Rs: REPEATED START condition R: Read bit (high level at SDA) W: Write bit (low level at SDA) A: Acknowledge bit (low level at SDA) A: Not acknowledge bit (high level at SDA) Data: 8-bit data byte P: STOP condition SLA: Slave Address In Figure 22-12 to Figure 22-18, circles are used to indicate that the TWINT Flag is set. The numbers in the circles show the status code held in TWSR, with the prescaler bits masked to zero. At these points, actions must be taken by the application to continue or complete the TWI transfer. The TWI transfer is suspended until the TWINT Flag is cleared by software. When the TWINT Flag is set, the status code in TWSR is used to determine the appropriate software action. For each status code, the required software action and details of the following serial transfer are given in Table 22-2 to Table 22-5. Note that the prescaler bits are masked to zero in these tables. 308 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 22.7.1 Master Transmitter Mode In the Master Transmitter mode, a number of data bytes are transmitted to a Slave Receiver (see Figure 22-11). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 22-11. Data Transfer in Master Transmitter Mode V CC Device 1 MASTER TRANSMITTER Device 2 SLAVE RECEIVER Device 3 ........ Device n R1 R2 SDA SCL Note Please note that R1 and R2 resistors may not be required. The internal pull-up resistors on SDA and SCL pads of AVR may be sufficient to setup a communication. However, if the edges are not strong enough to get a clean signals, R1 and R2 can be added. A START condition is sent by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X TWEN must be set to enable the 2-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT Flag. The TWI will then test the 2-wire Serial Bus and generate a START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT Flag is set by hardware, and the status code in TWSR will be 0x08 (see Table 22-2). In order to enter MT mode, SLA+W must be transmitted. This is done by writing SLA+W to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 0 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X When SLA+W have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x18, 0x20, or 0x38. The appropriate action to be taken for each of these status codes is detailed in Table 22-2. When SLA+W has been successfully transmitted, a data packet should be transmitted. This is done by writing the data byte to TWDR. TWDR must only be written when TWINT is high. If not, 309 TPR0327AY-SMS-30Jan09 the access will be discarded, and the Write Collision bit (TWWC) will be set in the TWCR Register. After updating TWDR, the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 0 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X This scheme is repeated until the last byte has been sent and the transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 0 TWSTO 1 TWWC X TWEN 1 - 0 TWIE X A REPEATED START condition is generated by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X After a repeated START condition (state 0x10) the 2-wire Serial Interface can access the same Slave again, or a new Slave without transmitting a STOP condition. Repeated START enables the Master to switch between Slaves, Master Transmitter mode and Master Receiver mode without losing control of the bus. Table 22-2. Status Code (TWSR) Prescaler Bits are 0 0x08 0x10 Status codes for Master Transmitter Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To/from TWDR STA Load SLA+W Load SLA+W or Load SLA+R 0 0 0 0 1 0 1 0 1 0 1 To TWCR STO 0 0 0 0 0 1 1 0 0 1 1 TWIN T 1 1 1 1 1 1 1 1 1 1 1 TWE A X X X X X X X X X X X Next Action Taken by TWI Hardware SLA+W will be transmitted; ACK or NOT ACK will be received SLA+W will be transmitted; ACK or NOT ACK will be received SLA+R will be transmitted; Logic will switch to Master Receiver mode Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset 0x18 SLA+W has been transmitted; ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action 0x20 SLA+W has been transmitted; NOT ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action 310 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 22-2. 0x28 Status codes for Master Transmitter Mode Data byte has been transmitted; ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action 0 1 0 1 0 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 X X X X X X X X X X Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset 2-wire Serial Bus will be released and not addressed Slave mode entered A START condition will be transmitted when the bus becomes free 0x30 Data byte has been transmitted; NOT ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action 0x38 Arbitration lost in SLA+W or data bytes No TWDR action or No TWDR action 311 TPR0327AY-SMS-30Jan09 Figure 22-12. Formats and States in the Master Transmitter Mode MT Successfull transmission to a slave receiver S SLA W A DATA A P $08 Next transfer started with a repeated start condition $18 $28 RS SLA W $10 Not acknowledge received after the slave address A P R $20 MR Not acknowledge received after a data byte A P $30 Arbitration lost in slave address or data byte A or A Other master continues A or A Other master continues $38 Arbitration lost and addressed as slave $38 Other master continues A $68 $78 $B0 To corresponding states in slave mode From master to slave DATA A Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-Wire Serial Bus. The prescaler bits are zero or masked to zero From slave to master n 22.7.2 Master Receiver Mode In the Master Receiver mode, a number of data bytes are received from a Slave Transmitter (Slave see Figure 22-13). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. 312 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 22-13. Data Transfer in Master Receiver Mode V CC Device 1 MASTER RECEIVER Device 2 SLAVE TRANSMITTER Device 3 ........ Device n R1 R2 SDA SCL Note Please note that R1 and R2 resistors may be useless. Indeed, internal pull-up resistors on SDA and SCL pads of AVR may be sufficient to setup a communication. Anyway, R1 and R2 are welcomed if the edges are not strong enough to get a clean signals. A START condition is sent by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X TWEN must be written to one to enable the 2-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be set to clear the TWINT Flag. The TWI will then test the 2-wire Serial Bus and generate a START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT Flag is set by hardware, and the status code in TWSR will be 0x08 (See Table 22-2). In order to enter MR mode, SLA+R must be transmitted. This is done by writing SLA+R to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 0 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X When SLA+R have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x38, 0x40, or 0x48. The appropriate action to be taken for each of these status codes is detailed in Table 22-3. Received data can be read from the TWDR Register when the TWINT Flag is set high by hardware. This scheme is repeated until the last byte has been received. After the last byte has been received, the MR should inform the ST by sending a NACK after the last received data byte. The transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR: TWCR value TWINT 1 TWEA X TWSTA 0 TWSTO 1 TWWC X TWEN 1 - 0 TWIE X A REPEATED START condition is generated by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE 313 TPR0327AY-SMS-30Jan09 value 1 X 1 0 X 1 0 X After a repeated START condition (state 0x10) the 2-wire Serial Interface can access the same Slave again, or a new Slave without transmitting a STOP condition. Repeated START enables the Master to switch between Slaves, Master Transmitter mode and Master Receiver mode without losing control over the bus. Table 22-3. Status Code (TWSR) Prescaler Bits are 0 0x08 0x10 Status codes for Master Receiver Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+R Load SLA+R or Load SLA+W STA 0 0 0 0 1 0 0 1 0 1 0 0 1 0 1 STO 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 TWIN T 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWE A X X X X X 0 1 X X X 0 1 X X X Next Action Taken by TWI Hardware SLA+R will be transmitted ACK or NOT ACK will be received SLA+R will be transmitted ACK or NOT ACK will be received SLA+W will be transmitted Logic will switch to Master Transmitter mode 2-wire Serial Bus will be released and not addressed Slave mode will be entered A START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset 0x38 Arbitration lost in SLA+R or NOT ACK bit No TWDR action or No TWDR action 0x40 SLA+R has been transmitted; ACK has been received No TWDR action or No TWDR action 0x48 SLA+R has been transmitted; NOT ACK has been received No TWDR action or No TWDR action or No TWDR action 0x50 Data byte has been received; ACK has been returned Data byte has been received; NOT ACK has been returned Read data byte or Read data byte 0x58 Read data byte or Read data byte or Read data byte 314 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 22-14. Formats and States in the Master Receiver Mode MR Successfull reception from a slave receiver S SLA R A DATA A DATA A P $08 Next transfer started with a repeated start condition $40 $50 $58 RS SLA R $10 Not acknowledge received after the slave address A P W $48 MT Arbitration lost in slave address or data byte A or A Other master continues A Other master continues $38 Arbitration lost and addressed as slave $38 Other master continues A $68 $78 $B0 To corresponding states in slave mode From master to slave DATA A Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-Wire Serial Bus. The prescaler bits are zero or masked to zero From slave to master n 22.7.3 Slave Receiver Mode In the Slave Receiver mode, a number of data bytes are received from a Master Transmitter (see Figure 22-15). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. 315 TPR0327AY-SMS-30Jan09 Figure 22-15. Data transfer in Slave Receiver mode V CC Device 1 SLAVE RECEIVER Device 2 MASTER TRANSMITTER Device 3 ........ Device n R1 R2 SDA SCL Note Please note that R1 and R2 resistors may be useless. Indeed, internal pull-up resistors on SDA and SCL pads of AVR may be sufficient to setup a communication. Anyway, R1 and R2 are welcomed if the edges are not strong enough to get a clean signals. To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows: TWAR value TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device's Own Slave Address The upper 7 bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address. TWCR value TWINT 0 TWEA 1 TWSTA 0 TWSTO 0 TWWC 0 TWEN 1 - 0 TWIE X TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the device's own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is "0" (write), the TWI will operate in SR mode, otherwise ST mode is entered. After its own slave address and the write bit have been received, the TWINT Flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 22-4. The Slave Receiver mode may also be entered if arbitration is lost while the TWI is in the Master mode (see states 0x68 and 0x78). If the TWEA bit is reset during a transfer, the TWI will return a "Not Acknowledge" ("1") to SDA after the next received data byte. This can be used to indicate that the Slave is not able to receive any more bytes. While TWEA is zero, the TWI does not acknowledge its own slave address. However, the 2-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the 2-wire Serial Bus. In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by 316 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 using the 2-wire Serial Bus clock as a clock source. The part will then wake up from sleep and the TWI will hold the SCL clock low during the wake up and until the TWINT Flag is cleared (by writing it to one). Further data reception will be carried out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. theTWI Serial Interface Data Register - TWDR does not reflect the last byte present on the bus when waking up from these Sleep modes. ! Caution Table 22-4. Status Code (TWSR) Prescaler Bits are 0 0x60 Status Codes for Slave Receiver Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware Own SLA+W has been received; ACK has been returned Arbitration lost in SLA+R/W as Master; own SLA+W has been received; ACK has been returned General call address has been received; ACK has been returned Arbitration lost in SLA+R/W as Master; General call address has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; NOT ACK has been returned To TWCR To/from TWDR No TWDR action or No TWDR action STA X X X X X X X X X X 0 0 1 STO 0 0 0 0 0 0 0 0 0 0 0 0 0 TWIN T 1 1 1 1 1 1 1 1 1 1 1 1 1 TWE A 0 1 0 1 0 1 0 1 0 1 0 1 0 Next Action Taken by TWI Hardware Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free 0x68 No TWDR action or No TWDR action No TWDR action or No TWDR action 0x70 0x78 No TWDR action or No TWDR action Read data byte or Read data byte Read data byte or Read data byte or Read data byte or 0x80 0x88 Read data byte 1 0 1 1 317 TPR0327AY-SMS-30Jan09 Table 22-4. 0x90 Status Codes for Slave Receiver Mode Previously addressed with general call; data has been received; ACK has been returned Previously addressed with general call; data has been received; NOT ACK has been returned Read data byte or Read data byte Read data byte or Read data byte or Read data byte or X X 0 0 1 0 0 0 0 0 1 1 1 1 1 0 1 0 1 0 Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free 0x98 Read data byte 1 0 1 1 0xA0 A STOP condition or repeated START condition has been received while still addressed as Slave No action 0 0 1 0 0 0 1 1 1 0 1 0 1 0 1 1 318 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 22-16. Formats and States in the Slave Receiver Mode Reception of the own slave address and one or more data bytes. All are acknowledged S SLA W A DATA A DATA A P or S $60 Last data byte received is not acknowledged $80 $80 $A0 A P or S $88 Arbitration lost as master and addressed as slave A $68 Reception of the general call address and one or more data bytes General Call A DATA A DATA A P or S $70 Last data byte received is not acknowledged $90 $90 $A0 A P or S $98 Arbitration lost as master and addressed as slave by general call A $78 From master to slave DATA A Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-Wire Serial Bus. The prescaler bits are zero or masked to zero From slave to master n 22.7.4 Slave Transmitter Mode In the Slave Transmitter mode, a number of data bytes are transmitted to a Master Receiver (see Figure 22-17). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. 319 TPR0327AY-SMS-30Jan09 Figure 22-17. Data Transfer in Slave Transmitter Mode V CC Device 1 SLAVE TRANSMITTER Device 2 MASTER RECEIVER Device 3 ........ Device n R1 R2 SDA SCL To initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows: TWAR value TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device's Own Slave Address The upper seven bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address. TWCR value TWINT 0 TWEA 1 TWSTA 0 TWSTO 0 TWWC 0 TWEN 1 - 0 TWIE X TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the device's own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is "1" (read), the TWI will operate in ST mode, otherwise SR mode is entered. After its own slave address and the write bit have been received, the TWINT Flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 22-5. The Slave Transmitter mode may also be entered if arbitration is lost while the TWI is in the Master mode (see state 0xB0). If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte of the transfer. State 0xC0 or state 0xC8 will be entered, depending on whether the Master Receiver transmits a NACK or ACK after the final byte. The TWI is switched to the not addressed Slave mode, and will ignore the Master if it continues the transfer. Thus the Master Receiver receives all "1" as serial data. State 0xC8 is entered if the Master demands additional data bytes (by transmitting ACK), even though the Slave has transmitted the last byte (TWEA zero and expecting NACK from the Master). While TWEA is zero, the TWI does not respond to its own slave address. However, the 2-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the 2-wire Serial Bus. 320 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by using the 2-wire Serial Bus clock as a clock source. The part will then wake up from sleep and the TWI will hold the SCL clock will low during the wake up and until the TWINT Flag is cleared (by writing it to one). Further data transmission will be carried out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. Note that the 2-wire Serial Interface Data Register - TWDR does not reflect the last byte present on the bus when waking up from these sleep modes. Table 22-5. Status Code (TWSR) Prescaler Bits are 0 0xA8 Status Codes for Slave Transmitter Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware Own SLA+R has been received; ACK has been returned To TWCR To/from TWDR Load data byte or Load data byte STA X X X X X X 0 0 1 STO 0 0 0 0 0 0 0 0 0 TWIN T 1 1 1 1 1 1 1 1 1 TWE A 0 1 0 1 0 1 0 1 0 Next Action Taken by TWI Hardware Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free 0xB0 Arbitration lost in SLA+R/W as Master; own SLA+R has been received; ACK has been returned Data byte in TWDR has been transmitted; ACK has been received Data byte in TWDR has been transmitted; NOT ACK has been received Load data byte or Load data byte Load data byte or Load data byte No TWDR action or No TWDR action or No TWDR action or 0xB8 0xC0 No TWDR action 1 0 1 1 0xC8 Last data byte in TWDR has been transmitted (TWEA = "0"); ACK has been received No TWDR action or No TWDR action or No TWDR action or 0 0 1 0 0 0 1 1 1 0 1 0 No TWDR action 1 0 1 1 321 TPR0327AY-SMS-30Jan09 Figure 22-18. Formats and States in the Slave Transmitter Mode Reception of the own slave address and one or more data bytes S SLA R A DATA A DATA A P or S $A8 Arbitration lost as master and addressed as slave $B8 $C0 A $B0 Last data byte transmitted. Switched to not addressed slave (TWEA = '0') A All 1's P or S $C8 From master to slave DATA A Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-Wire Serial Bus. The prescaler bits are zero or masked to zero From slave to master n 22.7.5 Miscellaneous States There are two status codes that do not correspond to a defined TWI state, see Table 22-6. Status 0xF8 indicates that no relevant information is available because the TWINT Flag is not set. This occurs between other states, and when the TWI is not involved in a serial transfer. Status 0x00 indicates that a bus error has occurred during a 2-wire Serial Bus transfer. A bus error occurs when a START or STOP condition occurs at an illegal position in the format frame. Examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. When a bus error occurs, TWINT is set. To recover from a bus error, the TWSTO Flag must set and TWINT must be cleared by writing a logic one to it. This causes the TWI to enter the not addressed Slave mode and to clear the TWSTO Flag (no other bits in TWCR are affected). The SDA and SCL lines are released, and no STOP condition is transmitted. Table 22-6. Status Code (TWSR) Prescaler Bits are 0 0xF8 0x00 Miscellaneous States Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware No relevant state information available; TWINT = "0" Bus error due to an illegal START or STOP condition To TWCR To/from TWDR No TWDR action No TWDR action 0 STA STO TWIN T TWE A Next Action Taken by TWI Hardware Wait or proceed current transfer X Only the internal hardware is affected, no STOP condition is sent on the bus. In all cases, the bus is released and TWSTO is cleared. No TWCR action 1 1 22.7.6 Combining Several TWI Modes In some cases, several TWI modes must be combined in order to complete the desired action. Consider for example reading data from a serial EEPROM. Typically, such a transfer involves the following steps: 322 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 1. The transfer must be initiated. 2. The EEPROM must be instructed what location should be read. 3. The reading must be performed. 4. The transfer must be finished. Note that data is transmitted both from Master to Slave and vice versa. The Master must instruct the Slave what location it wants to read, requiring the use of the MT mode. Subsequently, data must be read from the Slave, implying the use of the MR mode. Thus, the transfer direction must be changed. The Master must keep control of the bus during all these steps, and the steps should be carried out as an atomical operation. If this principle is violated in a multimaster system, another Master can alter the data pointer in the EEPROM between steps 2 and 3, and the Master will read the wrong data location. Such a change in transfer direction is accomplished by transmitting a REPEATED START between the transmission of the address byte and reception of the data. After a REPEATED START, the Master keeps ownership of the bus. The following figure shows the flow in this transfer. Figure 22-19. Combining Several TWI Modes to Access a Serial EEPROM Master Transmitter Master Receiver S SLA+W A ADDRESS A Rs SLA+R A DATA A P = STOP P S = START Transmitted from master to slave Rs = REPEATED START Transmitted from slave to master 22.8 Multi-master Systems and Arbitration If multiple masters are connected to the same bus, transmissions may be initiated simultaneously by one or more of them. The TWI standard ensures that such situations are handled in such a way that one of the masters will be allowed to proceed with the transfer, and that no data will be lost in the process. An example of an arbitration situation is depicted below, where two masters are trying to transmit data to a Slave Receiver. Figure 22-20. An Arbitration Example V CC Device 1 MASTER TRANSMITTER Device 2 MASTER TRANSMITTER Device 3 SLAVE RECEIVER ........ Device n R1 R2 SDA SCL Several different scenarios may arise during arbitration, as described below: 323 TPR0327AY-SMS-30Jan09 * Two or more masters are performing identical communication with the same Slave. In this case, neither the Slave nor any of the masters will know about the bus contention. * Two or more masters are accessing the same Slave with different data or direction bit. In this case, arbitration will occur, either in the READ/WRITE bit or in the data bits. The masters trying to output a one on SDA while another Master outputs a zero will lose the arbitration. Losing masters will switch to not addressed Slave mode or wait until the bus is free and transmit a new START condition, depending on application software action. * Two or more masters are accessing different slaves. In this case, arbitration will occur in the SLA bits. Masters trying to output a one on SDA while another Master outputs a zero will lose the arbitration. Masters losing arbitration in SLA will switch to Slave mode to check if they are being addressed by the winning Master. If addressed, they will switch to SR or ST mode, depending on the value of the READ/WRITE bit. If they are not being addressed, they will switch to not addressed Slave mode or wait until the bus is free and transmit a new START condition, depending on application software action. This is summarized in Figure 22-21. Possible status values are given in circles. Figure 22-21. Possible Status Codes Caused by Arbitration START SLA Data STOP Arbitration lost in SLA Arbitration lost in Data Own Address / General Call received No 38 TWI bus will be released and not addressed slave mode will be entered A START condition will be transmitted when the bus becomes free Yes Write 68/78 Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Direction Read B0 Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received 22.9 22.9.1 TWI Register Description TWBR - TWI Bit Rate Register Bit $0000B8 Read/write Initial value 7 TWBR7 R/W 0 6 TWBR6 R/W 0 5 TWBR5 R/W 0 4 TWBR4 R/W 0 3 TWBR3 R/W 0 2 TWBR2 R/W 0 1 TWBR1 R/W 0 0 TWBR0 R/W 0 0x00 TWBR * Bits 7..0 - TWI Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the Master modes. See "Bit Rate Generator Unit" on page 303 for calculating bit rates. 324 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 22.9.2 TWCR - TWI Control Register Bit $0000BC Read/write Initial value 7 TWINT R/W 0 6 TWEA R/W 0 5 TWSTA R/W 0 4 TWSTO R/W 0 3 TWWC R 0 2 TWEN R/W 0 1 - R 0 0 TWIE R/W 0 0x00 TWCR The TWCR is used to control the operation of the TWI. It is used to enable the TWI, to initiate a Master access by applying a START condition to the bus, to generate a Receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the TWDR. It also indicates a write collision if data is attempted written to TWDR while the register is inaccessible. * Bit 7 - TWINT: TWI Interrupt Flag This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT Flag is set, the SCL low period is stretched. The TWINT Flag must be cleared by software by writing a logic one to it. Note that this flag is not automatically cleared by hardware when executing the interrupt routine. Also note that clearing this flag starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this flag. * Bit 6 - TWEA: TWI Enable Acknowledge Bit The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to one, the ACK pulse is generated on the TWI bus if the following conditions are met: 1. The device's own slave address has been received. 2. A general call has been received, while the TWGCE bit in the TWAR is set. 3. A data byte has been received in Master Receiver or Slave Receiver mode. By writing the TWEA bit to zero, the device can be virtually disconnected from the 2-wire Serial Bus temporarily. Address recognition can then be resumed by writing the TWEA bit to one again. * Bit 5 - TWSTA: TWI START Condition Bit The application writes the TWSTA bit to one when it desires to become a Master on the 2-wire Serial Bus. The TWI hardware checks if the bus is available, and generates a START condition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition is detected, and then generates a new START condition to claim the bus Master status. TWSTA must be cleared by software when the START condition has been transmitted. * Bit 4 - TWSTO: TWI STOP Condition Bit Writing the TWSTO bit to one in Master mode will generate a STOP condition on the 2-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically. In Slave mode, setting the TWSTO bit can be used to recover from an error condition. This will not generate a STOP condition, but the TWI returns to a well-defined unaddressed Slave mode and releases the SCL and SDA lines to a high impedance state. * Bit 3 - TWWC: TWI Write Collision Flag 325 TPR0327AY-SMS-30Jan09 The TWWC bit is set when attempting to write to the TWI Data Register - TWDR when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is high. * Bit 2 - TWEN: TWI Enable Bit The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is written to one, the TWI takes control over the I/O pins connected to the SCL and SDA pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the TWI is switched off and all TWI transmissions are terminated, regardless of any ongoing operation. * Bit 1 - Res: Reserved Bit This bit is a reserved bit and will always read as zero. * Bit 0 - TWIE: TWI Interrupt Enable When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be activated for as long as the TWINT Flag is high. 22.9.3 TWSR - TWI Status Register Bit $0000B9 Read/write Initial value 7 TWS7 R 1 6 TWS6 R 1 5 TWS5 R 1 4 TWS4 R 1 3 TWS3 R 1 2 - R 0 1 TWPS1 R/W 0 0 TWPS0 R/W 0 0x00 TWSR * Bits 7..3 - TWS: TWI Status These 5 bits reflect the status of the TWI logic and the 2-wire Serial Bus. The different status codes are described later in this section. Note that the value read from TWSR contains both the 5-bit status value and the 2-bit prescaler value. The application designer should mask the prescaler bits to zero when checking the Status bits. This makes status checking independent of prescaler setting. This approach is used in this datasheet, unless otherwise noted. * Bit 2 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bits 1..0 - TWPS: TWI Prescaler Bits These bits can be read and written, and control the bit rate prescaler. Table 22-7. TWPS1 0 0 1 1 TWI Bit Rate Prescaler TWPS0 0 1 0 1 Prescaler Value 1 4 16 64 To calculate bit rates, see "Bit Rate Generator Unit" on page 303. The value of TWPS1..0 is used in the equation. 326 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 22.9.4 TWDR - TWI Data Register Bit $0000BB Read/write Initial value 7 TWD7 R/W 1 6 TWD6 R/W 1 5 TWD5 R/W 1 4 TWD4 R/W 1 3 TWD3 R/W 1 2 TWD2 R/W 1 1 TWD1 R/W 1 0 TWD0 R/W 1 0xFF TWDR In Transmit mode, TWDR contains the next byte to be transmitted. In Receive mode, the TWDR contains the last byte received. It is writable while the TWI is not in the process of shifting a byte. This occurs when the TWI Interrupt Flag (TWINT) is set by hardware. Note that the Data Register cannot be initialized by the user before the first interrupt occurs. The data in TWDR remains stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted in. TWDR always contains the last byte present on the bus, except after a wake up from a sleep mode by the TWI interrupt. In this case, the contents of TWDR is undefined. In the case of a lost bus arbitration, no data is lost in the transition from Master to Slave. Handling of the ACK bit is controlled automatically by the TWI logic, the CPU cannot access the ACK bit directly. * Bits 7..0 - TWD: TWI Data Register These eight bits constitute the next data byte to be transmitted, or the latest data byte received on the 2-wire Serial Bus. 22.9.5 TWAR - TWI (Slave) Address Register Bit $0000BA Read/write Initial value 7 TWA6 R/W 1 6 TWA5 R/W 1 5 TWA4 R/W 1 4 TWA3 R/W 1 3 TWA2 R/W 1 2 TWA1 R/W 1 1 TWA0 R/W 1 0 TWGCE R/W 0 0xFE TWAR The TWAR should be loaded with the 7-bit Slave address (in the seven most significant bits of TWAR) to which the TWI will respond when programmed as a Slave Transmitter or Receiver, and not needed in the Master modes. In multimaster systems, TWAR must be set in masters which can be addressed as Slaves by other Masters. The LSB of TWAR is used to enable recognition of the general call address (0x00). There is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. If a match is found, an interrupt request is generated. * Bits 7..1 - TWA: TWI (Slave) Address Register These seven bits constitute the slave address of the TWI unit. * Bit 0 - TWGCE: TWI General Call Recognition Enable Bit If set, this bit enables the recognition of a General Call given over the 2-wire Serial Bus. 327 TPR0327AY-SMS-30Jan09 22.9.6 TWAMR - TWI (Slave) Address Mask Register Bit $0000BD Read/write Initial value R/W 0 R/W 0 R/W 0 7 6 5 4 TWAM [6:0] R/W 0 R/W 0 R/W 0 R/W 0 3 2 1 0 R/W 0 0x00 TWAMR * Bits 7..1 - TWAM: TWI Address Mask The TWAMR can be loaded with a 7-bit Slave Address mask. Each of the bits in TWAMR can mask (disable) the corresponding address bit in the TWI Address Register (TWAR). If the mask bit is set to one then the address match logic ignores the compare between the incoming address bit and the corresponding bit in TWAR. Figure 22-22 shows the address match logic in detail. Figure 22-22. TWI Address Match Logic, Block Diagram TWAR0 Address Bit 0 TWAMR0 Address Bit Comparator 0 Address Match Address Bit Comparator 6..1 * Bit 0 - Res: Reserved Bit This bit is reserved and will always read as zero. 328 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 23. Keyboard Interface 23.1 Features * * * * Allows connection of a 8x8 matrix keyboard Based on 8 inputs pins and 8 outputs specific pins Supports slow edge pads to avoid abusive EMC generation (on outputs pads only) Specific Keyboard pins only available in Full Pin Count package. See "Pin List Configuration" on page 5. * Allows chip wake-up on key pressed event 23.2 23.2.1 General Description Overview The keyboard interfaces with the AVR core through 3 registers: KBLS, the Keyboard Level Selection register (page 332), KBE, The Keyboard interrupt Enable register (page 331), and KBF, the Keyboard Flag register (page 330). You can choose to create a Keyboard interface only by using Pin Change Management.This module's purpose is to ease the creation of little Pinpads. Note 23.2.2 Interrupt The keyboard inputs are considered as 8 independant interrupt sources sharing the same interrupt vector. An interrupt enable bit allows global enable or disable of the keyboard interrupt (see Figure 23-1). As detailed in Figure 23-2 each keyboard input can detect a programmable level according to KBLS.x bit value. Level detection is then reported in interrupt flags KBFR.x that can be masked by software using KBER.x bits. The KBFR.x flags are set by hardware when an active level is on input PAx. The KBFR register is reset by writing any data inside the KBFR. Figure 23-1. Keyboard Interface Block Diagram PA7: KbIN 7 PA6: KbIN 6 PA5: KbIN 5 PA4: KbIN 4 PA3: KbIN 3 PA2: KbIN 2 PA1: KbIN 1 PA0: KbIN 0 Input Circuitry Input Circuitry Input Circuitry Input Circuitry Input Circuitry Input Circuitry Input Circuitry Input Circuitry Global IT bit Keyboard IT Keyboard interface Interrupt request 329 TPR0327AY-SMS-30Jan09 Figure 23-2. Keyboard Input Circuitry 0 KbIN x 1 KBE.x KBLS.x KBF.x 23.2.3 Power Reduction Mode Keyboard inputs allow wake up from power-down, power-save, Standby, Extended Standbay modes "Active Clock Domains and Wake-up Sources in the Different Sleep Modes." on page 44. 23.3 23.3.1 Keyboard Register Description KBFR - KeyBoard Flag Register Bit $008F Read/write Initial value 7 KBF7 R/W 0 6 KBF6 R/W 0 5 KBF5 R/W 0 4 KBF4 R/W 0 3 KBF3 R/W 0 2 KBF2 R/W 0 1 KBF1 R/W 0 0 KBF0 R/W 0 0x00 KBFR * Bit 7- KBF7: Keyboard Flag for KbIN7 pin Set by hardware when the pin function KbIN7 (PA7) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE7 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 6 - KBF6: Keyboard Flag for KbIN6 pin Set by hardware when the pin function KbIN6 (PA6) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE6 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 5 - KBF5: Keyboard Flag for KbIN5 pin Set by hardware when the pin function KbIN5 (PA5) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE5 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 4 - KBF4: Keyboard Flag for KbIN4 pin Set by hardware when the pin function KbIN4 (PA4) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE4 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 3 - KBF3 : Keyboard Flag for KbIN3 pin Set by hardware when the pin function KbIN3 (PA3) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE3 bit is set. 330 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 2 - KBF2 : Keyboard Flag for KbIN2 pin Set by hardware when the pin function KbIN2 (PA2) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE2 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 1 - KBF1: Keyboard Flag for KbIN1 pin Set by hardware when the pin function KbIN1 (PA1) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE1 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register * Bit 0 - KBF0 : Keyboard Flag for KbIN0 pin Set by hardware when the pin function KbIN0 (PA0) detects a programmed level. It generates a Keyboard interrupt request if the KBER.KBE0 bit is set. Writing a `0' or a `1' into this bit will erase all the bits (including this one) of the KBFR register 23.3.2 KBER - KeyBoard Enable Register Bit $008E Read/write Initial value 7 KBE7 R/W 0 6 KBE6 R/W 0 5 KBE5 R/W 0 4 KBE4 R/W 0 3 KBE3 R/W 0 2 KBE2 R/W 0 1 KBE1 R/W 0 0 KBE0 R/W 0 0x00 KBER * Bit 7- KBE7 : Keyboard KbIN7 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF7 to generate an interrupt request. * Bit 6- KBE6 : Keyboard KbIN6 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF6 to generate an interrupt request. * Bit 5- KBE5 : Keyboard KbIN5 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF5 to generate an interrupt request. * Bit 4 - KBE4 : Keyboard KbIN4 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF4 to generate an interrupt request. * Bit 3 - KBE3 : Keyboard KbIN3 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF3 to generate an interrupt request. * Bit 2 - KBE2 : Keyboard KbIN2 Enable bit Cleared to enable standard I/O pin. 331 TPR0327AY-SMS-30Jan09 Set to enable KBFR.KBF2 to generate an interrupt request. * Bit 1 - KBE1 : Keyboard KbIN1 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF1 to generate an interrupt request. * Bit 0 - KBE0 : Keyboard KbIN0 Enable bit Cleared to enable standard I/O pin. Set to enable KBFR.KBF0 to generate an interrupt request. 23.3.3 KBLSR - KeyBoard Level Selection Register Bit $008D Read/write Initial value 7 KBLS7 R/W 0 6 KBLS6 R/W 0 5 KBLS5 R/W 0 4 KBLS4 R/W 0 3 KBLS3 R/W 0 2 KBLS2 R/W 0 1 KBLS1 R/W 0 0 KBLS0 R/W 0 0x00 KBLSR * Bit 7- KBLS7 : Keyboard KbIN7 Level Selection bit Cleared to enable low level detection on KbIN7. Set to enable a high level detection on KbIN7. * Bit 6- KBLS6 : Keyboard KbIN6 Level Selection bit Cleared to enable low level detection on KbIN6. Set to enable a high level detection on KbIN6. * Bit 5 - KBLS5 : Keyboard KbIN5 Level Selection bit Cleared to enable low level detection on KbIN5. Set to enable a high level detection on KbIN5. * Bit 4 - KBLS4 : Keyboard KbIN4 Level Selection bit Cleared to enable low level detection on KbIN4. Set to enable a high level detection on KbIN4. * Bit 3 - KBLS3 : Keyboard KbIN3 Level Selection bit Cleared to enable low level detection on KbIN3. Set to enable a high level detection on KbIN3. * Bit 2 - KBLS2 : Keyboard KbIN2 Level Selection bit Cleared to enable low level detection on KbIN2. Set to enable a high level detection on KbIN2. * Bit 1 - KBLS4 : Keyboard KbIN1 Level Selection bit Cleared to enable low level detection on KbIN1. Set to enable a high level detection on KbIN1. 332 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Bit 0 - KBLS0 : Keyboard KbIN0 Level Selection bit Cleared to enable low level detection on KbIN0. Set to enable a high level detection on KbIN0. 333 TPR0327AY-SMS-30Jan09 334 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 24. Random Number Generator 24.1 Features * Automatic generation of 8-bits Random Number * Private Oscillator source used for unpredictable random generation 24.2 RNG Definition The Random Number Generator of the AT90SCR100 uses a specific oscillator source controlled by the RNGCR.ROSCE bit. This oscillator adapt is used to activate a hardware process. This hardware process can be seeded through the LFSR3 to LFSR0 registers. The result of the hardware post-processing can be read from the RDWDR register. LFSR3 to LFSR0 registers must be changed while the oscillator source is stopped (RNGCR.ROSCE bit is cleared). When RNGCR.ROSCE bit is cleared, the oscillator source is stopped (as well as the shift register and the hardware post processing). When RNGCR.ROSCE bit is set, the oscillator is activated and the configuration of the shift register and of the hardware post-processing depends on the LFSR registers and previous hardware iterations. LFSR0 to LFSR3 Oscillator Hardware Postprocessing RDWDR Note After chip start-up, some oscillator cycles will be performed in order to initialise to a different random value after each chip power-up. 335 TPR0327AY-SMS-30Jan09 24.3 24.3.1 Random Number Generator Registers RNGCR - Random Number Generator Control Register Bit $000095 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 R 0 0 ROSCE R/W 0 0x00 RNGCR * Bit 7..1 : Reserved for Future Use These bits are reserved for future use. * Bit 0 - ROSCE: Random Oscillator Enable Set this bit to enable the oscillator source and to start the Random Number Generation. Clear this bit to stop the execution of the Random Number Generator. The value of the LFSRn and RDWDR registers will retain the value of the last oscillator step. 24.3.2 LFSR0 to LFSR3 - Initialization Registers Bit $000094 Read/write Initial value Bit $000093 Read/write Initial value Bit $000092 Read/write Initial value Bit $000091 Read/write Initial value R/W x R/W x R/W x R/W x 7 R/W x 6 R/W x 5 R/W x 7 R/W x 6 R/W x 5 R/W x 7 R/W x 6 R/W x 5 7 6 5 4 R/W x 4 R/W x 4 R/W x 4 R/W x 3 R/W x 3 R/W x 3 R/W x 3 R/W x 2 R/W x 2 R/W x 2 R/W x 2 R/W x 1 R/W x 1 R/W x 1 R/W x 1 R/W x 0 LFSR3 R/W x 0 LFSR2 R/W x 0 LFSR1 R/W x 0 LFSR0 R/W x LFSD [31..24] LFSD [23..16] LFSD [15..8] LFSD [7..0] * Bit 31..0 - LFSDxx: Current LFSR Generator Value These registers can be loaded, with an initial seed value for the hardware process, if the PMCR.ROSCE bit is cleared. The values of LFSRx registers are changed between two AVR clock cycles. 336 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 24.3.3 RDWDR - Random Word Data Register Bit $000090 Read/write Initial value R x R x R x 7 6 5 4 R x 3 R x 2 R x 1 R x 0 RDWDR R x RDD [7..0] * Bit 7..0 - RDDx: Random Word Generator Result Value Returns the post-processed random value. At each AVR clock this register value is changed with a value derived from the hardware process, seeded by the LFSR0 to LFSR3 registers. 337 TPR0327AY-SMS-30Jan09 338 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 25. AES 128/256 Engine To support all the security needs and requirements of embedded systems, the AT90SCR100 features a hardware AES engine. It provides an efficient and easy way to perform standard cryptographic calculus. 25.1 Features * * * * * * 128 and 256 bits key length Encryption and Decryption algorithm Supports ECB, CBC, and MAC algorithms Specific Encryption/Decryption key generation for optimized revet algorithm Auto-incremented pointer register on data write for fast data loading Interrupt generation on calculus completion 25.2 Overview The AES module of the AT90SCR100 includes an internal memory, dedicated to AES management. These registers are not directly accessible from the AVR core, and the user must use a specific interface to write both key and data. The AES module can only manage one data block of 128 bits at a time. The figure below shows how to access the internal memory of the AES block: Figure 25-1. AES Block Interface AESADDR AESACR AESACR.KD Address Decoder Internal Memory AES Key Register 0x31 AESACR.KD=0 AES Block AESDR AESACR.KD=1 0x00 AES Engine AES Data Register 0x15 0x00 AES Interrupt signal AES Control System 339 TPR0327AY-SMS-30Jan09 25.2.1 Memory Organization There are 2 address areas: Key and Data. Internal registers can be observed or modified via the AESADDR and AESDR registers. All bytes must be reverted in the AES Data and Key memory. This means that the data must be oriented LSB first ! Caution ! Caution As memory is reversed, the AES 128Key LSB will start at address #16 and MSB of AES128 key will be at address #31 ! Caution The result is also inverted in Data internal memory (LSB first). Below is a way to organize the memory according to an example: Figure 25-2. Example of memory organization AES128 Key: Data To cipher: 00010203050607080A0B0C0D0F101112 506812A45F08C889B97F5980038B8359 Ciphered Message: D8F532538289EF7D06B506A4FD5BE9C9 AES_Key #31 00 01 02 03 05 06 07 08 0A 0B 0C 0D 0F 10 11 12 AES_Data #15 50 68 12 A4 5F 08 C8 89 B9 7F 59 80 03 8B 83 59 AES_Result #15 D8 F5 32 53 82 89 EF 7D 06 B5 06 A4 FD 5B E9 C9 This is what can be read in the Data register after AES Run of AES128 encryption #16 #15 #00 #00 #0 Assembly code is available in section "Example. Code Sample" on page 343. 340 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 25.3 25.3.1 AES Registers description AESCR - AES Control Register Bit $0078 Read/write Initial value 7 AESIE R/W 0 6 AESIF R/W 0 5 R/W 0 4 R/W 0 3 KS R/W 0 2 R 0 1 ENCRYPT R/W 0 0 AESGO R/W 0 0x00 AESCR AUTOKEY KEYGN * Bit 7 - AESIE : AES Interrupt Enable Set (one) this bit to enable interrupt generation when AES operation is ended. Clear (zero) this bit to disable AES interrupt generation. * Bit 6 - AESIF : AES Interrupt Flag This bit is set by hardware on AES operation completion. If AESIE and SREG.I are set, an interrupt is automatically generated. This bit must be cleared by software. * Bit 5 - AUTOKEY : Encrypt/Decrypt Automatic Key Generation Mode This bit is set and cleared by software. If this bit is set, when AESGO is set, a decryption (encryption) key is automatically generated from the encryption (decryption) key and will be used in the decryption (encryption) operation. This key is available in the key internal register and can be read. If this bit is cleared, then AESGO performs a standard operation, using the key in its buffer. * Bit 4 - KEYGN : Key Generation Mode This bit is set and cleared by software. This bit allows a decryption key to be generated from an encryption key without processing AES data (which means that AES data registers won't change). When in this mode, a decryption key will be calculated from an encryption key if the ENCRYPT bit is set and an encryption key will be calculated from a decryption key if the ENCRYPT bit is cleared. If this bit is set, AES key calculation will be perform when setting AESGO bit. If this bit is cleared, AESGO bit will perform a standard operation, processing AES data. * Bit 3 - KS : Key Selection bit This bit is set and cleared by software. Set this bit to activate AES256 mode, using 256 bits key. Clear this bit to activate AES128 mode, using 128 LSB bits of the AES key (key[0..15]). The MSB bits (key[16..31]) are unused. * Bit 2 - Reserved bit This bit is reserved for future use. * Bit 1 - ENCRYPT : Encryption/Decryption bit 341 TPR0327AY-SMS-30Jan09 This bit is set and cleared by software. Set this bit to perform AES encryption when setting AESGO. Clear this bit to perform AES decryption when setting AESGO. * Bit 0 - AESGO : AES Run Bit This bit is set by software and cleared by hardware. Set this bit to run AES operation specified by the other register settings. This bit is cleared by hardware when the AES operation is complete. If this bit is equal to one, then the AES block is running and busy. 25.3.2 AESACR - AES Access Control Register Bit $0079 Read/write Initial value 7 R 0 6 R 0 5 R 0 4 R 0 3 XOR R/W 0 2 MANINC W 0 1 AUTOINC R/W 1 0 KD R/W 0 0x02 AESACR * Bit 7..4 - Reserved Bits These bits are reserved for future use. * Bit 3 - XOR : XOR Mode This bit is set and cleared by software. This bit has no influence if the KD bit is set. When this bit is cleared, writing new data in AESDR will copy the data in AES data memory, in accordance with AESADDR register. When this bit is set and new data is written into the AESDR, the data to the AES data memory, according to AESADDR register, will be `xored' with the new data. This is useful when performing a CBC algorithm, or MAC generation. * Bit 2 - MANINC : Manual Increment bit This bit is a write-only bit and always reads as `0'. This bit can only be set. Setting this bit will increment the AESADDR register by one. When performing a write operation to the AESACR register, with this bit set, it is not possible to change the state of the other register bits. This prevents the user accidentally changing the functional operation of the AES during a manual increment operation. Note * Bit 1 - AUTOINC : Automatic Increment Bit This bit is set and cleared by software. If this bit is set, writing new data in th AESDR register will automatically increment the AESADDR register by one, after the new data is loaded. The mechanism of automatic AESDR changes are active, which means that the AESDR contents will be updated with the data pointed by the new AESADDR register value. If this bit is cleared, the automatic increment is disabled. * Bit 0 - KD : Key/Data bit 342 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 This bit is set and cleared by software. When this bit is cleared, AESADDR register points to Key AES registers. When this bit is set, AESADDR register points to Data AES registers. 25.3.3 AESADDR - AES Address Register Bit $007A Read/write Initial value R/W x R/W x R/W x 7 6 5 4 R/W x 3 R/W x 2 R/W x 1 R/W x 0 AESADDR R/W x ADDR [7..0] This register permits to target a specific byte inside AES internal memory. According to AESACR.KD value, the AESADDR targets Key of Data internal registers. When writing this register, the AESDR data register will be updated to the newly data or key byte pointed. This register can be automatically increment, if AESACR.AUTOINC bit is set, when writing new data in AESDR. This will update AESDR after write operation, to the newly pointed byte. 25.3.4 AESDR - AES Data Register Bit $007B Read/write Initial value R/W x R/W x R/W x 7 6 5 4 R/W x 3 R/W x 2 R/W x 1 R/W x 0 AESDR R/W x DATA [7..0] This register permits to observe the internal key and data registers of the AES block. When AESADDR register is modified, this register is updated to the newly pointed address. When writing AESDR register, the data targeted by AESACR.KD and AESADDR will be automatically updated, according to AESACR.XOR bit. 25.4 Example. Code Sample Below is code examples of how to initialize AES block to perform AES CBC. ;- This routine performs a AES128 bit encryption ;-registers used: ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-When jumping into these procedures, Z targets the key to use and ;Y the data to encrypt. X targets to the storage of the encrypted ;data ;-It is assumed that interruptions are disabled vAES128_Encrypt: ; Loading Key ldi sts r16, (1< TPR0327AY-SMS-30Jan09 ; Init address in AES memory (for 128bits, starting at #16) ldi sts r16, 0x10 AESADDR, r16 call keydata_load ; Loading Data ldi sts r16, (1< movw ZL, YL call keydata_load ; Start Encryption ldi sts ori sts r16, (1< ; update internal address 344 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 dec r16 brne ReadResult ret ;---------------------------------------------------------keydata_load: ldi r16, 16 ; update Z register for reverted copy adiw ZL, 16 keydata_load_loop: ld sts dec r17, -Z AESDR, r17 r16 brne keydata_load_loop ret 345 TPR0327AY-SMS-30Jan09 346 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 26. JTAG Interface and On-chip Debug System 26.1 Features * JTAG (IEEE std. 1149.1 Compliant) Interface * Boundary-scan Capabilities According to the IEEE std. 1149.1 (JTAG) Standard * Debugger Access to: - All Internal Peripheral Units - Internal RAM - The Internal Register File - Program Counter - EEPROM and Flash Memories * Extensive On-chip Debug Support for Break Conditions, Including - AVR Break Instruction - Break on Change of Program Memory Flow - Single Step Break - Program Memory Break Points on Single Address or Address Range - Data Memory Break Points on Single Address or Address Range * Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface * On-chip Debugging Supported by AVR Studio(R) 26.2 Overview The AVR IEEE std. 1149.1 compliant JTAG interface can be used for * Testing PCBs by using the JTAG Boundary-scan capability * Programming the non-volatile memories, Fuses and Lock bits * On-chip debugging A brief description is given in the following sections. Detailed descriptions for Programming via the JTAG interface, and using the Boundary-scan Chain can be found in the sections "Programming via the JTAG Interface" on page 385 and "IEEE 1149.1 (JTAG) Boundary-scan" on page 353, respectively. The On-chip Debug support is considered being private JTAG instructions, and distributed within ATMEL and to selected third party vendors only. Figure 26-1 shows a block diagram of the JTAG interface and the On-chip Debug system. The TAP Controller is a state machine controlled by the TCK and TMS signals. The TAP Controller selects either the JTAG Instruction Register or one of several Data Registers as the scan chain (Shift Register) between the TDI - input and TDO - output. The Instruction Register holds JTAG instructions controlling the behavior of a Data Register. The ID-Register, Bypass Register, and the Boundary-scan Chain are the Data Registers used for board-level testing. The JTAG Programming Interface (actually consisting of several physical and virtual Data Registers) is used for serial programming via the JTAG interface. The Internal Scan Chain and Break Point Scan Chain are used for On-chip debugging only. 26.3 TAP - Test Access Port The JTAG interface is accessed through four of the AVR's pins. In JTAG terminology, these pins constitute the Test Access Port - TAP. These pins are: * TMS _ JTGTMS: Test mode select. This pin is used for navigating through the TAP-controller state machine. * TCK _ JTGTCK: Test Clock. JTAG operation is synchronous to TCK. 347 TPR0327AY-SMS-30Jan09 * TDI _ JTGTDI: Test Data In. Serial input data to be shifted in to the Instruction Register or Data Register (Scan Chains). * TDO _ JTGTDO: Test Data Out. Serial output data from Instruction Register or Data Register. The IEEE std. 1149.1 also specifies an optional TAP signal; TRST - Test ReSeT - which is not provided. When the JTAGEN Fuse is unprogrammed, these four TAP pins are normal port pins, and the TAP controller is in reset. When programmed, the input TAP signals are internally pulled high and the JTAG is enabled for Boundary-scan and programming. The device is shipped with this fuse programmed. For the On-chip Debug system, in addition to the JTAG interface pins, the RESET pin is monitored by the debugger to be able to detect external reset sources. The debugger can also pull the RESET pin low to reset the whole system, assuming only open collectors on the reset line are used in the application. Figure 26-1. Block Diagram I/O PORT 0 DEVICE BOUNDARY BOUNDARY SCAN CHAIN TDI TDO TCK TMS TAP CONTROLLER JTAG PROGRAMMING INTERFACE AVR CPU INSTRUCTION REGISTER ID REGISTER M U X BYPASS REGISTER FLASH MEMORY Address Data INTERNAL SCAN CHAIN PC Instruction BREAKPOINT UNIT FLOW CONTROL UNIT DIGITAL PERIPHERAL UNITS ANALOG PERIPHERIAL UNITS Analog inputs BREAKPOINT SCAN CHAIN ADDRESS DECODER JTAG / AVR CORE COMMUNICATION INTERFACE OCD STATUS AND CONTROL Control & Clock lines I/O PORT n 348 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 26-2. TAP Controller State Diagram 1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1 26.4 TAP Controller The TAP controller is a 16-state finite state machine that controls the operation of the Boundaryscan circuitry, JTAG programming circuitry, or On-chip Debug system. The state transitions depicted in Figure 26-2 depend on the signal present on TMS (shown adjacent to each state transition) at the time of the rising edge at TCK. The initial state after a Power-on Reset is TestLogic-Reset. As a definition in this document, the LSB is shifted in and out first for all Shift Registers. Assuming Run-Test/Idle is the present state, a typical scenario for using the JTAG interface is: * At the TMS input, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the Shift Instruction Register - Shift-IR state. While in this state, shift the four bits of the JTAG instructions into the JTAG Instruction Register from the TDI input at the rising edge of TCK. The TMS input must be held low during input of the 3 LSBs in order to remain in the Shift-IR state. The MSB of the instruction is shifted in when this state is left by setting TMS high. While the instruction is shifted in from the TDI pin, the captured IR-state 0x01 is shifted out on the TDO pin. The JTAG Instruction selects a particular Data Register as path between TDI and TDO and controls the circuitry surrounding the selected Data Register. 349 TPR0327AY-SMS-30Jan09 * Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched onto the parallel output from the Shift Register path in the Update-IR state. The Exit-IR, Pause-IR, and Exit2-IR states are only used for navigating the state machine. * At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the Shift Data Register - Shift-DR state. While in this state, upload the selected Data Register (selected by the present JTAG instruction in the JTAG Instruction Register) from the TDI input at the rising edge of TCK. In order to remain in the Shift-DR state, the TMS input must be held low during input of all bits except the MSB. The MSB of the data is shifted in when this state is left by setting TMS high. While the Data Register is shifted in from the TDI pin, the parallel inputs to the Data Register captured in the Capture-DR state is shifted out on the TDO pin. * Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. If the selected Data Register has a latched parallel-output, the latching takes place in the Update-DR state. The Exit-DR, Pause-DR, and Exit2-DR states are only used for navigating the state machine. As shown in the state diagram, the Run-Test/Idle state need not be entered between selecting JTAG instruction and using Data Registers, and some JTAG instructions may select certain functions to be performed in the Run-Test/Idle, making it unsuitable as an Idle state. Independent of the initial state of the TAP Controller, the Test-Logic-Reset state can always be entered by holding TMS high for five TCK clock periods. Note For detailed information on the JTAG specification, refer to the literature listed in "Bibliography" on page 352. 26.5 Using the Boundary-scan Chain A complete description of the Boundary-scan capabilities are given in the section "IEEE 1149.1 (JTAG) Boundary-scan" on page 353. 26.6 Using the On-chip Debug System As shown in Figure 26-1, the hardware support for On-chip Debugging consists mainly of * A scan chain on the interface between the internal AVR CPU and the internal peripheral units. * Break Point unit. * Communication interface between the CPU and JTAG system. All read or modify/write operations needed for implementing the Debugger are done by applying AVR instructions via the internal AVR CPU Scan Chain. The CPU sends the result to an I/O memory mapped location which is part of the communication interface between the CPU and the JTAG system. The Break Point Unit implements Break on Change of Program Flow, Single Step Break, two Program Memory Break Points, and two combined Break Points. Together, the four Break Points can be configured as either: * 4 single Program Memory Break Points. * 3 Single Program Memory Break Point + 1 single Data Memory Break Point. * 2 single Program Memory Break Points + 2 single Data Memory Break Points. 350 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * 2 single Program Memory Break Points + 1 Program Memory Break Point with mask ("range Break Point"). * 2 single Program Memory Break Points + 1 Data Memory Break Point with mask ("range Break Point"). A debugger, like the AVR Studio, may however use one or more of these resources for its internal purpose, leaving less flexibility to the end-user. A list of the On-chip Debug specific JTAG instructions is given in "On-chip Debug Specific JTAG Instructions" on page 351. The JTAGEN Fuse must be programmed to enable the JTAG Test Access Port. In addition, the OCDEN Fuse must be programmed and no Lock bits must be set for the On-chip debug system to work. As a security feature, the On-chip debug system is disabled when either of the LB1 or LB2 Lock bits are set. Otherwise, the On-chip debug system would have provided a back-door into a secured device. The AVR Studio enables the user to fully control execution of programs on an AVR device with On-chip Debug capability, AVR In-Circuit Emulator, or the built-in AVR Instruction Set Simulator. AVR Studio(R) supports source level execution of Assembly programs assembled with Atmel Corporation's AVR Assembler and C programs compiled with third party vendors' compilers. For a full description of the AVR Studio, please refer to the AVR Studio User Guide. Only highlights are presented in this document. You can also find information on the Atmel internet website. All necessary execution commands are available in AVR Studio, both on source level and on disassembly level. The user can execute the program, single step through the code either by tracing into or stepping over functions, step out of functions, place the cursor on a statement and execute until the statement is reached, stop the execution, and reset the execution target. In addition, the user can have an unlimited number of code Break Points (using the BREAK instruction) and up to two data memory Break Points, alternatively combined as a mask (range) Break Point. 26.7 On-chip Debug Specific JTAG Instructions The On-chip debug support is considered being private JTAG instructions, and distributed within ATMEL and to selected third party vendors only. Instruction opcodes are listed for reference. 26.7.1 PRIVATE0; 0x8 Private JTAG instruction for accessing On-chip debug system. 26.7.2 PRIVATE1; 0x9 Private JTAG instruction for accessing On-chip debug system. 26.7.3 PRIVATE2; 0xA Private JTAG instruction for accessing On-chip debug system. PRIVATE3; 0xB Private JTAG instruction for accessing On-chip debug system. 26.7.4 351 TPR0327AY-SMS-30Jan09 26.8 26.8.1 On-chip Debug Related Register in I/O Memory OCDR - On-chip Debug Register Bit 0x31 (0x51) Read/write Initial value 7 D7/IDRD R/W 0 6 D6 R/W 0 5 D5 R/W 0 4 D4 R/W 0 3 D3 R/W 0 2 D2 R/W 0 1 D1 R/W 0 0 D0 R/W 0 0x00 OCDR The OCDR Register provides a communication channel from the running program in the microcontroller to the debugger. The CPU can transfer a byte to the debugger by writing to this location. At the same time, an internal flag; I/O Debug Register Dirty - IDRD - is set to indicate to the debugger that the register has been written. When the CPU reads the OCDR Register the 7 LSB will be from the OCDR Register, while the MSB is the IDRD bit. The debugger clears the IDRD bit when it has read the information. In some AVR devices, this register is shared with a standard I/O location. In this case, the OCDR Register can only be accessed if the OCDEN Fuse is programmed, and the debugger enables access to the OCDR Register. In all other cases, the standard I/O location is accessed. Refer to the debugger documentation for further information on how to use this register. 26.9 Using the JTAG Programming Capabilities Programming of AVR parts via JTAG is performed via the 4-pin JTAG port, TCK, TMS, TDI, and TDO. These are the only pins that need to be controlled/observed to perform JTAG programming (in addition to power pins). It is not required to apply 12V externally. The JTAGEN Fuse must be programmed and the JTD bit in the MCUCR Register must be cleared to enable the JTAG Test Access Port. See "MCUCR - MCU Control Register" on page 356. The JTAG programming capability supports: * Flash programming and verifying. * EEPROM programming and verifying. * Fuse programming and verifying. * Lock bit programming and verifying. If the Lock bits LB1 or LB2 are programmed, the OCDEN Fuse cannot be programmed unless first doing a chip erase. This is a security feature that ensures no back-door exists for reading out the content of a secured device. The details on programming through the JTAG interface and programming specific JTAG instructions are given in the section "Programming via the JTAG Interface" on page 385. 26.10 Bibliography For more information about general Boundary-scan, the following literature can be consulted: * IEEE: IEEE Std. 1149.1-1990. IEEE Standard Test Access Port and Boundary-scan Architecture, IEEE, 1993. * Colin Maunder: The Board Designers Guide to Testable Logic Circuits, Addison-Wesley, 1992. 352 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 27. IEEE 1149.1 (JTAG) Boundary-scan 27.1 Features * * * * * JTAG (IEEE std. 1149.1 compliant) Interface Boundary-scan Capabilities According to the JTAG Standard Full Scan of all Port Functions as well as Analog Circuitry having Off-chip Connections Supports the Optional IDCODE Instruction Additional Public AVR_RESET Instruction to Reset the AVR 27.2 System Overview The Boundary-scan chain has the capability of driving and observing the logic levels on the digital I/O pins, as well as the boundary between digital and analog logic for analog circuitry having off-chip connections. At system level, all ICs having JTAG capabilities are connected serially by the TDI/TDO signals to form a long Shift Register. An external controller sets up the devices to drive values on their output pins, and observe the input values received from other devices. The controller compares the received data with the expected result. In this way, Boundary-scan provides a mechanism to test interconnections and integrity of components on Printed Circuits Boards by using the four TAP signals only. The four IEEE 1149.1 defined mandatory JTAG instructions IDCODE, BYPASS, SAMPLE/PRELOAD, and EXTEST, as well as the AVR specific public JTAG instruction AVR_RESET can be used to test the Printed Circuit Board. Initial scanning of the Data Register path will show the IDCode of the device, as IDCODE is the default JTAG instruction. It is advised to have the AVR device in reset during test mode. If not reset, inputs to the device may be determined by the scan operations, and the internal software may remain in an undetermined state when exiting the test mode. Entering reset, the outputs of any port pin will instantly enter in high impedance state, making the HIGHZ instruction redundant. If needed, the BYPASS instruction can be issued to make the shortest possible scan chain through the device. The device can be set in the reset state either by pulling the external RESET pin low, or issuing the AVR_RESET instruction with appropriate setting of the Reset Data Register. The EXTEST instruction is used to sample external pins and load output pins with data. The data from the output latch will be driven out on the pins as soon as the EXTEST instruction is loaded into the JTAG IR-Register. Therefore, the SAMPLE/PRELOAD should also be used to set initial values to the scan ring, to avoid damaging the board when issuing the EXTEST instruction for the first time. SAMPLE/PRELOAD can also be used to take a snapshot of the external pins during normal operation of the part. The JTAGEN Fuse must be programmed and the JTD bit in the I/O Register MCUCR must be cleared to enable the JTAG Test Access Port. When using the JTAG interface for Boundary-scan, using a JTAG TCK clock frequency higher than the internal chip frequency is possible. The chip clock is not required to run. 27.3 Data Registers The Data Registers relevant for Boundary-scan operations are: * Bypass Register * Device Identification Register * Reset Register * Boundary-scan Chain 353 TPR0327AY-SMS-30Jan09 27.3.1 Bypass Register The Bypass Register consists of a single Shift Register stage. When the Bypass Register is selected as path between TDI and TDO, the register is reset to 0 when leaving the Capture-DR controller state. The Bypass Register can be used to shorten the scan chain on a system when the other devices are to be tested. Device Identification Register Figure 27-1 shows the structure of the Device Identification Register. Figure 27-1. The Format of the Device Identification Register MSB Bit Device ID 31 Version 4 bits 28 27 Part Number 16 bits 12 11 Manufacturer ID 11 bits 1 0 1 1-bit LSB 27.3.2 Version Version is a 4-bit number identifying the revision of the component. The JTAG version number follows the revision of the device. Revision A is 0x0, revision B is 0x1 and so on. Part Number The part number is a 16-bit code identifying the component. The JTAG Part Number for AT90SCR100 is listed in Table 29-6 on page 380. Manufacturer ID The Manufacturer ID is a 11-bit code identifying the manufacturer. The JTAG manufacturer ID for ATMEL is listed in Table 29-6 on page 380. 27.3.3 Reset Register The Reset Register is a test Data Register used to reset the part. Since the AVR tri-states Port Pins when reset, the Reset Register can also replace the function of the unimplemented optional JTAG instruction HIGHZ. A high value in the Reset Register corresponds to pulling the external Reset low. The part is reset as long as there is a high value present in the Reset Register. Depending on the fuse settings for the clock options, the part will remain reset for a reset time-out period (refer to Table 73 on page 35) after having released the Reset Register. The output from this Data Register is not latched, so the reset will take place immediately, as shown in Figure 27-2. 354 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 27-2. Reset Register To TDO From Other Internal and External Reset Sources From TDI Internal reset D Q ClockDR * AVR_RESET 27.3.4 Boundary-scan Chain The Boundary-scan Chain has the capability of driving and observing the logic levels on the digital I/O pins, as well as the boundary between digital and analog logic for analog circuitry having off-chip connections. See "Boundary-scan Chain" on page 357 for a complete description. 27.4 Boundary-scan Specific JTAG Instructions The Instruction Register is 4-bit wide, supporting up to 16 instructions. Listed below are the JTAG instructions useful for Boundary-scan operation. Note that the optional HIGHZ instruction is not implemented, but all outputs with tri-state capability can be set in high-impedant state by using the AVR_RESET instruction, since the initial state for all port pins is tri-state. As a definition in this datasheet, the LSB is shifted in and out first for all Shift Registers. The OPCODE for each instruction is shown behind the instruction name in hex format. The text describes which Data Register is selected as path between TDI and TDO for each instruction. 27.4.1 EXTEST; 0x0 Mandatory JTAG instruction for selecting the Boundary-scan Chain as Data Register for testing circuitry external to the AVR package. For port-pins, Pull-up Disable, Output Control, Output Data, and Input Data are all accessible in the scan chain. For Analog circuits having off-chip connections, the interface between the analog and the digital logic is in the scan chain. The contents of the latched outputs of the Boundary-scan chain is driven out as soon as the JTAG IRRegister is loaded with the EXTEST instruction. The active states are: * Capture-DR: Data on the external pins are sampled into the Boundary-scan Chain. * Shift-DR: The Internal Scan Chain is shifted by the TCK input. * Update-DR: Data from the scan chain is applied to output pins. 27.4.2 IDCODE; 0x1 Optional JTAG instruction selecting the 32 bit ID-Register as Data Register. The ID-Register consists of a version number, a device number and the manufacturer code chosen by JEDEC. This is the default instruction after power-up. 355 TPR0327AY-SMS-30Jan09 The active states are: * Capture-DR: Data in the IDCODE Register is sampled into the Boundary-scan Chain. * Shift-DR: The IDCODE scan chain is shifted by the TCK input. 27.4.3 SAMPLE_PRELOAD; 0x2 Mandatory JTAG instruction for pre-loading the output latches and taking a snap-shot of the input/output pins without affecting the system operation. However, the output latches are not connected to the pins. The Boundary-scan Chain is selected as Data Register. The active states are: * Capture-DR: Data on the external pins are sampled into the Boundary-scan Chain. * Shift-DR: The Boundary-scan Chain is shifted by the TCK input. * Update-DR: Data from the Boundary-scan chain is applied to the output latches. However, the output latches are not connected to the pins. 27.4.4 AVR_RESET; 0xC The AVR specific public JTAG instruction for forcing the AVR device into the Reset mode or releasing the JTAG reset source. The TAP controller is not reset by this instruction. The one bit Reset Register is selected as Data Register. Note that the reset will be active as long as there is a logic "one" in the Reset Chain. The output from this chain is not latched. The active states are: * Shift-DR: The Reset Register is shifted by the TCK input. 27.4.5 BYPASS; 0xF Mandatory JTAG instruction selecting the Bypass Register for Data Register. The active states are: * Capture-DR: Loads a logic "0" into the Bypass Register. * Shift-DR: The Bypass Register cell between TDI and TDO is shifted. 27.5 27.5.1 Boundary-scan Related Register in I/O Memory MCUCR - MCU Control Register The MCU Control Register contains control bits for general MCU functions. Bit 0x35 (0x55) Read/write Initial value 7 JTD R/W 0 6 R 0 5 R 0 4 PUD R/W 0 3 R 0 2 R 0 1 IVSEL R/W 0 0 IVCE R/W 0 0x00 MCUCR * Bit 7 - JTD: JTAG Interface Disable When this bit is zero, the JTAG interface is enabled if the JTAGEN Fuse is programmed. If this bit is one, the JTAG interface is disabled. In order to avoid unintentional disabling or enabling of the JTAG interface, a timed sequence must be followed when changing this bit: The application software must write this bit to the desired value twice within four cycles to change its value. Note that this bit must not be altered when using the On-chip Debug system. 356 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * Others bits: Other bits are defined in other sections of the datasheet, but do not refer to the boundary scan management. 27.5.2 MCUSR - MCU Status Register The MCU Status Register provides information on which reset source caused an MCU reset. Bit 0x34 (0x54) Read/write Initial value 7 R 0 6 R 0 5 R 0 4 JTRF R/W x 3 WDRF R/W x 2 BORF R/W x 1 EXTRF R/W x 0 PORF R/W x MCUSR * Bit 4 - JTRF: JTAG Reset Flag This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Others bits: Other bits are defined in other sections of the datasheet, but do not refer to the boundary scan management. 27.6 Boundary-scan Chain The Boundary-scan chain has the capability of driving and observing the logic levels on the digital I/O pins, as well as the boundary between digital and analog logic for analog circuitry having off-chip connection. 27.6.1 Scanning the Digital Port Pins Figure 27-3 shows the Boundary-scan Cell for a bi-directional port pin. The pull-up function is disabled during Boundary-scan when the JTAG IR contains EXTEST or SAMPLE_PRELOAD. The cell consists of a bi-directional pin cell that combines the three signals Output Control OCxn, Output Data - ODxn, and Input Data - IDxn, into only a two-stage Shift Register. The port and pin indexes are not used in the following description The Boundary-scan logic is not included in the figures in the datasheet. Figure 27-4 shows a simple digital port pin as described in the section "I/O Ports" on page 75. The Boundary-scan details from Figure 27-3 replaces the dashed box in Figure 27-4. When no alternate port function is present, the Input Data - ID - corresponds to the PINxn Register value (but ID has no synchronizer), Output Data corresponds to the PORT Register, Output Control corresponds to the Data Direction - DD Register, and the Pull-up Enable - PUExn - corresponds to logic expression PUD * DDxn * PORTxn. Digital alternate port functions are connected outside the dotted box in Figure 27-4 to make the scan chain read the actual pin value. For analog function, there is a direct connection from the external pin to the analog circuit. There is no scan chain on the interface between the digital and the analog circuitry, but some digital control signal to analog circuitry are turned off to avoid driving contention on the pads. When JTAG IR contains EXTEST or SAMPLE_PRELOAD the clock is not sent out on the port pins even if the CKOUT fuse is programmed. Even though the clock is output when the JTAG IR contains SAMPLE_PRELOAD, the clock is not sampled by the boundary scan. 357 TPR0327AY-SMS-30Jan09 Figure 27-3. Boundary-scan Cell for Bi-directional Port Pin with Pull-up Function. ShiftDR To Next Cell EXTEST Vcc Pull-up Enable (PUE) 0 1 Output Control (OC) FF1 0 D 1 G Q D Q LD1 0 1 Output Data (OD) Port Pin (PXn) 0 1 0 D 1 FF0 Q LD0 D G Q 0 1 Input Data (ID) From Last Cell ClockDR UpdateDR 358 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 27-4. General Port Pin Schematic Diagram See Boundary-scan Description for Details! PUExn PUD Q D DDxn Q CLR OCxn RESET WDx RDx Pxn Q D ODxn IDxn SLEEP PORTxn Q CLR WRx RESET RRx SYNCHRONIZER D Q D PINxn RPx Q L Q Q CLK I/O PUD: PUExn: OCxn: ODxn: IDxn: SLEEP: PULLUP DISABLE PULLUP ENABLE for pin Pxn OUTPUT CONTROL for pin Pxn OUTPUT DATA to pin Pxn INPUT DATA from pin Pxn SLEEP CONTROL WDx: RDx: WRx: RRx: RPx: CLK I/O : WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN I/O CLOCK 27.6.2 Scanning the RESET Pin The RESET pin accepts 5V active low logic for standard reset operation. An observe-only cell as shown in Figure 27-5 is inserted for the 5V reset signal. Figure 27-5. Observe-only Cell To Next Cell ShiftDR From System Pin To System Logic FF1 0 D 1 Q From Previous Cell ClockDR DATA BUS 359 TPR0327AY-SMS-30Jan09 27.7 AT90SCR100 Boundary-scan Order Table 27-1 shows the Scan order between TDI and TDO when the Boundary-scan chain is selected as data path. Bit 0 is the LSB; the first bit scanned in, and the first bit scanned out. The scan order follows the pin-out order as far as possible. Therefore, the bits of Port A and Port K is scanned in the opposite bit order of the other ports. Exceptions from the rules are the Scan chains for the analog circuits, which constitute the most significant bits of the scan chain regardless of which physical pin they are connected to. In Figure 27-3, PXn. Data corresponds to FF0, PXn. Control corresponds to FF1, PXn. Bit 4, 5, 6 and 7 of Port F is not in the scan chain, since these pins constitute the TAP pins when the JTAG is enabled. Table 27-1. Bit Number 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 AT90SCR100 Boundary-scan Order Signal Name PE0.Data PE0.Control PE1.Data PE1.Control PE2.Data PE2.Control PE3.Data PE3.Control PE4.Data PE4.Control PE5.Data PE5.Control PE6.Data PE6.Control PE7.Data PE7.Control Port E Module 360 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 27-1. Bit Number 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 AT90SCR100 Boundary-scan Order (Continued) Signal Name PB0.Data PB0.Control PB1.Data PB1.Control PB2.Data PB2.Control PB3.Data PB3.Control PB4.Data PB4.Control PB5.Data PB5.Control PB6.Data PB6.Control PB7.Data PB7.Control RSTT PD0.Data PD0.Control PD1.Data PD1.Control PD2.Data PD2.Control PD3.Data PD3.Control PD4.Data PD4.Control PD5.Data PD5.Control PD6.Data PD6.Control PD7.Data PD7.Control Port D Reset Logic (Observe Only) Port B Module 361 TPR0327AY-SMS-30Jan09 Table 27-1. Bit Number 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 AT90SCR100 Boundary-scan Order (Continued) Signal Name PC0.Data PC0.Control PC1.Data PC1.Control PA7.Data PA7.Control PA6.Data PA6.Control PA5.Data PA5.Control PA4.Data PA4.Control PA3.Data PA3.Control PA2.Data PA2.Control PA1.Data PA1.Control PA0.Data PA0.Control Port A Port C Module 27.8 Boundary-scan Description Language Files Boundary-scan Description Language (BSDL) files describe Boundary-scan capable devices in a standard format used by automated test-generation software. The order and function of bits in the Boundary-scan Data Register are included in this description. BSDL files are available for AT90SCR100. 362 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 28. Boot Loader Support - Read-While-Write Self-Programming The Boot Loader Support provides a real Read-While-Write Self-Programming mechanism to download and upload program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a Flash-resident Boot Loader program. The Boot Loader program can use any available data interface and associated protocol to read and/or write (program) code into the Flash memory. The program code within the Boot Loader section has the capability to write into the entire Flash, including the Boot Loader memory. Thus, the Boot Loader can modify itself or erase itself from the code if the feature is not needed anymore. The size of the Boot Loader memory is configurable with fuses and the Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection. 28.1 Boot Loader Features * * * * * * * Read-While-Write Self-Programming Flexible Boot Memory Size High Security (Separate Boot Lock Bits for a Flexible Protection) Separate Fuse to Select Reset Vector Optimized Page Size Code Efficient Algorithm Efficient Read-Modify-Write Support Note A page is a section in the Flash consisting of several bytes (see Table 29-7 on page 381) used during programming sequence. The page organization does not affect normal operation. 28.2 Application and Boot Loader Flash Sections The Flash memory is organized in two main sections, the Application section and the Boot Loader section (see Figure 28-2). The size of the different sections is configured by the BOOTSZ Fuses as shown in Table 28-7 on page 376 and Figure 28-2. These two sections can have different level of protection because they have different sets of Lock bits. 28.2.1 Application Section The Application section is the section of the Flash that is used to store the application code. The protection level for the Application section can be selected by the application Boot Lock bits (Boot Lock bits 0), see Table 28-2 on page 366. The Application section can never store any Boot Loader code because the SPM instruction is disabled when executed from the Application section. BLS - Boot Loader Section While the Application section is used to store the application code, the The Boot Loader software must be located in the BLS because the SPM instruction can initiate a programming sequence when executing from the BLS only. The SPM instruction can access the entire Flash, including the BLS itself. The protection level for the Boot Loader section can be selected by the Boot Loader Lock bits (Boot Lock bits 1), see Table 28-3 on page 366. 28.2.2 363 TPR0327AY-SMS-30Jan09 28.3 Read-While-Write and No Read-While-Write Flash Sections Regarding the address targeted by a programming sequence, the CPU supports Read-WhileWrite or is halted during a Boot Loader software update. In addition to the two sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also divided into two fixed sections, the Read-While-Write (RWW) section and the No Read-While-Write (NRWW) section. The limit between the RWW- and NRWW sections is given in Table 28-1 and Figure 28-1 on page 365. The main differences between the two sections are: * The NRWW section can be read when erasing or writing a page located inside the RWW section. * The CPU is stopped when erasing or writing a page located inside the NRWW section. The user software can never read any code located inside the RWW section during a Boot Loader software operation. The syntax "Read-While-Write section" refers to the section that is being programmed (erased or written), not the section executed during a Boot Loader software update. Note 28.3.1 RWW - Read-While-Write Section If a Boot Loader software update is programming a page inside the RWW section you can only read code from the NRWW section. During an on-going programming, the software must ensure that the RWW section won't be read. If the user software is trying to read code located inside the RWW section (i.e., by load program memory, call, or jump instructions or an interrupt) during programming sequence, the software may end up in an unknown state. To avoid this, the interrupts should either be disabled or moved to the Boot Loader section. The Boot Loader section is always located in the NRWW section. The RWW Section Busy bit (RWWSB) in the Store Program Memory Control and Status Register (SPMCSR) will be read as logical one as long as the RWW section is blocked for read operation. After the end of a programming sequence, the RWWSB must be cleared by software before reading code located in the RWW section. See "SPMCSR - Store Program Memory Control and Status Register" on page 367. for details on how to clear RWWSB. 28.3.2 NRWW - No Read-While-Write Section The code located in the NRWW section can be read when the Boot Loader software is updating a page in the RWW section. When the Boot Loader code updates the NRWW section, the CPU is halted during the entire Page Erase or Page Write operation. Table 28-1. Read-While-Write Features Which Section Can be Read During Programming? NRWW Section None Is the CPU Halted? No Yes Read-While-Write Supported? Yes No Which Section does the Z-pointer Address During the Programming? RWW Section NRWW Section 364 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 28-1. Read-While-Write vs. No Read-While-Write Code Located in NRWW Section Can be Read During the Operation CPU is Halted During the Operation No Read-While-Write (NRWW) Section Z-pointer Addresses RWW Section Z-pointer Addresses NRWW Section Read-While-Write (RWW) Section Figure 28-2. Memory Sections No Read-While-Write Section Program Memory 0x7FFF 0x7E00 0x7C00 0x7800 0x7000 0x6FFF Application Flash Section Boot Loader Flash Section BOOTSZ='11' BOOTSZ='10' BOOTSZ='01' BOOTSZ='00' Start Boot Loader/End Application Limitation Read-While-Write Section Application Flash Section 0x0000 The parameters in the figure above are given in Table 28-7 on page 376. Note 365 TPR0327AY-SMS-30Jan09 28.4 Boot Loader Lock Bits If no Boot Loader capability is needed, the entire Flash is available for application code. The Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection. The user can select: * To protect the entire Flash from a software update by the MCU. * To protect only the Boot Loader Flash section from a software update by the MCU. * To protect only the Application Flash section from a software update by the MCU. * Allow software update in the entire Flash. See Table 28-2 and Table 28-3 for further details. The Boot Lock bits can be set in software and in Serial Pogramming mode, but they can be cleared by a Chip Erase command only. The general Write Lock (Lock Bit mode 2) does not control the programming of the Flash memory by SPM instruction. Similarly, the general Read/Write Lock (Lock Bit mode 1) does not control reading nor writing by (E)LPM/SPM, if it is attempted. Table 28-2. BLB0 Mode 1 2 Boot Lock Bit0 Protection Modes (Application Section)(1) BLB02 1 1 BLB01 1 0 Protection No restrictions for SPM or (E)LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and (E)LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. (E)LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. 3 0 0 4 0 1 Table 28-3. BLB1 Mode 1 2 Boot Lock Bit1 Protection Modes (Boot Loader Section)(1) BLB12 1 1 BLB11 1 0 Protection No restrictions for SPM or (E)LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and (E)LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. (E)LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. 3 0 0 4 0 1 Note: 1. "1" means unprogrammed, "0" means programmed 366 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 28.5 Entering the Boot Loader Program Entering the Boot Loader takes place by a jump or call from the application program. This may be initiated by a trigger such as a command received via USART, or SPI interface. Alternatively, the Boot Reset Fuse can be programmed so that the Reset Vector is pointing to the Boot Flash start address after a reset. In this case, the Boot Loader is started after a reset. After the application code is loaded, the program can start executing the application code. Note that the fuses cannot be changed by the MCU itself. This means that once the Boot Reset Fuse is programmed, the Reset Vector will always point to the Boot Loader Reset and the fuse can only be changed through the serial programming interface. Table 28-4. BOOTRST 1 0 Note: Boot Reset Fuse(1) Reset Address Reset Vector = Application Reset (address 0x0000) Reset Vector = Boot Loader Reset (see Table 28-7 on page 376) 1. "1" means unprogrammed, "0" means programmed 28.5.1 SPMCSR - Store Program Memory Control and Status Register The Store Program Memory Control and Status Register contains the control bits needed to control the Boot Loader operations. Bit 0x37 (0x57) Read/write Initial value 7 SPMIE R/W 0 6 RWWSB R 0 5 R/W 0 4 R/W 1 3 R/W 0 2 PGWRT R/W 0 1 PGERS R/W 0 0 SPMEN R/W 0 0x00 SPMCSR SIGRD RWWSRE BLBSET * Bit 7 - SPMIE: SPM Interrupt Enable If the SPMIE bit is set (one), and if the I-bit in the Status Register is set (one), the SPM ready interrupt will be enabled. The SPM ready Interrupt will remain activated as long as the SPMEN bit in the SPMCSR Register is cleared (zero). * Bit 6 - RWWSB: Read-While-Write Section Busy When a Self-Programming (Page Erase or Page Write) operation to the RWW section is initiated, the RWWSB will be set (one) by hardware. When the RWWSB bit is set, the RWW section cannot be accessed. The RWWSB bit will be cleared if the RWWSRE bit is written to one after a Self-Programming operation is completed. Alternatively the RWWSB bit will automatically be cleared if a page load operation is initiated. * Bit 5 - SIGRD: Signature Row Read If this bit is written to one at the same time as SPMEN, the next LPM instruction within three clock cycles will read a byte from the signature row into the destination register. see "Reading the Signature Row from Software" on page 373 for details. An SPM instruction within four cycles after SIGRD and SPMEN are set will have no effect. This operation is reserved for future use and should not be used. * Bit 4 - RWWSRE: Read-While-Write Section Read Enable 367 TPR0327AY-SMS-30Jan09 When programming (Page Erase or Page Write) to the RWW section, the RWW section is blocked for reading (the RWWSB will be set by hardware). To re-enable the RWW section, the user software must wait until the programming is completed (SPMEN will be cleared). Then, if the RWWSRE bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles re-enables the RWW section. The RWW section cannot be re-enabled while the Flash is busy with a Page Erase or a Page Write (SPMEN is set). If the RWWSRE bit is written while the Flash is being loaded, the Flash load operation will abort and the data loaded will be lost. * Bit 3 - BLBSET: Boot Lock Bit Set If this bit is set (one) at the same time as SPMEN, the next SPM instruction within four clock cycles sets Boot Lock bits, according to the data in R0. The data in R1 and the address in the Zpointer are ignored. The BLBSET bit will automatically be cleared upon completion of the Lock bit set operation, or if no SPM instruction is executed within four clock cycles. An (E)LPM instruction within three cycles after BLBSET and SPMEN are set in the SPMCSR Register, will read either the Lock bits or the Fuse bits (depending on Z0 in the Z-pointer) into the destination register. See "Reading the Fuse and Lock Bits from Software" on page 372 for details. * Bit 2 - PGWRT: Page Write If this bit is set (one)at the same time as SPMEN, the next SPM instruction within four clock cycles executes Page Write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will be automatically cleared upon completion of a Page Write, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is addressed. * Bit 1 - PGERS: Page Erase If this bit is set (one) at the same time as SPMEN, the next SPM instruction within four clock cycles executes Page Erase. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGERS bit will be automatically cleared upon completion of a Page Erase, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is addressed. * Bit 0 - SPMEN: Store Program Memory Enable This bit enables the SPM instruction for the next four clock cycles. If written to one together with either RWWSRE, BLBSET, PGWRT' or PGERS, the following SPM instruction will have a special meaning, see description above. If only SPMEN is written, the following SPM instruction will store the value of R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of the Z-pointer is ignored. The SPMEN bit will be automatically cleared upon completion of an SPM instruction, or if no SPM instruction is executed within four clock cycles. During Page Erase and Page Write, the SPMEN bit remains high until the operation is completed. Writing any other combination than "10001", "01001", "00101", "00011" or "00001" in the lower five bits will have no effect. Only one SPM instruction should be active at any time. Note 368 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 28.6 Addressing the Flash During Self-Programming The Z-pointer is used to address the SPM commands. The Z pointer consists of the Z-registers ZL and ZH in the register file. The number of bits actually used is implementation dependent. Bit ZH (R31) ZH (R30) 15 Z15 Z7 7 14 Z14 Z6 6 13 Z13 Z5 5 12 Z12 Z4 4 11 Z11 Z3 3 10 Z10 Z2 2 7 Z9 Z1 1 8 Z8 Z0 0 Since the Flash is organized in pages (see Table 29-7 on page 381), the Program Counter can be treated as having two different sections. One section, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. This is shown in Figure 28-3. Note that the Page Erase and Page Write operations are addressed independently. Therefore it is of major importance that the Boot Loader software addresses the same page in both the Page Erase and Page Write operation. Once a programming operation is initiated, the address is latched and the Z-pointer can be used for other operations. The (E)LPM instruction use the Z-pointer to store the address. Since this instruction addresses the Flash byte-by-byte, also bit Z0 of the Z-pointer is used. Figure 28-3. Addressing the Flash During SPM BIT Z - REGISTER PCMSB PROGRAM COUNTER PCPAGE 15 ZPCMSB ZPAGEMSB 10 0 PAGEMSB PCWORD PAGE ADDRESS WITHIN THE FLASH PROGRAM MEMORY PAGE WORD ADDRESS WITHIN A PAGE PAGE INSTRUCTION WORD PCWORD[PAGEMSB:0]: 00 01 02 PAGEEND Only one SPM instruction should be active at any time. Note 369 TPR0327AY-SMS-30Jan09 28.7 Self-Programming the Flash The program memory is updated page by page. Before programming a page with the data stored in the temporary page buffer, the page must be erased. The temporary page buffer is filled one word per word using SPM instruction and the buffer can be filled either before the Page Erase command or between a Page Erase and a Page Write operation: Alternative 1, fill the buffer before a Page Erase * Fill temporary page buffer * Perform a Page Erase * Perform a Page Write Alternative 2, fill the buffer after Page Erase * Perform a Page Erase * Fill temporary page buffer * Perform a Page Write If only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. When using alternative 1, the Boot Loader provides an effective Read-Modify-Write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. If alternative 2 is used, it is not possible to read the old data while loading because the page is already erased. The temporary page buffer can be accessed in a random sequence. It is essential that the page address used in both the Page Erase and Page Write operation is addressing the same page. See "Simple Assembly Code Example for a Boot Loader" on page 374 for an assembly code example. 28.7.1 Performing Page Erase by SPM To execute Page Erase, set up the address in the Z-pointer, write "X0000011" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 are ignored. The page address must be written to PCPAGE in the Z-register. Other bits in the Z-pointer will be ignored during this operation. * Page Erase to the RWW section: The NRWW section can be read during the Page Erase. * Page Erase to the NRWW section: The CPU is halted during the operation. 28.7.2 Filling the Temporary Buffer (Page Loading) To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write "00000001" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The content of PCWORD in the Z-register is used to address the data in the temporary buffer. The temporary buffer will be automatically erased after a Page Write operation or by writing the RWWSRE bit in SPMCSR. It is also erased after a system reset. Note that it is not possible to write more than one time to each address without erasing the temporary buffer. If the EEPROM is written in the middle of an SPM Page Load operation, all data loaded will be lost. 370 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 28.7.3 Performing a Page Write To execute Page Write, set up the address in the Z-pointer, write "X0000101" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer must be written to zero during this operation. * Page Write to the RWW section: The NRWW section can be read during the Page Write. * Page Write to the NRWW section: The CPU is halted during the operation. 28.7.4 Using the SPM Interrupt If the SPM interrupt is enabled, the SPM interrupt will generate a constant interrupt when the SPMEN bit in SPMCSR is cleared. This means that the interrupt can be used instead of polling the SPMCSR Register in software. When using the SPM interrupt, the Interrupt Vectors should be moved to the BLS section to avoid that an interrupt is accessing the RWW section when it is blocked for reading. How to move the interrupts is described in "Interrupts" on page 63. Consideration While Updating BLS Special care must be taken if the user allows the Boot Loader section to be updated by leaving Boot Lock bit11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the entire Boot Loader, and further software updates might be impossible. If it is not necessary to change the Boot Loader software itself, it is recommended to program the Boot Lock bit11 to protect the Boot Loader software from any internal software changes. Prevent Reading the RWW Section During Self-Programming During Self-Programming (either Page Erase or Page Write), the RWW section is always blocked for reading. The user software itself must prevent that this section is addressed during the self programming operation. The RWWSB in the SPMCSR will be set as long as the RWW section is busy. During Self-Programming the Interrupt Vector table should be moved to the BLS as described in "Interrupts" on page 63, or the interrupts must be disabled. Before addressing the RWW section after the programming is completed, the user software must clear the RWWSB by writing the RWWSRE. See "Simple Assembly Code Example for a Boot Loader" on page 374 for an example. Setting the Boot Loader Lock Bits by SPM To set the Boot Loader Lock bits and general Lock Bits, write the desired data to R0, write "X0001001" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. Bit R0 7 1 6 1 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 LB2 0 LB1 28.7.5 28.7.6 28.7.7 See Table 28-2 and Table 28-3 for how the different settings of the Boot Loader bits affect the Flash access. If bits 5..0 in R0 are cleared (zero), the corresponding Lock bit will be programmed if an SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCSR. The Zpointer is not used during this operation, but for future compatibility it is recommended to load the Z-pointer with 0x0001 value (same as used for reading the lOck bits). For future compatibility it is also recommended to set bits 7 and 6 in R0 to "1" when writing the Lock bits. When programming the Lock bits the entire Flash can be read during the operation. 371 TPR0327AY-SMS-30Jan09 28.7.8 EEPROM Write Prevents Writing to SPMCSR Note that an EEPROM write operation will block all software programming to Flash. Reading the Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEPE) in the EECR Register and verifies that the bit is cleared before writing to the SPMCSR Register. Reading the Fuse and Lock Bits from Software It is possible to read both the Fuse and Lock bits from software. To read the Lock bits, load the Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCSR. When an (E)LPM instruction is executed within three CPU cycles after the BLBSET and SPMEN bits are set in SPMCSR, the value of the Lock bits will be loaded in the destination register. The BLBSET and SPMEN bits will auto-clear upon completion of reading the Lock bits or if no (E)LPM instruction is executed within three CPU cycles or no SPM instruction is executed within four CPU cycles. When BLBSET and SPMEN are cleared, (E)LPM will work as described in the Instruction set Manual. Bit Rd 7 6 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 LB2 0 LB1 28.7.9 The algorithm for reading the Fuse Low byte is similar to the one described above for reading the Lock bits. To read the Fuse Low byte, load the Z-pointer with 0x0000 and set the BLBSET and SPMEN bits in SPMCSR. When an (E)LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low byte (FLB) will be loaded in the destination register as shown below. Refer to Table 29-5 on page 380 for a detailed description and mapping of the Fuse Low byte. Bit Rd 7 FLB7 6 FLB6 5 FLB5 4 FLB4 3 FLB3 2 FLB2 1 FLB1 0 FLB0 Similarly, when reading the Fuse High byte, load 0x0003 in the Z-pointer. When an (E)LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse High byte (FHB) will be loaded in the destination register as shown below. Refer to Table 29-4 on page 379 for detailed description and mapping of the Fuse High byte. Bit Rd 7 FHB7 6 FHB6 5 FHB5 4 FHB4 3 FHB3 2 FHB2 1 FHB1 0 FHB0 When reading the Extended Fuse byte, load 0x0002 in the Z-pointer. When an (E)LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Extended Fuse byte (EFB) will be loaded in the destination register as shown below. Refer to Table 29-3 on page 379 for detailed description and mapping of the Extended Fuse byte. Bit Rd 7 6 5 4 3 2 EFB2 1 EFB1 0 EFB0 Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are unprogrammed, will be read as one. 372 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 28.7.10 Reading the Signature Row from Software To read the Signature Row from software, load the Z-pointer with the signature byte address given in Table 28-5 on page 373 and set the SIGRD and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the SIGRD and SPMEN bits are set in SPMCSR, the signature byte value will be loaded in the destination register. The SIGRD and SPMEN bits will auto-clear upon completion of reading the Signature Row Lock bits or if no LPM instruction is executed within three CPU cycles. When SIGRD and SPMEN are cleared, LPM will work as described in the Instruction set Manual. Table 28-5. Signature Row Addressing(1) Z-Pointer Address 0x0000 0x0002 0x0004 0x0001 0x0006 0x0008 0x000A 0x000C 0x000E 0x0010 0x0012 0x0014 0x0016 Signature Byte Device Signature Byte 1 Device Signature Byte 2 Device Signature Byte 3 RC Oscillator Calibration Byte Serial Number byte 0 Serial Number byte 1 Serial Number byte 2 Serial Number byte 3 Serial Number byte 4 Serial Number byte 5 Serial Number byte 6 Serial Number byte 7 Serial Number byte 8 Note: 1. All other addresses are reserved for future use. 28.7.11 Preventing Flash Corruption During periods of low VCC, the Flash program can be corrupted because the supply voltage is too low for the CPU and the Flash to operate properly. These issues are the same as for board level systems using the Flash, and the same design solutions should be applied. A Flash program corruption can be caused by two situations when the voltage is too low. First, a regular write sequence to the Flash requires a minimum voltage to operate correctly. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltage for executing instructions is too low. Flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. If there is no need for a Boot Loader update in the system, program the Boot Loader Lock bits to prevent any Boot Loader software updates. 2. Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal Brown-out Detector (BOD) if the operating voltage matches the detection level. If not, an external low VCC reset protection circuit can be used. If a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 373 TPR0327AY-SMS-30Jan09 3. Keep the AVR core in Power-down sleep mode during periods of low VCC. This will prevent the CPU from attempting to decode and execute instructions, effectively protecting the SPMCSR Register and thus the Flash from unintentional writes. 28.7.12 Programming Time for Flash when Using SPM The calibrated RC Oscillator is used to time Flash accesses. Table 28-6 shows the typical programming time for Flash accesses from the CPU. Table 28-6. SPM Programming Time Symbol Flash write (Page Erase, Page Write, and write Lock bits by SPM) Min Programming Time 3.7 ms Max Programming Time 4.5 ms Note These programming time are true after production calibration. If the oscillator trimming is modified, these values will be changed. 28.7.13 Simple Assembly Code Example for a Boot Loader ;-the routine writes one page of data from RAM to Flash ; the first data location in RAM is pointed to by the Y pointer ; the first data location in Flash is pointed to by the Z-pointer ;-error handling is not included ;-the routine must be placed inside the Boot space ; (at least the Do_spm sub routine). Only code inside NRWW section can ; be read during Self-Programming (Page Erase and Page Write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-It is assumed that either the interrupt table is moved to the Boot ; loader section or that the interrupts are disabled. .equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words .org SMALLBOOTSTART Write_page: ; Page Erase ldi spmcrval, (1< AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 subi sbci ldi call ZL, low(PAGESIZEB) ;restore pointer ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256 spmcrval, (1< For details about these two section, see "NRWW - No Read-While-Write Section" on page 364 and "RWW - Read-While-Write Section" on page 364. 375 TPR0327AY-SMS-30Jan09 28.7.14 AT90SCR100 Boot Loader Parameters In Table 28-7 through Table 28-9, the parameters used in the description of the Self-Programming are given. Boot Size Configuration Boot Reset Address (Start Boot Loader Section) 0x7E00 0x7C00 0x7800 0x7000 Table 28-7. BOOTSZ1 1 1 0 0 BOOTSZ0 1 0 1 0 Boot Size 512 words 1024 words 2048 words 4096 words Pages 4 8 16 32 Application Flash Section 0x0000 - 0x7DFF 0x0000 - 0x7BFF 0x0000 - 0x77FF 0x0000 - 0x6FFF Boot Loader Flash Section 0x7E00 - 0x7FFF 0x7C00 - 0x7FFF 0x7800 - 0x7FFF 0x7000 - 0x7FFF End Application Section 0x7DFF 0x7BFF 0x77FF 0x6FFF The different BOOTSZ Fuse configurations are shown in Figure 28-2. Table 28-8. Section Read-While-Write Limit(1) Pages 224 32 Address 0x0000 - 0x6FFF 0x7000 - 0x7FFF Read-While-Write section (RWW) No Read-While-Write section (NRWW) Note: 1. For details about these two section, see "NRWW - No Read-While-Write Section" on page 364 and "RWW - Read-WhileWrite Section" on page 364. Table 28-9. Variable PCMSB PAGEMSB ZPCMSB ZPAGEMSB PCPAGE PCWORD Note: Explanation of different variables used in Figure 28-3 and the mapping to the Z-pointer Correspondig Z-value 14 7 Z15 Z8 PC[14:7] PC[6:0] Z15:Z7 Z7:Z1 Description(1) Most significant bit in the Program Counter. (The Program Counter is 15 bits PC[14:0]) Most significant bit which is used to address the words within one page (128 words in a page requires seven bits PC [6:0]). Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not used, the ZPCMSB equals PCMSB + 1. Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not used, the ZPAGEMSB equals PAGEMSB + 1. Program Counter page address: Page select, for Page Erase and Page Write Program Counter word address: Word select, for filling temporary buffer (must be zero during Page Write operation) 1. Z0: should be zero for all SPM commands, byte select for the (E)LPM instruction. See "Addressing the Flash During Self-Programming" on page 369 for details about the use of Z-pointer during Self-Programming. 376 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 29. Memory Programming 29.1 Program And Data Memory Lock Bits The AT90SCR100 provides six Lock bits which can be left unprogrammed ("1") or can be programmed ("0") to obtain the additional features listed in Table 29-2. The Lock bits can only be erased to "1" with the Chip Erase command. Table 29-1. - - BLB12 BLB11 BLB02 BLB01 LB2 LB1 Notes: Lock Bit Byte(1) Bit No 7 6 5 4 3 2 1 0 Description - - Boot Lock bit Boot Lock bit Boot Lock bit Boot Lock bit Lock bit Lock bit Default Value 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) Lock Bit Byte 1. "1" means unprogrammed, "0" means programmed 377 TPR0327AY-SMS-30Jan09 Table 29-2. Lock Bit Protection Modes(1) Protection Type LB1 1 0 No memory lock features enabled. Further programming of the Flash and EEPROM is disabled in Serial Programming mode. The Fuse bits are locked in Serial Programming mode. Further programming and verification of the Flash and EEPROM is disabled in Serial Programming mode. The Boot Lock bits and Fuse bits are locked in both Serial Programming mode. Memory Lock Bits LB Mode 1 2 LB2 1 1 3 BLB0 Mode 1 2 0 BLB02 1 1 0 BLB01 1 0 No restrictions for SPM or (E)LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and (E)LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. (E)LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. 3 0 0 4 0 1 BLB1 Mode 1 2 BLB12 1 1 BLB11 1 0 No restrictions for SPM or (E)LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and (E)LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. (E)LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. 3 0 0 4 0 1 Notes: 1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2. 378 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 29.2 Fuse Bits The AT90SCR100 has four Fuse bytes. Table 29-3 - Table 29-5 describe briefly the functionality of all the fuses and how they are mapped into the Fuse bytes. Note that the fuses are read as logical zero, "0", if they are programmed. Table 29-3. - - - - - - - BODENABLE(1) Notes: Extended Fuse Byte Bit No 7 6 5 4 3 2 1 0 Description - - - - - - - Brown-out Detector Enable Control Default Value 1 1 1 1 1 1 1 1 (unprogrammed) Fuse Low Byte 1. Refer to Table 9-2 on page 54 to get decoding of BODENABLE bit. Table 29-4. Fuse High Byte Bit No 7 6 5 4 3 2 1 0 Description Enable OCD Enable JTAG Enable Serial Program and Data Downloading Watchdog Timer always on EEPROM memory is preserved through the Chip Erase Select Boot Size (see Table 28-7 for details) Select Boot Size (see Table 28-7 for details) Select Reset Vector Default Value 1 (unprogrammed, OCD disabled) 0 (programmed, JTAG enabled) 0 (programmed, SPI prog. enabled) 1 (unprogrammed) 1 (unprogrammed, EEPROM not preserved) 0 (programmed)(4) 0 (programmed)(4) 1 (unprogrammed) Fuse High Byte OCDEN(1) JTAGEN SPIEN(2) WDTON(3) EESAVE BOOTSZ1 BOOTSZ0 BOOTRST Notes: 1. Never ship a product with the OCDEN Fuse programmed regardless of the setting of Lock bits and JTAGEN Fuse. A programmed OCDEN Fuse enables some parts of the clock system to be running in all sleep modes. This may increase the power consumption. 2. The SPIEN Fuse is not accessible in serial programming mode. 3. See "WDTCSR - Watchdog Timer Control Register" on page 61 for details. 4. The default value of BOOTSZ1..0 results in maximum Boot Size. See Table 28-7 on page 376 for details 379 TPR0327AY-SMS-30Jan09 Table 29-5. CKOUT SUT1 SUT0 CKSEL3 CKSEL0 Notes: (1) Fuse Low Byte Bit No 7 6 5 4 3 2 1 0 Description Clock output Select start-up time Select start-up time Select Clock source Select Clock source Default Value 1 1 (unprogrammed) 1 (unprogrammed)(2) 0 (programmed)(2) 1 (unprogrammed) 0 (3) 0 (3) 1 (unprogrammed) Fuse Low Byte 1. The CKOUT Fuse allow the system clock to be output on PORTB1. See "Clock Output Buffer" on page 40 for details. 2. The default value of SUT1..0 results in maximum start-up time for the default clock source. See Table 7-3 on page 35 for details. 3. These values are fixed. They used to select clocks that are not available for AT90SCR100. The status of the Fuse bits is not affected by Chip Erase. Note that the Fuse bits are locked if Lock bit1 (LB1) is programmed. Program the Fuse bits before programming the Lock bits. 29.2.1 Latching of Fuses The fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves Programming mode. This does not apply to the EESAVE Fuse which will take effect once it is programmed. The fuses are also latched on Power-up in Normal mode. 29.3 29.3.1 Signature Bytes Device and JTAG IDs All Atmel microcontrollers have a three-byte signature code which identifies the device. This code can be read in both serial and parallel mode, also when the device is locked. The three bytes reside in a separate address space. The AT90SCR100 signature bytes are given in Table 29-6. Table 29-6. Device and JTAG ID Signature Bytes Address Part AT90SCR100 0x000 0x1E 0x001 0x96 0x002 0x09 Part Number 96C1 JTAG Manufacture ID 0x1F 29.3.2 Serial Number The Serial Number is composed of 9 bytes. You can only read these bytes. They are programmed during probe sessions and are unique for each die. They are composed of: * SN0: Chip ID: same for all AT90SCR100 ICs * SN1: Silicon Revision 380 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 * SN2: Production year * SN3: Fab & Quarter * SN4: Lot number high order byte * SN5: Lot number low order byte * SN6: Wafer number within the lot * SN7: Chip number (on the Wafer) low order byte (row number) * SN8: Chip number (on the Wafer) high order byte (column number) 29.4 Calibration Byte The AT90SCR100 has a byte calibration value for the internal RC Oscillator. This byte resides in the high byte of address 0x000 in the signature address space. During reset, this byte is automatically written into the internal calibration register to ensure correct frequency of the calibrated RC Oscillator. 29.5 Page Size No. of Words in a Page and No. of Pages in the Flash Flash Size 32K words (64 Kbytes) Page Size 128 words PCWORD PC[6:0] No. of Pages 256 PCPAGE PC[14:7] PCMSB 14 Table 29-7. Device AT90SCR100 Table 29-8. Device AT90SCR100 No. of Words in a Page and No. of Pages in the EEPROM EEPROM Size 4 Kbytes Page Size 32 bytes PCWORD EEA[2:0] No. of Pages 128 PCPAGE EEA[10:3] EEAMSB 10 29.6 Serial Downloading Both the Flash and EEPROM memory arrays can be programmed using a serial programming bus while RESET is pulled to GND. The serial programming interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the Programming Enable instruction needs to be executed first before program/erase operations can be executed. 29.6.1 Serial Programming Pin Mapping Table 29-9. Symbol MOSI MISO SCK Pin Mapping Serial Programming Pins PB5 PB6 PB7 I/O I O I Description Serial Data in Serial Data out Serial Clock 381 TPR0327AY-SMS-30Jan09 Figure 29-1. Serial Programming and Verify +1.8 - 5.5V VCC +1.8 - 5.5V(2) MOSI MISO SCK XT AL1 AVCC RESET GND When programming the EEPROM, an auto-erase cycle is built into the self-timed programming operation (in the Serial mode ONLY) and there is no need to first execute the Chip Erase instruction. The Chip Erase operation turns the content of every memory location in both the Program and EEPROM arrays into 0xFF. Depending on CKSEL Fuses, a valid clock must be present. The minimum low and high periods for the serial clock (SCK) input are defined as follows: Low: > 2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz High: > 2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz 29.6.2 Serial Programming Algorithm When writing serial data to the AT90SCR100, data is clocked on the rising edge of SCK. When reading data from the AT90SCR100, data is clocked on the falling edge of SCK. See Figure 29-3 for timing details. To program and verify the AT90SCR100 in the serial programming mode, the following sequence is recommended (See four byte instruction formats in Table 29-11): 1. Power-up sequence: Apply power between VCC and GND while RESET and SCK are set to "0". In some systems, the programmer can not guarantee that SCK is held low during power-up. In this case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to "0". 2. Wait for at least 20 ms and enable serial programming by sending the Programming Enable serial instruction to pin MOSI. 3. The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte (0x53), will echo back when issuing the third byte of the Programming Enable instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a positive pulse and issue a new Programming Enable command. 4. The Flash is programmed one page at a time. The memory page is loaded one byte at a time by supplying the 7 LSB of the address and data together with the Load Program Memory Page instruction. To ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. The Program Memory Page is stored by loading the Write Program Memory Page instruction with the 382 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 address lines 15..8. Before issuing this command, make sure the instruction Load Extended Address Byte has been used to define the MSB of the address. The extended address byte is stored until the command is re-issued, i.e., the command needs only be issued for the first page, and when crossing the 64KWord boundary. If polling (RDY/BSY) is not used, the user must wait at least tWD_FLASH before issuing the next page. (See Table 29-10.) Accessing the serial programming interface before the Flash write operation completes can result in incorrect programming. 5. The EEPROM array is programmed one byte at a time by supplying the address and data together with the appropriate Write instruction. An EEPROM memory location is first automatically erased before new data is written. If polling is not used, the user must wait at least tWD_EEPROM before issuing the next byte. (See Table 29-10.) In a chip erased device, no 0xFFs in the data file(s) need to be programmed. 6. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO. When reading the Flash memory, use the instruction Load Extended Address Byte to define the upper address byte, which is not included in the Read Program Memory instruction. The extended address byte is stored until the command is re-issued, i.e., the command needs only be issued for the first page, and when crossing the 64KWord boundary. 7. At the end of the programming session, RESET can be set high to commence normal operation. 8. Power-off sequence (if needed): Set RESET to "1". Turn VCC power off. Table 29-10. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location Symbol tWD_FLASH tWD_EEPROM tWD_ERASE Minimum Wait Delay 4.5 ms 9.0 ms 9.0 ms 29.7 Serial Programming Instruction set Table 29-11 on page 383 and Figure 29-2 on page 385 describes the Instruction set. Table 29-11. Serial Programming Instruction Set (Hexadecimal values) Instruction Format Instruction/Operation Programming Enable Chip Erase (Program Memory/EEPROM) Poll RDY/BSY Load Instructions Load Extended Address byte(1) Load Program Memory Page, High byte Load Program Memory Page, Low byte Load EEPROM Memory Page (page access) Read Instructions Read Program Memory, High byte $28 adr MSB adr LSB high data byte out $4D $48 $40 $C1 $00 $00 $00 $00 Extended adr adr LSB adr LSB 0000 000aa (2) Byte 1 $AC $AC $F0 Byte 2 $53 $80 $00 Byte 3 $00 $00 $00 Byte4 $00 $00 data byte out $00 high data byte in low data byte in data byte in 383 TPR0327AY-SMS-30Jan09 Table 29-11. Serial Programming Instruction Set (Hexadecimal values) Instruction Format Instruction/Operation Read Program Memory, Low byte Read EEPROM Memory Read Lock bits Read Signature Byte Read Fuse bits Read Fuse High bits Read Extended Fuse Bits Read Calibration Byte Write Instructions Write Program Memory Page Write EEPROM Memory Write EEPROM Memory Page (page access) Write Lock bits Write Fuse bits Write Fuse High bits Write Extended Fuse Bits Notes: 2. a = address $4C $C0 $C2 $AC $AC $AC $AC adr MSB 0000 00aa(2) 0000 00aa(2) $E0 $A0 $A8 $A4 adr LSB aaaa aaaa(2) aaaa aa00(2) $00 $00 $00 $00 $00 data byte in $00 data byte in data byte in data byte in data byte in Byte 1 $20 $A0 $58 $30 $50 $58 $50 $38 Byte 2 adr MSB 0000 00aa $00 $00 $00 $08 $08 $00 (2) Byte 3 adr LSB aaaa aaaa $00 0000 aaaa(2) $00 $00 $00 $00 (2) Byte4 low data byte out data byte out data byte out data byte out data byte out data byte out data byte out data byte out 1. Not all instructions are applicable for all parts. 1. Bits are programmed `0', unprogrammed `1'. Note 2. To ensure future compatibility, unused Fuses and Lock bits should be unprogrammed (`1') . 3. Refer to the correspondig section for Fuse and Lock bits, Calibration and Signature bytes and Page size. 4. See htt://www.atmel.com/avr for Application Notes regarding programming and programmers. If the LSB in RDY/BSY data byte out is `1', a programming operation is still pending. Wait until this bit returns `0' before the next instruction is carried out. Within the same page, the low data byte must be loaded prior to the high data byte. After data is loaded to the page buffer, program the EEPROM page, see Figure 29-2 on page 385. 384 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 29-2. Serial Programming Instruction example Serial Programming Instruction Load Program Memory Page (High/Low Byte)/ Load EEPROM Memory Page (page access) Write Program Memory Page/ Write EEPROM Memory Page Byte 1 Byte 2 A MSB Adr MSB Bit 15 B Byte 3 Adr LSB 0 Byte 4 Byte 1 Byte 2 Adr MSB Bit 15 B Byte 3 Adr LSB Adr LSB rS 0 Byte 4 Page Buffer Page Offset Page 0 Page 1 Page 2 Page Number Page N-1 Program Memory/ EEPROM Memory 29.7.1 Serial Programming Characteristics For characteristics of the Serial Programming module. See "SPI Timing Characteristics TBC/TBD" on page 413. Figure 29-3. Serial Programming Waveforms SERIAL DA TA INPUT (MOSI) SERIAL DA TA OUTPUT (MISO) SERIAL CLOCK INPUT (SCK) SAMPLE MSB LSB MSB LSB 29.8 Programming via the JTAG Interface Programming through the JTAG interface requires control of the four JTAG specific pins: TCK, TMS, TDI, and TDO. Control of the reset and clock pins is not required. To be able to use the JTAG interface, the JTAGEN Fuse must be programmed. The device is default shipped with the fuse programmed. In addition, the JTD bit in MCUCSR must be cleared. Alternatively, if the JTD bit is set, the external reset can be forced low. Then, the JTD bit will be cleared after two chip clocks, and the JTAG pins are available for programming. This provides a 385 TPR0327AY-SMS-30Jan09 means of using the JTAG pins as normal port pins in Running mode while still allowing In-System Programming via the JTAG interface. Note that this technique can not be used when using the JTAG pins for Boundary-scan or On-chip Debug. In these cases the JTAG pins must be dedicated for this purpose. During programming the clock frequency of the TCK Input must be less than the maximum frequency of the chip. The System Clock Prescaler can not be used to divide the TCK Clock Input into a sufficiently low frequency. As a definition in this datasheet, the LSB is shifted in and out first of all Shift Registers. 29.8.1 Programming Specific JTAG Instructions The Instruction Register is 4-bit wide, supporting up to 16 instructions. The JTAG instructions useful for programming are listed below. The OPCODE for each instruction is shown behind the instruction name in hex format. The text describes which Data Register is selected as path between TDI and TDO for each instruction. The Run-Test/Idle state of the TAP controller is used to generate internal clocks. It can also be used as an idle state between JTAG sequences. The state machine sequence for changing the instruction word is shown in Figure 29-4. Figure 29-4. State Machine Sequence to Change the Instruction Word 1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1 386 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 29.8.2 AVR_RESET (0xC) The AVR specific public JTAG instruction to set the AVR device in the Reset mode or to take the device out from the Reset mode. The TAP controller is not reset by this instruction. The one bit Reset Register is selected as Data Register. Note that the reset will be active as long as there is a logic "one" in the Reset Chain. The output from this chain is not latched. The active states are: * Shift-DR: The Reset Register is shifted by the TCK input. 29.8.3 PROG_ENABLE (0x4) The AVR specific public JTAG instruction to enable the programming via the JTAG port. The 16bit Programming Enable Register is selected as Data Register. The active states are the following: * Shift-DR: The programming enable signature is shifted into the Data Register. * Update-DR: The programming enable signature is compared to the correct value, and Programming mode is entered if the signature is valid. 29.8.4 PROG_COMMANDS (0x5) The AVR specific public JTAG instruction for entering programming commands via the JTAG port. The 15-bit Programming Command Register is selected as Data Register. The active states are the following: * Capture-DR: The result of the previous command is loaded into the Data Register. * Shift-DR: The Data Register is shifted by the TCK input, shifting out the result of the previous command and shifting in the new command. * Update-DR: The programming command is applied to the Flash inputs * Run-Test/Idle: One clock cycle is generated, executing the applied command 29.8.5 PROG_PAGELOAD (0x6) The AVR specific public JTAG instruction to directly load the Flash data page via the JTAG port. An 8-bit Flash Data Byte Register is selected as the Data Register. This is physically the 8 LSBs of the Programming Command Register. The active states are the following: * Shift-DR: The Flash Data Byte Register is shifted by the TCK input. * Update-DR: The content of the Flash Data Byte Register is copied into a temporary register. A write sequence is initiated that within 11 TCK cycles loads the content of the temporary register into the Flash page buffer. The AVR automatically alternates between writing the low and the high byte for each new Update-DR state, starting with the low byte for the first Update-DR encountered after entering the PROG_PAGELOAD command. The Program Counter is pre-incremented before writing the low byte, except for the first written byte. This ensures that the first data is written to the address set up by PROG_COMMANDS, and loading the last location in the page buffer does not make the program counter increment into the next page. 29.8.6 PROG_PAGEREAD (0x7) The AVR specific public JTAG instruction to directly capture the Flash content via the JTAG port. An 8-bit Flash Data Byte Register is selected as the Data Register. This is physically the 8 LSBs of the Programming Command Register. The active states are the following: 387 TPR0327AY-SMS-30Jan09 * Capture-DR: The content of the selected Flash byte is captured into the Flash Data Byte Register. The AVR automatically alternates between reading the low and the high byte for each new Capture-DR state, starting with the low byte for the first Capture-DR encountered after entering the PROG_PAGEREAD command. The Program Counter is post-incremented after reading each high byte, including the first read byte. This ensures that the first data is captured from the first address set up by PROG_COMMANDS, and reading the last location in the page makes the program counter increment into the next page. * Shift-DR: The Flash Data Byte Register is shifted by the TCK input. 29.8.7 Data Registers The Data Registers are selected by the JTAG instruction registers described in section "Programming Specific JTAG Instructions" on page 386. The Data Registers relevant for programming operations are: * Reset Register * Programming Enable Register * Programming Command Register * Flash Data Byte Register 29.8.8 Reset Register The Reset Register is a Test Data Register used to reset the part during programming. It is required to reset the part before entering Programming mode. A high value in the Reset Register corresponds to pulling the external reset low. The part is reset as long as there is a high value present in the Reset Register. The part will remain reset for a Reset Time-out period (refer to Table 7-3, "Start-up Times for the Low Power Crystal Oscillator Clock Selection," on page 35) after releasing the Reset Register. The output from this Data Register is not latched, so the reset will take place immediately, as shown in Figure 27-2 on page 355. 29.8.9 Programming Enable Register The Programming Enable Register is a 16-bit register. The contents of this register is compared to the programming enable signature, binary code 0b1010_0011_0111_0000. When the contents of the register is equal to the programming enable signature, programming via the JTAG port is enabled. The register is reset to 0 on Power-on Reset, and should always be reset when leaving Programming mode. Figure 29-5. Programming Enable Register TDI D A T A 0xA370 = D Q Programming Enable ClockDR & PROG_ENABLE TDO 388 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 29.8.10 Programming Command Register The Programming Command Register is a 15-bit register. This register is used to serially shift in programming commands, and to serially shift out the result of the previous command, if any. The JTAG Programming Instruction Set is shown in Table 29-12. The state sequence when shifting in the programming commands is illustrated in Figure 29-7. Figure 29-6. Programming Command Register TDI S T R O B E S A D D R E S S / D A T A Flash EEPROM Fuses Lock Bits TDO 389 TPR0327AY-SMS-30Jan09 Table 29-12. JTAG Programming Instruction Set a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don't care Instruction TDI Sequence 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 0110011_10000000 0100011_00010000 0001011_cccccccc 0000111_aaaaaaaa 0000011_bbbbbbbb 0010011_iiiiiiii 0010111_iiiiiiii 0110111_00000000 1110111_00000000 0110111_00000000 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 0110111_00000000 0100011_00000010 0001011_cccccccc 0000111_aaaaaaaa 0000011_bbbbbbbb 0110010_00000000 0110110_00000000 0110111_00000000 0100011_00010001 0000111_aaaaaaaa 0000011_bbbbbbbb 0010011_iiiiiiii 0110111_00000000 1110111_00000000 0110111_00000000 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 TDO Sequence xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) (2) (2) (3) (2) (1) Notes 1a. Chip Erase 1b. Poll for Chip Erase Complete 2a. Enter Flash Write 2b. Load Address Extended High Byte 2c. Load Address High Byte 2d. Load Address Low Byte 2e. Load Data Low Byte 2f. Load Data High Byte 2g. Latch Data 2h. Write Flash Page (3) 2i. Poll for Page Write Complete 3a. Enter Flash Read 3b. Load Address Extended High Byte 3c. Load Address High Byte 3d. Load Address Low Byte 3e. Read Data Low and High Byte 4a. Enter EEPROM Write 4b. Load Address High Byte 4c. Load Address Low Byte 4d. Load Data Byte 4e. Latch Data (1) Low byte High byte 4f. Write EEPROM Page (3) 390 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table 29-12. JTAG Programming Instruction (Continued) Set (Continued) a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don't care Instruction 4g. Poll for Page Write Complete 5a. Enter EEPROM Read 5b. Load Address High Byte 5c. Load Address Low Byte 5d. Read Data Byte 6a. Enter Fuse Write 6b. Load Data Low Byte(4) TDI Sequence 0110011_00000000 0100011_00000011 0000111_aaaaaaaa 0000011_bbbbbbbb 0110011_bbbbbbbb 0110010_00000000 0110011_00000000 0100011_01000000 0010011_iiiiiiii 0111011_00000000 0111001_00000000 0111011_00000000 0111011_00000000 0110111_00000000 0010011_iiiiiiii 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 0110111_00000000 0010011_iiiiiiii 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0110011_00000000 0100011_00100000 0010011_11iiiiii 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0110011_00000000 0100011_00000100 0111010_00000000 0111011_00000000 0111110_00000000 0111111_00000000 TDO Sequence xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_oooooooo (8) (5) (2) Notes (1) 6c. Write Fuse Extended Byte (3) 6d. Poll for Fuse Write Complete 6e. Load Data Low Byte(6) (1) (5) 6f. Write Fuse High Byte (3) 6g. Poll for Fuse Write Complete 6h. Load Data Low Byte(6) (1) (5) 6i. Write Fuse Low Byte (3) 6j. Poll for Fuse Write Complete 7a. Enter Lock Bit Write 7b. Load Data Byte(7) (1) 7c. Write Lock Bits (3) 7d. Poll for Lock Bit Write complete 8a. Enter Fuse/Lock Bit Read 8b. Read Extended Fuse Byte(4) 8c. Read Fuse High Byte(6) (1) 391 TPR0327AY-SMS-30Jan09 Table 29-12. JTAG Programming Instruction (Continued) Set (Continued) a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don't care Instruction 8d. Read Fuse Low Byte(9) 8e. Read Lock Bits(7) TDI Sequence 0110010_00000000 0110011_00000000 0110110_00000000 0110111_00000000 0111010_00000000 0111110_00000000 0110010_00000000 0110110_00000000 0110111_00000000 0100011_00001000 0000011_bbbbbbbb 0110010_00000000 0110011_00000000 0100011_00001000 0000011_bbbbbbbb 0110110_00000000 0110111_00000000 0100011_00000000 0110011_00000000 1. Repeat until o = "1". 2. Address bits exceeding PCMSB and EEAMSB (Table 29-7 and Table 29-8) are don't care 3. This command sequence is not required if the seven MSB are correctly set by the previous command sequence (which is normally the case). 4. The bit mapping for Fuses Extended byte is listed in Table 29-3 on page 379 5. Set bits to "0" to program the corresponding Fuse, "1" to unprogram the Fuse. 6. The bit mapping for Fuses High byte is listed in Table 29-4 on page 379 7. The bit mapping for Lock bits byte is listed in Table 29-1 on page 377 8. Set bits to "0" to program the corresponding Lock bit, "1" to leave the Lock bit unchanged. 9. The bit mapping for Fuses Low byte is listed in Table 29-5 on page 380 10. "0" = programmed, "1" = unprogrammed. TDO Sequence xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxoooooo xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (10) Notes (10) 8f. Read Fuses and Lock Bits Fuse Ext. byte Fuse High byte Fuse Low byte Lock bits 9a. Enter Signature Byte Read 9b. Load Address Byte 9c. Read Signature Byte 10a. Enter Calibration Byte Read 10b. Load Address Byte 10c. Read Calibration Byte 11a. Load No Operation Command Notes: All TDI and TDO sequences are represented by binary digits (0b...). Note 392 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Figure 29-7. State Machine Sequence to Change/Read the Data Word 1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1 29.8.11 Flash Data Byte Register The Flash Data Byte Register provides an efficient way to load the entire Flash page buffer before executing Page Write, or to read out/verify the content of the Flash. A state machine sets up the control signals to the Flash and senses the strobe signals from the Flash, thus only the data words need to be shifted in/out. The Flash Data Byte Register actually consists of the 8-bit scan chain and a 8-bit temporary register. During page load, the Update-DR state copies the content of the scan chain over to the temporary register and initiates a write sequence that within 11 TCK cycles loads the content of the temporary register into the Flash page buffer. The AVR automatically alternates between writing the low and the high byte for each new Update-DR state, starting with the low byte for the first Update-DR encountered after entering the PROG_PAGELOAD command. The Program Counter is pre-incremented before writing the low byte, except for the first written byte. This ensures that the first data is written to the address set up by PROG_COMMANDS, and loading the last location in the page buffer does not make the Program Counter increment into the next page. During Page Read, the content of the selected Flash byte is captured into the Flash Data Byte Register during the Capture-DR state. The AVR automatically alternates between reading the low and the high byte for each new Capture-DR state, starting with the low byte for the first Cap- 393 TPR0327AY-SMS-30Jan09 ture-DR encountered after entering the PROG_PAGEREAD command. The Program Counter is post-incremented after reading each high byte, including the first read byte. This ensures that the first data is captured from the first address set up by PROG_COMMANDS, and reading the last location in the page makes the program counter increment into the next page. Figure 29-8. Flash Data Byte Register STROBES TDI State Machine ADDRESS Flash EEPROM Fuses Lock Bits D A T A TDO The state machine controlling the Flash Data Byte Register is clocked by TCK. During normal operation in which eight bits are shifted for each Flash byte, the clock cycles needed to navigate through the TAP controller automatically feeds the state machine for the Flash Data Byte Register with sufficient number of clock pulses to complete its operation transparently for the user. However, if too few bits are shifted between each Update-DR state during page load, the TAP controller should stay in the Run-Test/Idle state for some TCK cycles to ensure that there are at least 11 TCK cycles between each Update-DR state. 29.8.12 Programming Algorithm All references below of type "1a", "1b", and so on, refer to Table 29-12. Entering Programming Mode 1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset Register. 2. Enter instruction PROG_ENABLE and shift 0b1010_0011_0111_0000 in the Programming Enable Register. 29.8.14 Leaving Programming Mode 1. Enter JTAG instruction PROG_COMMANDS. 2. Disable all programming instructions by using no operation instruction 11a. 3. Enter instruction PROG_ENABLE and shift 0b0000_0000_0000_0000 in the programming Enable Register. 4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register. 29.8.13 394 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 29.8.15 Performing Chip Erase 1. Enter JTAG instruction PROG_COMMANDS. 2. Start Chip Erase using programming instruction 1a. 3. Poll for Chip Erase complete using programming instruction 1b. 29.8.16 Programming the Flash Before programming the Flash a Chip Erase must be performed. See "Performing Chip Erase" on page 395. 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash write using programming instruction 2a. 3. Load address Extended High byte using programming instruction 2b. 4. Load address High byte using programming instruction 2c. 5. Load address Low byte using programming instruction 2d. 6. Load data using programming instructions 2e, 2f and 2g. 7. Repeat steps 5 and 6 for all instruction words in the page. 8. Write the page using programming instruction 2h. 9. Poll for Flash write complete using programming instruction 2i. 10. Repeat steps 3 to 9 until all data have been programmed. A more efficient data transfer can be achieved using the PROG_PAGELOAD instruction: 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash write using programming instruction 2a. 3. Load the page address using programming instructions 2b, 2c and 2d. PCWORD (refer to Table 29-7 on page 381) is used to address within one page and must be written as 0. 4. Enter JTAG instruction PROG_PAGELOAD. 5. Load the entire page by shifting in all instruction words in the page byte-by-byte, starting with the LSB of the first instruction in the page and ending with the MSB of the last instruction in the page. Use Update-DR to copy the contents of the Flash Data Byte Register into the Flash page location and to auto-increment the Program Counter before each new word. 6. Enter JTAG instruction PROG_COMMANDS. 7. Write the page using programming instruction 2h. 8. Poll for Flash write complete using programming instruction 2i. 9. Repeat steps 3 to 8 until all data have been programmed. 29.8.17 Reading the Flash 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 3. Load address using programming instructions 3b, 3c and 3d. 4. Read data using programming instruction 3e. 5. Repeat steps 3 and 4 until all data have been read. A more efficient data transfer can be achieved using the PROG_PAGEREAD instruction: 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 395 TPR0327AY-SMS-30Jan09 3. Load the page address using programming instructions 3b, 3c and 3d. PCWORD (refer to Table 29-7 on page 381) is used to address within one page and must be written as 0. 4. Enter JTAG instruction PROG_PAGEREAD. 5. Read the entire page (or Flash) by shifting out all instruction words in the page (or Flash), starting with the LSB of the first instruction in the page (Flash) and ending with the MSB of the last instruction in the page (Flash). The Capture-DR state both captures the data from the Flash, and also auto-increments the program counter after each word is read. Note that Capture-DR comes before the shift-DR state. Hence, the first byte which is shifted out contains valid data. 6. Enter JTAG instruction PROG_COMMANDS. 7. Repeat steps 3 to 6 until all data have been read. 29.8.18 Programming the EEPROM Before programming the EEPROM a Chip Erase must be performed. See "Performing Chip Erase" on page 395. 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable EEPROM write using programming instruction 4a. 3. Load address High byte using programming instruction 4b. 4. Load address Low byte using programming instruction 4c. 5. Load data using programming instructions 4d and 4e. 6. Repeat steps 4 and 5 for all data bytes in the page. 7. Write the data using programming instruction 4f. 8. Poll for EEPROM write complete using programming instruction 4g. 9. Repeat steps 3 to 8 until all data have been programmed. Note that the PROG_PAGELOAD instruction can not be used when programming the EEPROM. 29.8.19 Reading the EEPROM 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable EEPROM read using programming instruction 5a. 3. Load address using programming instructions 5b and 5c. 4. Read data using programming instruction 5d. 5. Repeat steps 3 and 4 until all data have been read. Note that the PROG_PAGEREAD instruction can not be used when reading the EEPROM. 29.8.20 Programming the Fuses 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse write using programming instruction 6a. 3. Load data high byte using programming instructions 6b. A bit value of "0" will program the corresponding fuse, a "1" will unprogram the fuse. 4. Write Fuse High byte using programming instruction 6c. 5. Poll for Fuse write complete using programming instruction 6d. 6. Load data low byte using programming instructions 6e. A "0" will program the fuse, a "1" will unprogram the fuse. 7. Write Fuse low byte using programming instruction 6f. 8. Poll for Fuse write complete using programming instruction 6g. 396 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 29.8.21 Programming the Lock Bits 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Lock bit write using programming instruction 7a. 3. Load data using programming instructions 7b. A bit value of "0" will program the corresponding lock bit, a "1" will leave the lock bit unchanged. 4. Write Lock bits using programming instruction 7c. 5. Poll for Lock bit write complete using programming instruction 7d. 29.8.22 Reading the Fuses and Lock Bits 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse/Lock bit read using programming instruction 8a. 3. To read all Fuses and Lock bits, use programming instruction 8e. To only read Fuse High byte, use programming instruction 8b. To only read Fuse Low byte, use programming instruction 8c. To only read Lock bits, use programming instruction 8d. 29.8.23 Reading the Signature Bytes 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Signature byte read using programming instruction 9a. 3. Load address 0x00 using programming instruction 9b. 4. Read first signature byte using programming instruction 9c. 5. Repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third signature bytes, respectively. 29.8.24 Reading the Calibration Byte 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Calibration byte read using programming instruction 10a. 3. Load address 0x00 using programming instruction 10b. 4. Read the calibration byte using programming instruction 10c. 397 TPR0327AY-SMS-30Jan09 398 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 30. Application Information 30.1 Ordering Information Ordering Information (1) Voltage Range (V) 2.4-5.5 2.4-5.5 2.4-5.5 2.4-5.5 2.4-5.5 2.4-5.5 2.4-5.5 2.4-5.5 (2) Table 30-1. Part Number AT90SCR100LSD-Z1T(2) AT90SCR100LSD-Z1R AT90SCR100LHS-Z1T AT90SCR100H-ALT AT90SCR100H-ALR AT90SCR100H-Z1T AT90SCR100H-Z1R Note: (3) (3) Temperature Range Industrial & Green Industrial & Green Industrial & Green Industrial & Green Industrial & Green Industrial & Green Industrial & Green Industrial & Green Package QFN32 QFN32 QFN32 QFN32 LQFP64 LQFP64 QFN64 QFP64 Packing Tray Reel Tray Reel Tray Reel Tray Reel AT90SCR100LHS-Z1R 1. For differences between different configurations please see "Pin List Configuration" on page 5. 2. Standard SPI present see "Pin List Configuration" on page 5 for complete configuration. 3. High-Speed SPI present see "Pin List Configuration" on page 5 for complete configuration. On AT90SCR100LSD and AT90SCR100LHS, the JTAG is not accessible. Note On AT90SCR100LHS, the ISP though SPI is neither accessible. ! Caution On all packages, the e-pad must be connected to ground. 399 TPR0327AY-SMS-30Jan09 30.2 Typical Application C3 C4 DVcc 3.3V UCAP Vcc C1 C2 Vcc1 Vcc2 Vcc3 Vcc4 Vss Vss2 Vss3 AVss CC4 CC8 CIO R5 R3 R4 Card C4/D+ Card C8/DCard IO AT90SCR100 CVcc CVss Li C9 Card Vcc Host RESET R1 R2 RST Lo D+ D- L1 3.3V (1) D+ D- Vdcdc CVsense XTAL2 Q1 Rs XTAL1 RTC1 RTC2 Q2 Led0 Rled 3.3V (1) : As DCDC generates noise, we encourage the use of another supply power than global Vcc, if possible. C5 C6 C7 C8 Dled Table 30-2. Reference R1, R2 R3, R4 R5 Rs C1 C2 C3 C4 C5, C6 C7, C8 C9 L1 Q1 Q2 Rled/Dled External Components, Bill Of Materials Description USB Pad Serial Resistor CIO Pull-up Resistor DCDC Sense Resistor Power Supply Decoupling capacitor Power Supply Filter capacitor Internal Core Regulator Decoupling capacitor Internal USB Regulator Decoupling capacitor PLL Filter capacitors RTC Filter capacitors DCDC Decoupling Capacitor DCDC inductance Crystal Real Time Crystal LED mechanism Value 22 +/-10% 10K +/-10% 200m +/-2% 125mW 4.7F +/-10% 100nF 2.2F +/-10% 2.2F +/-10% 47pF +/-10% 22pF +/-10% 10F +/-10% esr=100m 6.8H esr=20.2m 8.0 Mhz 3.768 Mhz -Only if Real Time Counter is used Depends on the configuration of the Led Controller Comment (Optional) Can be required for high speed communication Current Sensing: Overcurrent detection Maximum application capacitance allowed by USB standard is 10F Used for internal regulator stability Used for internal regulator stability Only if Real Time Counter is used. Tantalum capacitor is needed Recommended: AVX: TPSE106-035-200 Recommended: Gowanda: SMP3316LP-681M 400 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 30.2.1 Recommendations 1. In Order to reduce the board parasitics, the external components for DCDC converter should be as close as possible to the chip pins (ideally solded directly on the pins). 2. In order to have a correct current limitation, the board parasitic resistances must be taken into account in the choice of the Rs value (e.g., if each metal line connecting Rs to the chip adds a 10 m resistance, the correct Rs value should be 200-2x10=180m) 3. CVcc and CVss lines must have very low resistance (short and wide metal line). 4. R1, R2, R3 and R4 must be placed as close as possible to the chip pins. 5. Connect e-pad to ground. If possible connect it to ground plane 401 TPR0327AY-SMS-30Jan09 30.3 30.3.1 Pinout AT90SCR100LSD - QFN32 => Standard SPI ( PD TxD ) 0 (R RE xD SE ) T LO 32 31 30 29 28 27 26 25 Vcc1 DVcc Vss3 XTal1 XTal2 CC4/Host_D+ CC8/Host_DUSB_D1 2 3 4 5 6 7 8 9 US cd CV c Se CV nse ss Vs s1 PD 1 Vd 24 23 22 Li CVcc AVss CCLK CRST CIO CPRES Vss2 QFN32 21 20 19 18 17 10 11 12 13 14 15 16 ) (ss 4 PB c2 Vc k) (sc ) i 7 PB mos 5( ) PB iso (m 6 0) PB led ( 2 PC AP UC D+ B_ 402 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 30.3.2 AT90SCR100LHS - QFN32 => High-Speed SPI ( PD TxD ) 0 (R RE xD SE ) T LO 32 31 30 29 28 27 26 25 Vcc1 DVcc Vss3 XTal1 XTal2 CC4/Host_D+ CC8/Host_DUSB_D1 2 3 4 5 6 7 8 9 US cd CV c Se CV nse ss Vs s1 PD 1 Vd 24 23 22 Li CVcc AVss CCLK CRST CIO CPRES Vss2 QFN32 21 20 19 18 17 10 11 12 13 14 15 16 s) s-s (h 4 PD ) c2 ck Vc hs-s i) ( os 5 PD hs-m ) 6( iso PD s-m (h 7 0) PD led ( 2 PC AP UC D+ B_ 403 TPR0327AY-SMS-30Jan09 30.3.3 AT90SCR100H - QFN64 & LQFP64 (K PA bO 3 0 (K ) bI PE n0 2 (K ) PE bO 2 1 (K ) PE bO 1 0 (K ) PA bO 0 5 (K ) bI PA n5 4 (K ) bI PB n4 2 ) PD 1 (T PD xD ) 0 (R xD PC ) 1 (sd PC a) 0 (sc RE l) SE T LO 64 63 62 61 60 59 58 57 56 55 54 53 52 51 PA1 (KbIn1) PA2 (KbIn2) PA3 (KbIn3) PE4 (KbO4) PE5 (KbO5) Vcc1 Vcc2 DVcc RTC1 (Tosc1) RTC2 (Tosc2) XTal1 XTal2 CC4/Host_D+ CC8/Host_DUSB_DUSB_D+ 1 2 3 4 5 6 7 8 Vd cd c CV Se n 50 49 48 47 46 45 44 43 42 41 PE 3 se LI CVcc CCLK CRST CIO CPRES Vcc5 PA7 (KbIn7) PA6 (KbIn6) PD2 (int0) PD3 (int1) PB0 (int2) PB1 (int3) PD4 (hs-ss) PB3 (pwm) PB4 (ss) QFN64 9 10 11 12 13 14 15 16 40 39 38 37 36 35 34 33 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 404 AT90SCR100 TPR0327AY-SMS-30Jan09 UC PC 2 PC 3 (le d0 ) PC 4 PC 5 Vc c3 PB NC c4 ck) Vc s-s (h 5 PD ck) (s osi) 7 PB s-m (h 6 i) PD os (m ) 5 7 PB bO (K ) 7 6 PE bO (K iso) 6 PE s-m (h 7 ) PD iso (m 6 AP (le d1 (le d2 ) (le ) d3 ) e-pad, underneath package must be connected to ground NC: Not Connected (pin16, 32) AT90SCR100 30.4 30.4.1 Mechanical Information QFN32 D 1 2 3 Pin 1 ID E SIDE VIEW TOP VIEW A2 0.10 A3 A1 K D2 A 0.05 C COMMON DIMENSIONS (Unit of Measure = mm) E2 3 2 1 Pitch #1 Notch (0.20 R) SYMBOL A MIN - - - NOM - - 0.65 0.20 REF MAX 0.90 0.05 0.70 0.45 K A1 A2 A3 b e L b D 0.18 0.25 5.00 BSC 0.30 BOTTOM VIEW D2 E E2 3.40 3.50 5.00 BSC 3.80 Note: JEDEC Standard MO-220, Fig. 2 (Anvil Singulation), VHHD-2 e 0.50 BSC 1. All dimensions are in millimeters. 2. Die thickness allowable is 0.305mm maximum. L 0.35 0.40 3. Dimensioning & Tolerances conform to ASME Y14.5M. 1994. K 0.35 - 4. The Pin #1 identifier must be placed on the top surface of the package by using identification mark or other feature of package body. 5. Exact shape and size of this feature is optimal. 6. Package warpage max 0.08mm. 7. Applied for exposed pad and terminals. Exclude embedding part of exposed pard from measuring 8. Applied only to terminals 3.40 3.50 3.60 0.45 - 405 TPR0327AY-SMS-30Jan09 30.4.2 QFN 64 Pin 1 ID E SIDE VIEW A2 D A A1 TOP VIEW C 0.05 C D2 COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL A A1 E2 A2 D/E 3 2 1 Pitch #1 Notch (0.20 R) MIN 0.80 0 - 8.90 3.25 NOM - - - 9.00 - 0.50 BSC MAX 1.00 0.05 0.95 9.10 7.50 D2/E2 e L b 0.30 0.18 0.40 0.25 0.55 0.3 b e L BOTTOM VIEW Note: Compliant JEDEC Standard MO-220 variation VMMD-3 406 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 30.4.3 LQFP64 _ TBC PIN 1 b PIN 1 IDENTIFIER 64-lead COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL A A1 MIN - 0.05 1.35 NOM - - 1.40 12.00 BSC 10.00 BSC 7.50 12.00 BSC 10.00 BSC 7.50 0.17 0.09 0.45 0.20 - 0.60 1.00 REF 0.50 BSC 0.27 0.20 0.75 MAX 1.60 0.15 1.45 e E2 E1 E A2 D D1 D2 E E1 D2 D1 D c 0~7 L1 A1 A2 A E2 b c L L1 e L Notes: 1. This drawing is for general information only. Refer to JEDEC drawing MS-026 for additional information. 407 TPR0327AY-SMS-30Jan09 408 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 31. Electrical Characteristics Absolute Maximum Ratings* Operating Temperature.................................... -40C to +85C Storage Temperature ..................................... -65C to +150C Voltage on any Pin except RESET with respect to Ground ................................-0.5V to VCC+0.5V Voltage on RESET with respect to Ground......-0.5V to +13.0V Maximum Operating Voltage ............................................ 6.0V DC Current VCC and GND Pins.........................................TBD *NOTICE: Stresses beyond those listed under "Absolute Maximum Ratings" may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability. 31.1 Scope The AT90SCR100 application can make the use of the internal DC/DC converter or not. Please pay attention to the configuration of the AT90SCR100 before reading the table, to match your particular needs. AT90SCR100 without active DC/DC: Vcc range: 2.4V - 5.5V AT90SCR100 with active DC/DC: Vcc range: 2.7V - 5.5V ! Caution All DC Characteristics contained in this datasheet are based on characterization of other AVR microcontrollers and peripherals. These values are preliminary values representing design targets, and will be updated after characterization of silicon ! Caution This datasheet is only a preliminary version. All values indicated here are indicative values, describing what the product should achieve. ALL THESE VALUES ARE TO BE CONFIRMED OR TO BE DEFINED 409 TPR0327AY-SMS-30Jan09 31.2 DC Characteristics TBC/TBD Min.(1) -0.3 2.0 (4) TA = -40C to 85C, VCC = 2.4V to 5.5V (unless otherwise noted) Symbol VIL(2) VIH (2) (2) Parameter Input Low Voltage Input High Voltage Hysteresis on Input Output Low Voltage, Output High Voltage, Input Leakage Current I/O Pin Input Leakage Current I/O Pin Reset Pull-up Resistor I/O Pin Pull-up Resistor Condition VCC = 2.4V - 5.5V VCC = 2.4V - 5.5V VCC = 2.4V - 5.5V VCC = 2.4V - 5.5V VCC = 2.4V - 5.5V VCC = 5.5V, pin low (absolute value) VCC = 5.5V, pin high (absolute value) Typ. Max.(1) 0.8(3) VCC + 0.3 0.7 0.4 Units V V V V V VIHys 0.4 VOL(2) VOH(2) IIL(2) IIH(2) RRST RPU VCC - 0.4 1 1 30 20 60 50 TBD TBD 100(7) 150 A A k k mA mA A ICC Power Supply Current (5) Active 8MHz, VCC = 5V (AT90SCR100) Idle 8MHz, VCC = 5V (AT90SCR100) VCC = 5V Power-down mode(6) Notes: 1. All DC Characteristics contained in this datasheet are based on characterization of other AVR microcontrollers and peripherals. These values are preliminary values representing design targets, and will be updated after characterization of silicon. 2. These parameters are only for standard I/Os. These only include: Keyboard Inputs, External Interrupts, Standard Serial Peripheral Interface (SPI), High-speed Serial Peripheral Interface (HSSPI), JTAG/LED ports (driving only 2 or 4mA), 2-Wire Interface, Timers I/Os, USART. 3. "Max" means the highest value where the pin is guaranteed to be read as low 4. "Min" means the lowest value where the pin is guaranteed to be read as high 5. Values with "PRR0 - Power Reduction Register 0" and "PRR1 - Power Reduction Register 1" disabled (0x00). 6. Power-down values includes Input Leakage Current. 7. For USB Suspend power-down current measure, you should add 200A generated by the different resistors on USB D+/Dlines. 31.3 Symbol IOL IOL IOL PORT Parameter Output Low Current, PC2, PC3, PC4, PC5 LED modes Output Low Current, PORT E Output Low Current, all other PORTS Note: (TA = -20C to +50C, VCC - VOL = 2 V ) Min 1 2 Typ 3 6 Max 5 8 2 8 Unit mA mA mA mA Test Conditions 2 mA configuration 4 mA configuration 410 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 31.4 31.4.1 Clocks XTAL1 : External Clock In TBC/TBD This clock relates to Core and System clock. See "Clock Sources" on page 33. Table 31-1. Symbol 1/tCPXIN tCHXIN tCLCX CIN RIN XTAL1 = XIN Clock Electrical Characteristics Parameter XIN Clock Frequency XIN Clock High Half-Period XIN Clock Low HAlf-Period XIN Input Capacitance XIN Pulldown Resistor Min. 8 0.4 x tCPXIN 0.4 x tCPXIN Max. Units MHz 31.4.2 Calibrated Internal RC Oscillator Accuracy This clock concerns the Flash/Eeprom specific clock. See "Internal RC Oscillator" on page 37. Calibration Accuracy of Internal RC Oscillator Frequency VCC 3V 2.4V - 5.5V Temperature 25C -40C - 85C Calibration Accuracy 5% 1% 10.0 MHz 9.5 - 10.5 MHz Table 31-2. Factory Calibration User Calibration 31.5 31.5.1 Communication Interfaces 2-wire Serial Interface Characteristics TBC/TBD Table 31-3 describes the requirements for devices connected to the 2-wire Serial Bus. The AT90SCR100 2-wire Serial Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 31-1. Table 31-3. Symbol VIL VIH Vhys VOL (1) (1) 2-wire Serial Bus Requirements Parameter Input Low-voltage Input High-voltage Hysteresis of Schmitt Trigger Inputs Output Low-voltage Rise Time for both SDA and SCL Output Fall Time from VIHmin to VILmax Spikes Suppressed by Input Filter Capacitance for each I/O Pin SCL Clock Frequency Hold Time (repeated) START Condition fCK (4) Condition Min -0.5 0.6 VCC 0.05 VCC (2) Max 0.3 VCC VCC + 0.5 - 0.4 (2)(3) Units V V V V ns ns ns pF kHz s s 3 mA sink current 0 20 + 0.1Cb tr(1)(8) tof(1)(8) tSP(1)(8) Ci (1)(8) 300 250 50(2) 10 400 - - 10 pF < Cb < 400 pF(3) 20 + 0.1Cb(2)(3) 0 - fSCL tHD;STA > max(16fSCL, 250kHz) fSCL 100 kHz fSCL > 100 kHz (5) 0 4.0 0.6 411 TPR0327AY-SMS-30Jan09 Table 31-3. Symbol tLOW tHIGH tSU;STA tHD;DAT tSU;DAT tSU;STO tBUF Notes: 2-wire Serial Bus Requirements (Continued) Parameter Low Period of the SCL Clock Condition fSCL 100 kHz(6) fSCL > 100 kHz (7) Min 4.7 1.3 4.0 0.6 4.7 0.6 0 0 250 100 4.0 0.6 4.7 1.3 Max - - - - - - 3.45 0.9 - - - - - - Units s s s s s s s s ns ns s s s s High period of the SCL clock fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz Set-up time for a repeated START condition Data hold time Data setup time Setup time for STOP condition Bus free time between a STOP and START condition 2. Required only for fSCL > 100 kHz. 3. Cb = capacitance of one bus line in pF. 4. fCK = CPU clock frequency 1. In AT90SCR100, this parameter is characterized and not 100% tested. 5. This requirement applies to all AT90SCR100 Two-wire Serial Interface operation. Other devices connected to the Two-wire Serial Bus need only obey the general fSCL requirement. 6. The actual low period generated by the AT90SCR100 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus fCK must be greater than 6 MHz for the low time requirement to be strictly met at fSCL = 100 kHz. 7. The actual low period generated by the AT90SCR100 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus the low time requirement will not be strictly met for fSCL > 308 kHz when fCK = 8 MHz. Still, AT90SCR100 devices connected to the bus may communicate at full speed (400 kHz) with other AT90SCR100 devices, as well as any other device with a proper tLOW acceptance margin. 8. This parameter is theorical and is not part of the production test flow. It represents a some idea of the size of the parameter, but the exact value is not guaranteed. Figure 31-1. 2-wire Serial Bus Timing tof tLOW SCL tSU;STA SDA tHD;STA tHD;DAT tSU;DAT tSU;STO tHIGH tLOW tr tBUF 31.5.2 High-Speed SPI Interface Characteristics TBD 412 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 31.5.3 SPI Timing Characteristics TBC/TBD See Figure 31-2 and Figure 31-3 for details. SPI Timing Parameters(2) Description 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Notes: SCK period SCK high/low Rise/Fall time Setup Hold Out to SCK SCK to out SCK to out high SS low to out SCK period SCK high/low(1) Rise/Fall time Setup Hold SCK to out SCK to SS high SS high to tri-state SS low to SCK Mode Master Master Master Master Master Master Master Master Slave Slave Slave Slave Slave Slave Slave Slave Slave Slave 20 20 10 10 tck 15 4 * tck 2 * tck 1600 Min Typ See Table 20-4 50% duty cycle 3.6 10 10 0.5 * tsck 10 10 15 ns Max Table 31-4. 1. In SPI Programming mode the minimum SCK high/low period is: - 2 tCLCL for fCK < 12 MHz - 3 tCLCL for fCK > 12 MHz 2. These values are for information only. They are not tested to production test flow. They are deduced from characterization session. Figure 31-2. SPI Interface Timing Requirements (Master Mode) SS 6 1 SCK (CPOL = 0) 2 2 SCK (CPOL = 1) 4 5 3 MISO (Data Input) MSB 7 ... LSB 8 MO SI (Data Output) MSB ... LSB 413 TPR0327AY-SMS-30Jan09 Figure 31-3. SPI Interface Timing Requirements (Slave Mode) SS 9 10 16 SCK (CPOL = 0) 11 11 SCK (CPOL = 1) 13 14 12 MO SI (Data Input) MSB 15 ... LSB 17 MISO (Data Output) MSB ... LSB X 31.6 USB Interface Characteristics TBC/TBD USB Electrical Parameters Parameter Input Level High (driven) Input Level High (floating) Input Level Low Differential Input Sensitivity Differential Common Mode Range Static Output Low Static Output High Input Capacitance Rise Time Fall Time Rise / Fall Time matching (tr/tr ) Driver Output Resistance Full Speed Data Rate Frame Interval Steady State Drive Average Bit Rate Cout = 50 pF Cout = 50 pF 4 4 90 28 11.97 0.9995 2.8 0.2 0.8 2.5 0.3 3.6 20 20 20 110 44 12.03 1.0005 Condition Min. 2.0 2.7 0.8 Typ. Max. Units V V V V V V V pF ns ns % ohm Mb/s ms Table 31-5. Symbol VIH VIHZ VIL VDI VCM VOL1 VOH1 CIN tr tf trfm Zdrv tdrate tframe 414 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 31.7 Smart Card Interface Characteristics All Characteristics contained in this section are based on characterization of other products. These values are preliminary values representing design targets, and will be updated after characterization of silicon This datasheet is only a preliminary version. All values indicated here are indicative values, describing what the product should achieve. ALL THESE VALUES ARE TO BE CONFIRMED OR TO BE DEFINED ! Caution ! Caution Table 31-6. Symbol CVCC Smart Card Class A, 5V (CVcc) Parameter Smart card voltage with Vcc = 2.7V to 2.85V with Vcc > 2.85V Spikes on CVCC Min 4.6 4.6 Typ 5 5 TBD TBD TBD TBD TBD TBD TBD Max 5.4 5.4 Unit V V V V s s Test Conditions Load = 50mA Load = 60mA Vcardok up Vcardok down TVHL TVLH Vcardok high level threshold Vcardok low level threshold CVCC valid to 0.4V CVCC 0 to valid Table 31-7. Symbol CVCC Smart Card Class B, 3V (CVcc) Parameter Smart card voltage with Vcc = 2.7V to 2.85V with Vcc > 2.85V Spikes on CVCC Min 2.76 2.76 Typ 3 3 TBD TBD TBD TBD TBD TBD TBD Max 3.24 3.24 Unit V V V V s s Test Conditions Load = 50mA Load = 60mA Vcardok up Vcardok down TVHL TVLH Vcardok high level threshold Vcardok low level threshold CVCC valid to 0.4V CVCC 0 to valid Table 31-8. Symbol CVCC Smart Card C, 1.8V (CVcc) Parameter Smart card voltage Spikes on CVCC Min 1.66 Typ 1.8 TBD TBD Max 1.944 Unit V V V Test Conditions Load = 35mA Vcardok up Vcardok high level threshold 415 TPR0327AY-SMS-30Jan09 Table 31-8. Symbol Vcardok down TVHL TVLH Smart Card C, 1.8V (CVcc) Parameter Vcardok low level threshold CVCC valid to 0.4V CVCC 0 to valid Min TBD TBD TBD TBD TBD TBD Typ Max Unit V s s Test Conditions Table 31-9. Symbol Smart Card Card Presence (CPRES) Parameter Min Typ Max Unit Test Conditions Short to VSS IOL1 CPRES weak pull-up output current 3 10 25 A PULLUP = 1: Internal pull-up active 31.8 USB Host Controller Characteristics TBD 416 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 32. Register Summary Address (0xFF) (0xFE) (0xFD) (0xFC) (0xFB) (0xFA) (0xF9) (0xF8) (0xF7) (0xF6) (0xF5) (0xF4) (0xF3) (0xF2) (0xF1) (0xF0) (0xEF) (0xEE) (0xED) (0xEC) (0xEB) (0xEA) (0xE9) (0xE8) (0xE7) (0xE6) (0xE5) (0xE4) (0xE3) (0xE2) (0xE1) (0xE0) (0xDF) (0xDE) (0xDD) (0xDC) (0xDB) (0xDA) (0xD9) (0xD8) (0xD7) (0xD6) (0xD5) (0xD4) (0xD3) (0xD2) (0xD1) (0xD0) (0xCF) (0xCE) (0xCD) (0xCC) (0xCB) (0xCA) (0xC9) (0xC8) (0xC7) (0xC6) (0xC5) (0xC4) (0xC3) (0xC2) (0xC1) (0xC0) Name SCICR SCCON SCISR SCIIR SCIER SCSR SCIBUF SCETUH SCETUL SCGTH SCGTL SCWT3 SCWT2 SCWT1 SCWT0 SCICLK DCCR Reserved USBDMAB USBDMADH USBDMADL USBDMACS USBFNH USBFNL USBFA USBGS USBRSTE USBEIM USBEI USBPIM USBPI USBCR HSSPIDMAB HSSPIDMADH HSSPIDMADL HSSPIDMACS HSSPICR HSSPIIR HSSPICFG HSSPISR HSSPITDR HSSPIRDR HSSPIGTR HSSPIIER HSSPICNT HSSPITOH HSSPITOL Reserved Reserved Reserved USBFCEX USBDBCEX USBCSEX USBENUM Reserved Reserved Reserved UDR0 UBRR0H UBRR0L Reserved UCSR0C UCSR0B UCSR0A Bit 7 RESET CLK SCTBE SCTBI ESCTBI COMP WT31 WT23 WT15 WT7 XTSCS DCON FN7 RSTE4 EP7IM EP7I URMWU TIMEOUT SPICKDIV2 - Bit 6 CARDDET CARDIN CARDINE BGTEN WT30 WT22 WT14 WT6 DCRDY EPS2 FN6 FADD6 RSTE6 EP7IM EP6I BTD SPICKDIV1 - Bit 5 VCARD1 CARDC8 WT29 WT21 WT13 WT5 SCICLK5 DCBUSY - Bit 4 VCARD0 CARDC4 VCARDOK VCARDERR IVCARDER CREPSEL - Bit 3 UART CARDIO SCWTO SCWTI ESCWTI CPRESRES ETU [7:0] GT [7:0] WT27 WT19 WT11 WT3 SCICLK3 USBDMAB [6..0] Bit 2 WTEN CARDCLK SCTC SCTI ESCTI - Bit 1 CREP CARDRST SCRC SCRI ESCRI ETU [10:8] Bit 0 CONV CARDVCC SCPE SCPI ESCPI - Page 190 192 193 195 196 196 197 198 198 SCIBUFD [7..0] WT28 WT20 WT12 WT4 SCICLK4 - WT26 WT18 WT10 WT2 SCICLK2 - WT25 WT17 WT9 WT1 SCICLK1 - GT8 WT24 WT16 WT8 WT0 SCICLK0 - 198 198 199 199 199 199 199 203 176 175 175 USBDMAD [13..8] USBDMAD [7..0] EPS1 FN5 FADD5 RSTE5 EP5IM EP5I UPUC HSSPIDMAD [7..0] RCVOF SPICKDIV0 NSSRE DPRAM DPRAMRDY NSSFE CPHA NSS DMAERR STTTO CPOL RXBUFF DMADIR RETTO MSTR TXBUFE DMAR CS SPIEN SPICKRDY EPS0 FNEND FN4 FADD4 RSTE4 EP4IM EP4I FEURI FNERR FN3 FADD3 RSMON RSTE3 EP3IM EP4I SOFIM SOFI DMAERR FN10 FN2 FADD2 RMWUE RSTE2 EP2IM EP2I RMWUIM RMWUI HSSPIDMAB [4..0] HSSPIDMAD [13..8] DMAIR FN9 FN1 FADD1 FCF RSTE1 EP1IM EP1I RESIM RESI USBE DMAR FN8 FN0 FADD0 FAF RSTE0 EP0IM EP0I SUSIM SUSI - 173 172 172 171 171 170 167 166 166 165 164 295 295 295 293 290 288 287 290 291 291 291 HSSPITDD [7..0] HSSPIRDD [7..0] HSSPIGTD [7..0] TIMEOUTIE BTDIE RCVOFIE SPITIMEOUT[15:8] SPITIMEOUT[7:0] EPE BCT7 UMSEL01 RXCIE0 RXC0 BCT6 IERR UMSEL00 TXCIE0 TXC0 BCT5 FSTALL UPM01 UDRIE0 UDRE0 BCT4 TXPB UPM00 RXEN0 FE0 USBS0 TXEN0 DOR0 BCT3 STSENT ENUM3 EPDIR BCT2 RXSETUP ENUM2 EPTYP1 BCT1 RCVD ENUM1 EPTYP0 BCT0 TXC ENUM0 NSSIE HSSPICNT [4..0] - 289 291 292 292 169 169 167 167 USART0 I/O Data Register USART0 Baud Rate Register High Byte UCSZ01 UCSZ02 UPE0 UCSZ00 RXB80 U2X0 UCPOL0 TXB80 MPCM0 USART0 Baud Rate Register Low Byte 249 253 253 251 250 249 417 TPR0327AY-SMS-30Jan09 Address (0xBF) (0xBE) (0xBD) (0xBC) (0xBB) (0xBA) (0xB9) (0xB8) (0xB7) (0xB6) (0xB5) (0xB4) (0xB3) (0xB2) (0xB1) (0xB0) (0xAF) (0xAE) (0xAD) (0xAC) (0xAB) (0xAA) (0xA9) (0xA8) (0xA7) (0xA6) (0xA5) (0xA4) (0xA3) (0xA2) (0xA1) (0xA0) (0x9F) (0x9E) (0x9D) (0x9C) (0x9B) (0x9A) (0x99) (0x98) (0x97) (0x96) (0x95) (0x94) (0x93) (0x92) (0x91) (0x90) (0x8F) (0x8E) (0x8D) (0x8C) (0x8B) (0x8A) (0x89) (0x88) (0x87) (0x86) (0x85) (0x84) (0x83) (0x82) (0x81) (0x80) (0x7F) (0x7E) Name Reserved Reserved TWAMR TWCR TWDR TWAR TWSR TWBR Reserved ASSR Reserved OCR2B OCR2A TCNT2 TCCR2B TCCR2A UPDATX UPIENX UPCFG2X UPSTAX UPCFG1X UPCFG0X UPCRX UPRST UPNUM UPINTX UPINRQX UHFLEN UHFNUMH UHFNUML UHADDR UHIEN UHINT UHCR UPERRX UPBCXH UPBCXL UPINT UHSR Reserved Reserved Reserved RNGCR LFSR3 LFSR2 LFSR1 LFSR0 RDWDR KBFR KBER KBLSR Reserved OCR1BH OCR1BL OCR1AH OCR1AL ICR1H ICR1L TCNT1H TCNT1L Reserved TCCR1C TCCR1B TCCR1A Reserved Reserved Bit 7 TWAM6 TWINT TWA6 TWS7 - Bit 6 TWAM5 TWEA TWA5 TWS6 EXCLK - Bit 5 TWAM4 TWSTA TWA4 TWS5 AS2 - Bit 4 TWAM3 TWSTO TWA3 TWS4 TCN2UB - Bit 3 TWAM2 TWWC TWA2 TWS3 OCR2AUB - Bit 2 TWAM1 TWEN TWA1 OCR2BUB - Bit 1 TWAM0 TWA0 TWPS1 TCR2AUB - Bit 0 TWIE TWGCE TWPS0 TCR2BUB - Page 328 325 327 327 326 324 150 150 150 149 2-wire Serial Interface Data Register 2-wire Serial Interface Bit Rate Register Timer/Counter2 Output Compare Register B Timer/Counter2 Output Compare Register A Timer/Counter2 (8 Bit) FOC2A COM2A1 FLERRE CFGOK PTYPE [1..0] FIFOCON PFREEZE NAKEDI RWAL FOC2B COM2A0 NAKEDE OVERFI COM2B1 UNDERFI PSIZE [0..2] PTOKEN [0..1] INMODE PERRI INRQ [7..0] FLEN [7..0] UHEN HWUPE HWUPI PAD [1..0] COUNTER [1..0] HSOFE HSOFI RXRSME RXRSMI FRZCLK CRC16 LFSD [31..24] LFSD [23..16] LFSD [15..8] LFSD [7..0] RDD [7..0] KBF7 KBE7 KBLS7 KBF6 KBE6 KBLS6 KBF5 KBE5 KBLS5 KBF4 KBE4 KBLS4 KBF3 KBE3 KBLS3 KBF2 KBE2 KBLS2 KBF1 KBE1 KBLS1 KBF0 KBE0 KBLS0 FNUM [7..0] HADDR [6..0] RSMEDE RSMEDI TIMEOUT PBYTCT [7..0] PINT3 SPEED PINT2 PINT1 PINT0 ROSCE RSTE RSTI RESUME PID DDISCE DDISCI RESET DATAPID PBYTCT [10..8] DCONNE DCONNI SOFEN DATATGL FNUM [10..8] RSTDT P3RST TXSPI P2RST TXOUTI COM2B0 PDAT [7..0] PERRE TXSTPE TXOUTE RXSTALLE ALLOC PEPNUM [0..3] P1RST PNUM1 RXSTALLI PEN P0RST PNUM0 RXINI RXINE NBUSYB INTFRQ [7..0] DTSEQ [1..0] PBK [0..1 WGM22 CS22 CS21 WGM21 CS20 WGM20 148 145 229 229 225 225 224 223 222 222 222 227 226 221 221 221 221 220 219 217 226 230 230 230 218 336 336 336 336 336 337 330 331 332 131 131 131 131 131 131 130 130 Timer/Counter1 - Output Compare Register B High Byte Timer/Counter1 - Output Compare Register B Low Byte Timer/Counter1 - Output Compare Register A High Byte Timer/Counter1 - Output Compare Register A Low Byte Timer/Counter1 - Input Capture Register High Byte Timer/Counter1 - Input Capture Register Low Byte Timer/Counter1 - Counter Register High Byte Timer/Counter1 - Counter Register Low Byte FOC1A ICNC1 COM1A1 FOC1B ICES1 COM1A0 COM1B1 WGM13 COM1B0 WGM12 CS12 CS11 WGM11 CS10 WGM10 - 129 128 126 418 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Address (0x7D) (0x7C) (0x7B) (0x7A) (0x79) (0x78) (0x77) (0x76) (0x75) (0x74) (0x73) (0x72) (0x71) (0x70) (0x6F) (0x6E) (0x6D) (0x6C) (0x6B) (0x6A) (0x69) (0x68) (0x67) (0x66) (0x65) (0x64) (0x63) (0x62) (0x61) (0x60) 0x3F (0x5F) 0x3E (0x5E) 0x3D (0x5D) 0x3C (0x5C) 0x3B (0x5B) 0x3A (0x5A) 0x39 (0x59) 0x38 (0x58) 0x37 (0x57) 0x36 (0x56) 0x35 (0x55) 0x34 (0x54) 0x33 (0x53) 0x32 (0x52) 0x31 (0x51) 0x30 (0x50) 0x2F (0x4F) 0x2E (0x4E) 0x2D (0x4D) 0x2C (0x4C) 0x2B (0x4B) 0x2A (0x4A) 0x29 (0x49) 0x28 (0x48) 0x27 (0x47) 0x26 (0x46) 0x25 (0x45) 0x24 (0x44) 0x23 (0x43) 0x22 (0x42) 0x21 (0x41) 0x20 (0x40) 0x1F (0x3F) 0x1E (0x3E) 0x1D (0x3D) 0x1C (0x3C) Name Reserved Reserved AESDR AESADDR AESACR AESCR Reserved Reserved LEDCR Reserved PCMSK3 Reserved Reserved TIMSK2 TIMSK1 TIMSK0 PCMSK2 PCMSK1 PCMSK0 Reserved EICRA PCICR Reserved OSCCAL PRR1 PRR0 SMONCR PLLCR CLKPR WDTCSR SREG SPH SPL Reserved Reserved Reserved Reserved Reserved SPMCSR Reserved MCUCR MCUSR SMCR Reserved OCDR Reserved Reserved SPDR SPSR SPCR GPIOR2 GPIOR1 Reserved OCR0B OCR0A TCNT0 TCCR0B TCCR0A GTCCR EEARH EEARL EEDR EECR GPIOR0 EIMSK EIFR Bit 7 - Bit 6 - Bit 5 - Bit 4 - Bit 3 DATA [0..8] ADDR [0..8] Bit 2 - Bit 1 - Bit 0 - Page 343 343 MANINC LED1 PCINT26 OCIE2B OCIE1B OCIE0B PCINT18 PCINT10 PCINT2 ISC10 PCIE2 CAL2 PRHSSPI PRSPI CLKPS2 WDP2 N SP10 SP2 PGWRT BORF SM1 D2 CPHA AUTOINC ENCRYPT LED0 PCINT25 OCIE2A OCIE1A OCIE0A PCINT17 PCINT9 PCINT1 ISC01 PCIE1 CAL1 PRUSB PRUSART0 LOCK CLKPS1 WDP1 Z SP9 SP1 PGERS IVSEL EXTRF SM0 D1 SPR1 PCINT24 TOIE2 TOIE1 TOIE0 PCINT16 PCINT8 PCINT0 ISC00 PCIE0 CAL0 PRSCUSB SMONEN ON/OFF CLKPS0 WDP0 C SP8 SP0 SPMEN IVCE PORF SE D0 274 SPI2X SPR0 274 272 29 29 103 103 102 CS02 CS01 WGM01 PSRASY EEARH [11:8] CS00 WGM00 PSRSYNC 101 98 155 24 24 24 EEMPE INT2 INTF2 EEPE INT1 INTF1 EERE INT0 INTF0 24 30 70 70 352 67, 82, 356 60 45 367 39 46 45 60 40 40 61 15 17 17 69 71 153 132 103 73 73 73 73 KD AESGO 77 342 341 KS - AESIE LED3 PCINT31 PCINT23 PCINT15 PCINT7 ISC31 CAL7 PRTWI SMONIF PLLMUX WDIF I SP15 SP7 SPMIE JTD D7/IDRD SPIF SPIE AESIF PCINT30 PCINT22 PCINT14 PCINT6 ISC30 CAL6 PRTIM2 SMONIE WDIE T SP14 SP6 RWWSB D6 WCOL SPE AUTOKEY LED2 PCINT29 ICIE1 PCINT21 PCINT13 PCINT5 ISC21 CAL5 PRKB PRTIM0 WDP3 H SP13 SP5 SIGRD D5 DORD KEYGN PCINT28 PCINT20 PCINT12 PCINT4 ISC20 CAL4 PRAES WDCE S SP12 SP4 RWWSRE PUD JTRF D4 MSTR XOR PCINT27 PCINT19 PCINT11 PCINT3 ISC11 PCIE3 CAL3 PRSCI PRTIM1 CLKPS3 WDE V SP11 SP3 BLBSET WDRF SM2 D3 CPOL SPI 0 Data Register General Purpose I/O Register 2 General Purpose I/O Register 1 Timer/Counter0 Output Compare Register B Timer/Counter0 Output Compare Register A Timer/Counter0 (8 Bit) FOC0A COM0A1 TSM FOC0B COM0A0 COM0B1 COM0B0 EEARL [7:0] EEPROM Data Register EEPM1 EEPM0 EERIE INT3 INTF3 General Purpose I/O Register 0 WGM02 - 419 TPR0327AY-SMS-30Jan09 Address 0x1B (0x3B) 0x1A (0x3A) 0x19 (0x39) 0x18 (0x38) 0x17 (0x37) 0x16 (0x36) 0x15 (0x35) 0x14 (0x34) 0x13 (0x33) 0x12 (0x32) 0x11 (0x31) 0x10 (0x30) 0x0F (0x2F) 0x0E (0x2E) 0x0D (0x2D) 0x0C (0x2C) 0x0B (0x2B) 0x0A (0x2A) 0x09 (0x29) 0x08 (0x28) 0x07 (0x27) 0x06 (0x26) 0x05 (0x25) 0x04 (0x24) 0x03 (0x23) 0x02 (0x22) 0x01 (0x21) 0x00 (0x20) Name PCIFR EIRR Reserved Reserved TIFR2 TIFR1 TIFR0 Reserved Reserved Reserved Reserved Reserved Reserved PORTE DDRE PINE PORTD DDRD PIND PORTC DDRC PINC PORTB DDRB PINB PORTA DDRA PINA Bit 7 PORTE7 DDE7 PINE7 PORTD7 DDD7 PIND7 PORTB7 DDB7 PINB7 PORTA7 DDA7 PINA7 Bit 6 PORTE6 DDE6 PINE6 PORTD6 DDD6 PIND6 PORTB6 DDB6 PINB6 PORTA6 DDA6 PINA6 Bit 5 ICF1 PORTE5 DDE5 PINE5 PORTD5 DDD5 PIND5 PORTC5 DDC5 PINC5 PORTB5 DDB5 PINB5 PORTA5 DDA5 PINA5 Bit 4 PORTE4 DDE4 PINE4 PORTD4 DDD4 PIND4 PORTC4 DDC4 PINC4 PORTB4 DDB4 PINB4 PORTA4 DDA4 PINA4 Bit 3 PCIF3 INTD3 PORTE3 DDE3 PINE3 PORTD3 DDD3 PIND3 PORTC3 DDC3 PINC3 PORTB3 DDB3 PINB3 PORTA3 DDA3 PINA3 Bit 2 PCIF2 INTD2 OCF2B OCF1B OCF0B PORTE2 DDE2 PINE2 PORTD2 DDD2 PIND2 PORTC2 DDC2 PINC2 PORTB2 DDB2 PINB2 PORTA2 DDA2 PINA2 Bit 1 PCIF1 OCF2A OCF1A OCF0A PORTE1 DDE1 PINE1 PORTD1 DDD1 PIND1 PORTC1 DDC1 PINC1 PORTB1 DDB1 PINB1 PORTA1 DDA1 PINA1 Bit 0 PCIF0 TOV2 TOV1 TOV0 PORTE0 DDE0 PINE0 PORTD0 DDD0 PIND0 PORTC0 DDC0 PINC0 PORTB0 DDB0 PINB0 PORTA0 DDA0 PINA0 Page 72 71 153 132 104 84 85 85 84 84 84 84 84 84 83 83 83 83 83 83 Note 1. For compatiliblity with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. 2. I/O registers within the address range $00-$1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using SBIS and SBIC instructions. 3. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O register, writing a one back into any flag read as set, this clearing the flag. The CBI and SBI instructions work with registers $00 to $1F only. 4. When using the I/O specific commands IN and OUT, the I/O addresses $00-$3F must be used. When addressing I/O registers as data space using LD and ST instructions, $20 must be added to these addresses. The AT90SCR100 is a complex microcontroller with more peripheral units than can be supported within the 64 locations reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from $60$FF, only the ST/STS/STD and LD/LDS/LDD instructions ca be used. All `Reserved' registers must not be read or written. Writing or Reading these registers may generate unhandled state. ! Caution 420 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 33. Instruction Set Summary Mnemonics ADD ADC ADIW SUB SUBI SBC SBCI SBIW AND ANDI OR ORI EOR COM NEG SBR CBR INC DEC TST CLR SER MUL MULS MULSU FMUL FMULS FMULSU RJMP IJMP JMP RCALL ICALL CALL RET RETI CPSE CP CPC CPI SBRC SBRS SBIC SBIS BRBS BRBC BREQ BRNE BRCS BRCC BRSH BRLO BRMI BRPL BRGE BRLT BRHS BRHC BRTS BRTC BRVS BRVC Rd,Rr Rd,Rr Rd,Rr Rd,K Rr, b Rr, b P, b P, b s, k s, k k k k k k k k k k k k k k k k k k k k Operands Rd, Rr Rd, Rr Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd Rd Rd,K Rd,K Rd Rd Rd Rd Rd Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr k Description Add two Registers Add with Carry two Registers Add Immediate to Word Subtract two Registers Subtract Constant from Register Subtract with Carry two Registers Subtract with Carry Constant from Reg. Subtract Immediate from Word Logical AND Registers Logical AND Register and Constant Logical OR Registers Logical OR Register and Constant Exclusive OR Registers One's Complement Two's Complement Set Bit(s) in Register Clear Bit(s) in Register Increment Decrement Test for Zero or Minus Clear Register Set Register Multiply Unsigned Multiply Signed Multiply Signed with Unsigned Fractional Multiply Unsigned Fractional Multiply Signed Fractional Multiply Signed with Unsigned BRANCH INSTRUCTIONS Relative Jump Indirect Jump to (Z) Direct Jump Relative Subroutine Call Indirect Call to (Z) Direct Subroutine Call Subroutine Return Interrupt Return Compare, Skip if Equal Compare Compare with Carry Compare Register with Immediate Skip if Bit in Register Cleared Skip if Bit in Register is Set Skip if Bit in I/O Register Cleared Skip if Bit in I/O Register is Set Branch if Status Flag Set Branch if Status Flag Cleared Branch if Equal Branch if Not Equal Branch if Carry Set Branch if Carry Cleared Branch if Same or Higher Branch if Lower Branch if Minus Branch if Plus Branch if Greater or Equal, Signed Branch if Less Than Zero, Signed Branch if Half Carry Flag Set Branch if Half Carry Flag Cleared Branch if T Flag Set Branch if T Flag Cleared Branch if Overflow Flag is Set Branch if Overflow Flag is Cleared Operation Rd Rd + Rr Rd Rd + Rr + C Rdh:Rdl Rdh:Rdl + K Rd Rd - Rr Rd Rd - K Rd Rd - Rr - C Rd Rd - K - C Rdh:Rdl Rdh:Rdl - K Rd Rd * Rr Rd Rd * K Rd Rd v Rr Rd Rd v K Rd Rd Rr Rd 0xFF - Rd Rd 0x00 - Rd Rd Rd v K Rd Rd * (0xFF - K) Rd Rd + 1 Rd Rd - 1 Rd Rd * Rd Rd Rd Rd Rd 0xFF R1:R0 Rd x Rr R1:R0 Rd x Rr R1:R0 Rd x Rr Flags Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,C,N,V Z,C,N,V,H Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V None Z,C Z,C Z,C Z,C Z,C Z,C None None None None None None None I None Z, N,V,C,H Z, N,V,C,H Z, N,V,C,H None None None None None None None None None None None None None None None None None None None None None None #Clocks 1 1 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 4 4 5 5 5 1/2/3 1 1 1 1/2/3 1/2/3 1/2/3 1/2/3 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 ARITHMETIC AND LOGIC INSTRUCTIONS 1 R1:R0 (Rd x Rr) << 1 R1:R0 (Rd x Rr) << 1 PC PC + k + 1 PC Z PC k PC PC + k + 1 PC Z PC k PC STACK PC STACK if (Rd = Rr) PC PC + 2 or 3 Rd - Rr Rd - Rr - C Rd - K if (Rr(b)=0) PC PC + 2 or 3 if (Rr(b)=1) PC PC + 2 or 3 if (P(b)=0) PC PC + 2 or 3 if (P(b)=1) PC PC + 2 or 3 if (SREG(s) = 1) then PCPC+k + 1 if (SREG(s) = 0) then PCPC+k + 1 if (Z = 1) then PC PC + k + 1 if (Z = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (N = 1) then PC PC + k + 1 if (N = 0) then PC PC + k + 1 if (N V= 0) then PC PC + k + 1 if (N V= 1) then PC PC + k + 1 if (H = 1) then PC PC + k + 1 if (H = 0) then PC PC + k + 1 if (T = 1) then PC PC + k + 1 if (T = 0) then PC PC + k + 1 if (V = 1) then PC PC + k + 1 if (V = 0) then PC PC + k + 1 R1:R0 (Rd x Rr) << 421 TPR0327AY-SMS-30Jan09 Mnemonics BRIE BRID SBI CBI LSL LSR ROL ROR ASR SWAP BSET BCLR BST BLD SEC CLC SEN CLN SEZ CLZ SEI CLI SES CLS SEV CLV SET CLT SEH CLH MOV MOVW LDI LD LD LD LD LD LD LDD LD LD LD LDD LDS ST ST ST ST ST ST STD ST ST ST STD STS LPM LPM LPM ELPM SPM IN OUT Operands k k P,b P,b Rd Rd Rd Rd Rd Rd s s Rr, b Rd, b Description Branch if Interrupt Enabled Branch if Interrupt Disabled Operation if ( I = 1) then PC PC + k + 1 if ( I = 0) then PC PC + k + 1 I/O(P,b) 1 I/O(P,b) 0 Rd(n+1) Rd(n), Rd(0) 0 Rd(n) Rd(n+1), Rd(7) 0 Rd(0)C,Rd(n+1) Rd(n),CRd(7) Rd(7)C,Rd(n) Rd(n+1),CRd(0) Rd(n) Rd(n+1), n=0..6 Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) SREG(s) 1 SREG(s) 0 T Rr(b) Rd(b) T C1 C0 N1 N0 Z1 Z0 I1 I0 S1 S0 V1 V0 T1 T0 H1 H0 Rd Rr Rd+1:Rd Rr+1:Rr Rd K Rd (X) Rd (X), X X + 1 X X - 1, Rd (X) Rd (Y) Rd (Y), Y Y + 1 Y Y - 1, Rd (Y) Rd (Y + q) Rd (Z) Rd (Z), Z Z+1 Z Z - 1, Rd (Z) Rd (Z + q) Rd (k) (X) Rr (X) Rr, X X + 1 X X - 1, (X) Rr (Y) Rr (Y) Rr, Y Y + 1 Y Y - 1, (Y) Rr (Y + q) Rr (Z) Rr (Z) Rr, Z Z + 1 Z Z - 1, (Z) Rr (Z + q) Rr (k) Rr R0 (Z) Rd (Z) Rd (Z), Z Z+1 Rd (Z) (Z) R1:R0 Rd P P Rr Flags None None None None Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V None SREG(s) SREG(s) T None C C N N Z Z I I S S V V T T H H None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None #Clocks 1/2 1/2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 1 1 BIT AND BIT-TEST INSTRUCTIONS Set Bit in I/O Register Clear Bit in I/O Register Logical Shift Left Logical Shift Right Rotate Left Through Carry Rotate Right Through Carry Arithmetic Shift Right Swap Nibbles Flag Set Flag Clear Bit Store from Register to T Bit load from T to Register Set Carry Clear Carry Set Negative Flag Clear Negative Flag Set Zero Flag Clear Zero Flag Global Interrupt Enable Global Interrupt Disable Set Signed Test Flag Clear Signed Test Flag Set Twos Complement Overflow. Clear Twos Complement Overflow Set T in SREG Clear T in SREG Set Half Carry Flag in SREG Clear Half Carry Flag in SREG DATA TRANSFER INSTRUCTIONS Rd, Rr Rd, Rr Rd, K Rd, X Rd, X+ Rd, - X Rd, Y Rd, Y+ Rd, - Y Rd,Y+q Rd, Z Rd, Z+ Rd, -Z Rd, Z+q Rd, k X, Rr X+, Rr - X, Rr Y, Rr Y+, Rr - Y, Rr Y+q,Rr Z, Rr Z+, Rr -Z, Rr Z+q,Rr k, Rr Rd, Z Rd, Z+ Rd, Z Rd, P P, Rr Move Between Registers Copy Register Word Load Immediate Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Direct from SRAM Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Direct to SRAM Load Program Memory Load Program Memory Load Program Memory and Post-Inc Extended Load Program Memory Store Program Memory In Port Out Port 422 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Mnemonics PUSH POP NOP SLEEP WDR BREAK Operands Rr Rd Description Push Register on Stack Pop Register from Stack Operation STACK Rr Rd STACK Flags None None None #Clocks 2 2 1 1 1 N/A MCU CONTROL INSTRUCTIONS No Operation Sleep Watchdog Reset Break (see specific descr. for Sleep function) (see specific descr. for WDR/timer) For On-chip Debug Only None None None 423 TPR0327AY-SMS-30Jan09 424 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 34. Datasheet Revision History 34.1 Rev. AY-30Jan09 1. All sections updated. 2. USB Host Controller section: Caution on the pipe sizes. 3. HSSPI section: Update of Figure 21-8 on page 285. 4. I/O Ports section: "LEDCR - LED Control Register" in read only. 34.2 Rev. AX-13Nov08 1. Initial Revision 425 TPR0327AY-SMS-30Jan09 426 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 Table of Contents General Features....................................................................................... 1 1 2 3 4 5 Block Diagram .......................................................................................... 3 Pin List Configuration ............................................................................. 5 Resources ................................................................................................. 9 About Code Examples ........................................................................... 11 AVR CPU Core ........................................................................................ 13 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 Introduction ......................................................................................................13 Architectural Overview .....................................................................................13 ALU - Arithmetic Logic Unit .............................................................................14 Status Register ................................................................................................15 General Purpose Register File ........................................................................16 Stack Pointer ...................................................................................................17 Instruction Execution Timing ...........................................................................17 Reset and Interrupt Handling ...........................................................................18 6 AT90SCR100 Memories ......................................................................... 21 6.1 6.2 6.3 6.4 In-System Reprogrammable Flash Program Memory .....................................21 SRAM Data Memory ........................................................................................22 EEPROM Data Memory ..................................................................................23 I/O Memory ......................................................................................................29 7 Clock System ......................................................................................... 31 7.1 7.2 7.3 7.4 Overview ..........................................................................................................31 Clock Sources .................................................................................................33 Clock Output Buffer .........................................................................................40 Clock System Registers ..................................................................................40 8 Power Management and Sleep Modes ................................................. 43 8.1 8.2 8.3 8.4 Power Modes Descriptions ..............................................................................43 Power Reduction Register ...............................................................................45 Important note about: Entering and Leaving low consumption modes ............47 Minimizing Power Consumption ......................................................................48 9 System Control and Reset .................................................................... 51 9.1 Resetting the AVR ...........................................................................................51 TPR0327AY-SMS-30Jan09 4 2 7 9.2 9.3 9.4 9.5 9.6 Reset Sources .................................................................................................51 Internal Voltage Reference ..............................................................................55 Supply monitor .................................................................................................56 Watchdog Timer ..............................................................................................57 Register Description ........................................................................................60 10 Interrupts ................................................................................................ 63 10.1 Interrupt Vectors in AT90SCR100 ...................................................................63 11 External Interrupts ................................................................................. 69 11.1 External Interrupt Registers .............................................................................69 12 I/O Ports .................................................................................................. 75 12.1 12.2 12.3 12.4 12.5 Standard IO Ports ............................................................................................75 Specific Low Speed Keyboard Output .............................................................76 LED ..................................................................................................................76 Ports as General Digital I/O .............................................................................77 Register Description for I/O-Ports ....................................................................83 13 Timers ..................................................................................................... 87 13.1 13.2 13.3 13.4 8-bit Timer/Counter0 with PWM ......................................................................87 16-bit Timer/Counter1 with PWM ..................................................................105 8-bit Timer/Counter2 with PWM and Asynchronous Operation (RTC) ..........134 Timer/Counter Prescaler ...............................................................................154 14 USB Device Interface ........................................................................... 157 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 Features ........................................................................................................157 Overview ........................................................................................................157 Endpoints Description ....................................................................................159 Attachment Procedure ...................................................................................160 USB Interrupts ...............................................................................................160 Suspend and Resume Modes .......................................................................161 Double Buffering ............................................................................................163 USB Device Registers Description ................................................................164 USBDMA Controller .......................................................................................172 15 Smart Card Interface Block (SCIB) ..................................................... 177 15.1 15.2 15.3 Features ........................................................................................................177 Overview ........................................................................................................177 Block Diagram ...............................................................................................177 428 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 15.4 15.5 15.6 15.7 Definitions ......................................................................................................178 Functional Description ...................................................................................180 Additional Features ........................................................................................187 Smart Card Interface Block Registers ...........................................................190 16 DC/DC Converter .................................................................................. 201 16.1 16.2 16.3 16.4 16.5 Overview ........................................................................................................201 Features ........................................................................................................201 Description .....................................................................................................201 Summary: State Machine ..............................................................................202 DC/DC Registers ...........................................................................................203 17 USB Host Controller ............................................................................ 205 17.1 17.2 17.3 17.4 17.5 17.6 17.7 Features ........................................................................................................205 USB Host Smart Card Interface Description .................................................205 USB-IC Design ..............................................................................................206 Memory Management ....................................................................................207 USB Host Controller Description ...................................................................208 Interrupt system .............................................................................................216 USB Host Controller Registers ......................................................................217 18 USART ................................................................................................... 231 18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 18.10 18.11 18.12 Features ........................................................................................................231 USART0 ........................................................................................................231 Overview ........................................................................................................231 Clock Generation ...........................................................................................232 Frame Formats ..............................................................................................235 USART Initialization .......................................................................................236 Data Transmission - The USART Transmitter ..............................................238 Data Reception - The USART Receiver .......................................................240 Asynchronous Data Reception ......................................................................244 Multi-processor Communication Mode ..........................................................247 USART Register Description .........................................................................249 Examples of Baud Rate Setting .....................................................................254 19 USART in SPI Mode ............................................................................. 257 19.1 19.2 19.3 Features ........................................................................................................257 Overview ........................................................................................................257 Clock Generation ...........................................................................................257 429 TPR0327AY-SMS-30Jan09 19.4 19.5 19.6 19.7 19.8 SPI Data Modes and Timing ..........................................................................258 Frame Formats ..............................................................................................259 Data Transfer .................................................................................................260 USART MSPIM Register Description ............................................................262 AVR USART MSPIM vs. AVR SPI ................................................................265 20 SPI - Serial Peripheral Interface .......................................................... 267 20.1 20.2 20.3 20.4 20.5 Features ........................................................................................................267 Description .....................................................................................................267 SS Pin Functionality ......................................................................................272 SPI Registers .................................................................................................272 Data Modes ...................................................................................................275 21 High-Speed SPI Controller .................................................................. 277 21.1 21.2 21.3 21.4 21.5 21.6 Features ........................................................................................................277 Description .....................................................................................................277 HSSS line Functionality .................................................................................286 Data Modes ...................................................................................................286 HSSPI Interface Registers .............................................................................287 HSSPIDMA Controller ...................................................................................292 22 2-wire Serial Interface _ TWI ............................................................... 297 22.1 22.2 22.3 22.4 22.5 22.6 22.7 22.8 22.9 Features ........................................................................................................297 TWI Serial Interface Bus Definition ................................................................297 Data Transfer and Frame Format ..................................................................298 Multi-master Bus Systems, Arbitration and Synchronization .........................301 Overview of the TWI Module .........................................................................302 Using the TWI ................................................................................................305 Transmission Modes .....................................................................................308 Multi-master Systems and Arbitration ............................................................323 TWI Register Description ...............................................................................324 23 Keyboard Interface .............................................................................. 329 23.1 23.2 23.3 Features ........................................................................................................329 General Description .......................................................................................329 Keyboard Register Description ......................................................................330 24 Random Number Generator ................................................................ 335 24.1 Features ........................................................................................................335 430 AT90SCR100 TPR0327AY-SMS-30Jan09 AT90SCR100 24.2 24.3 RNG Definition ...............................................................................................335 Random Number Generator Registers ..........................................................336 25 AES 128/256 Engine ............................................................................. 339 25.1 25.2 25.3 25.4 Features ........................................................................................................339 Overview ........................................................................................................339 AES Registers description .............................................................................341 Example. Code Sample .................................................................................343 26 JTAG Interface and On-chip Debug System ..................................... 347 26.1 26.2 26.3 26.4 26.5 26.6 26.7 26.8 26.9 26.10 Features ........................................................................................................347 Overview ........................................................................................................347 TAP - Test Access Port ................................................................................347 TAP Controller ...............................................................................................349 Using the Boundary-scan Chain ....................................................................350 Using the On-chip Debug System .................................................................350 On-chip Debug Specific JTAG Instructions ...................................................351 On-chip Debug Related Register in I/O Memory ...........................................352 Using the JTAG Programming Capabilities ...................................................352 Bibliography ...................................................................................................352 27 IEEE 1149.1 (JTAG) Boundary-scan ................................................... 353 27.1 27.2 27.3 27.4 27.5 27.6 27.7 27.8 Features ........................................................................................................353 System Overview ...........................................................................................353 Data Registers ...............................................................................................353 Boundary-scan Specific JTAG Instructions ...................................................355 Boundary-scan Related Register in I/O Memory ...........................................356 Boundary-scan Chain ....................................................................................357 AT90SCR100 Boundary-scan Order .............................................................360 Boundary-scan Description Language Files ..................................................362 28 Boot Loader Support - Read-While-Write Self-Programming .......... 363 28.1 28.2 28.3 28.4 28.5 28.6 28.7 Boot Loader Features ....................................................................................363 Application and Boot Loader Flash Sections .................................................363 Read-While-Write and No Read-While-Write Flash Sections ........................364 Boot Loader Lock Bits ...................................................................................366 Entering the Boot Loader Program ................................................................367 Addressing the Flash During Self-Programming ...........................................369 Self-Programming the Flash ..........................................................................370 431 TPR0327AY-SMS-30Jan09 29 Memory Programming ......................................................................... 377 29.1 29.2 29.3 29.4 29.5 29.6 29.7 29.8 Program And Data Memory Lock Bits ...........................................................377 Fuse Bits ........................................................................................................379 Signature Bytes .............................................................................................380 Calibration Byte .............................................................................................381 Page Size ......................................................................................................381 Serial Downloading ........................................................................................381 Serial Programming Instruction set ...............................................................383 Programming via the JTAG Interface ............................................................385 30 Application Information ....................................................................... 399 30.1 30.2 30.3 30.4 Ordering Information ......................................................................................399 Typical Application .........................................................................................400 Pinout ............................................................................................................402 Mechanical Information .................................................................................405 31 Electrical Characteristics .................................................................... 409 31.1 31.2 31.3 31.4 31.5 31.6 31.7 31.8 Scope ............................................................................................................409 DC Characteristics TBC/TBD ........................................................................410 PORT .............................................................................................................410 Clocks ............................................................................................................411 Communication Interfaces .............................................................................411 USB Interface Characteristics TBC/TBD ......................................................414 Smart Card Interface Characteristics ............................................................415 USB Host Controller Characteristics .............................................................416 32 Register Summary ............................................................................... 417 33 Instruction Set Summary .................................................................... 421 34 Datasheet Revision History ................................................................ 425 34.1 34.2 Rev. AY-30Jan09 ..........................................................................................425 Rev. AX-13Nov08 ..........................................................................................425 Table of Contents.................................................................................. 427 432 AT90SCR100 TPR0327AY-SMS-30Jan09 Headquarters Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131 USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600 International Atmel Asia Unit 01-05 & 16, 19/F BEA Tower, Millennium City 5 418 Kwun Tong Road Kwun Tong, Kowloon Hong Kong Tel: (852) 2245-6100 Fax: (852) 2722-1369 Atmel Europe Le Krebs 8, Rue Jean-Pierre Timbaud BP 309 78054 Saint-Quentin-enYvelines Cedex France Tel: (33) 1-30-60-70-00 Fax: (33) 1-30-60-71-11 Atmel Japan 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581 Product Contact Web Site www.atmel.com Technical Support scr@atmel.com Sales Contact www.atmel.com/contacts Literature Requests www.atmel.com/literature Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL'S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL'S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel's products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. (c) Atmel Corporation 2008. All Rights Reserved. Atmel (R), Atmel logo and combinations thereof, AVR (R) and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others. TPR0327AY-SMS-30Jan09 |
Price & Availability of AT90SCR100LSD-Z1R |
|
|
All Rights Reserved © IC-ON-LINE 2003 - 2022 |
[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy] |
Mirror Sites : [www.datasheet.hk]
[www.maxim4u.com] [www.ic-on-line.cn]
[www.ic-on-line.com] [www.ic-on-line.net]
[www.alldatasheet.com.cn]
[www.gdcy.com]
[www.gdcy.net] |