General Features • High Performance, Low Power AVR® 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 • • • • • • • • • • • 2 – 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 (-40°C to +85°C) 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 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 1. Block Diagram Block Diagram CP CCRES L CR K ST CI O CC 4 CC , D 8, P DM Figure 1-1. PC5, JTGTDI, LED3 PC4, JTGTDO, LED2 PC3, JTGTMS, LED1 PC2, JTGTCK, LED0 PC1, SDA, INT3b PC0, SCL, INT2b PORT A Standard ISO7816 Supply Monitor USB Host Controller Keyboard Interface On-chip Debug USB DMA PORT E PE7, KbO7, PCINT31 PE6, KbO6, PCINT30 PE5, KbO5, PCINT29 PE4, KbO4, PCINT28 PE3, KbO3, PCINT27 PE2, KbO2, PCINT26 PE1, KbO1, PCINT25 PE0, KbO0, PCINT24 Smart Card Interface Watchdog Interrupt Controller cpu JTAG PORT 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 c Vc Power Management LED port TWI High-Speed SPI SRAM 4 KB FLASH 64 KB Code EEPROM 4 KB Data USART SPI AES 256 PORT B 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 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 RNG USB 8bit T/C 0 8bit T/C 2 16bit T/C 1 48MHz Timers/Counters 2 1 SC TO Note SC TO Clock Management 1 AL XT 2 AL XT USB device D UC ap RTC D+ PWM Except for the PORTC, all the other ports are connected to a Pin Change Interrupt Controller. 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 ! Caution SCR100LSD SCR100LHS Vcc x x x Vss1 x x e(1) AVss x x RST x Xtal1 x Supply SCR100H ID Portmap 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. Pin List Configuration Table 2-1. Unmapped, generic pins • PCINTx refer to Pin Change Interrupts. See “External Interrupt Registers” on page 69. Configuration, Role Vcc Voltage Supply Vss1 Ground e(1) AVss PLL Ground x x RST Reset signal: Drive low to reinitialize the chip x x - XTAL1 Vcc Clock Input: Support up to 8 Mhz crystals Xtal2 x x x XTAL2 DVcc x x x DVcc Digital Vcc:Used for internal regulator decoupling Vcc2 x x x Vcc2 Voltage Supply: To be tied to same supply voltage as Vcc Vcc3 - - x Vcc3 Voltage Supply: To be tied to same supply voltage as Vcc Vcc4 - - x Vcc4 Voltage Supply: To be tied to same supply voltage as Vcc Vcc5 - - x Vcc5 Voltage Supply: To be tied to same supply voltage as Vcc Vdcdc x x x Vdcdc Voltage Supply for DC/DC Converter. Vss2 x x e(1) Vss2 Second Vss: To be tied to Vss Vss3 x x e(1) Vss3 Third Vss: To be tied to Vss D+ x x x D+ D- x x x UCap x x x - USB USB Interface D- Reg UCap USB Decoupling: Used for specific USB regulator decoupling 5 TPR0327AY–SMS–30Jan09 Pin List Configuration - x RTC2 - - x PA7 - - x KbIN7 PCINT7 PA6 - - x KbIN6 PCINT6 PA5 - - x KbIN5 PCINT5 PA4 - - x KbIN4 PCINT4 PA3 - - x KbIN3 PCINT3 PA2 - - x KbIN2 PCINT2 PA1 - - x KbIN1 PCINT1 PA0 - - x KbIN0 PCINT0 PB7 x - x SCK OC2A PCINT15 PB6 x - x MISO OC2B PCINT14 PB5 x - x MOSI OC1A PCINT13 PB4 x - x SS OC0B PCINT12 PB3 - - x PWM OC0A PCINT11 PORT A PORT B PORT C(3) PORT D 6 Supply - SCR100H SCR100LHS RTC1 Portmap ID SCR100LSD Table 2-1. Configuration, Role TOSC1 Vcc TOSCx: 32.768 Khz crystals input for Real Time Clock. (Please note that these pins are not GPIO accessible). TOSC2 Vcc Vcc ICP1 PCINT10 KbINx: Input for “Keyboard Interface” 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” PB2 - - x PB1 - - x INT3 T1 CLKO PCINT9 PB0 - - x INT2 T0 XCK PCINT8 PC5 - - x JTGTDI LED3 PC4 - - x JTGTDO LED2 JTGxxx: “JTAG Interface and On-chip Debug System” PC3 - - x JTGTMS LED1 SDA, SCL: “2-wire Serial Interface _ TWI” signals PC2 x x x JTGTCK LED0 PC1 - - x SDA INT3b PC0 - - x SCL INT2b PD7 - x x HSMISO PCINT23 PD6 - x x HSMOSI PCINT22 PD5 - x x HSSCK PCINT21 PD4 - x x HSSS PCINT20 PD3 - - x INT1 PCINT19 TXD, RXD: “USART” signals PD2 - - x INT0 PCINT18 OCxB: Output Comparators: See “Timers” on page 87. PD1 x x x TXD PCINT17 PD0 x x x RXD PCINT16 Vcc Vcc OC1B INTx: “External Interrupts” , default configuration CLKO: System clock output. (only active if CKOUT fuse is enabled). “Fuse Low Byte” . LEDx: “LED” Outputs (IO driving current) INTxb: “External Interrupts” , bis configuration HSxxxx: “High-Speed SPI Controller” (MISO, MOSI, SCK, SS) INTx: “External Interrupts” , default configuration AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Pin List Configuration - - x KbO7 PCINT31 PE6 - - x KbO6 PCINT30 PE5 - - x KbO5 PCINT29 PE4 - - x KbO4 PCINT28 PE3 - - x KbO3 PCINT27 PE2 - - x KbO2 PCINT26 PE1 - - x KbO1 PCINT25 PE0 - - x KbO0 PCINT24 x x x x x x x x x x x x x x x x x x CC8, DM x x x CVcc x x x x x (1) x x x LI x x x LO Smart Card PORT PORT E Notes: Supply SCR100H SCR100LHS PE7 Portmap ID SCR100LSD Table 2-1. Configuration, Role e Vcc Vcc KbOx: Output for “Keyboard Interface” CPRES CCLK CVcc CRST CIO (2) Cx: “Smart Card Interface Block (SCIB)” : Standard ISO7816 port and “USB Host Controller” . CC4, DP CVSense CVcc CVss Smart Card Interface: “DC/DC Converter” Supply Signals 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 32 x 8 General Purpose Registrers Instruction Register Indirect Addressing Control Lines Direct Addressing Instruction Decoder Interrupt Unit SPI Unit Watchdog Timer ALU 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 7 6 5 4 3 2 1 0 0x3F (0x5F) I T H S V N Z C Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 SREG 0x00 • 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 0 Addr. R0 0x00 R1 0x01 R2 0x02 … R13 0x0D General R14 0x0E Purpose R15 0x0F Working R16 0x10 Registers R17 0x11 … R26 0x1A X-register Low Byte R27 0x1B X-register High Byte R28 0x1C Y-register Low Byte R29 0x1D Y-register High Byte R30 0x1E Z-register Low Byte R31 0x1F Z-register High Byte Most of the instructions operating on the Register File have direct access to all registers, and most of them are single cycle instructions. As shown in Figure 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 16 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. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Figure 5-3. The X-, Y-, and Z-registers 15 X-register XH XL 7 0 R27 (0x1B) YH YL 7 0 R29 (0x1D) 0 7 0 R28 (0x1C) 15 Z-register 0 R26 (0x1A) 15 Y-register 0 7 ZH ZL 7 0 R31 (0x1F) 0 7 0 R30 (0x1E) 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 15 13 12 11 10 9 8 0x3E (0x5E) - - - SP12 SP11 SP10 SP9 SP8 SPH 0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPH 7 6 5 4 3 2 1 0 R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 1 0 0 0 0 0x10 1 1 1 1 1 1 1 1 0xFF Read/write Initial value 5.7 14 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 ; store SREG value ; disable interrupts during timed sequence sbi EECR, EEMPE ; start EEPROM write sbi EECR, EEPE out SREG, r16 ; restore SREG value (I-bit) C Code Example char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ __disable_interrupt(); EECR |= (1<<EEMPE); /* start EEPROM write */ EECR |= (1<<EEPE); SREG = cSREG; /* restore SREG value (I-bit) */ When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example. 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. Full Memory Map Program Memory EEPROM Memory 0x7FFF 0x1000 Boot Flash Section 0x7000 0x6FFF EEPROM Data Memory 0x0000 Data Memory 0x10FF Application Flash Section SRAM Memory Peripheral Registers IO Registers 32 General Purpose Working Registers 0x0000 16 bits 6.2 0x0100 0x00FF 0x0060 0x005F 0x0020 0x001F 0x0000 8 bits 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 Compute Address Address valid Write Data WR Read Data RD Memory Access Instruction 6.3 Next Instruction 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 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) 15 14 13 12 - - - - 0x21 (0x41) 11 10 9 8 EEAR [11..8] EEARH EEAR [7..0] EEARL Bit 7 6 5 4 3 2 1 0 Read/write R R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 x x x x x x x x x x x x Initial value • 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 7 6 5 4 Read/write R/W R/W R/W R/W Initial value 0 0 0 0 0x20 (0x40) 3 2 1 0 R/W R/W R/W R/W 0 0 0 0 EEDR [7..0] EEDR 0x00 • 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 7 6 5 4 3 2 1 0 0x1F (0x3F) - - EEPM1 EEPM0 EERIE EEMPE EEPE EERE Read/write R R R/W R/W R/W R/W R/W R/W Initial value 0 0 x x 0 0 x 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. EEPROM Mode Bits EEPM1 EEPM0 Programming Time 0 0 3.4 ms TBC Erase and Write in one operation (Atomic Operation) 0 1 1.8 ms TBC Erase Only 1 0 1.8 ms TBC Write Only 1 1 – Operation 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. ! Caution 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. 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. 6.3.5 26 EEPROM Programming Time Symbol Number of Calibrated RC Oscillator Cycles Typ Programming Time EEPROM write (from CPU) 26,368 TBC 3.3 ms TBC 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. 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<<EEPE)) ; /* Set up address and Data Registers */ EEAR = uiAddress; EEDR = ucData; /* Write logical one to EEMPE */ EECR |= (1<<EEMPE); /* Start eeprom write by setting EEPE */ EECR |= (1<<EEPE); } 27 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 r16,EEDR ret C Code Example unsigned char EEPROM_read(unsigned int uiAddress) { /* Wait for completion of previous write */ while(EECR & (1<<EEPE)) ; /* Set up address register */ EEAR = uiAddress; /* Start eeprom read by writing EERE */ EECR |= (1<<EERE); /* Return data from Data Register */ return EEDR; } 6.3.6 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. 6.4.2 GPIOR2 – General Purpose I/O Register 2 Bit 7 6 5 0x2B (0x4B) 6.4.3 4 3 2 1 0 GPIOR2 [7..0] GPIOR2 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 5 4 3 2 1 0 0x00 GPIOR1 – General Purpose I/O Register 1 Bit 7 6 0x2A (0x4A) GPIOR1 [7..0] GPIOR1 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 29 TPR0327AY–SMS–30Jan09 6.4.4 GPIOR0 – General Purpose I/O Register 0 Bit 7 6 5 0x1E (0x3E) 30 4 3 2 1 0 GPIOR0 [7..0] GPIOR0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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. TOSC1 Clock Distribution clk ASY (2) Tn Clock Controller T1 clk Tn (2) T0 clk I/O clk XTAL clk PLL (1) IOx Clock Controller Tn 0 (2) (default) PRR0.PR (IOx) 1 IOx 0 (1) (default) PLL Clock clkMUX Multi-plexer Core Divider clk CPU clk Core CPU Core (by 1, 4, 5, 6, 8, 12, 24, 48, 96) (Divider by 1 Only for Clk XTAL) clk Flash Glitches free clk Write_Flash Internal RC Oscillator 96Mhz PLL PRR0.PR (Tx) 1 HS SPI Divider clk HSSPI Flash & Eeprom PRR1.PRHSSPI 1 0 (default) High Speed SPI Block (by 4, 5, 6, 8, 12, 24, 48, 96) XTAL1 clk XTAL SCI Divider clk SCI PRR1.PRSCI 1 0 (default) Smart Card Interface Block (by 8, 12, 16, 20, 24, 48, ...) XTAL2 x 1/2 clk USB 48Mhz PRR1.PRUSB 1 0 (default) USB PRR1.PRSCUSB 1 0 (default) USB Host Controller (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. 7.1.3 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. Note 7.1.4 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. 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. 7.1.6 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. Note 32 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. 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) Device Clocking Option Low Power Crystal Oscillator 1 External Clock 0 Notes: 7.2.1 CKSEL3 1. For all fuses “1” means unprogrammed while “0” means programmed. 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 = 5.0V) Typ Time-out (VCC = 3.0V) Number of Cycles 0 ms 0 ms 0 4.1 ms 4.3 ms 512 65 ms 69 ms 8K (8,192) 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 7.2.3.1 C2 = 47pF 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 Additional Delay from Reset (VCC = 5.0V) CKSEL0 SUT1..0 Ceramic resonator, fast rising power 258 CK 14CK + 4.1 ms(1) 0 00 Ceramic resonator, slowly rising power 258 CK 14CK + 65 ms(1) 0 01 Ceramic resonator, BOD enabled 1K CK 14CK(2) 0 10 Ceramic resonator, fast rising power 1K CK 14CK + 4.1 ms(2) 0 11 Ceramic resonator, slowly rising power 1K CK 14CK + 65 ms(2) 1 00 Crystal Oscillator, BOD enabled 16K CK 14CK 1 01 Crystal Oscillator, fast rising power 16K CK 14CK + 4.1 ms 1 10 Crystal Oscillator, slowly rising power 16K CK 14CK + 65 ms 1 11 Oscillator Source / Power Conditions Notes: 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 Start-up Times for the External Clock Selection Table 7-4. Start-up Time from Powerdown and Power-save Additional Delay from Reset (VCC = 5.0V) SUT1..0 BOD enabled 6 CK 14CK 00 Fast rising power 6 CK 14CK + 4.1 ms 01 Slowly rising power 6 CK 14CK + 65 ms 10 Power Conditions Reserved 11 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. Note 7.2.4 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. 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. ! These values are preliminary values representing design targets, and will be updated after characterization of the silicon Caution Calibrated 8 MHz RC Oscillator Frequency vs. Temperature Figure 7-5. CALIBRATED 8 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE 8,3 5.5V 5.0V 4.5V 4.0V 3.3V 2.7V 8,2 FRC (MHz) 8,1 8 7,9 7,8 7,7 -60 -40 -20 0 20 40 60 80 100 Temperature Calibrated 8 MHz RC Oscillator Frequency vs. Operating Voltage Figure 7-6. CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. OPERATING VOLTAGE 8,5 8,4 8,3 85°C FRC (M Hz ) 8,2 8,1 25°C 8 7,9 7,8 -40°C 7,7 7,6 7,5 1,5 2 2,5 3 3,5 4 4,5 5 5,5 V CC (V) 38 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 7.2.5.2 OSCCAL – Oscillator Calibration Register Bit $000066 Read/write 7 6 5 4 3 2 1 0 CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 R/W R/W R/W R/W R/W R/W R/W R/W Initial value 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 7 6 5 4 3 2 1 0 PLLMUX - - - - - LOCK ON Read/write R/W R R R R R R R/W Initial value 0 0 0 0 0 0 0 0 $000062 PLLCR 0x00 • 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. ! Caution 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 7 6 5 4 3 2 $000061 - - - - CLKPS3 CLKPS2 1 0 Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 CLKPS1 CLKPS0 CLKPR 0x00 • 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. Clock Prescaler Select (clkCPU) CLKPS3 CLKPS2 CLKPS1 CLKPS0 CLKPR Clock Division Factor clkCPU (clkMUX = clkPLL)(1) clkCPU (clkMUX = clkXTAL)(2) 0 0 0 0 0x00 1(3) 16Mhz(3) 8Mhz 0 0 0 1 0x01 4 24Mhz 2Mhz 0 0 1 0 0x02 5 19.2Mhz 1.60Mhz 0 0 1 1 0x03 6 16Mhz 1.33Mhz 0 1 0 0 0x04 8 12Mhz 1Mhz 0 1 0 1 0x05 12 8Mhz 0.67Mhz 0 1 1 0 0x06 24 4Mhz 0.33Mhz 0 1 1 1 0x07 48 2Mhz 0.17Mhz 1 0 0 0 0x08 96 1Mhz 0.08Mhz 1 0 0 1 0x09 1 0 1 0 0x0A 1 0 1 1 0x0B 1 1 0 0 0x0C 1 1 0 1 0x0D 1 1 1 0 0x0E 1 1 1 1 0X0F Notes: 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 ! Caution Note 8.1.1 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. 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. ! Caution 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. 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. 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. X X(1) Power-down Power-save Standby X Extended Standby Notes: X(1) X (1) X X (1) X X X (2) X X X(2) X X(2) X (2) X X X X X X X X X X X X X X Other I/O X WDT Interrupt X pressed Timer2 request Communication Coherent Pin Change INT3:0 clkASY X Keyboard Pin X Wake-up Sources SPM/ EEPROM Ready X Oscillators clkHSSPI, clkUSB clkI/O clkFlash, clkSCI Sleep Mode Idle clkCPU Active Clock Domains Timer Osc Enabled Table 8-1. Main Clock Source Enabled 8.1.5 X 1. If Timer/Counter2 is running in asynchronous mode. 2. For INT3:0, only level interrupt. 44 AT90SCR100 TPR0327AY–SMS–30Jan09 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 7 6 5 4 3 2 1 0 0x33 (0x53) - - - - SM2 SM1 SM0 SE Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 SMCR 0x00 • 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. Note: Sleep Mode Select SM2 SM1 SM0 Sleep Mode 0 0 0 Idle 0 0 1 Reserved 0 1 0 Power-down 0 1 1 Power-save 1 0 0 Reserved 1 0 1 Reserved 1 1 0 Standby(1) 1 1 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 7 6 5 4 3 2 1 0 PRTWI PRTIM2 PRTIM0 - PRTIM1 PRSPI PRUSART0 - Read/write R/W R/W R/W R R/W R/W R/W R Initial value 0 0 0 0 0 0 0 0 $000064 PRR0 0x00 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 7 6 5 4 3 2 1 0 $000065 - - PRKB PRAES PRSCI PRHSSPI PRUSB PRUSBH Read/write R/W R/W R/W R R/W R/W R/W R Initial value 0 0 0 0 0 0 0 0 PRR1 0x00 • 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 8.4 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. 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. 8.4.2 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. 8.4.3 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. 8.4.4 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.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 PORF BORF EXTRF WDRF JTRF MCU Status Register (MCUSR) Power-on Reset Circuit Brown-out Reset Circuit BODLEVEL Pull-up Resistor SPIKE FILTER JTAG Reset Register Watchdog Oscillator Clock Controller CK Delay Counters TIMEOUT SUT[1:0] Table 9-1. Symbol VPOT Parameter Condition Min Typ Max Units Power-on Reset Threshold Voltage (rising) 1.4 1.8 V Power-on Reset Threshold Voltage (falling)(2) 1.3 1.8 V 0.2VCC V 1.5 μs RESET Pin ViL VRST RESET Pin ViH Minimum pulse width on RESET Pin tRST Notes: Reset Characteristics(1) 0.85VCC 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 52 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. 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 RESET MCU Start-up, RESET Tied to VCC V POT V RST tTOUT TIME-OUT INTERNAL RESET Figure 9-3. V CC RESET TIME-OUT MCU Start-up, RESET Extended Externally V POT V RST 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 External Reset During Operation Figure 9-4. CC 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 BODENABLE Fuse Table 9-3. Min VBOT Typ VBOT 1 BOD Disabled 0 2.3 V Max VBOT Brown-out Characteristics Symbol Parameter VHYST Brown-out Detector Hysteresis tBOD 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 VBOT- VBOT+ RESET tTOUT TIME-OUT 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. Watchdog Reset During Operation CC 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: 9.4 Internal Voltage Reference Characteristics(1) Parameter Condition Reference start-up time VCC = 2.7 TA = 25°C Min Typ Max Units 40 70 μs 1. Values are guidelines only. Actual values are TBD. 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. Supply Monitor References Symbol Parameter Min Typ Max Units VSMON Supply Monitor Level 2.5 V VSMHYST Supply Monitor Hysteresis 50 mV tSMON Min Pulse Width on Brown-out Reset 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 Watchdog Timer 125kHz OSCILLATOR WATCHDOG RESET WDE OSC/2K OSC/4K OSC/8K OSC/16K OSC/32K OSC/64K OSC/128K OSC/256K OSC/512K OSC/1024K Figure 9-8. WDP0 WDP1 WDP2 WDP3 MCU RESET WDIF WDIE INTERRUPT 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 r16, MCUSR andi r16, (0xff & (0<<WDRF)) out MCUSR, r16 ; Write logical one to WDCE and WDE ; Keep old prescaler setting to prevent unintentional time-out in r16, WDTCSR ori r16, (1<<WDCE) | (1<<WDE) out WDTCSR, r16 ; Turn off WDT ldi r16, (0<<WDE) out WDTCSR, r16 ; Turn on global interrupt sei ret C Code Example void WDT_off(void) { __disable_interrupt(); __watchdog_reset(); /* Clear WDRF in MCUSR */ MCUSR &= ~(1<<WDRF); /* Write logical one to WDCE and WDE */ /* Keep old prescaler setting to prevent unintentional time-out */ WDTCSR |= (1<<WDCE) | (1<<WDE); /* Turn off WDT */ WDTCSR = 0x00; __enable_interrupt(); } 58 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 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. Note 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 r16, WDTCSR ori r16, (1<<WDCE) | (1<<WDE) out WDTCSR, r16 ; -- Got four cycles to set the new values from here - ; Set new prescaler(time-out) value = 64K cycles (~0.5 s) ldi r16, (1<<WDE) | (1<<WDP2) | (1<<WDP0) out WDTCSR, r16 ; -- Finished setting new values, used 2 cycles - ; Turn on global interrupt sei ret C Code Example void WDT_Prescaler_Change(void) { __disable_interrupt(); __watchdog_reset(); /* Start timed Sequence */ WDTCSR |= (1<<WDCE) | (1<<WDE); /* Set new prescaler(time-out) value = 64K cycles (~0.5 s) */ WDTCSR = (1<<WDE) | (1<<WDP2) | (1<<WDP0); __enable_interrupt(); } Note 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 7 6 5 4 3 2 1 0 0x34 (0x54) - - - JTRF WDRF BORF EXTRF PORF Read/write R R R R/W R/W R/W R/W R/W Initial value 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 7 0x0063 6 SMONIF SMONIE 5 4 3 2 1 - - - - - 0 SMONEN SMONCR Read/write R/W R/W R R R R R R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 4 3 2 1 0 WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $000060 WDTCSR 0x00 • 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. Watchdog Timer Configuration WDTON(1) WDE WDIE 0 0 0 Mode Action on Time-out 0 Stopped None 0 1 Interrupt Mode Interrupt 0 1 0 System Reset Mode Reset 0 1 1 Interrupt and System Reset Mode Interrupt, then go to System Reset Mode 1 x x System Reset Mode Reset Notes: 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. Watchdog Timer Prescale Select Table 9-7. 62 WDP3 WDP2 WDP1 WDP0 Number of WDT Oscillator Cycles Typical Time-out at VCC = 5.0V 0 0 0 0 2K (2048) cycles 15.625 ms 0 0 0 1 4K (4096) cycles 31.25 ms 0 0 1 0 8K (8192) cycles 62.5 ms 0 0 1 1 16K (16384) cycles 0.122 s 0 1 0 0 32K (32768) cycles 0.24 s 0 1 0 1 64K (65536) cycles 0.48 s 0 1 1 0 128K (131072) cycles 0.97 s 0 1 1 1 256K (262144) cycles 1.95 s 1 0 0 0 512K (524288) cycles 3.9 s 1 0 0 1 1024K (1048576) cycles 7.81 s 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 Reserved 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. Reset and Interrupt Vectors Vector No. Program Address(1) Source Interrupt Definition 1 $0000(2) RESET External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, and JTAG AVR Reset 2 $0002 INT0 External Interrupt Request 0 3 $0004 INT1 External Interrupt Request 1 4 $0006 INT2 External Interrupt Request 2 5 $0008 INT3 External Interrupt Request 3 6 $000A PCINT0 Pin Change Interrupt Request 0 7 $000C PCINT1 Pin Change Interrupt Request 1 8 $000E PCINT2 Pin Change Interrupt Request 2 9 $0010 WDT 10 $0012 TIMER2_COMPA Timer/Counter2 Compare Match A 11 $0014 TIMER2_COMPB Timer/Counter2 Compare Match B 12 $0016 TIMER2_OVF 13 $0018 TIMER1_CAPT 14 $001A TIMER1_COMPA Timer/Counter1 Compare Match A 15 $001C TIMER1_COMPB Timer/Counter1 Compare Match B 16 $001E TIMER1_OVF 17 $0020 TIMER0_COMPA Timer/Counter0 Compare Match A 18 $0022 TIMER0_COMPB Timer/Counter0 Compare Match B 19 $0024 TIMER0_OVF 20 $0026 SPI_STC 21 $0028 USART_RX 22 $002A USART_UDRE 23 $002C USART_TX 24 $002E SUPPLY_MON 25 -- RFU 26 $0032 EE_READY 27 $0034 TWI 28 $0036 SPM_READY Watchdog Time-out Interrupt Timer/Counter2 Overflow Timer/Counter1 Capture Event Timer/Counter1 Overflow 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 Reset and Interrupt Vectors (Continued) Table 10-1. Vector No. Program Address(1) Source 29 $0038 KEYBOARD 30 $003A AES 31 $003C HSSPI 32 $003E USB Endpoint USB Endpoint linked Interrupt 33 $0040 USB Protocol USB Protocol Interrupt 34 $0042 SCIB Smart Card Reader Interface 35 $0044 USB Host Control USB Host Controller Interrupt 36 $0046 USB Host Pipe USB Host Pipe Interrupt 37 $0048 CPRES Card Presence Detection $004A PCINT3 Pin Change Interrupt Request 3 38 Notes: Interrupt Definition Keyboard Input Changed AES Block Operation Ended High-Speed SPI Interface 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. Reset and Interrupt Vectors Placement(1) BOOTRST IVSEL 1 Note: Reset Address Interrupt Vectors Start Address 0 0x0000 0x0002 1 1 0x0000 Boot Reset Address + 0x0002 0 0 Boot Reset Address 0x0002 0 1 Boot Reset Address 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 64 Labels Code jmp jmp jmp jmp jmp jmp jmp Comments RESET INT0 INT1 INT2 INT3 PCINT0 PCINT1 ; ; ; ; ; ; ; Reset Handler IRQ0 Handler IRQ1 Handler IRQ2 Handler IRQ3 Handler PCINT0 Handler PCINT1 Handler 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 ... RESET: ... 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 PCINT2 WDT TIM2_COMPA TIM2_COMPB TIM2_OVF TIM1_CAPT TIM1_COMPA TIM1_COMPB TIM1_OVF TIM0_COMPA TIM0_COMPB TIM0_OVF SPI_STC USART0_RXC USART0_UDRE USART0_TXC SUPPLY_MON NO_VECT EE_RDY TWI SPM_RDY KEYBOARD AES HSSPI USB_Endpoint USB_Protocol SCIB USB_Host_Ctl USB_Host_Pipe CPRES PCINT3 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; PCINT2 Handler Watchdog Timeout Handler Timer2 CompareA Handler Timer2 CompareB Handler Timer2 Overflow Handler Timer1 Capture Handler Timer1 CompareA Handler Timer1 CompareB Handler Timer1 Overflow Handler Timer0 CompareA Handler Timer0 CompareB Handler Timer0 Overflow Handler SPI Transfer Complete USART0 RX Complete Handler USART0,UDR Empty Handler USART0 TX Complete Handler Vcc dropped too low Vector Forbidden EEPROM Ready Handler 2-wire Serial Handler SPM Ready Handler Keyboard Handler Crypto AES Handler HighSPI IT Handler USB Endpoint IT Handler USB Protocol IT Handler Smart Card Interface IT USB Host Controller IT USB Host Pipe IT Card inserted/removed PCINT3 Handler ldi out r16, high(RAMEND) SPH,r16 ; Main program start ; Set Stack Pointer to top of RAM ldi out sei <instr> ... r16, low(RAMEND) SPL,r16 ; Enable interrupts xxx ... 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 Comments 0x00000 RESET: ldi r16,high(RAMEND); Main program start 0x00001 SPH,r16 out ; Set Stack Pointer to top of RAM 65 TPR0327AY–SMS–30Jan09 0x00002 ldi r16,low(RAMEND) 0x00003 0x00004 out sei SPL,r16 0x00005 <instr> ; Enable interrupts xxx ; .org 0x1F002 0x1F002 jmp EXT_INT0 ; IRQ0 Handler 0x1F004 jmp EXT_INT1 ; IRQ1 Handler ... ... ... ; 0x1FO36 jmp SPM_RDY ; 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 Comments .org 0x0002 0x00002 jmp EXT_INT0 ; IRQ0 Handler 0x00004 jmp EXT_INT1 ; IRQ1 Handler ... ... ... ; 0x00036 jmp SPM_RDY ; SPM Ready Handler ; .org 0x1F000 0x1F000 RESET: ldi r16,high(RAMEND); Main program start 0x1F001 out SPH,r16 0x1F002 ldi r16,low(RAMEND) 0x1F003 0x1F004 out sei SPL,r16 0x1F005 <instr> ; Set Stack Pointer to top of RAM ; Enable interrupts xxx 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 Comments ; .org 0x1F000 0x1F000 0x1F002 jmp jmp RESET EXT_INT0 ; Reset handler ; IRQ0 Handler 0x1F004 jmp EXT_INT1 ; IRQ1 Handler ... ... ... ; 0x1F036 jmp SPM_RDY ; SPM Ready Handler ; 66 0x1F03E RESET: ldi r16,high(RAMEND); Main program start 0x1F03F out SPH,r16 0x1F040 ldi r16,low(RAMEND) 0x1F041 0x1F042 out sei SPL,r16 0x1FO43 <instr> ; Set Stack Pointer to top of RAM ; Enable interrupts xxx 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. 10.1.2 MCUCR – MCU Control Register Bit 7 6 5 4 3 2 1 0 0x35 (0x55) JTD - - PUD - - IVSEL IVCE Read/write R/W R R R/W R R R/W R/W Initial value 0 0 0 0 0 0 0 0 MCUCR 0x00 • 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. Note 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. • 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<<IVCE) out MCUCR, r16 ; Move interrupts to Boot Flash section ldi r17, (1<<IVSEL) out MCUCR, r17 ret C Code Example void Move_interrupts(void) { uchar temp; /* Get MCUCR */ temp = MCUCR; /* Enable change of Interrupt Vectors */ MCUCR = temp|(1<<IVCE); /* Move interrupts to Boot Flash section */ MCUCR = temp|(1<<IVSEL); } 68 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 7 6 5 4 3 2 1 0 ISC31 ISC30 ISC21 ISC20 ISC11 ISC10 ISC01 ISC00 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $000069 EICRA 0x00 • 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. Interrupt Sense Control(1) Table 11-1. ISCn1 ISCn0 0 0 The low level of INTn generates an interrupt request. 0 1 Any edge of INTn generates asynchronously an interrupt request. 1 0 The falling edge of INTn generates asynchronously an interrupt request. 1 1 The rising edge of INTn generates asynchronously an interrupt request. Note: 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 Asynchronous External Interrupt Characteristics Parameter Condition Min Minimum pulse width for asynchronous external interrupt tINT 11.1.2 Description Typ 50 Max Units ns EIMSK – External Interrupt Mask Register Bit 7 6 5 4 3 2 1 0 0x1D (0x3D) - - - - INT3 INT2 INT1 INT0 Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 EIMSK 0x00 • 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 7 6 5 4 3 2 1 0 0x1C (0x3C) - - - - INTF3 INTF2 INTF1 INTF0 Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 EIFR 0x00 • 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 7 6 5 4 3 2 1 0 0x1A (0x3A) - - - - INTD3 INTD2 - - Read/write R R R R R/W R/W R R Initial value 0 0 0 0 0 0 0 0 EIRR 0x00 • 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. External Interruption 3 Pad location INTD3 Interruption 3 Pad Description 0 PB1 INT3 active, INT3b inactive 1 PC1 INT3 inactive, INT3b active • Bit 2 – INTD2 : External Interruption 2 Direction This bit is set and cleared by software. Table 11-4. 11.1.5 External Interruption 2 Pad location INTD3 Interruption 3 Pad Description 0 PB0 INT2 active, INT2b inactive 1 PC0 INT2 inactive, INT2b active PCICR – Pin Change Interrupt Control Register Bit 7 6 5 4 3 2 1 0 0x68 - - - - PCIE3 PCIE2 PCIE1 PCIE0 Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 PCICR 0x00 • 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 7 6 5 4 3 2 1 0 0x1B (0x3B) - - - - PCIF3 PCIF2 PCIF1 PCIF0 Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 PCIFR 0x00 • 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 7 0x000073 6 5 4 3 2 1 0 PCINT31 PCINT30 PCINT29 PCINT28 PCINT27 PCINT26 PCINT25 PCINT24 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 PCMSK3 0x00 • 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 7 0x00006D 6 5 4 3 2 1 0 PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 PCMSK2 0x00 • 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 7 0x00006C 6 5 4 3 2 1 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 0 PCINT8 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 PCMSK1 0x00 • 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 7 6 5 4 3 2 1 0 0x00006B PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 PCMSK0 0x00 • 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 Logic Pxn 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 NMOS N N Port Latch Data CTRL Power Management Control SMCR + CPU status The current limitation of the CTRL block requires a polarisation current of about 250μA. 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 N LEDCR LEDn.0 LEDn.1 Port Latch Data 1. When switching a low level, LEDCR device has a permanent current of about N mA/15 (N is 2 or 4) Note 76 2. The port must be configured and driven as standard IO port. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 LED Configuration Table 12-1. Notes: 12.3.1 LEDx.1 LEDx.0 Port Latch Data NMOS PIN 0 0 0 1 0 0 0 1 0 1 0 1 0 0 0 0 1 1 0 1 1 0 0 0 0 1 0 1 0 1 Comments LED control disabled(1) LED mode 2 mA LED mode 4 mA 1. When LED control disabled, a current of ~8mA is provided on the port. LEDCR - LED Control Register Bit 7 $000075 LED3 [1..0] 6 5 LED2 [1..0] 4 3 2 Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 LED1 [1..0] 1 0 LED0 [1..0] LEDCR 0x00 • Bit 7..6, 5..4, 3..2, 1..0 - LEDn [1..0]: LED Port configuration bits Table 13-1 .LED Port Selection LEDn1 LEDn0 Description 0 0 LED control disabled 0 1 2 mA Current Source 1 0 4 mA Current Source 1 1 Reserved Configuration Note 12.4 For implementation example, please see section “Typical Application” on page 400. 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 WDx RESET DATA BUS RDx 1 Q Pxn D 0 PORTxn Q CLR RESET WRx SLEEP WPx RRx SYNCHRONIZER D Q L Q D RPx Q PINxn Q clk I/O PUD: SLEEP: clk I/O : Note 12.4.1 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 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. 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 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. 12.4.3 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. 12.4.4 Port Pin Configurations DDxn PORTxn PUD (in MCUCR) I/O Pull-up 0 0 X Input No Tri-state (Hi-Z) 0 1 0 Input Yes Pxn will source current if ext. pulled low. 0 1 1 Input No Tri-state (Hi-Z) 1 0 X Output No Output Low (Sink) 1 1 X Output No Output High (Source) Comment 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 XXX XXX in r17, PINx SYNC LATCH PINxn r17 0x00 0xFF t pd, max t pd, min Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between ½ and 1½ system clock period depending upon the time of assertion. When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 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 0xFF out PORTx, r16 nop in r17, PINx SYNC LATCH PINxn r17 0x00 0xFF t pd The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin 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 r16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0) ldi r17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0) out PORTB,r16 out DDRB,r17 ; Insert nop for synchronization nop ; Read port pins in r16,PINB ... C Code Example(1) unsigned char i; ... /* Define pull-ups and set outputs high */ /* Define directions for port pins */ PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0); DDRB = (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0); /* Insert nop for synchronization*/ __no_operation(); /* Read port pins */ i = PINB; ... Note: 12.4.5 1. For the assembly program, two temporary registers are used to minimize the time from pullups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. 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 7 6 5 4 3 2 1 0 0x35 (0x55) JTD - - PUD - - IVSEL IVCE Read/write R/W R R R/W R R R/W R/W Initial value 0 0 0 0 0 0 0 0 MCUCR 0x00 • 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 7 6 5 0x02 (0x22) 12.5.2 4 PORTA R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 5 4 3 2 1 0 0x00 DDRA – Port A Data Direction Register 7 6 DDA [7..0] DDRA Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 3 2 1 0 0x00 PINA – Port A Input Pins Address 7 6 5 4 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value N/A N/A N/A N/A N/A N/A N/A N/A 6 5 4 3 2 1 0 0x00 (0x20) PINA [7..0] PINA PORTB – Port B Data Register Bit 7 0x05 (0x25) PORTB [7..0] PORTB Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 3 2 1 0 0x00 DDRB – Port B Data Direction Register Bit 7 6 5 4 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 5 4 3 2 1 0 0x04 (0x24) 12.5.6 0 R/W Bit 12.5.5 1 R/W 0x01 (0x21) 12.5.4 2 Read/write Bit 12.5.3 3 PORTA [7..0] DDB [7..0] DDRB 0x00 PINB – Port B Input Pins Address Bit 7 6 0x03 (0x23) PINB [7..0] PINB Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value N/A N/A N/A N/A N/A N/A N/A N/A 83 TPR0327AY–SMS–30Jan09 12.5.7 12.5.8 PORTC – Port C Data Register Bit 7 6 0x08 (0x28) - - Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 12.5.10 5 4 3 2 1 0 7 6 0 PORTC - - R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 5 4 3 2 1 0 DDC [5..0] 0x00 DDRC 0x00 PINC – Port C Input Pins Address Bit 7 6 0x06 (0x26) - - Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value N/A N/A N/A N/A N/A N/A N/A N/A 6 5 4 3 2 1 0 PINC [5..0] PINC PORTD – Port D Data Register 7 PORTD [7..0] PORTD Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 5 4 3 2 1 0 0x00 DDRD – Port D Data Direction Register 7 6 0x0A (0x2A) DDD [7..0] DDRD Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 3 2 1 0 0x00 PIND – Port D Input Pins Address Bit 7 6 5 4 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value N/A N/A N/A N/A N/A N/A N/A N/A 6 5 4 3 2 1 0 0x09 (0x29) PIND [7..0] PIND PORTE – Port E Data Register Bit 7 0x0E (0x2E) 84 1 Read/write Bit 12.5.13 2 PORTC [5..0] 0x0B (0x2B) 12.5.12 3 0x07 (0x27) Bit 12.5.11 4 DDRC – Port C Data Direction Register Bit 12.5.9 5 PORTE [7..0] PORTE Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 12.5.14 DDRE – Port E Data Direction Register Bit 7 6 5 4 0x0D (0x2D) 12.5.15 3 2 1 0 DDE [7..0] DDRE Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 3 2 1 0 0x00 PINE – Port E Input Pins Address Bit 7 6 5 4 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value N/A N/A N/A N/A N/A N/A N/A N/A 0x0C (0x2C) PINE [7..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: • • • • • • • 13.1.1 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) 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 TOVn (Int.Req.) Control Logic clk T0 Clock Select Edge Detector TOP T0 BOTTOM ( From Prescaler ) Timer/Counter TCNT0 = =0 OC0A (Int.Req.) Waveform Generation = OC0A OCR0A DATA BUS Fixed TOP Value Waveform Generation = OC0B OCR0B TCCR0A 13.1.1.1 OC0B (Int.Req.) TCCR0B 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. Definitions BOTTOM The counter reaches the BOTTOM when it becomes 0x00. MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255). TOP The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0A Register. The assignment is dependent on the mode of operation. 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. 13.1.3 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 TOV0 (Int.Req.) DATA BUS Clock Select count clear TCNT0 Control Logic clk Tn Edge Detector T0 direction ( From Prescaler ) bottom top Signal description (internal signals): count Increment or decrement TCNT0 by 1. direction Select between increment and decrement. clear Clear TCNT0 (set all bits to zero). clkTn Timer/Counter clock, referred to as clkT0 in the following. top Signifies that TCNT0 has reached maximum value. bottom 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 Waveform Generator OC0x FOC0x 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). 13.1.4.2 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. 13.1.4.3 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”. 91 TPR0327AY–SMS–30Jan09 Figure 13-4. Compare Match Output Unit, Schematic COM0x1 COM0x0 FOC0n Waveform Generator D Q 1 OC0x DATA BUS D 0 OC0x Pin Q 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 (COM0x1:0 = 1) 1 2 3 4 An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is 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 (COM0x1:0 = 2) OC0x (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 (COM0x1:0 = 2) OC0x (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 OCR0x + 1 OCR0x + 2 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) TOP - 1 TOP BOTTOM OCR0x BOTTOM + 1 TOP OCF0x 13.1.9 13.1.9.1 8-bit Timer/Counter0 Register Description TCCR0A – Timer/Counter Control Register A Bit 7 0x24 (0x44) 6 5 4 COM0A1 COM0A0 COM0B1 COM0B0 3 2 1 0 - - WGM01 WGM00 Read/write R/W R/W R/W R/W R R R/W R/W Initial value 0 0 0 0 0 0 0 0 TCCR0A 0x00 • 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. Compare Output Mode, non-PWM Mode COM0A1 COM0A0 Description 0 0 Normal port operation, OC0A disconnected. 0 1 Toggle OC0A on Compare Match 1 0 Clear OC0A on Compare Match 1 1 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. Compare Output Mode, Fast PWM Mode(1) COM0A1 COM0A0 0 0 Normal port operation, OC0A disconnected. 0 1 WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. 1 0 Clear OC0A on Compare Match, set OC0A at BOTTOM (non-inverting mode) 1 1 Set OC0A on Compare Match, clear OC0A at BOTTOM (inverting mode) Note: Description 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. Compare Output Mode, Phase Correct PWM Mode(1) COM0A1 COM0A0 0 0 Normal port operation, OC0A disconnected. 0 1 WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. 1 0 Clear OC0A on Compare Match when up-counting. Set OC0A on Compare Match when down-counting. 1 1 Set OC0A on Compare Match when up-counting. Clear OC0A on Compare Match when down-counting. Note: Description 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. Compare Output Mode, non-PWM Mode COM0B1 COM0B0 Description 0 0 Normal port operation, OC0B disconnected. 0 1 Toggle OC0B on Compare Match 1 0 Clear OC0B on Compare Match 1 1 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. Compare Output Mode, Fast PWM Mode(1) COM0B1 COM0B0 0 0 Normal port operation, OC0B disconnected. 0 1 Reserved 1 0 Clear OC0B on Compare Match, set OC0B at BOTTOM (non-inverting mode) 1 1 Set OC0B on Compare Match, clear OC0B at BOTTOM (inverting mode) Note: Description 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. Compare Output Mode, Phase Correct PWM Mode(1) COM0B1 COM0B0 0 0 Normal port operation, OC0B disconnected. 0 1 Reserved 1 0 Clear OC0B on Compare Match when up-counting. Set OC0B on Compare Match when down-counting. 1 1 Set OC0B on Compare Match when up-counting. Clear OC0B on Compare Match when down-counting. Note: Description 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). Waveform Generation Mode Bit Description Table 13-8. Mode WGM2 WGM1 WGM0 Timer/Counter Mode of Operation 0 0 0 0 Normal 0xFF Immediate MAX 1 0 0 1 PWM, Phase Correct 0xFF TOP BOTTOM 2 0 1 0 CTC OCRA Immediate MAX 3 0 1 1 Fast PWM 0xFF TOP MAX 4 1 0 0 Reserved – – – 5 1 0 1 PWM, Phase Correct OCRA TOP BOTTOM 6 1 1 0 Reserved – – – 7 1 1 1 Fast PWM OCRA TOP TOP Note: 13.1.9.2 TOP Update of OCRx at TOV Flag Set on(1) 1. MAX = 0xFF, BOTTOM = 0x00 TCCR0B – Timer/Counter Control Register B Bit 7 6 5 4 3 2 1 0 0x25 (0x45) FOC0A FOC0B Read/write W W - - WGM02 CS02 CS01 CSO0 R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TCCR0B 0x00 • 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. Clock Select Bit Description Table 13-9. CS02 CS01 CS00 Description 0 0 0 No clock source (Timer/Counter stopped) 0 0 1 clkI/O/(No prescaling) 0 1 0 clkI/O/8 (From prescaler) 0 1 1 clkI/O/64 (From prescaler) 1 0 0 clkI/O/256 (From prescaler) 1 0 1 clkI/O/1024 (From prescaler) 1 1 0 External clock source on T0 pin. Clock on falling edge. 1 1 1 External clock source on T0 pin. Clock on rising edge. If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 13.1.9.3 TCNT0 – Timer/Counter Register Bit 7 6 5 4 Read/write R/W R/W R/W R/W Initial value 0 0 0 0 0x26 (0x46) 3 2 1 0 R/W R/W R/W R/W 0 0 0 0 TCNT0 [7..0] TCNT0 0x00 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 7 6 5 0x27 (0x47) 4 3 2 1 0 OCR0A [7..0] OCR0A Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 7 6 5 0x26 (0x46) 4 3 2 1 0 OCR0B [7..0] OCR0B Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 7 6 5 4 3 2 1 0 0x6E - - - - - OCIE0B OCIE0A TOIE0 Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TIMSK0 0x00 • 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 7 6 5 4 3 2 1 0 0x15 (0x35) - - - - - OCF0B OCF0A TOV0 Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TIFR0 0x00 • 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 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) 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. 105 TPR0327AY–SMS–30Jan09 Figure 13-12. 16-bit Timer/Counter Block Diagram Count Clear Direction TOV1 (Int.Req.) Control Logic clk Tn Clock Select Edge Detector TOP T1 BOTTOM ( From Prescaler ) Timer/Counter TCNT1 = =0 OC1A (Int.Req.) Waveform Generation = OC1A DATA BUS OCR1A OC1B (Int.Req.) Fixed TOP Values = Waveform Generation OC1B Noise Canceler ICP1 OCR1B ICF1 (Int.Req.) Edge Detector ICR1 TCCR1A 13.2.1.1 TCCR1B 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 13.2.2 BOTTOM The counter reaches the BOTTOM when it becomes 0x0000. MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535). TOP The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be 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. 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 13.2.3 110 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. 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 TCNT1 (16-bit Counter) Control Logic clk Tn Edge Detector T1 ( From Prescaler ) TOP BOTTOM Signal description (internal signals): Count Increment or decrement TCNT1 by 1. Direction Select between increment and decrement. Clear Clear TCNT1 (set all bits to zero). clkTn Timer/Counter clock. TOP Signifies that TCNT1 has reached maximum value. BOTTOM 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) ICR1 (16-bit Register) ICP1 TCNT1L (8-bit) TCNT1 (16-bit Counter) ICNC ICES 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. Note 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. 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) Buffer (16-bit Register) OCR1xH (8-bit) OCR1xL TCNT1L (8-bit) TCNT1 (16-bit Counter) (8-bit) OCR1x (16-bit Register) = (16-bit Comparator ) OCF1x (Int.Req.) TOP BOTTOM Waveform Generator WGM13:0 OC1x 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). 13.2.6.2 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. 13.2.6.3 Using the Output Compare Unit Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT1 when using any of the Output Compare channels, independent of whether the Timer/Counter is running or not. If the value written to TCNT1 equals the OCR1x value, the compare match will be missed, resulting in incorrect waveform generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP values. The compare match for the TOP will be ignored and the counter will continue to 0xFFFF. Similarly, do not write the TCNT1 value equal to BOTTOM when the counter is downcounting. The setup of the OC1x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC1x value is to use the Force Output Compare (FOC1x) strobe bits in Normal mode. The OC1x Register keeps its value even when changing between Waveform Generation modes. Changing the COM1x1:0 bits will take effect immediately. 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 DATA BUS D 0 OC1x Pin Q 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 (COM1A1:0 = 1) 1 2 3 4 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 118 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- 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 (COM1x1:0 = 2) OC1x (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 120 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 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 (COM1x1:0 = 2) OC1x (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 (COM1x1:0 = 2) OC1x (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 OCR1x - 1 OCR1x OCR1x + 1 OCR1x + 2 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 OCR1x + 1 OCR1x + 2 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) TCNT1 (PC and PFC PWM) TOP - 1 TOP BOTTOM BOTTOM + 1 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) clkI/O clkTn (clkI/O/8) TCNT1 (CTC and FPWM) TCNT1 (PC and PFC PWM) TOP - 1 TOP BOTTOM BOTTOM + 1 TOP - 1 TOP TOP - 1 TOP - 2 TOV1 (FPWM) and ICF1 (if used as TOP) OCR1x Old OCR1x Value (Update at TOP) 13.2.10 13.2.10.1 New OCR1x Value 16-bit Timer/Counter Register Description TCCR1A – Timer/Counter1 Control Register A Bit 7 $000080 6 5 4 3 COM1A1 COM1A0 COM1B1 COM1B0 2 1 0 - - WGM11 WGM10 Read/write R/W R/W R/W R/W R R R/W R/W Initial value 0 0 0 0 0 0 0 0 TCCR1A 0x00 • 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 126 COM1A1/COM1B1 COM1A0/COM1B0 Description 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 Toggle OC1A/OC1B on Compare Match. 1 0 Clear OC1A/OC1B on Compare Match (Set output to low level). 1 1 Set OC1A/OC1B on Compare Match (Set output to high level). 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 COM1A0/COM1B0 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 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. 1 0 Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode) 1 1 Set OC1A/OC1B on Compare Match, clear OC1A/OC1B at BOTTOM (inverting mode) Note: Description 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 COM1A0/COM1B0 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 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. 1 0 Clear OC1A/OC1B on Compare Match when upcounting. Set OC1A/OC1B on Compare Match when downcounting. 1 1 Set OC1A/OC1B on Compare Match when upcounting. Clear OC1A/OC1B on Compare Match when downcounting. Note: Description 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 WGM13 WGM12 (CTCn) WGM11 (PWMn1) WGM10 (PWMn0) Timer/Counter Mode of Operation TOP Update of OCR1x at TOV1 Flag Set on 0 0 0 0 0 Normal 0xFFFF Immediate MAX 1 0 0 0 1 PWM, Phase Correct, 8-bit 0x00FF TOP BOTTOM 2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF TOP BOTTOM 3 0 0 1 1 PWM, Phase Correct, 10-bit 0x03FF TOP BOTTOM 4 0 1 0 0 CTC OCR1A Immediate MAX 5 0 1 0 1 Fast PWM, 8-bit 0x00FF BOTTOM TOP 6 0 1 1 0 Fast PWM, 9-bit 0x01FF BOTTOM TOP 7 0 1 1 1 Fast PWM, 10-bit 0x03FF BOTTOM TOP 8 1 0 0 0 PWM, Phase and Frequency Correct ICR1 BOTTOM BOTTOM 9 1 0 0 1 PWM, Phase and Frequency Correct OCR1A BOTTOM BOTTOM 10 1 0 1 0 PWM, Phase Correct ICR1 TOP BOTTOM 11 1 0 1 1 PWM, Phase Correct OCR1A TOP BOTTOM 12 1 1 0 0 CTC ICR1 Immediate MAX 13 1 1 0 1 (Reserved) – – – 14 1 1 1 0 Fast PWM ICR1 BOTTOM TOP 1 1 1 1 Fast PWM OCR1A BOTTOM TOP 15 Note: 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 7 6 5 4 3 2 1 0 ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10 Read/write R/W R/W R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $000081 TCCR1B 0x00 • 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 CS11 CS10 Description 0 0 0 No clock source (Timer/Counter stopped). 0 0 1 clkI/O/1 (No prescaling) 0 1 0 clkI/O/8 (From prescaler) 0 1 1 clkI/O/64 (From prescaler) 1 0 0 clkI/O/256 (From prescaler) 1 0 1 clkI/O/1024 (From prescaler) 1 1 0 External clock source on Tn pin. Clock on falling edge. 1 1 1 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 7 6 5 4 3 2 1 0 FOC1A FOC1B - - - - - - Read/write R/W R/W R R R R R R Initial value 0 0 0 0 0 0 0 0 TCCR1C 0x00 • 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 15 14 13 12 11 10 9 8 $000085 TCNT[15..8] TCNT1H $000084 TCNT [7..0] TCNT1L Bit Read/write Initial value 7 6 5 4 3 2 1 0 R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 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 15 14 13 $000089 Read/write Initial value 13.2.10.6 11 10 9 8 OCR1A[15..8] $000088 Bit 12 OCR1AH OCR1A [7..0] OCR1AL 7 6 5 4 3 2 1 0 R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 11 10 9 8 OCR1BH and OCR1BL – Output Compare Register 1 B Bit 15 14 13 12 $00008B OCR1B[15..8] OCR1BH $00008A OCR1B [7..0] OCR1BL Bit Read/write Initial value 7 6 5 4 3 2 1 0 R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 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 15 14 13 12 11 10 9 8 $000087 ICR1[15..8] ICR1H $000086 ICR1 [7..0] ICR1L Bit Read/write Initial value 7 6 5 4 3 2 1 0 R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 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 7 6 5 4 3 2 1 0 $00006F - - ICIE1 - - OCIE1B OCIE1A TOIE1 Read/write R R R/W R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TIMSK1 0x00 • 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 7 6 5 4 3 2 1 0 $000016 - - ICF1 - - OCF1B OCF1A TOV1 Read/write R R R/W R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TIFR1 0x00 • 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: • • • • • • • 13.3.1 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 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 TOV2 (Int.Req.) Clear Direction Control Logic clk Tn TOSC1 T/C Oscillator TOP TOSC2 Prescaler BOTTOM clk I/O Timer/Counter TCNT2 = =0 OC2A (Int.Req.) Waveform Generation = OC2A OCR2A DATA BUS Fixed TOP Value OC2B (Int.Req.) Waveform Generation = OCR2B Synchronized Status flags Synchronization Unit OC2B clk I/O clk ASY Status flags ASSR TCCR2A 134 asynchronous mode select (AS2) TCCR2B 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 The counter reaches the BOTTOM when it becomes zero (0x00). MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255). TOP The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR2A Register. The assignment is dependent on the mode of operation. 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. 13.3.3 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. 135 TPR0327AY–SMS–30Jan09 Figure 13-26. Counter Unit Block Diagram TOV2 (Int.Req.) DATA BUS TOSC1 count TCNT2 clear clk Control Logic Tn Prescaler T/C Oscillator direction bottom TOSC2 clkI/O top Signal description (internal signals): count Increment or decrement TCNT2 by 1. direction Selects between increment and decrement. clear Clear TCNT2 (set all bits to zero). clkTn Timer/Counter clock, referred to as clkT2 in the following. top Signalizes that TCNT2 has reached maximum value. bottom 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 Waveform Generator OC2x FOC2 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). 13.3.4.2 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. 13.3.4.3 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. 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 DATA BUS D 0 OC2x Pin Q 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 138 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 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 (COM2x1:0 = 1) 1 2 3 4 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 140 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. 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 (COM2x1:0 = 2) OC2x (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 (COM2x1:0 = 2) OC2x (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 OCR2x - 1 OCR2x OCR2x + 1 OCR2x + 2 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) TOP - 1 TOP OCR2x 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 7 6 5 4 3 2 1 0 COM2A1 COM2A0 COM2B1 COM2B0 - - WGM21 WGM20 Read/write R/W R/W R/W R/W R R R/W R/W Initial value 0 0 0 0 0 0 0 0 $0000B0 TCCR2A 0x00 • 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 COM2A0 Description 0 0 Normal port operation, OC0A disconnected. 0 1 Toggle OC2A on Compare Match 1 0 Clear OC2A on Compare Match 1 1 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 COM2A0 0 0 Normal port operation, OC2A disconnected. 0 1 WGM22 = 0: Normal Port Operation, OC0A Disconnected. WGM22 = 1: Toggle OC2A on Compare Match. 1 0 Clear OC2A on Compare Match, set OC2A at BOTTOM (non-inverting mode) 1 1 Set OC2A on Compare Match, clear OC2A at BOTTOM (inverting mode) Note: Description 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 COM2A0 0 0 Normal port operation, OC2A disconnected. 0 1 WGM22 = 0: Normal Port Operation, OC2A Disconnected. WGM22 = 1: Toggle OC2A on Compare Match. 1 0 Clear OC2A on Compare Match when up-counting. Set OC2A on Compare Match when down-counting. 1 1 Set OC2A on Compare Match when up-counting. Clear OC2A on Compare Match when down-counting. Note: Description 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 COM2B0 Description 0 0 Normal port operation, OC2B disconnected. 0 1 Toggle OC2B on Compare Match 1 0 Clear OC2B on Compare Match 1 1 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 COM2B0 0 0 Normal port operation, OC2B disconnected. 0 1 Reserved 1 0 Clear OC2B on Compare Match, set OC2B at BOTTOM (non-inverting mode) 1 1 Set OC2B on Compare Match, clear OC2B at BOTTOM (inverting mode) Note: Description 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 COM2B0 0 0 Normal port operation, OC2B disconnected. 0 1 Reserved 1 0 Clear OC2B on Compare Match when up-counting. Set OC2B on Compare Match when down-counting. 1 1 Set OC2B on Compare Match when up-counting. Clear OC2B on Compare Match when down-counting. Note: Description 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 TOP Update of OCRx at TOV Flag Set on(1) Mode WGM22 WGM21 WGM20 0 0 0 0 Normal 0xFF Immediate MAX 1 0 0 1 PWM, Phase Correct 0xFF TOP BOTTOM 2 0 1 0 CTC OCR2A Immediate MAX 3 0 1 1 Fast PWM 0xFF BOTTOM MAX 4 1 0 0 Reserved – – – 5 1 0 1 PWM, Phase Correct OCR2A TOP BOTTOM 6 1 1 0 Reserved – – – 7 1 1 1 Fast PWM OCR2A BOTTOM TOP Note: 13.3.8.2 Timer/Counter Mode of Operation 1. MAX= 0xFF, BOTTOM= 0x00 TCCR2B – Timer/Counter Control Register B Bit 7 6 5 4 3 2 1 0 FOC2A FOC2B - - WGM22 CS22 CS21 CS20 Read/write W W R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $0000B1 TCCR2B 0x00 • 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 CS21 CS20 Description 0 0 0 No clock source (Timer/Counter stopped). 0 0 1 clkT2S/(No prescaling) 0 1 0 clkT2S/8 (From prescaler) 0 1 1 clkT2S/32 (From prescaler) 1 0 0 clkT2S/64 (From prescaler) 1 0 1 clkT2S/128 (From prescaler) 1 1 0 clkT2S/256 (From prescaler) 1 1 1 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 7 6 5 $0000B2 4 3 2 1 0 TCNT2 [7..0] TCNT2 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 7 6 5 4 $0000B3 3 2 1 0 OCR2A [7..0] OCR2A Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 7 6 5 4 $0000B4 3 2 1 0 OCR2B [7..0] OCR2B Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 Asynchronous operation of the Timer/Counter 13.3.9.1 ASSR – Asynchronous Status Register Bit 7 6 5 4 3 2 1 0 $0000B6 - EXCLK AS2 TCN2UB Read/write R R/W R/W R R R R R Initial value 0 0 0 0 0 0 0 0 OCR2AUB OCR2BUB TCR2AUB TCR2BUB ASSR 0x00 • 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 7 6 5 4 3 2 1 0 $000070 - - - - - OCIE2B OCIE2A TOIE2 Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TIMSK2 0x00 • 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 7 6 5 4 3 2 1 0 0x17 (0x37) - - - - - OCF2B OCF2A TOV2 Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TIFR2 0x00 • 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 PSRASY clkT2S/1024 clkT2S/256 clkT2S/128 AS2 clkT2S/64 10-BIT T/C PRESCALER Clear clkT2S/8 TOSC1 clkT2S clkT2S/32 clkI/O 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 AT90SCR100 13.4.1 GTCCR – General Timer/Counter Control Register Bit 7 6 5 4 3 2 1 0 0x23 (0x43) TSM - - - - - Read/write R/W R R R R R R/W R/W Initial value 0 0 0 0 0 0 0 0 PSRASY PSRSYNC GTCCR 0x00 • 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 • • • • 14.2 – 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 Overview The following diagram represents the USB module that contains the necessary logic to communicate via a Full-Speed USB port. Note 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. 157 TPR0327AY–SMS–30Jan09 Figure 14-1. USB Module Diagram USB MODULE USBDM (D-) USB SIE (Serial Interface Engine) USB Transceiver USBDP (D+) XIN XOUT Clock and Suspend / Resume Manager USB Control and Status, USB Interrupt, ... USB UFI (Universal Function Interface) USBDMA Controller Data Exchanges 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. Endpoints Description Endpoint Number Size in Bytes Double- Buffering Capability EP0 64 NO CONTROL EP1 2x64 YES BULK(1) EP2 2x64 YES BULK (1) EP3 2x64 YES BULK (1) EP4 8 NO CONTROL, BULK, INTERRUPT(2) EP5 8 NO CONTROL, BULK, INTERRUPT(2) EP6 8 NO CONTROL, BULK, INTERRUPT(2) EP7 8 NO CONTROL, BULK, INTERRUPT(2) Notes: Recommended Data Transfer Type 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. Note Note 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. 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. Note A USB interrupt is triggered assuming bits SREG.I is set (one) in order to enable the interrupt. 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 FEURIM SOFI SOFIM RMWUI RMWUIM RESI RESIM SUSI SUSIM USBEI UCSE7 UCSE6 UCSE5 UCSE4 UCSE3 UCSE2 LOGICAL OR USBPIM AVR INTERRUPT LOGIC USB PROTOCOL USBEIM EP7I EP6I EP5I EP4I EP3I EP2I UCSE1 UCSE3 EP1I UCSE0 UCSE3 EP0I EP7IM EP6IM EP5IM USB ENDPOINT EP4IM EP3IM EP2IM EP1IM EP0IM ENDPOINT INTERRUPT 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. Note 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. 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. Note 14.6.1 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. 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. Note When the USBGS.RSMON bit is cleared, do not forget to clear USBCR.URMWU bit, for next Remote Wake Up sequence. 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... Control to be cleared by software USBCR.URMWU ...and wait the end of the generation. USBGS.RMSON USBPI.RMWUI 162 ~13ms Flag to be cleared by software 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 USBCSEX.TXPB = 0 ? YES NO NO USBCSEX.TXC = 1 ? (POLLING or INTERRUPT) YES CLEAR bit USBCSEX.TXC LAST DATA PACKET REACHED ? NO YES END 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 NO USBCSEX.RCVD = 1 ? (POLLING or INTERRUPT) READ register USBDBCEX -> NbBytes 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 7 6 5 4 3 2 1 0 URMWU - UPUC - - - USBE - Read/write R/W R R/W R R R R/W R Initial value 0 0 0 0 0 0 0 0 $0000E0 USBCR 0x00 • 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 7 6 5 4 3 2 1 0 $0000E1 - - - FEURI SOFI RMWUI RESI SUSI Read/write R R R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 USBPI 0x00 • 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 7 6 5 4 3 2 1 0 $0000E2 - - - - SOFIM RMWUIM RESIM SUSIM Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 1 0 USBPIM 0x02 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 7 6 5 4 3 2 1 0 EP7I EP6I EP5I EP4I EP3I EP2I EP1I EP0I Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 $0000E3 USBEI 0x00 • 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): Note • 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 7 6 5 4 3 2 1 0 EP7IM EP6IM EP5IM EP4IM EP3IM EP2IM EP1IM EP0IM Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $0000E5 USBEIM 0x00 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 7 6 5 4 3 $0000CA - - - - - 2 1 0 Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 ENUM [2..0] USBENUM 0x00 • 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 7 6 5 4 3 $0000CB - IERR FSTALL TXPB Read/write R R R/W R/W R/W Initial value 0 0 0 0 0 2 1 0 RCVD TXC R/W R/W R/W 0 0 0 STSENT RXSETUP USBCSEX 0x00 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 7 6 5 4 3 2 1 0 $0000CC BCT7 BCT6 BCT5 BCT4 BCT3 BCT2 BCT1 BCT0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 USBDBCEX 0x00 • 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 7 6 5 4 3 2 1 0 $0000CD EPE - - - - EPDIR Read/write R/W R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 EPTYP1 EPTYP0 USBFCEX 0x00 • 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 14.8.10 EPTYP1 EPTYP0 Transfer 0 0 Control 0 1 Isochronous 1 0 Bulk 1 1 Interrupt USBRSTE - USB Reset Endpoint Register Bit 7 6 5 4 3 2 1 RSTE7 RSTE6 RSTE5 RSTE4 RSTE3 RSTE2 RSTE1 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $0000E5 0 RSTE0 USBRSTE 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 7 6 5 4 3 2 1 0 $0000E6 - - - - RSMON RMWUE FCF FAF Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 USBGS 0x00 • 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 7 6 5 4 3 2 1 0 $0000E7 - FADD6 FADD5 FADD4 FADD3 FADD2 FADD1 FADD0 Read/write R R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 USBFA 0x00 • 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 15 14 13 12 11 10 9 8 $0000E9 - - - FNEND FNERR FN10 FN9 FN8 USBFNH $0000E8 FN7 FN6 FN5 FN4 FN3 FN2 FN1 FN0 USBFNL Bit 7 6 5 4 3 2 1 0 Read/write R R R R R R R R R R R R R R R R 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 Initial value • 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. Note 14.9 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). 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. ! Caution 172 All the USB registers described in this section cannot be accessed if the USB module is not enabled. 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.EPS2:0 USBDMACS.DMADIR USBDMACS.DMAERR RAM $10FF DMAB 000 DMAD 0 USBDMACS.DMAR 0 1 001 1 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 14.9.1 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. USBDMACS - USBDMA Control and Status Register This is the control and status register of the USBDMA controller. Bit 7 6 5 4 3 2 1 0 $0000EA - EPS2 EPS1 EPS0 - Read/write R R/W R/W R/W R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 USBDMAERR USBDMAIR USBDMAR USBDMACS 0x00 • 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. Note Table 14-2. 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 EPS2 EPS1 EPS0 Endpoint Selected Endpoint Size (Bytes) 0 0 0 Endpoint 0 64 0 0 1 Endpoint 1 2x64 0 1 0 Endpoint 2 2x64 0 1 1 Endpoint 3 64 1 0 0 Endpoint 4 8 1 0 1 Endpoint 5 8 1 1 0 Endpoint 6 8 1 1 1 Endpoint 7 8 • 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. ! Caution Don’t forget to clear the USBDMACS.DMAERR bit before leaving the interruption routine to avoid repetitive and endless interruptions. • 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. Note A USBDMA operation can not be interrupted because the CPU is not available during this time. Note 14.9.2 USBDMAD - USBDMA ADdress Registers Bit 15 14 - - Bit 7 6 5 4 3 2 1 0 Read/write R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 1 0x01 0 0 0 0 0 0 0 0 0x00 $0000EC 13 12 11 10 9 8 USBDMAD [13..8] $0000EB USBDMADH USBDMAD [7..0] Initial value USBDMADL • 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 7 6 5 4 3 2 1 0 $0000ED - Read/write R R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 USBDMAB [6..0] USBDMAB 0x00 • 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 176 The maximum value allowed for USBDMAB depends on the endpoint selected. 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 • • • • • • • • • • • • 15.2 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 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 Waiting Time Counter CRST CC4 (out) CC8 (out) SCI Registers CC4 (in) CC8 (in) INT 15.4 Interrupt Generator Power_on Power_off fsm VCARD 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 Functional Description The architecture of the Smart Card Interface Block can be detailed as follows: 15.5.1 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. Note 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. 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 Transmission to ICC Reception from ICC CHAR 1 CHAR 2 Write SCGT with a value for Guard Time CHAR n CHAR 1 >= Block Guard Time CHAR 2 >= 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 Block Guard Time Counter 9 bits 9 bits Comparator Transmit Enable Comparator 9 bits 9 bits Shadow SCGTH Transmit Enable Shadow SCGTL GT[8..0] SCGTH SCGTL 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 RECEPTION Bloc 1 CHAR 1 CHAR 2 Bloc n CHAR n CHAR 1 < BWT 184 CHAR 2 CHAR n < CWT 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 Data Ta + tb Tb + tc 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 Data Td=T + te Td + Tf 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 15.5.8 186 8 Clock Cycles Undefined 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. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Figure 15-11. SCIB Interrupt Sources Transmit buffer copied to shift register SCTBI ESCTBI Output voltage out of range VCARDERR EVCARDER Timer on WT counter SCWTI ESCWTI SCIB Interrupt Transmission complete SCTI ESCTI Reception complete SCRI ESCRI Parity error detected SCPI ESCPI 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. ! Caution 15.6 15.6.1 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. 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." Note If Card Presence interruption is enabled, the AT90SCR100 wakes up from low power mode as soon as an event on CPRES is detected. 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. ! Caution 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. Figure 15-12. Character Transmission Diagram SCISR Register SCTBE SCTC SCPE Parity Error SCIBUF Shift Register Transmitted Character I/O Pin SCIER.ESCTBI SCIER.ESCTI Parity Error SCTBI SCTI SCPI SCIIR Register 189 TPR0327AY–SMS–30Jan09 Figure 15-13. Character Reception Diagram SCISR Register SCTBE SCRC Shift Register SCPE SCIBUF I/O Pin Received Character SCIER.ESCRI SCTBI SCRI SCPI SCIIR Register 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 7 $0000FF 6 SCIRESET CARDDET 5 4 VCARD [1..0] 3 2 1 0 UART WTEN CREP CONV Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 SCICR 0x00 • 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. Note When clearing this bit by software, it is required to wait till this bit is cleared before using the interface. • 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. ! Caution SCIER.CARDINIE must be set only when CARDDET bit is correctly configured. • Bit 5..4 – VCARD[1..0]: Card Voltage Selection Table 15-1. Card Voltage Selection VCARD1 VCARD0 0 0 0 1 1 0 3.0V 1 1 5.0V Note ! Caution CVcc 1.8V 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. • 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. Note Character repetition mode is specified for T=0 protocol only and should not be used in T=1 protocol (block oriented protocol) • 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 7 6 5 4 3 2 1 0 $0000FE CLK - CARDC8 CARDC4 Read/write R/W R R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 CARDIO CARDCLK CARDRST CARDVCC SCCON 0x00 • 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 7 6 5 4 3 2 1 0 SCTBE CARDIN - VCARDOK SCWTO SCTC SCRC SCPE Read/write R R R R R R/W R/W R/W Initial value 1 0 0 0 0 0 0 0 $0000FD SCISR 0x80 • 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. ! Caution 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. • 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. Note To modify the bits CARDC8, CARDC4, CARDIO, CARDCLK and CARDRST in register SCCON, the bit VCAROK must be equal to 1. • 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 7 6 5 4 3 2 1 0 SCTBI - - VCARDERR SCWTI SCTI SCRI SCPI Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 $0000FC SCIIR 0x00 • 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. Note 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. 195 TPR0327AY–SMS–30Jan09 15.7.5 SCIER - Smart Card UART Interrupt Enable Register Bit 7 $0000FD 6 5 ESCTBI CARDINE - 4 3 EVCARDER ESCWTI 2 1 0 ESCTI ESCRI ESCPI Read/write R/W R R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 SCIER 0x00 • 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 7 6 5 4 3 $0000FA - BGTEN - - - - Read/write R R/W R R/W R/W R R R Initial value 0 0 0 0 0 0 0 0 CREPSEL CPRESRES 2 1 0 SCSR 0x00 • 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 7 6 5 $0000F9 4 3 2 1 0 SCIBUFD [7..0] SCIBUF Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 15 14 13 12 11 COMP - - - - 7 6 5 4 3 2 1 0 R/W R R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 1 0x01 0 1 1 1 0 1 0 0 0x74 $0000F7 9 8 ETU [10..8] SCETUH ETU [7..0] Bit Read/write 10 Initial value 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 15.7.9 Do not change this register during character reception or transmission or while Guard Time or Waiting Time Counters are running. SCGT - Smart Card Guard Time Register Bit $0000F6 15 14 13 12 - - - - $0000F5 11 10 9 8 - - - GT8 GT [7..0] SCGTH SCGTL Bit 7 6 5 4 3 2 1 0 Read/write R R R R R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 1 1 0 0 0x0C Initial value • 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 7 6 5 4 3 2 1 0 $0000F4 WT [31..24] SCWT3 $0000F3 WT (23..16] SCWT2 $0000F2 WT [15..8] SCWT1 $0000F1 WT [7..0] SCWT0 R/W Initial value R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 0 0 1 0 0 1 0 1 0x25 1 0 0 0 0 0 0 0 0x80 • 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. ! Caution 15.7.11 If SCICR.WTEN=0, the Waiting Time Counter is loaded by writting SCWT2 and resetting SCICR.WTEN. SCICLK - Smart Card Clock Register Bit 7 6 5 4 3 2 1 0 $0000F0 - - Read/write R R R/W R/W R/W R/W R/W R/W Initial value 0 0 1 0 1 1 1 1 SCICLK [5..0] SCICLK 0x2F • 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. 200 Clock Dividers For Smart Card Interface ClkPLL SCICLK [5-0] SCIB Frequency (Mhz) Divider 96 0x00 48 2 96 0x01 32 3 96 0x02 24 4 96 0x03 19.2 5 96 0x04 16 6 96 0x05 8 12 96 0x06 6 16 96 0x07 4.8 20 96 0x08 4 24 96 0x09 3 32 96 0x0A 2.4 40 96 0x0B 2 48 96 0x0C Reserved Reserved 96 0x0D Reserved Reserved 96 0x0E Reserved Reserved 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. Note 16.3.1 It is mandatory to switch off the DC/DC Converter before entering in Power-down mode, by clearing DCCR.DCON. Initialization Procedure To generate a specific voltage on CVcc, please follow at the following diagram: ! Caution 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. 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 No DCCR.DCRDY=1? Poll DC/DC Converter is ready Yes Set SCICR.VCARD Configure the Voltage to generate No Card Presence required Wait for Card Insertion This can be done either by polling or interruption. See Card Presence Input section SCCON.CARDVCC=1 Ask for CVcc generation No SCISR.VCARDOK=1 ? Poll to know when CVcc has reached the desired voltage Yes CVcc generated Need activation sequence ! Caution 16.3.2 As the DCDC voltage is now generated, the activation sequence can be processed This procedure does not take into account any error signal. This should be added for full Smart Card Interface management. 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 ~200μs DCCR.RDY DCCR.BUSY (*) (*) >20μs CVcc Signal >20μs Modification of SCICR.VCARD OK DCCR.DCON =1 DCCR.DRDY SCCON.CARDVCC =1 Modification of SCICR.VCARD OK DCCR.BUSY SCCON.CARDVCC =0 SCCON.CARDVCC =1 Shutdown procedure DCCR.BUSY SCCON.CARDVCC =0 DCCR.DCON =0 (*): This timing depends on SCICR.VCARD configuration but is, at least, 20μs 16.5 16.5.1 DC/DC Registers DCCR - DC/DC Converter Register Bit 7 6 5 4 3 2 1 0 DCON DCRDY DCBUSY - - - - - Read/write R/W R R R R R R R Initial value 0 0 0 0 0 0 0 0 $0000EF DCCR 0x00 • 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 • • • • • 17.2 – 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 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. ! Caution 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-. 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 DC/DC CC8 UHCR.UHEN=1 CC8 CC4 UHCR.UHEN=1 clk USB UHCR.PAD = '01' USB-IC Pad UHCR.PAD D+ = '01' D- Logical D+ CC4 Logical D- USB Host Controller CC8 D+ D- = '00' = '00' 15KÉ CPU (SRAM) On-Chip USB DPRAM Pipe 0 Pipe 1 168 Bytes Pipe 2 Pipe 3 Internal Vcc 17.3 15KÉ USB 2.0 USB Regulator 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 D+ CC8 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 Free Free Free 3 3 3 3 2 2 LOST MEMORY 1 PEN=0 (ALLOC=1) 2 1 (bigger size) 0 0 0 0 Pipe Activation Pipe Disable Free its memory (ALLOC=0) Pipe Activation 2 Conflict PEN=1 ALLOC=1 • 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 208 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: 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 <Any other State> 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. ! Caution 17.5.4 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. 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 210 Pipe Configuration The following flow must be respected in order to activate a Pipe: 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: ! • The pipe 0 size must not be greater than 32 bytes. Caution • 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. 17.5.11 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.12 OUT Pipe management The Pipe must be configured and not frozen first. Note 17.5.12.1 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. “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 OUT HW UPINTX.TXOUTI SW UPINTX.FIFOCON SW SW SW Write data from CPU Bank 0 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 UPINTX.FIFOCON SW SW SW SW Write data from CPU Bank 0 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 UPINTX.FIFOCON SW SW Write data from CPU Bank 0 17.5.12.2 214 SW SW SW Write data from CPU Bank 1 Write data from CPU Bank 0 “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. 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 IN DATA (to Bank 0) ACK HW UPINTX.RXINI HW SW UPINTX.FIFOCON SW SW Read data from CPU Bank 0 Read data from CPU Bank 0 Example with 2 IN data banks IN DATA (to Bank 0) ACK IN HW UPINTX.RXINI DATA (to Bank 1) ACK HW SW UPINTX.FIFOCON SW SW Read data from CPU Bank 0 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 17.6 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. Interrupt system Figure 17-9. USB Host Controller Interrupt System HWUPI UHINT.6 HWUPE UHIEN.6 HSOFI UHINT.5 RXRSMI UHINT.4 RSMEDI UHINT.3 RSTI UHINT.2 DDISCI UHINT.1 DCONNI UHINT.0 216 HSOFE UHIEN.5 RXRSME UHIEN.4 USB Host Interrupt RSMEDE UHIEN.3 RSTE UHIEN.2 DDISCE UHIEN.1 DCONNE UHIEN.0 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Figure 17-10. USB Host Controller Pipe Interrupt System PIPE 3 PIPE 2 PIPE 1 PIPE 0 OVERFI UPSTAX.6 UNDERFI UPSTAX.5 FLERRE UPIEN.7 NAKEDI UPINTX.6 NAKEDE UPIEN.6 PERRI UPINTX.4 PERRE UPIEN.4 TXSTPI UPINTX.3 TXSTPE UPIEN.3 TXOUTI UPINTX.2 USB Host Pipe Interrupt FLERRE UPIEN.7 TXOUTE UPIEN.2 RXSTALLI UPINTX.1 RXSTALLE UPIEN.1 RXINI UPINTX.0 17.6.1 17.7 17.7.1 RXINE UPIEN.0 Idle and Power-Down The CPU exits from Idle and Power-Down mode with any USB Interrupts. USB Host Controller Registers UHCR - USB Host Control Register Bit 7 $009E UHEN 6 5 PAD [1..0] 4 3 2 1 0 FRZCLK - RESUME RESET SOFEN Read/write R/W R/W R/W R/W R R/W R/W R/W Initial value 0 0 0 1 0 0 0 0 UHCR 0x00 • 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 7 6 5 4 3 2 1 0 $0099 - - - - SPEED - - - Read/write R R R R R R R R Initial value 0 0 0 0 1 0 0 0 UHSR 0x08 • 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 7 6 5 4 $009F - HWUPI HSOFI Read/write R R/W R/W R/W Initial value 0 0 0 0 3 2 1 0 RSTI DDISCI DCONNI R/W R/W R/W R/W 0 0 0 0 RXRSMI RSMEDI UHINT 0x00 • 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 7 6 5 4 $00A0 - HWUPE HSOFE Read/write R R/W R/W R/W Initial value 0 0 0 0 3 2 1 0 RSTE DDISCE DCONNE R/W R/W R/W R/W 0 0 0 0 RXRSME RSMEDE UHIEN 0x00 • 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 7 6 5 4 3 2 1 0 $00A1 - Read/write R R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 HADDR [6..0] UHADDR 0x00 • 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 15 14 13 12 11 - - - - - $00A2 10 9 8 FNUM [10..8] UHFNUMH FNUM [7..0] UHFNUML Bit 7 6 5 4 3 2 1 0 Read/write R R R R R R R R R R R R R R R R 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 Initial value • 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 7 6 5 $00A4 4 3 2 1 0 FLEN [7..0] UHFLEN Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 4 3 $00A7 2 1 0 - PNUM1 PNUM0 Read/write R R R R R R R/W R/W Initial value 0 0 0 0 0 0 0 0 UPNUM 0x00 • 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 7 6 5 4 3 2 1 0 $00A8 - - - - P3RST P2RST P1RST P0RST Read/write R R R R R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 UPRST 0x00 • 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 7 6 $00A9 - Read/write R R/W Initial value 0 0 5 4 3 2 1 0 - RSTDT - - PEN R/W R R/W R R R/W 0 0 0 0 0 0 PFREEZE INMODE UPCRX 0x00 • 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 7 6 $00AA PTYPE [1..0] 5 4 3 PTOKEN [1..0] 2 1 0 PEPNUM [3..0] UPCFG0X Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 4 3 $00AB - Read/write R R/W R/W R/W R/W R/W R/W R Initial value 0 0 0 0 0 0 0 0 PSIZE [0..2] 2 PBK [0..1] 1 0 ALLOC UPCFG1X 0x00 • 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 7 6 5 $00AD 4 3 2 1 0 INTFRQ [7..0] UPCFG2X Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 $00AC 6 CFGOK 5 OVERFI UNDERFI 4 3 - DTSEQ [1..0] 2 1 0 NBUSYBK [1..0] Read/write R R/W R/W R R R R R Initial value 0 0 0 0 0 0 0 0 UPSTAX 0x00 • 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. Note 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. • 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 7 6 5 4 $00A5 3 2 1 0 INRQ [7..0] UPINRQX Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 $009D 6 5 COUNTER [1..0] 4 3 2 1 0 CRC16 PTIMEOUT PID Read/write R R/W R/W R/W R/W R/W DATAPID DATATGL UPERRX R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 4 3 FIFOCON NAKEDI RWAL PERRI TXSTPI Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $00A6 2 1 TXOUTI RXSTALLI 0 RXINI UPINTX 0x00 • 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 7 6 5 4 FLERRE NAKEDE - PERRE Read/write R/W R/W R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $00AE 3 2 1 TXSTPE TXOUTE RXSTALLE 0 RXINE UPIENX 0x00 • 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 7 6 5 $00AF 4 3 2 1 0 PDAT [7..0] UPDATX Read/write R/W R/W R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 15 14 13 12 11 - - - - - $009C $009B 10 9 8 PBYTCT [10..8] UPBCXH PBYTCT [7..0] Bit 7 Read/write 6 5 4 UPBCXL 3 2 1 0 R R R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 Initial value • 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 7 6 5 4 3 2 1 0 $009A - - - - PINT3 PINT2 PINT1 PINT0 Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 UPINT 0x00 • 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 • • • • • • • • • • • • 18.2 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 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 TX CONTROL UDR (Transmit) DATA BUS PARITY GENERATOR PIN CONTROL TRANSMIT SHIFT REGISTER TxD Receiver UCSRA CLOCK RECOVERY RX CONTROL RECEIVE SHIFT REGISTER DATA RECOVERY PIN CONTROL UDR (Receive) PARITY CHECKER UCSRB RxD 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 U2X fosc Prescaling Down-Counter UBRR+1 /2 /4 /2 0 1 0 Clk io or XCK DDR_XCK xcki XCK Pin Sync Register Edge Detector 0 UCPOL txclk UMSEL 1 xcko DDR_XCK 1 1 0 rxclk Signal description: txclk Transmitter clock (Internal Signal). rxclk Receiver base clock (Internal Signal). xcki operation. 18.4.1 Input from XCK pin (internal Signal). Used for synchronous slave xcko Clock output to XCK pin (Internal Signal). Used for synchronous master operation. fOSC 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. 1. Equations for Calculating Baud Rate Register Setting Operating Mode Equation for Calculating Baud Rate (1) 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 Equation for Calculating UBRR Value 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] St Start bit, always low. (n) Data bits (0 to 8). P Parity bit. Can be odd or even. Sp Stop bit, always high. IDLE must be [7] [8] [P] Sp1 [Sp2] (St / IDLE) 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 Parity bit using even parity Podd Parity bit using odd parity dn 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. Note 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 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 UBRRH0, r17 out UBRRLn0 r16 ; Enable receiver and transmitter ldi r16, (1<<RXEN0)|(1<<TXEN0) out UCSR0B,r16 ; Set frame format: 8data, 2stop bit ldi r16, (1<<USBS0)|(3<<UCSZ00) out UCSR0C,r16 ret 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<<RXEN0)|(1<<TXEN0); /* Set frame format: 8data, 2stop bit */ UCSR0C = (1<<USBS0)|(3<<UCSZ00); } Note: 1. See “About Code Examples” on page 11. More advanced initialization routines can be made that include frame format as parameters, disable interrupts and so on. However, many applications use a fixed setting of the baud and control registers, and for these types of applications the initialization code can be placed directly in the main routine, or be combined with initialization code for other I/O modules. 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 UDR0,r16 ret C Code Example (1) void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSR0A & (1<<UDRE0)) ) ; /* Put data into buffer, sends the data */ UDR0 = data; } Note: 1. See “About Code Examples” on page 11. 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. If the Data Register Empty interrupt is utilized, the interrupt routine writes the data into the buffer. 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 UCSR0B,TXB8 sbrc r17,0 sbi UCSR0B,TXB8 ; Put LSB data (r16) into buffer, sends the data out UDR0,r16 ret C Code Example (1) void USART_Transmit( unsigned int data ) { /* Wait for empty transmit buffer */ while ( !( UCSR0A & (1<<UDRE0))) ) ; /* Copy 9th bit to TXB8 */ UCSR0B &= ~(1<<TXB8); if ( data & 0x0100 ) UCSR0B |= (1<<TXB8); /* Put data into buffer, sends the data */ UDR0 = data; } Note: 1. These transmit functions are written to be general functions. They can be optimized if the contents of the UCSR0B is static. For example, only the TXB8 bit of the UCSR0B Register is used after initialization. See “About Code Examples” on page 11. The ninth bit can be used for indicating an address frame when using multi processor communication mode or for other protocol handling as for example synchronization. 18.7.3 Transmitter Flags and Interrupts The USART Transmitter has two flags that indicate its state: USART Data Register Empty (UDRE0) and Transmit Complete (TXC0). Both flags can be used to generate interrupts. The Data Register Empty (UDRE0) Flag indicates whether the transmit buffer is ready to receive new data. This bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not already been moved into the Shift Register. For compatibility with future devices, always write this bit to zero when writing the UCSR0A Register. 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. 18.7.5 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.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 r16, UDR0 ret C Code Example(1) unsigned char USART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSR0A & (1<<RXC0)) ) ; /* Get and return received data from buffer */ return UDR0; } Note: 1. See “About Code Examples” on page 11. The function simply waits for data to be present in the receive buffer by checking the RXC0 Flag, before reading the buffer and returning the value. 18.8.2 Receiving Frames with 9 Data Bits If 9-bit characters are used (UCSZ0=7) the ninth bit must be read from the RXB80 bit in UCSR0B before reading the low bits from the UDRn. This rule applies to the FE0, DOR0 and UPE0 Status Flags as well. Read status from UCSR0A, then data from UDR0. Reading the UDR0 I/O location will change the state of the receive buffer FIFO and consequently the TXB80, FE0, DOR0 and UPE0 bits, which all are stored in the FIFO, will change. The following code example shows a simple USART receive function that handles both nine bit characters and the status bits. 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 r18, UCSR0A in r17, UCSR0B in r16, UDR0 ; If error, return -1 andi r18,(1<<FE0)|(1<<DOR0)|(1<<UPE0) breq USART_ReceiveNoError ldi r17, HIGH(-1) ldi r16, LOW(-1) USART_ReceiveNoError: ; Filter the 9th bit, then return lsr r17 andi r17, 0x01 ret C Code Example(1) unsigned int USART_Receive( void ) { unsigned char status, resh, resl; /* Wait for data to be received */ while ( !(UCSR0A & (1<<RXC0)) ) ; /* Get status and 9th bit, then data */ /* from buffer */ status = UCR0A; resh = UCSR0B; resl = UDR0; /* If error, return -1 */ if ( status & (1<<FE0)|(1<<DOR0)|(1<<UPE0) ) return -1; /* Filter the 9th bit, then return */ resh = (resh >> 1) & 0x01; return ((resh << 8) | resl); } Note: 1. See “About Code Examples” on page 11. 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 18.8.7 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 C Code Example(1) void USART_Flush( void ) { unsigned char dummy; while ( UCSR0A & (1<<RXC0) ) dummy = UDR0; } Note: 18.9 1. See “About Code Examples” on page 11. 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 244 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. 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 + 2 )S R fast = ----------------------------------( D + 1 )S + S M D Sum of character size and parity size (D = 5 to 10 bit) S Samples per bit. S = 16 for Normal Speed mode and S = 8 for Double Speed mode. SF First sample number used for majority voting. SF = 8 for normal speed and SF = 4 for Double Speed mode. SM Middle sample number used for majority voting. SM = 9 for normal speed and SM = 5 for Double Speed mode. Rslow 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) D # (Data+Parity Bit) Rslow (%) Rfast (%) Max Total Error (%) Recommended Max Receiver Error (%) 5 93.20 106.67 +6.67/-6.8 ± 3.0 6 94.12 105.79 +5.79/-5.88 ± 2.5 7 94.81 105.11 +5.11/-5.19 ± 2.0 8 95.36 104.58 +4.58/-4.54 ± 2.0 9 95.81 104.14 +4.14/-4.19 ± 1.5 10 96.17 103.78 +3.78/-3.83 ± 1.5 Table 18-3. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode (U2Xn = 1) D # (Data+Parity Bit) Rslow (%) Rfast (%) Max Total Error (%) Recommended Max Receiver Error (%) 5 94.12 105.66 +5.66/-5.88 ± 2.5 6 94.92 104.92 +4.92/-5.08 ± 2.0 7 95.52 104,35 +4.35/-4.48 ± 1.5 8 96.00 103.90 +3.90/-4.00 ± 1.5 9 96.39 103.53 +3.53/-3.61 ± 1.5 10 96.70 103.23 +3.23/-3.30 ± 1.0 The recommendations of the maximum receiver baud rate error was made under the 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 7 6 5 4 3 2 1 0 UDR0 $0000C6 RXB[7..0] (Read) $0000C6 TXB[7..0] (Write) Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 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 7 6 5 4 3 2 1 0 RXC0 TXC0 UDRE0 FE0 DOR0 UPE0 U2X0 MPCM0 Read/write R R/W R R R R R/W R/W Initial value 0 0 1 0 0 0 0 0 $0000C0 UCSR0A 0x20 • 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 7 6 5 4 3 2 1 0 RXCIE0 TXCIE0 UDRIE0 RXEN0 TXEN0 UCSZ02 RXB80 TXB80 Read/write R/W R/W R/W R/W R/W R/W R R/W Initial value 0 0 0 0 0 0 0 0 $0000C1 UCSR0B 0x00 • 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 7 6 5 4 3 2 1 0 UMSEL01 UMSEL00 UPM01 UPM00 USBS0 UCSZ01 UCSZ00 UCPOL0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 1 1 0 $0000C2 UCSR0C 0x06 • 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. UMSEL0 Bits Settings UMSEL01 UMSEL00 0 0 Mode Asynchronous USART 251 TPR0327AY–SMS–30Jan09 Table 18-4. Note: UMSEL0 Bits Settings UMSEL01 UMSEL00 Mode 0 1 Synchronous USART 1 0 (Reserved) 1 1 Master SPI (MSPIM)(1) 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. UPM0 Bits Settings UPM01 UPM00 Parity Mode 0 0 Disabled 0 1 Reserved 1 0 Enabled, Even Parity 1 1 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 Stop Bit(s) 0 1-bit 1 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. 252 UCSZ0 Bits Settings UCSZ02 UCSZ01 UCSZ00 Character Size 0 0 0 5-bit 0 0 1 6-bit 0 1 0 7-bit 0 1 1 8-bit 1 0 0 Reserved AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Table 18-7. UCSZ0 Bits Settings UCSZ02 UCSZ01 UCSZ00 Character Size 1 0 1 Reserved 1 1 0 Reserved 1 1 1 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. Transmitted Data Changed (Output of TxD0 Pin) Received Data Sampled (Input on RxD0 Pin) 0 Rising XCK Edge Falling XCK Edge 1 Falling XCK Edge Rising XCK Edge UCPOL0 18.11.5 UCPOLn Bit Settings UBRR0L and UBRR0H – USART Baud Rate Registers Bit 7 6 5 4 $0000C5 - - - - $0000C4 Read/write Initial value 3 2 1 0 UBRR[11..8] UBRRH0 UBRR[7..0] UBRRL0 R R R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 • 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 Examples of UBRR0 Settings accessible Oscillator Frequencies Table 18-9. fosc = 8.0000 MHz fosc = 16 MHz fosc = 19.2 MHz Baud Rate (bps) UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error UBRR Error 2400 207 0.2% 416 -0.1% 416 -0.1% 832 0% 499 0% 999 0% 4800 103 0.2% 207 0.2% 207 0.2% 416 -0.1% 249 0% 499 0% 9600 51 0.2% 103 0.2% 103 0.2% 207 0.2% 124 0% 249 0% 14.4k 34 -0.8% 68 0.6% 68 0.6% 138 -0.1% 82 0.4% 166 -0.2% 19.2k 25 0.2% 51 0.2% 51 0.2% 103 0.2% 62 -0.8% 124 0% 28.8k 16 2.1% 34 -0.8% 34 -0.8% 68 0.6% 41 -0.8% 82 0.4% 38.4k 12 0.2% 25 0.2% 25 0.2% 51 0.2% 30 0.8% 62 -0.8% 57.6k 8 -3.5% 16 2.1% 16 2.1% 34 -0.8% 20 -0.8% 41 -0.8% 76.8k 6 -7% 12 0.2% 12 0.2% 25 0.2% 15 2.3% 30 0.8% 115.2k 3 8.5% 8 -3.5% 8 -3.5% 16 2.1% 9 4.2% 20 -0.8% 230.4k 1 8.5% 3 8.5% 3 8.5% 8 -3.5% 4 4.2% 9 4.2% 250k 1 0% 3 0% 3 0% 7 0% 4 -4% 9 -4% 500k 0 0% 1 0% 1 0% 3 0% 1 20% 4 -4% 1M - - 0 0% 0 0% 1 0% 0 20% 1 20% 1.5M - - - - - - 0 33.3% - -% 1 -20% 2M - - - - - - 0 0% - -% 0 20% Max. Note: 254 (1) U2X0 = 0 U2X0 = 1 500kbps 1Mbps U2X0 = 0 1Mbps U2X0 = 1 2Mbps U2X0 = 0 1.2Mbps U2X0 = 1 2.4Mbps 1. UBRR = 0, Error = 0.0% AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Table 18-10. Examples of UBRR0 Settings accessible Oscillator Frequencies (Continued) fosc = 20 MHz Baud Rate (bps) UBRR Error UBRR Error 2400 520 0% 1041 0% 4800 259 0.2% 520 0% 9600 129 0.2% 259 0.2% 14.4k 86 -0.2% 173 -0.2% 19.2k 64 0.2% 129 0.2% 28.8k 42 0.9% 86 -0.2% 38.4k 32 -1.4% 64 0.2% 57.6k 21 -1.4% 42 0.9% 76.8k 15 1.7% 32 -1.4% 115.2k 10 -1.4% 21 -1.4% 230.4k 4 8.5% 10 -1.4% 250k 4 0% 9 0% 500k 2 -16.7% 4 0% 1M 0 25% 2 -16.7% 1.5M 1 -16.7% 2M 0 25% Max. Note: (1) U2X0 = 0 U2X0 = 1 1.25Mbps 2.5Mbps 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 • • • • • • • • 19.2 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 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. 1. 19.4 Equations for Calculating Baud Rate Register Setting Operating Mode Equation for Calculating Baud Rate (1) Equation for Calculating UBRR0 Value Synchronous Master mode f OSC BAUD = --------------------------------------2 ( UBRRn + 1 ) f OSC UBRRn = -------------------- – 1 2BAUD The baud rate is defined to be the transfer rate in bit per second (bps) BAUD Baud rate (in bits per second, bps) fOSC System Oscillator clock frequency: clkIO UBRR0 Contents of the UBRR0H and UBRR0L Registers, (0-4095) 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. 258 UCPOL0 and UCPHA0 Functionality- UCPOL0 UCPHA0 SPI Mode Leading Edge Trailing Edge 0 0 0 Sample (Rising) Setup (Falling) 0 1 1 Setup (Rising) Sample (Falling) 1 0 2 Sample (Falling) Setup (Rising) 1 1 3 Setup (Falling) Sample (Rising) AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Figure 19-1. UCPHA0 and UCPOL0 data transfer timing diagrams. UCPHA=0 UCPHA=1 UCPOL=0 19.5 UCPOL=1 XCK XCK Data setup (TXD) Data setup (TXD) Data sample (RXD) Data sample (RXD) XCK XCK Data setup (TXD) Data setup (TXD) Data sample (RXD) Data sample (RXD) 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. Note 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. 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<<UMSEL01)|(1<<UMSEL00)|(0<<UCPHA0)|(0<<UCPOL0) out UCSR0C,r18 ; Enable receiver and transmitter. ldi r18, (1<<RXEN0)|(1<<TXEN0) out UCSR0B,r18 ; Set baud rate. ; IMPORTANT: The Baud Rate must be set after the transmitter is enabled! out UBRR0H, r17 out UBRR0L, r18 ret C Code Example void USART_Init( unsigned int baud ) { UBRR0 = 0; /* Setting the XCK0 port pin as output, enables master mode. */ XCK0_DDR |= (1<<XCK0); /* Set MSPI mode of operation and SPI data mode 0. */ UCSR0C = (1<<UMSEL01)|(1<<UMSEL00)|(0<<UCPHA0)|(0<<UCPOL0); /* Enable receiver and transmitter. */ UCSR0B = (1<<RXEN0)|(1<<TXEN0); /* Set baud rate. */ /* IMPORTANT: The Baud Rate must be set after the transmitter is enabled */ UBRR0 = baud; } 19.6 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. Note 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. 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<<UDRE0)) ); /* Put data into buffer, sends the data */ UDR0 = data; /* Wait for data to be received */ while ( !(UCSR0A & (1<<RXC0)) ); /* Get and return received data from buffer */ return UDR0; } 19.6.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. 19.6.2 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.7 USART MSPIM Register Description The following section describes the registers used for SPI operation using the USART. 19.7.1 262 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. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 19.7.2 UCSR0A – USART MSPIM Control and Status Register 0 A Bit 7 6 5 4 3 2 1 0 RXC0 TXC0 UDRE0 - - - - - Read/write R R/W R R R R R/W R/W Initial value 0 0 1 0 0 0 0 0 $0000C0 UCSR0A 0x20 • 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 7 6 5 4 3 2 1 0 RXCIE0 TXCIE0 UDRIE0 RXE0 TXE0 - - - Read/write R/W R/W R/W R/W R/W R/W R R/W Initial value 0 0 0 0 0 0 0 0 $0000C1 UCSR0B 0x00 • 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 7 6 5 4 3 2 1 0 UMSEL01 UMSEL00 - - - UDORD0 UCPHA UCPOL0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 1 1 0 $0000C2 UCSR0C 0x06 • 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. UMSEL0 Bits Settings UMSEL01 UMSEL00 Mode 0 0 Asynchronous USART 0 1 Synchronous USART 1 0 (Reserved) 1 1 Master SPI (MSPIM) • 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 19.8 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. 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. USART_MSPIM SPI Comment TxD0 MOSI Master Out only RxD0 MISO Master In only XCK0 SCK (Functionally identical) (N/A) SS Not supported by USART in MSPIM 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 • • • • • • • • 20.2 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 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 SPI2X SPI2X DIVIDER /2/4/8/16/32/64/128 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 SPI Pin Overrides Direction, Master SPI Direction, Slave SPI MOSI User Defined Input MISO Input User Defined SCK User Defined Input SS User Defined 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 r17,(1<<DD_MOSI)|(1<<DD_SCK) out DDR_SPI,r17 ; Enable SPI, Master, set clock rate fck/16 ldi r17,(1<<SPE)|(1<<MSTR)|(1<<SPR0) out SPCR,r17 ret SPI_MasterTransmit: ; Start transmission of data (r16) out SPDR,r16 Wait_Transmit: ; Wait for transmission complete sbis SPSR,SPIF rjmp Wait_Transmit ret C Code Example void SPI_MasterInit(void) { /* Set MOSI and SCK output, all others input */ DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK); /* Enable SPI, Master, set clock rate fck/16 */ SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0); } void SPI_MasterTransmit(char cData) { /* Start transmission */ SPDR = cData; /* Wait for transmission complete */ while(!(SPSR & (1<<SPIF))) ; } 270 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 r17,(1<<DD_MISO) out DDR_SPI,r17 ; Enable SPI ldi r17,(1<<SPE) out SPCR,r17 ret SPI_SlaveReceive: ; Wait for reception complete sbis SPSR,SPIF rjmp SPI_SlaveReceive ; Read received data and return in r16,SPDR ret C Code Example void SPI_SlaveInit(void) { /* Set MISO output, all others input */ DDR_SPI = (1<<DD_MISO); /* Enable SPI */ SPCR = (1<<SPE); } char SPI_SlaveReceive(void) { /* Wait for reception complete */ while(!(SPSR & (1<<SPIF))) ; /* Return Data Register */ return SPDR; } 271 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 7 6 5 4 3 2 1 0 0x2C (0x4C) SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 SPCR 0x00 • 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: CPOL Functionality Table 20-2. CPOL Leading Edge Trailing Edge 0 Rising Falling 1 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: CPHA Functionality Table 20-3. CPHA Leading Edge Trailing Edge 0 Sample Setup 1 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. Relationship Between SCK and the Oscillator Frequency SPI2X SPR1 SPR0 SCK Frequency 0 0 0 clkIO/4 0 0 1 clkIO/16 0 1 0 clkIO/64 0 1 1 clkIO/128 1 0 0 clkIO/2 273 TPR0327AY–SMS–30Jan09 Table 20-4. 20.4.2 Relationship Between SCK and the Oscillator Frequency SPI2X SPR1 SPR0 SCK Frequency 1 0 1 clkIO/8 1 1 0 clkIO/32 1 1 1 clkIO/64 SPSR – SPI Status Register Bit 7 6 5 4 3 2 1 0 SPIF WCOL - - - - - SPI2X Read/write R R R R R R R R/W Initial value 0 0 0 0 0 0 0 0 0x2D (0x4D) SPSR 0x00 • 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 7 6 5 4 Read/write R/W R/W R/W R/W Initial value x x x x 0x2E (0x4E) 3 2 1 0 R/W R/W R/W R/W x x x x SPDR [7:0] SPDR 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: CPOL Functionality Table 20-5. Leading Edge Trailing eDge SPI Mode CPOL=0, CPHA=0 Sample (Rising) Setup (Falling) 0 CPOL=0, CPHA=1 Setup (Rising) Sample (Falling) 1 CPOL=1, CPHA=0 Sample (Falling) Setup (Rising) 2 CPOL=1, CPHA=1 Setup (Falling) Sample (Rising) 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 Tx 8-Bit Shift Register HSMISO Lsb Rx 8-Bit Shift Register M M Buffer HSMOSI DPRAM S clk HSSPI Clock HSSPI Clock (Master) S HSSPI Controller HSSCK M S HSSS HSSPI Status Register MSTR CPOL CPHA BTD 32 SPIEN SPICKRDY M HSSPI Control Register 32 32 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 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 8 Bit Shift Register Lsb Msb HSMISO Slave Lsb 8 Bit Shift Register HSMOSI Master HSSPI Clock Generator Chip as Master HSSCK Chip as Slave The DPRAM stores two 16 Bytes buffers for transmission and two 16 Bytes buffers for reception. 21.2.1 21.2.1.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. 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 YES TXBUFE? (HSSPISR) 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) Data to receive? Wait BTD (HSSPIIR) 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 YES TXBUFE? (HSSPISR) 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 YES nb_data to receive >16? nb_data to receive >16? Write 16 in HSSPICNT Write 16 in HSSPICNT NO NO Write nb_data left in HSSPICNT Write nb_data to receive in HSSPICNT 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 Read nb_data in HSSPICNT Copy nb_data into RAM using HSSPIDMA. Read received data directly into RAM YES Copy 16 into RAM using HSSPIDMA. Read received data directly into RAM Clear TIMEOUT (HSSPIIR) Disable DMA (Clear HSSPICFG.DPRAM) Enable DMA (Set HSSPICFG.DPRAM) Clear BTD (HSSPIIR) 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. SPI Pin Overrides Pin Direction, Master SPI Direction, Slave SPI MOSI Output Input MISO Input Output SCK Output Input NSS Output 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 7 $0000D9 6 5 SPICKDIV [2..0] 4 DPRAM 3 2 1 0 HSCPHA HSCPOL HSMSTR HSSPIEN Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 1 0 0 0 0 0 0 0 HSSPICFG 0x80 • 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. HSSPI dividers(1) Table 21-2. SPICKDIV2 SCKCKDIV1 SCKCKDIV0 Divider External clock divider ratio(1) 0 0 0 4 24 Mhz 0 0 1 5 19.2 Mhz 0 1 0 6 16 Mhz 0 1 1 8 12 Mhz 1 0 0 12 8 Mhz 1 0 1 24 4 Mhz 1 1 0 48 2 Mhz 1 1 1 96 1 Mhz Note: Note 1. Base frequency is clkIO = 96Mhz 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. Note 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. • 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 Configuration CPHA Leading edge Trailing edge 0 Sample Setup 1 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 Configuration CPOL Leading edge Trailing edge 0 Rising Falling 1 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. Note 21.5.2 Configuring and activating the HSSPI peripheral with the same instruction is a valid action. HSSPIIR - HSSPI Interrupt Register Bit 7 6 5 4 3 2 1 0 TIMEOUT BTD RCVOF NSSRE NSSFE - - - Read/write R/W R/W R/W R/W R/W R R R Initial value 0 0 0 0 0 0 0 0 $0000DA HSSPIIR 0x00 • 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 7 6 5 4 TIMEOUTIE BTDIE RCVOFIE NSSIE 3 2 1 0 - - - - Read/write R/W R/W R/W R/W R R R R Initial value 0 0 0 0 0 0 0 0 HSSPIIER 0x00 • 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 7 6 5 4 3 2 1 0 $0000DB - - - - - STTTO RETTO CS Read/write R R R R R W W W Initial value 0 0 0 0 0 0 0 0 HSSPICR 0x00 • 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 7 6 5 4 3 2 1 0 $0000D8 - - - DPRAMRDY NSS RXBUFF Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 TXBUFE SPICKRDY HSSPISR 0x00 • 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 7 6 5 $0000D7 4 3 2 1 0 HSSPITDD [7..0] HSSPITDR Read/write W W W W W W W W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 $0000D6 4 3 2 1 0 HSSPIRDD [7..0] HSSPIRDR Read/write R R R R R R R R Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 $0000D5 4 3 2 1 0 HSSPIGTD [7..0] HSSPIGTR Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 $0000D3 - - - 4 3 2 1 0 Read/write R R R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 HSSPICNTD [4..0] HSSPICNT 0x00 • 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. Thus, the DMA controller will point to the other DPRAM buffer. Note 21.5.10 HSSPITIMEOUT - HSSPI Timeout Register Bit 15 14 13 $0000D2 11 10 9 8 SPITIMEOUT[15..8] $0000D1 HSSPITOH SPITIMEOUT [7..0] Bit Read/write 12 HSSPITOL 7 6 5 4 3 2 1 0 R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W 0 0 0 0 0 0 0 0 0x00 0 0 0 0 0 0 0 0 0x00 Initial value • 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. ! Caution All the registers described in this section cannot be accessed if the HSSPI module is not enabled. 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 Reception DPRAM RAM $10FF DMAB DMAD 0 16 bytes HSSPIDMACS.DMAR 0 1 16 bytes 1 0 HSSPIDMACS.DMAR 16 bytes 1 $100 16 bytes Transmission DPRAM DMA Controller Diagram Automatic Switch 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. Note 21.6.1 HSSPIDMACS - HSSPIDMA Control and Status register This is the control and status register of the HSSPIDMA controller. Bit 7 6 5 4 3 2 1 0 $0000DC - - - - - HSSPIDMAERR HSSPIDMADIR HSSPIDMAR Read/write R R R R R R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 HSSPIDMACS 0x00 • 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. ! Caution Don’t forget to clear the HSSPIDMACS.DMAERR bit before leaving the interruption routine to avoid repetitive and endless interruptions. • 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. Note Note 294 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. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 21.6.2 HSSPIDMAD - HSSPIDMA ADdress registers Bit 15 14 - - Bit 7 6 5 4 3 2 1 0 Read/write R R R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W R/W $0000DE 13 12 11 10 9 8 HSSPIDMAD [13..8] $0000DD HSSPIDMADH HSSPIDMAD [8..0] Initial value HSSPIDMADL 0 0 0 0 0 0 0 1 0x01 0 0 0 0 0 0 0 0 0x00 • 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 7 6 5 4 3 2 1 0 $00DF - - - Read/write R R R R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 HSSPIDMAB [4..0] HSSPIDMAB 0x00 • 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 296 The maximum value allowed for HSSPIDMAB is 16. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 22. 2-wire Serial Interface _ TWI 22.1 Features • • • • • • • • • • 22.2 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 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. TWI Terminology Term Description Master The device that initiates and terminates a transmission. The Master also generates the SCL clock. 297 TPR0327AY–SMS–30Jan09 Table 22-1. TWI Terminology Term Description Slave The device addressed by a Master. Transmitter The device placing data on the bus. Receiver 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 22.3 22.3.1 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. 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 298 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 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 22.3.3 STOP REPEATED START START STOP 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 Addr LSB R/W ACK 7 8 9 SDA SCL 1 2 START 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 Data LSB ACK 8 9 Aggregate SDA SDA from Transmitter SDA from Receiver SCL from Master 1 2 7 SLA+R/W 22.3.5 STOP, REPEATED START or Next Data Byte Data Byte 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 1 START 300 2 Addr LSB R/W ACK Data MSB 7 8 9 1 SLA+R/W 2 7 Data Byte Data LSB ACK 8 9 ST 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 Slew-rate Control SDA Spike Filter Slew-rate Control Spike Filter Bus Interface Unit START / STOP Control Bit Rate Generator Spike Suppression Address/Data Shift Register (TWDR) Arbitration detection Prescaler Address Match Unit Address Register (TWAR) Bit Rate Register (TWBR) Ack Control Unit Status Register (TWSR) Address Comparator Control Register (TWCR) State Machine and Status control TWI Unit SCL 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. 22.5.2 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: CPU Clock frequency SCL frequency = ----------------------------------------------------------TWPS 16 + 2(TWBR) ⋅ 4 • TWBR = Value of the TWI Bit Rate Register. 303 TPR0327AY–SMS–30Jan09 • TWPS = Value of the prescaler bits in the TWI Status Register Note 22.5.3 Pull-up resistor values should be selected according to the SCL frequency and the capacitive bus line load. 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. 22.5.5 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. 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. Application Action Figure 22-10. Interfacing the Application to the TWI in a Typical Transmission 1. Application writes to TWCR to initiate transmission of START TWI Hardware Action TWI bus 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. START 2. TWINT set. Status code indicates START condition sent SLA+W 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 A 4. TWINT set. Status code indicates SLA+W sent, ACK received Data 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 A 6. TWINT set. Status code indicates data sent, ACK received STOP 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 1 ldi r16, (1<<TWINT)|(1<<TWSTA)| in r16,TWCR andi r16, 0xF8 cpi 3 TWDR, r16 ldi r16, (1<<TWINT) | (1<<TWEN) out TWCR, r16 wait2: in r16,TWCR andi r16, 0xF8 cpi 5 ; if ((TWSR & 0xF8) != START) ERROR(); r16, MT_SLA_ACK brne ERROR ldi r16, DATA out TWDR, r16 ldi r16, (1<<TWINT) | (1<<TWEN) out Wait for TWINT Flag set. This indicates that the START condition has been transmitted Check value of TWI Status Register. Mask prescaler bits. If status different from START go to ERROR TWDR = SLA_W; TWCR = (1<<TWINT) | (1<<TWEN); while (!(TWCR & (1<<TWINT))) ; sbrs r16,TWINT rjmp wait2 in r16,TWSR Send START condition while (!(TWCR & (1<<TWINT))) r16, START brne ERROR ldi r16, SLA_W out 4 (1<<TWEN) sbrs r16,TWINT rjmp wait1 in r16,TWSR Comments TWCR = (1<<TWINT)|(1<<TWSTA)| (1<<TWEN) out TWCR, r16 wait1: 2 C Example if ((TWSR & 0xF8) != MT_SLA_ACK) ERROR(); Load SLA_W into TWDR Register. Clear TWINT bit in TWCR to start transmission of address Wait for TWINT Flag set. This indicates that the SLA+W has been transmitted, and ACK/NACK has been received. Check value of TWI Status Register. Mask prescaler bits. If status different from MT_SLA_ACK go to ERROR TWDR = DATA; TWCR = (1<<TWINT) | (1<<TWEN); Load DATA into TWDR Register. Clear TWINT bit in TWCR to start transmission of data TWCR, r16 307 TPR0327AY–SMS–30Jan09 Assembly Code Example wait3: 6 in while (!(TWCR & (1<<TWINT))) r16,TWCR ; sbrs r16,TWINT rjmp wait3 in r16,TWSR if ((TWSR & 0xF8) != MT_DATA_ACK) andi r16, 0xF8 cpi 7 C Example ERROR(); r16, MT_DATA_ACK brne ERROR ldi r16, (1<<TWINT)|(1<<TWEN)| 22.7 Wait for TWINT Flag set. This indicates that the DATA has been transmitted, and ACK/NACK has been received. Check value of TWI Status Register. Mask prescaler bits. If status different from MT_DATA_ACK go to ERROR TWCR = (1<<TWINT)|(1<<TWEN)| (1<<TWSTO); (1<<TWSTO) out Comments Transmit STOP condition TWCR, r16 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 Device 2 MASTER TRANSMITTER Device 3 SLAVE RECEIVER ........ R1 Device n 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 1 0 X 1 0 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 0 0 X 1 0 X When SLA+W have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x18, 0x20, or 0x38. The appropriate action to be taken for each of these status codes is detailed in Table 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 0 0 X 1 0 X This scheme is repeated until the last byte has been sent and the transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 0 1 X 1 0 X A REPEATED START condition is generated by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE 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 of the bus. Table 22-2. Status Code (TWSR) Prescaler Bits are 0 Status codes for Master Transmitter Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware To/from TWDR 0x08 A START condition has been transmitted 0x10 A repeated START condition has been transmitted 0x18 0x20 310 SLA+W has been transmitted; ACK has been received SLA+W has been transmitted; NOT ACK has been received To TWCR STA STO TWIN T TWE A Load SLA+W 0 0 1 X SLA+W will be transmitted; ACK or NOT ACK will be received Load SLA+W or 0 0 1 X Load SLA+R 0 0 1 X SLA+W will be transmitted; ACK or NOT ACK will be received SLA+R will be transmitted; Logic will switch to Master Receiver mode Load data byte or 0 0 1 X No TWDR action or No TWDR action or 1 0 0 1 1 1 X X No TWDR action 1 1 1 X Load data byte or 0 0 1 X No TWDR action or No TWDR action or 1 0 0 1 1 1 X X No TWDR action 1 1 1 X Next Action Taken by TWI Hardware 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 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Table 22-2. 0x28 0x30 0x38 Status codes for Master Transmitter Mode Data byte has been transmitted; ACK has been received Data byte has been transmitted; NOT ACK has been received Arbitration lost in SLA+W or data bytes Load data byte or 0 0 1 X No TWDR action or No TWDR action or 1 0 0 1 1 1 X X No TWDR action 1 1 1 X Load data byte or 0 0 1 X No TWDR action or No TWDR action or 1 0 0 1 1 1 X X No TWDR action 1 1 1 X No TWDR action or 0 0 1 X No TWDR action 1 0 1 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 311 TPR0327AY–SMS–30Jan09 Figure 22-12. Formats and States in the Master Transmitter Mode MT Successfull transmission to a slave receiver S SLA $08 W A DATA $18 A P $28 Next transfer started with a repeated start condition RS SLA W $10 Not acknowledge received after the slave address A R P $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 $38 Arbitration lost and addressed as slave A $68 From master to slave From slave to master 22.7.2 312 A or A Other master continues $38 Other master continues $78 DATA To corresponding states in slave mode $B0 A n 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 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. 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 1 0 X 1 0 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 0 0 X 1 0 X When SLA+R have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x38, 0x40, or 0x48. The appropriate action to be taken for each of these status codes is detailed in Table 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 0 1 X 1 0 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 Status codes for Master Receiver Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware To TWCR To/from TWDR STA STO TWIN T TWE A Next Action Taken by TWI Hardware 0x08 A START condition has been transmitted Load SLA+R 0 0 1 X SLA+R will be transmitted ACK or NOT ACK will be received 0x10 A repeated START condition has been transmitted Load SLA+R or 0 0 1 X Load SLA+W 0 0 1 X SLA+R will be transmitted ACK or NOT ACK will be received SLA+W will be transmitted Logic will switch to Master Transmitter mode No TWDR action or 0 0 1 X No TWDR action 1 0 1 X No TWDR action or 0 0 1 0 No TWDR action 0 0 1 1 No TWDR action or No TWDR action or 1 0 0 1 1 1 X X No TWDR action 1 1 1 X 0 0 1 0 0x38 0x40 0x48 Arbitration lost in SLA+R or NOT ACK bit SLA+R has been transmitted; ACK has been received SLA+R has been transmitted; NOT ACK has been received 0x50 Data byte has been received; ACK has been returned Read data byte or Read data byte 0 0 1 1 0x58 Data byte has been received; NOT ACK has been returned Read data byte or Read data byte or 1 0 0 1 1 1 X X Read data byte 1 1 1 X 314 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 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 $08 R A DATA $40 A DATA $50 A P $58 Next transfer started with a repeated start condition RS SLA R $10 Not acknowledge received after the slave address A W P $48 MT Arbitration lost in slave address or data byte A or A Other master continues $38 Arbitration lost and addressed as slave A $68 From master to slave From slave to master 22.7.3 A Other master continues $38 Other master continues $78 DATA To corresponding states in slave mode $B0 A n 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 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 TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device’s Own Slave Address value The upper 7 bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address. TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 0 1 0 0 0 1 0 X TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the 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. ! Caution Table 22-4. Status Code (TWSR) Prescaler Bits are 0 theTWI Serial Interface Data Register – TWDR does not reflect the last byte present on the bus when waking up from these Sleep modes. Status Codes for Slave Receiver Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware To TWCR To/from TWDR STA STO TWIN T TWE A X 0 1 0 0x60 Own SLA+W has been received; ACK has been returned No TWDR action or No TWDR action X 0 1 1 0x68 Arbitration lost in SLA+R/W as Master; own SLA+W has been received; ACK has been returned No TWDR action or X 0 1 0 No TWDR action X 0 1 1 0x70 General call address has been received; ACK has been returned No TWDR action or X 0 1 0 No TWDR action X 0 1 1 0x78 Arbitration lost in SLA+R/W as Master; General call address has been received; ACK has been returned No TWDR action or X 0 1 0 No TWDR action X 0 1 1 0x80 Previously addressed with own SLA+W; data has been received; ACK has been returned Read data byte or X 0 1 0 Read data byte X 0 1 1 0x88 Previously addressed with own SLA+W; data has been received; NOT ACK has been returned Read data byte or 0 0 1 0 Read data byte or 0 0 1 1 Read data byte or 1 0 1 0 Read data byte 1 0 1 1 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 317 TPR0327AY–SMS–30Jan09 Table 22-4. Status Codes for Slave Receiver Mode 0x90 Previously addressed with general call; data has been received; ACK has been returned Read data byte or X Read data byte X 0 1 1 0x98 Previously addressed with general call; data has been received; NOT ACK has been returned Read data byte or 0 0 1 0 Read data byte or 0 0 1 1 Read data byte or 1 0 1 0 Read data byte 1 0 1 1 No action 0 0 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0xA0 318 A STOP condition or repeated START condition has been received while still addressed as Slave 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 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 $60 A DATA $80 Last data byte received is not acknowledged A P or S $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 $70 A DATA $90 Last data byte received is not acknowledged A P or S $90 $A0 A P or S $98 Arbitration lost as master and addressed as slave by general call A $78 From master to slave From slave to master 22.7.4 DATA A n 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 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 Device 2 SLAVE TRANSMITTER Device 3 MASTER RECEIVER ........ Device n R1 R2 SDA SCL To initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows: TWAR TWA6 TWA5 value 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 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 0 1 0 0 0 1 0 X TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the 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 0xB0 0xB8 0xC0 0xC8 Status Codes for Slave Transmitter Mode Application Software Response Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware To TWCR To/from TWDR STA STO TWIN T TWE A Load data byte or X 0 1 0 Load data byte X 0 1 1 Arbitration lost in SLA+R/W as Master; own SLA+R has been received; ACK has been returned Load data byte or X 0 1 0 Load data byte X 0 1 1 Data byte in TWDR has been transmitted; ACK has been received Load data byte or X 0 1 0 Load data byte X 0 1 1 Data byte in TWDR has been transmitted; NOT ACK has been received No TWDR action or 0 0 1 0 No TWDR action or 0 0 1 1 No TWDR action or 1 0 1 0 No TWDR action 1 0 1 1 No TWDR action or 0 0 1 0 No TWDR action or 0 0 1 1 No TWDR action or 1 0 1 0 No TWDR action 1 0 1 1 Own SLA+R has been received; ACK has been returned Last data byte in TWDR has been transmitted (TWEA = “0”); ACK has been received 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 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 $A8 Arbitration lost as master and addressed as slave DATA $B8 A P or S $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 From slave to master 22.7.5 Any number of data bytes and their associated acknowledge bits A 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 n 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. Miscellaneous States Status Code (TWSR) Prescaler Bits are 0 Status of the 2-wire Serial Bus and 2-wire Serial Interface Hardware Application Software Response To TWCR To/from TWDR 0xF8 No relevant state information available; TWINT = “0” No TWDR action 0x00 Bus error due to an illegal START or STOP condition No TWDR action 22.7.6 322 STA STO TWIN T TWE A No TWCR action 0 1 1 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. 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: 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 S SLA+W A ADDRESS S = START A Rs SLA+R A DATA Rs = REPEATED START Transmitted from master to slave 22.8 Master Receiver A P P = STOP Transmitted from slave to master 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 Device 2 MASTER TRANSMITTER 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 Arbitration lost in SLA Own Address / General Call received No STOP Arbitration lost in Data 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 Direction Write 68/78 Read Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received B0 22.9 22.9.1 Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned TWI Register Description TWBR – TWI Bit Rate Register Bit 7 6 5 4 3 2 1 0 TWBR7 TWBR6 TWBR5 TWBR4 TWBR3 TWBR2 TWBR1 TWBR0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $0000B8 TWBR 0x00 • 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 7 6 5 4 3 2 1 0 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE Read/write R/W R/W R/W R/W R R/W R R/W Initial value 0 0 0 0 0 0 0 0 $0000BC TWCR 0x00 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 7 6 5 4 3 2 1 0 TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 Read/write R R R R R R R/W R/W Initial value 1 1 1 1 1 0 0 0 TWSR 0x00 • 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. TWI Bit Rate Prescaler TWPS1 TWPS0 Prescaler Value 0 0 1 0 1 4 1 0 16 1 1 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 7 6 5 4 3 2 1 0 TWD7 TWD6 TWD5 TWD4 TWD3 TWD2 TWD1 TWD0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 1 1 1 1 1 1 1 1 $0000BB TWDR 0xFF 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 7 6 5 4 3 2 1 0 TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 1 1 1 1 1 1 1 0 $0000BA TWAR 0xFE 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 7 6 5 $0000BD 4 3 2 1 TWAM [6:0] 0 - Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 TWAMR 0x00 • 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 Match Address Bit 0 TWAMR0 Address Bit Comparator 0 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). Note 23.2.2 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. 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 Input Circuitry PA6: KbIN 6 Input Circuitry PA5: KbIN 5 Input Circuitry PA4: KbIN 4 Input Circuitry PA3: KbIN 3 Input Circuitry PA2: KbIN 2 Input Circuitry PA1: KbIN 1 Input Circuitry PA0: KbIN 0 Input Circuitry Keyboard IT Keyboard interface Interrupt request Global IT bit 329 TPR0327AY–SMS–30Jan09 Figure 23-2. Keyboard Input Circuitry 0 KBF.x KbIN x 1 KBE.x KBLS.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 Keyboard Register Description 23.3.1 KBFR - KeyBoard Flag Register Bit 7 6 5 4 3 2 1 0 KBF7 KBF6 KBF5 KBF4 KBF3 KBF2 KBF1 KBF0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $008F KBFR 0x00 • 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 7 6 5 4 3 2 1 0 KBE7 KBE6 KBE5 KBE4 KBE3 KBE2 KBE1 KBE0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $008E KBER 0x00 • 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 7 6 5 4 3 2 1 0 KBLS7 KBLS6 KBLS5 KBLS4 KBLS3 KBLS2 KBLS1 KBLS0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 $008D KBLSR 0x00 • 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 7 6 5 4 3 2 1 0 $000095 - - - - - - - ROSCE Read/write R R R R R R R R/W Initial value 0 0 0 0 0 0 0 0 RNGCR 0x00 • 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 7 6 5 $000094 4 3 2 1 0 LFSD [31..24] LFSR3 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value x x x x x x x x Bit 7 6 5 4 3 2 1 0 $000093 LFSD [23..16] LFSR2 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value x x x x x x x x Bit 7 6 5 4 3 2 1 0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value x x x x x x x x Bit 7 6 5 4 3 2 1 0 $000092 LFSD [15..8] $000091 LFSR1 LFSD [7..0] LFSR0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value x x x x x x x x • 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 7 6 5 $000090 4 3 2 1 0 RDD [7..0] RDWDR Read/write R R R R R R R R Initial value x x x x x x x x • 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 • • • • • • 25.2 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 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 Internal Memory AESADDR AESACR AESACR.KD Address Decoder AES Key Register AES Block 0x31 AESACR.KD=0 AESDR AES Engine AESACR.KD=1 0x00 AES Data Register 0x15 0x00 AES Control System AES Interrupt signal 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. ! Caution ! Caution ! All bytes must be reverted in the AES Data and Key memory. This means that the data must be oriented LSB first As memory is reversed, the AES 128Key LSB will start at address #16 and MSB of AES128 key will be at address #31 The result is also inverted in Data internal memory (LSB first). Caution Below is a way to organize the memory according to an example: Figure 25-2. Example of memory organization AES128 Key: 00010203050607080A0B0C0D0F101112 Data To cipher: 506812A45F08C889B97F5980038B8359 Ciphered Message: D8F532538289EF7D06B506A4FD5BE9C9 AES_Key AES_Data AES_Result #31 #15 #15 #16 #15 00 01 02 03 05 06 07 08 0A 0B 0C 0D 0F 10 11 12 #00 50 68 12 A4 5F 08 C8 89 B9 7F 59 80 03 8B 83 59 #00 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 #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 7 6 AESIE AESIF Read/write R/W R/W R/W Initial value 0 0 0 $0078 5 4 3 2 1 0 KS - ENCRYPT AESGO R/W R/W R R/W R/W 0 0 0 0 0 AUTOKEY KEYGN AESCR 0x00 • 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 7 6 5 4 3 2 1 0 $0079 - - - - XOR MANINC AUTOINC KD Read/write R R R R R/W W R/W R/W Initial value 0 0 0 0 0 0 1 0 AESACR 0x02 • 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. Note 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. • 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 7 6 5 4 Read/write R/W R/W R/W R/W Initial value x x x x $007A 3 2 1 0 R/W R/W R/W R/W x x x x ADDR [7..0] AESADDR 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 7 6 5 4 Read/write R/W R/W R/W R/W Initial value x x x x $007B 3 2 1 0 R/W R/W R/W R/W x x x x DATA [7..0] AESDR 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 r16, (1<<AUTOINC) sts AESACR, r16 343 TPR0327AY–SMS–30Jan09 ; Init address in AES memory (for 128bits, starting at #16) ldi r16, 0x10 sts AESADDR, r16 call keydata_load ; Loading Data ldi r16, (1<<AUTOINC) || (1<<KD) sts AESACR, r16 ; Init address in AES memory clr r16 sts AESADDR, r16 movw ZL, YL call keydata_load ; Start Encryption ldi r16, (1<<ENCRYPT) sts AESCR, r16 ori r16, (1<<AESGO) sts AESCR, r16 poll_end_AES: lds r16, AESCR sbrs r16, AESIF rjmp poll_end_AES ; read the result back ldi r16, (1<<KD) sts AESACR, r1 clr r16 sts AESADDR, r16 ldi r16, 16 ldi r17, (1<<KD) ori r17, (1<<MANINC) ; update X register for reverted copy adiw XL, 16 ReadResult: ; copy the result in the X targeted area lds r18, AESDR st -X, r18 ; update internal address sts 344 AESACR, r17 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 r17, -Z sts AESDR, r17 dec 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® 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 JTAG PROGRAMMING INTERFACE TAP CONTROLLER AVR CPU FLASH MEMORY INSTRUCTION REGISTER ID REGISTER M U X Address Data BREAKPOINT UNIT BYPASS REGISTER INTERNAL SCAN CHAIN PC Instruction 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 1 0 1 0 1 Capture-DR Capture-IR 0 0 Shift-DR Shift-IR 0 1 Exit1-DR 0 Pause-DR 0 0 Pause-IR 1 1 0 Exit2-DR Exit2-IR 1 1 Update-DR 26.4 1 Exit1-IR 0 1 0 1 1 0 1 Select-IR Scan Update-IR 0 1 0 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. Note 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. 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® 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. 26.7.4 PRIVATE3; 0xB Private JTAG instruction for accessing On-chip debug system. 351 TPR0327AY–SMS–30Jan09 26.8 26.8.1 On-chip Debug Related Register in I/O Memory OCDR – On-chip Debug Register Bit 7 6 5 4 3 2 1 0 0x31 (0x51) D7/IDRD D6 D5 D4 D3 D2 D1 D0 Read/write R/W R/W R/W R/W R/W R/W R/W R/W Initial value 0 0 0 0 0 0 0 0 OCDR 0x00 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 • • • • • 27.2 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 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. 27.3.2 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 LSB 28 27 12 11 1 0 Version Part Number Manufacturer ID 1 4 bits 16 bits 11 bits 1-bit 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 D Q Internal reset 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 7 6 5 4 3 2 1 0 0x35 (0x55) JTD - - PUD - - IVSEL IVCE Read/write R/W R R R/W R R R/W R/W Initial value 0 0 0 0 0 0 0 0 MCUCR 0x00 • 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 7 6 5 4 3 2 1 0 0x34 (0x54) - - - JTRF WDRF BORF EXTRF PORF Read/write R R R R/W R/W R/W R/W R/W Initial value 0 0 0 x x x x 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. To Next Cell ShiftDR EXTEST Pull-up Enable (PUE) Vcc 0 1 Output Control (OC) FF1 LD1 0 D Q D Q 0 1 1 G 0 1 FF0 LD0 0 D Q D 1 Q 0 1 Port Pin (PXn) Output Data (OD) G Input Data (ID) From Last Cell 358 ClockDR UpdateDR 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 RESET OCxn WDx Q Pxn ODxn DATA BUS RDx D PORTxn Q CLR WRx IDxn RESET RRx SLEEP SYNCHRONIZER D Q RPx Q D PINxn L Q Q CLK PUD: PUExn: OCxn: ODxn: IDxn: SLEEP: 27.6.2 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: I/O WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN I/O CLOCK 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 Q 1 From Previous Cell ClockDR 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. 360 AT90SCR100 Boundary-scan Order Bit Number Signal Name 68 PE0.Data 67 PE0.Control 66 PE1.Data 65 PE1.Control 64 PE2.Data 63 PE2.Control 62 PE3.Data 61 PE3.Control 60 PE4.Data 59 PE4.Control 58 PE5.Data 57 PE5.Control 56 PE6.Data 55 PE6.Control 54 PE7.Data 53 PE7.Control Module Port E AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Table 27-1. AT90SCR100 Boundary-scan Order (Continued) Bit Number Signal Name 52 PB0.Data 51 PB0.Control 50 PB1.Data 49 PB1.Control 48 PB2.Data 47 PB2.Control 46 PB3.Data 45 PB3.Control 44 PB4.Data 43 PB4.Control 42 PB5.Data 41 PB5.Control 40 PB6.Data 39 PB6.Control 38 PB7.Data 37 PB7.Control 36 RSTT 35 PD0.Data 34 PD0.Control 33 PD1.Data 32 PD1.Control 31 PD2.Data 30 PD2.Control 29 PD3.Data 28 PD3.Control 27 PD4.Data 26 PD4.Control 25 PD5.Data 24 PD5.Control 23 PD6.Data 22 PD6.Control 21 PD7.Data 20 PD7.Control Module Port B Reset Logic (Observe Only) Port D 361 TPR0327AY–SMS–30Jan09 Table 27-1. 27.8 AT90SCR100 Boundary-scan Order (Continued) Bit Number Signal Name 19 PC0.Data 18 PC0.Control 17 PC1.Data 16 PC1.Control 15 PA7.Data 14 PA7.Control 13 PA6.Data 12 PA6.Control 11 PA5.Data 10 PA5.Control 9 PA4.Data 8 PA4.Control 7 PA3.Data 6 PA3.Control 5 PA2.Data 4 PA2.Control 3 PA1.Data 2 PA1.Control 1 PA0.Data 0 PA0.Control Module Port C Port A 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 28.2 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. 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. 28.2.2 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. 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. 364 Read-While-Write Features Which Section does the Z-pointer Address During the Programming? Which Section Can be Read During Programming? Is the CPU Halted? Read-While-Write Supported? RWW Section NRWW Section No Yes NRWW Section None Yes No 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 NRWW Section Z-pointer Addresses RWW Section Read-While-Write (RWW) Section No Read-While-Write Section Figure 28-2. Memory Sections Program Memory 0x7FFF Boot Loader Flash Section 0x7E00 BOOTSZ=’11’ 0x7C00 BOOTSZ=’10’ 0x7800 BOOTSZ=’01’ 0x7000 Read-While-Write Section 0x6FFF Application Flash Section Start Boot Loader/End Application Limitation BOOTSZ=’00’ 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 BLB02 BLB01 1 1 1 No restrictions for SPM or (E)LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 0 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. 1 (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 4 Table 28-3. 0 0 Protection Boot Lock Bit1 Protection Modes (Boot Loader Section)(1) BLB1 Mode BLB12 BLB11 1 1 1 No restrictions for SPM or (E)LPM accessing the Boot Loader section. 2 1 0 SPM is not allowed to write to the Boot Loader section. 0 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. 1 (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 4 Note: 366 Boot Lock Bit0 Protection Modes (Application Section)(1) 0 0 Protection 1. “1” means unprogrammed, “0” means programmed 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. Boot Reset Fuse(1) BOOTRST Note: 28.5.1 Reset Address 1 Reset Vector = Application Reset (address 0x0000) 0 Reset Vector = Boot Loader Reset (see Table 28-7 on page 376) 1. “1” means unprogrammed, “0” means programmed 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 7 6 5 4 0x37 (0x57) SPMIE RWWSB Read/write R/W R R/W R/W Initial value 0 0 0 1 3 2 1 0 PGWRT PGERS SPMEN R/W R/W R/W R/W 0 0 0 0 SIGRD RWWSRE BLBSET SPMCSR 0x00 • 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 15 14 13 12 11 10 7 8 ZH (R31) Z15 Z14 Z13 Z12 Z11 Z10 Z9 Z8 ZH (R30) Z7 Z6 Z5 Z4 Z3 Z2 Z1 Z0 7 6 5 4 3 2 1 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 15 ZPCMSB ZPAGEMSB Z - REGISTER 1 0 0 PCMSB PROGRAM COUNTER PAGEMSB PCPAGE PAGE ADDRESS WITHIN THE FLASH PROGRAM MEMORY PAGE PCWORD 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. 28.7.5 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. 28.7.6 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. 28.7.7 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 7 6 5 4 3 2 1 0 R0 1 1 BLB12 BLB11 BLB02 BLB01 LB2 LB1 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. 28.7.9 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 7 6 5 4 3 2 1 0 Rd - - BLB12 BLB11 BLB02 BLB01 LB2 LB1 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 7 6 5 4 3 2 1 0 Rd FLB7 FLB6 FLB5 FLB4 FLB3 FLB2 FLB1 FLB0 Similarly, when reading the Fuse High byte, load 0x0003 in the Z-pointer. When an (E)LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse High byte (FHB) will be loaded in the destination register as shown below. Refer to Table 29-4 on page 379 for detailed description and mapping of the Fuse High byte. Bit 7 6 5 4 3 2 1 0 Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0 When reading the Extended Fuse byte, load 0x0002 in the Z-pointer. When an (E)LPM 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 7 6 5 4 3 2 1 0 Rd - - - - - EFB2 EFB1 EFB0 Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are unprogrammed, will be read as one. 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 Byte Z-Pointer Address Device Signature Byte 1 0x0000 Device Signature Byte 2 0x0002 Device Signature Byte 3 0x0004 RC Oscillator Calibration Byte 0x0001 Serial Number byte 0 0x0006 Serial Number byte 1 0x0008 Serial Number byte 2 0x000A Serial Number byte 3 0x000C Serial Number byte 4 0x000E Serial Number byte 5 0x0010 Serial Number byte 6 0x0012 Serial Number byte 7 0x0014 Serial Number byte 8 0x0016 Note: 28.7.11 Signature Row Addressing(1) 1. All other addresses are reserved for future use. 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. Symbol Min Programming Time Max Programming Time Flash write (Page Erase, Page Write, and write Lock bits by SPM) 3.7 ms 4.5 ms Note 28.7.13 SPM Programming Time These programming time are true after production calibration. If the oscillator trimming is modified, these values will be changed. 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<<PGERS) | (1<<SPMEN) call Do_spm ; re-enable the RWW section ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN) call Do_spm ; transfer data from RAM to Flash page buffer ldi looplo, low(PAGESIZEB) ;init loop variable ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256 Wrloop: ld r0, Y+ ld r1, Y+ ldi spmcrval, (1<<SPMEN) call Do_spm adiw ZH:ZL, 2 sbiw loophi:looplo, 2 ;use subi for PAGESIZEB<=256 brne Wrloop ; execute Page Write 374 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 subi sbci ldi call ZL, low(PAGESIZEB) ;restore pointer ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256 spmcrval, (1<<PGWRT) | (1<<SPMEN) Do_spm ; re-enable the RWW section ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN) call Do_spm ; read back and check, optional ldi looplo, low(PAGESIZEB) ;init loop variable ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256 subi YL, low(PAGESIZEB) ;restore pointer sbci YH, high(PAGESIZEB) Rdloop: elpm r0, Z+ ld r1, Y+ cpse r0, r1 jmp Error sbiw loophi:looplo, 1 ;use subi for PAGESIZEB<=256 brne Rdloop ; return to RWW section ; verify that RWW section is safe to read Return: in temp1, SPMCSR sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet ret ; re-enable the RWW section ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN) call Do_spm rjmp Return Do_spm: ; check for previous SPM complete Wait_spm: in temp1, SPMCSR sbrc temp1, SPMEN rjmp Wait_spm ; input: spmcrval determines SPM action ; disable interrupts if enabled, store status in temp2, SREG cli ; check that no EEPROM write access is present Wait_ee: sbic EECR, EEPE rjmp Wait_ee ; SPM timed sequence out SPMCSR, spmcrval spm ; restore SREG (to enable interrupts if originally enabled) out SREG, temp2 ret Note 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. Table 28-7. Boot Size Configuration Application Flash Section Boot Loader Flash Section End Application Section Boot Reset Address (Start Boot Loader Section) 4 0x0000 - 0x7DFF 0x7E00 - 0x7FFF 0x7DFF 0x7E00 1024 words 8 0x0000 - 0x7BFF 0x7C00 - 0x7FFF 0x7BFF 0x7C00 1 2048 words 16 0x0000 - 0x77FF 0x7800 - 0x7FFF 0x77FF 0x7800 0 4096 words 32 0x0000 - 0x6FFF 0x7000 - 0x7FFF 0x6FFF 0x7000 BOOTSZ1 BOOTSZ0 Boot Size 1 1 512 words 1 0 0 0 Pages The different BOOTSZ Fuse configurations are shown in Figure 28-2. Table 28-8. Read-While-Write Limit(1) Section Pages Address Read-While-Write section (RWW) 224 0x0000 - 0x6FFF No Read-While-Write section (NRWW) 32 0x7000 - 0x7FFF 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. Explanation of different variables used in Figure 28-3 and the mapping to the Z-pointer Correspondig Z-value Variable Description(1) PCMSB 14 Most significant bit in the Program Counter. (The Program Counter is 15 bits PC[14:0]) PAGEMSB 7 Most significant bit which is used to address the words within one page (128 words in a page requires seven bits PC [6:0]). ZPCMSB Z15 Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not used, the ZPCMSB equals PCMSB + 1. ZPAGEMSB Z8 Bit in Z-pointer that is mapped to PCMSB. Because Z0 is not used, the ZPAGEMSB equals PAGEMSB + 1. PCPAGE PC[14:7] Z15:Z7 Program Counter page address: Page select, for Page Erase and Page Write PCWORD PC[6:0] Z7:Z1 Program Counter word address: Word select, for filling temporary buffer (must be zero during Page Write operation) Note: 1. Z0: should be zero for all SPM commands, byte select for the (E)LPM instruction. See “Addressing the Flash During Self-Programming” on page 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. Lock Bit Byte(1) Table 29-1. Notes: Lock Bit Byte Bit No Description Default Value – 7 – 1 (unprogrammed) – 6 – 1 (unprogrammed) BLB12 5 Boot Lock bit 1 (unprogrammed) BLB11 4 Boot Lock bit 1 (unprogrammed) BLB02 3 Boot Lock bit 1 (unprogrammed) BLB01 2 Boot Lock bit 1 (unprogrammed) LB2 1 Lock bit 1 (unprogrammed) LB1 0 Lock bit 1 (unprogrammed) 1. “1” means unprogrammed, “0” means programmed 377 TPR0327AY–SMS–30Jan09 Table 29-2. Lock Bit Protection Modes(1) Memory Lock Bits LB Mode LB2 LB1 1 1 1 No memory lock features enabled. 2 1 0 Further programming of the Flash and EEPROM is disabled in Serial Programming mode. The Fuse bits are locked in Serial Programming mode. 3 0 0 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. BLB0 Mode BLB02 BLB01 1 1 1 No restrictions for SPM or (E)LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 0 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 4 0 1 BLB1 Mode BLB12 BLB11 1 1 1 No restrictions for SPM or (E)LPM accessing the Boot Loader section. 2 1 0 SPM is not allowed to write to the Boot Loader section. 0 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. 1 (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 4 Notes: 378 Protection Type 0 0 1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2. 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. Extended Fuse Byte Fuse Low Byte Bit No Description Default Value – 7 – 1 – 6 – 1 – 5 – 1 – 4 – 1 – 3 – 1 – 2 – 1 – 1 – 1 BODENABLE(1) 0 Brown-out Detector Enable Control 1 (unprogrammed) Notes: 1. Refer to Table 9-2 on page 54 to get decoding of BODENABLE bit. Table 29-4. Fuse High Byte Fuse High Byte Bit No Description Default Value OCDEN(1) 7 Enable OCD 1 (unprogrammed, OCD disabled) JTAGEN 6 Enable JTAG 0 (programmed, JTAG enabled) SPIEN(2) 5 Enable Serial Program and Data Downloading 0 (programmed, SPI prog. enabled) WDTON(3) 4 Watchdog Timer always on 1 (unprogrammed) EESAVE 3 EEPROM memory is preserved through the Chip Erase 1 (unprogrammed, EEPROM not preserved) BOOTSZ1 2 Select Boot Size (see Table 28-7 for details) 0 (programmed)(4) BOOTSZ0 1 Select Boot Size (see Table 28-7 for details) 0 (programmed)(4) BOOTRST 0 Select Reset Vector 1 (unprogrammed) 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. Fuse Low Byte Fuse Low Byte Bit No Description Default Value 7 - 1 6 Clock output 1 (unprogrammed) SUT1 5 Select start-up time 1 (unprogrammed)(2) SUT0 4 Select start-up time 0 (programmed)(2) CKSEL3 3 Select Clock source 1 (unprogrammed) - 2 - 0 (3) - 1 - 0 (3) CKSEL0 0 Select Clock source 1 (unprogrammed) CKOUT Notes: (1) 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 29.3 29.3.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. 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 29.3.2 JTAG Part 0x000 0x001 0x002 Part Number Manufacture ID AT90SCR100 0x1E 0x96 0x09 96C1 0x1F 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 Table 29-7. No. of Words in a Page and No. of Pages in the Flash Device AT90SCR100 Table 29-8. Flash Size 32K words (64 Kbytes) PCWORD No. of Pages PCPAGE PCMSB 128 words PC[6:0] 256 PC[14:7] 14 No. of Words in a Page and No. of Pages in the EEPROM Device AT90SCR100 29.6 Page Size EEPROM Size Page Size PCWORD No. of Pages PCPAGE EEAMSB 4 Kbytes 32 bytes EEA[2:0] 128 EEA[10:3] 10 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. Pin Mapping Serial Programming Symbol Pins I/O Description MOSI PB5 I Serial Data in MISO PB6 O Serial Data out SCK PB7 I Serial Clock 381 TPR0327AY–SMS–30Jan09 Figure 29-1. Serial Programming and Verify +1.8 - 5.5V VCC +1.8 - 5.5V(2) MOSI AVCC MISO SCK XT AL1 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 29.7 Symbol Minimum Wait Delay tWD_FLASH 4.5 ms tWD_EEPROM 9.0 ms tWD_ERASE 9.0 ms 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 Byte 1 Byte 2 Byte 3 Byte4 Programming Enable $AC $53 $00 $00 Chip Erase (Program Memory/EEPROM) $AC $80 $00 $00 Poll RDY/BSY $F0 $00 $00 data byte out Load Extended Address byte(1) $4D $00 Extended adr $00 Load Program Memory Page, High byte $48 $00 adr LSB high data byte in Load Program Memory Page, Low byte $40 $00 adr LSB Load Instructions Load EEPROM Memory Page (page access) $C1 $00 $28 adr MSB 0000 000aa low data byte in (2) data byte in Read Instructions Read Program Memory, High byte adr LSB high data byte out 383 TPR0327AY–SMS–30Jan09 Table 29-11. Serial Programming Instruction Set (Hexadecimal values) Instruction Format Instruction/Operation Byte 1 Byte 2 Byte 3 Byte4 Read Program Memory, Low byte $20 adr MSB adr LSB low data byte out Read EEPROM Memory $A0 0000 00aa(2) aaaa aaaa(2) data byte out Read Lock bits $58 $00 $00 data byte out 0000 aaaa (2) Read Signature Byte $30 $00 Read Fuse bits $50 $00 $00 data byte out Read Fuse High bits $58 $08 $00 data byte out Read Extended Fuse Bits $50 $08 $00 data byte out Read Calibration Byte $38 $00 $00 data byte out $4C adr MSB data byte out Write Instructions Write Program Memory Page Write EEPROM Memory $C0 (2) 0000 00aa (2) $00 aaaa aaaa (2) data byte in aaaa aa00 (2) $00 Write EEPROM Memory Page (page access) $C2 Write Lock bits $AC $E0 $00 data byte in Write Fuse bits $AC $A0 $00 data byte in Write Fuse High bits $AC $A8 $00 data byte in Write Extended Fuse Bits $AC $A4 $00 data byte in Notes: 0000 00aa adr LSB 1. Not all instructions are applicable for all parts. 2. a = address 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) Byte 1 Byte 2 Adr MSB A MSB Bit 15 B Byte 3 Write Program Memory Page/ Write EEPROM Memory Page Byte 1 Byte 4 Byte 2 Adr MSB Adr LSB Bit 15 B 0 Byte 3 Byte 4 A Adr drr LS LSB SB 0 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) MSB LSB SERIAL DA TA OUTPUT (MISO) MSB LSB SERIAL CLOCK INPUT (SCK) SAMPLE 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 1 0 1 0 1 Capture-DR Capture-IR 0 0 Shift-DR Shift-IR 0 1 1 0 Pause-DR 0 0 Pause-IR 1 1 0 Exit2-DR Exit2-IR 1 1 Update-DR 386 1 Exit1-IR 0 1 0 1 Exit1-DR 0 1 Select-IR Scan Update-IR 0 1 0 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 TDO Sequence 1a. Chip Erase 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx 1b. Poll for Chip Erase Complete 0110011_10000000 xxxxxox_xxxxxxxx 2a. Enter Flash Write 0100011_00010000 xxxxxxx_xxxxxxxx 2b. Load Address Extended High Byte 0001011_cccccccc xxxxxxx_xxxxxxxx 2c. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx 2d. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 2e. Load Data Low Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx 2f. Load Data High Byte 0010111_iiiiiiii xxxxxxx_xxxxxxxx 2g. Latch Data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 2h. Write Flash Page 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 2i. Poll for Page Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (1) 3a. Enter Flash Read 0100011_00000010 xxxxxxx_xxxxxxxx 3b. Load Address Extended High Byte 0001011_cccccccc xxxxxxx_xxxxxxxx 3c. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx 3d. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 3e. Read Data Low and High Byte 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo 4a. Enter EEPROM Write 0100011_00010001 xxxxxxx_xxxxxxxx 4b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx 4c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 4d. Load Data Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx 4e. Latch Data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 4f. Write EEPROM Page 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 390 Notes (1) (2) (2) Low byte High byte (2) 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 TDI Sequence TDO Sequence Notes 4g. Poll for Page Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (1) 5a. Enter EEPROM Read 0100011_00000011 xxxxxxx_xxxxxxxx 5b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx 5c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 5d. Read Data Byte 0110011_bbbbbbbb 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 0100011_01000000 xxxxxxx_xxxxxxxx 6b. Load Data Low Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx (5) 6c. Write Fuse Extended Byte 0111011_00000000 0111001_00000000 0111011_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 6d. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (1) 6e. Load Data Low Byte(6) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (5) 6f. Write Fuse High Byte 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 6g. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (1) 6h. Load Data Low Byte(6) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (5) 6i. Write Fuse Low Byte 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 6j. Poll for Fuse Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (1) 7a. Enter Lock Bit Write 0100011_00100000 xxxxxxx_xxxxxxxx 0010011_11iiiiii xxxxxxx_xxxxxxxx (8) 7c. Write Lock Bits 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) 7d. Poll for Lock Bit Write complete 0110011_00000000 xxxxxox_xxxxxxxx (1) 8a. Enter Fuse/Lock Bit Read 0100011_00000100 xxxxxxx_xxxxxxxx 8b. Read Extended Fuse Byte(4) 0111010_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 8c. Read Fuse High Byte(6) 0111110_00000000 0111111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 6a. Enter Fuse Write (4) 7b. Load Data Byte (7) (2) 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 TDI Sequence TDO Sequence 8d. Read Fuse Low Byte(9) 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 8e. Read Lock Bits(7) 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxoooooo 8f. Read Fuses and Lock Bits 0111010_00000000 0111110_00000000 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_oooooooo 9a. Enter Signature Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx 9b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 9c. Read Signature Byte 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 10a. Enter Calibration Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx 10b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 10c. Read Calibration Byte 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 11a. Load No Operation Command 0100011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx Notes: Notes (10) (10) Fuse Ext. byte Fuse High byte Fuse Low byte Lock bits 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. 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 1 0 0 1 1 Capture-DR Capture-IR 0 0 0 Shift-DR 1 1 Exit1-DR 0 0 Pause-DR 0 Pause-IR 1 1 0 Exit2-DR Exit2-IR 1 1 Update-DR 29.8.11 1 Exit1-IR 0 1 0 Shift-IR 1 0 1 Select-IR Scan Update-IR 0 1 0 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. 29.8.13 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. 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 Table 30-1. Ordering Information (1) Part Number Voltage Range (V) Temperature Range Package (2) AT90SCR100LSD-Z1T 2.4-5.5 Industrial & Green QFN32 Tray AT90SCR100LSD-Z1R(2) 2.4-5.5 Industrial & Green QFN32 Reel AT90SCR100LHS-Z1T(3) 2.4-5.5 Industrial & Green QFN32 Tray (3) 2.4-5.5 Industrial & Green QFN32 Reel AT90SCR100LHS-Z1R Note: Packing AT90SCR100H-ALT 2.4-5.5 Industrial & Green LQFP64 Tray AT90SCR100H-ALR 2.4-5.5 Industrial & Green LQFP64 Reel AT90SCR100H-Z1T 2.4-5.5 Industrial & Green QFN64 Tray AT90SCR100H-Z1R 2.4-5.5 Industrial & Green QFP64 Reel 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. On all packages, the e-pad must be connected to ground. Caution 399 TPR0327AY–SMS–30Jan09 30.2 Typical Application C3 C4 DVcc Vcc Card C4/D+ Card C8/D- CIO Card IO R5 C2 Vss Vss2 Vss3 AVss Host R3 R4 CC4 CC8 Vcc1 Vcc2 Vcc3 Vcc4 3.3V C1 UCAP AT90SCR100 Card Vcc CVcc C9 CVss Li RESET L1 RST Lo D+ D- R1 R2 CVsense RTC1 XTAL2 : As DCDC generates noise, we encourage the use of another supply power than global Vcc, if possible. Table 30-2. C5 RTC2 Q2 Q1 (1) (1) Vdcdc D+ D- XTAL1 3.3V C7 C6 Rled C8 Rs Led0 3.3V Dled External Components, Bill Of Materials Reference Description Value Comment R1, R2 R3, R4 USB Pad Serial Resistor 22Ω +/-10% - R5 CIO Pull-up Resistor 10KΩ +/-10% (Optional) Can be required for high speed communication Rs DCDC Sense Resistor 200mΩ +/-2% 125mW Current Sensing: Overcurrent detection C1 Power Supply Decoupling capacitor 4.7μF +/-10% Maximum application capacitance allowed by USB standard is 10μF C2 Power Supply Filter capacitor 100nF - C3 Internal Core Regulator Decoupling capacitor 2.2μF +/-10% Used for internal regulator stability C4 Internal USB Regulator Decoupling capacitor 2.2μF +/-10% Used for internal regulator stability C5, C6 PLL Filter capacitors 47pF +/-10% - C7, C8 RTC Filter capacitors 22pF +/-10% Only if Real Time Counter is used. C9 DCDC Decoupling Capacitor 10μF +/-10% esr=100mΩ Tantalum capacitor is needed Recommended: AVX: TPSE106-035-200 L1 DCDC inductance 6.8μH esr=20.2mΩ Recommended: Gowanda: SMP3316LP-681M Q1 Crystal 8.0 Mhz Q2 Real Time Crystal 3.768 Mhz Only if Real Time Counter is used Rled/Dled LED mechanism -- Depends on the configuration of the Led Controller 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 Vs s1 PD 1 cd CV c Se CV nse ss AT90SCR100LSD - QFN32 => Standard SPI ( PD TxD ) 0 (R RE xD SE ) T LO 30.3.1 Pinout Vd 30.3 32 31 30 29 28 27 26 25 Vcc1 1 24 Li DVcc 2 23 CVcc Vss3 3 22 AVss XTal1 4 21 CCLK XTal2 5 20 CRST CC4/Host_D+ 6 19 CIO CC8/Host_D- 7 18 CPRES USB_D- 8 17 Vss2 QFN32 9 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_ US 402 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Vd Vs s1 PD 1 cd CV c Se CV nse ss AT90SCR100LHS - QFN32 => High-Speed SPI ( PD TxD ) 0 (R RE xD SE ) T LO 30.3.2 32 31 30 29 28 27 26 25 Vcc1 1 24 Li DVcc 2 23 CVcc Vss3 3 22 AVss XTal1 4 21 CCLK XTal2 5 20 CRST CC4/Host_D+ 6 19 CIO CC8/Host_D- 7 18 CPRES USB_D- 8 17 Vss2 QFN32 9 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_ US 403 TPR0327AY–SMS–30Jan09 63 62 61 60 59 58 57 56 55 54 53 52 51 Vd cd c CV Se n 3 PE 64 se AT90SCR100H - QFN64 & LQFP64 (K PA bO 3 0 (K ) b PE In 0 2 (K ) PE bO 2 1 (K ) PE bO 1 0 (K ) PA bO 0 5 (K ) b PA In 5 4 (K ) b PB In 4) 2 PD 1 (T PD xD ) 0 (R x PC D ) 1 (sd PC a) 0 (sc RE l) SE T LO 30.3.3 50 49 PA1 (KbIn1) 1 48 LI PA2 (KbIn2) 2 47 CVcc PA3 (KbIn3) 3 46 CCLK PE4 (KbO4) 4 45 CRST PE5 (KbO5) 5 44 CIO Vcc1 6 43 CPRES Vcc2 7 42 Vcc5 DVcc 8 41 PA7 (KbIn7) QFN64 RTC1 (Tosc1) 9 40 PA6 (KbIn6) RTC2 (Tosc2) 10 39 PD2 (int0) XTal1 11 38 PD3 (int1) XTal2 12 37 PB0 (int2) CC4/Host_D+ 13 36 PB1 (int3) CC8/Host_D- 14 35 PD4 (hs-ss) USB_D- 15 34 PB3 (pwm) USB_D+ 16 33 PB4 (ss) Vc PB 24 25 26 27 28 29 30 31 32 ) ) d3 (le ) d2 (le ) d1 d0 (le (le 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 o) (K 6 mis PE s (h 7 ) PD iso (m 6 23 c3 22 5 PC AP 4 PC 21 PC UC 20 PC 19 3 18 2 17 e-pad, underneath package must be connected to ground NC: Not Connected (pin16, 32) 404 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 30.4 Mechanical Information 30.4.1 QFN32 D 1 2 3 Pin 1 ID E SIDE VIEW 0.10 A3 TOP VIEW A2 A1 K A D2 0.05 C COMMON DIMENSIONS (Unit of Measure = mm) E2 0.45 Pitch #1 Notch (0.20 R) 3 2 K 1 SYMBOL MIN NOM MAX A – – 0.90 A1 – – 0.05 A2 – 0.65 0.70 A3 e b L b 0.20 REF 0.18 D BOTTOM VIEW D2 0.30 5.00 BSC 3.40 3.50 3.80 5.00 BSC E E2 0.25 3.40 3.50 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.60 0.45 – 405 TPR0327AY–SMS–30Jan09 30.4.2 QFN 64 Pin 1 ID E SIDE VIEW A2 D A1 A TOP VIEW C 0.05 C D2 COMMON DIMENSIONS (Unit of Measure = mm) E2 Pitch #1 Notch (0.20 R) 3 2 1 b SYMBOL MIN NOM MAX A 0.80 – 1.00 A1 0 – 0.05 A2 – – 0.95 D/E 8.90 9.00 9.10 D2/E2 3.25 – 7.50 e e 0.50 BSC L 0.30 0.40 0.55 b 0.18 0.25 0.3 L BOTTOM VIEW Note: Compliant JEDEC Standard MO-220 variation VMMD-3 406 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 30.4.3 LQFP64 _ TBC 64-lead PIN 1 COMMON DIMENSIONS (Unit of Measure = mm) b PIN 1 IDENTIFIER E2 E1 E e D2 D1 D c 0°~7° L L1 A1 A2 A SYMBOL MIN NOM MAX A – – 1.60 A1 0.05 – 0.15 A2 1.35 1.40 1.45 D 12.00 BSC D1 10.00 BSC D2 7.50 E 12.00 BSC E1 10.00 BSC E2 7.50 b 0.17 0.20 0.27 c 0.09 – 0.20 L 0.45 0.60 0.75 L1 1.00 REF e 0.50 BSC 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.................................... -40°C to +85°C Storage Temperature ..................................... -65°C to +150°C 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 *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. DC Current VCC and GND Pins.........................................TBD 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 ! 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 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 TA = -40°C to 85°C, VCC = 2.4V to 5.5V (unless otherwise noted) Symbol VIL (2) VIH (2) Parameter Min.(1) Condition Input Low Voltage VCC = 2.4V - 5.5V Typ. -0.3 0.8 (4) (3) Units V Input High Voltage VCC = 2.4V - 5.5V Hysteresis on Input VCC = 2.4V - 5.5V VOL(2) Output Low Voltage, VCC = 2.4V - 5.5V (2) Output High Voltage, VCC = 2.4V - 5.5V IIL(2) Input Leakage Current I/O Pin VCC = 5.5V, pin low (absolute value) 1 μA IIH(2) Input Leakage Current I/O Pin VCC = 5.5V, pin high (absolute value) 1 μA RRST Reset Pull-up Resistor 30 60 kΩ RPU I/O Pin Pull-up Resistor 20 50 kΩ Active 8MHz, VCC = 5V (AT90SCR100) TBD mA Idle 8MHz, VCC = 5V (AT90SCR100) TBD mA 150 μA VIHys VOH (2) ICC Power Supply Current (5) Power-down mode(6) Notes: 2.0 Max.(1) VCC + 0.3 V 0.7 V 0.4 V 0.4 VCC - 0.4 V 100(7) VCC = 5V 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 200μA generated by the different resistors on USB D+/Dlines. 31.3 PORT Symbol Parameter Min Typ Max Unit Test Conditions IOL Output Low Current, PC2, PC3, PC4, PC5 LED modes 1 2 3 6 5 8 mA mA 2 mA configuration 4 mA configuration IOL Output Low Current, PORT E 2 mA IOL Output Low Current, all other PORTS 8 mA Note: 410 (TA = -20°C to +50°C, VCC - VOL = 2 V ) AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 31.4 Clocks 31.4.1 XTAL1 : External Clock In TBC/TBD This clock relates to Core and System clock. See “Clock Sources” on page 33. XTAL1 = XIN Clock Electrical Characteristics Table 31-1. 31.4.2 Symbol Parameter 1/tCPXIN XIN Clock Frequency Max. Units 8 MHz tCHXIN XIN Clock High Half-Period 0.4 x tCPXIN tCLCX XIN Clock Low HAlf-Period 0.4 x tCPXIN CIN XIN Input Capacitance RIN XIN Pulldown Resistor Calibrated Internal RC Oscillator Accuracy This clock concerns the Flash/Eeprom specific clock. See “Internal RC Oscillator” on page 37. Table 31-2. Calibration Accuracy of Internal RC Oscillator Frequency VCC Temperature Calibration Accuracy 10.0 MHz 3V 25⋅C ±5% 9.5 - 10.5 MHz 2.4V - 5.5V -40⋅C - 85⋅C ±1% Factory Calibration User Calibration 31.5 Min. Communication Interfaces 31.5.1 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. 2-wire Serial Bus Requirements Symbol Parameter VIL VIH Input Low-voltage -0.5 0.3 VCC V Input High-voltage 0.6 VCC VCC + 0.5 V – V 0.4 V 20 + 0.1Cb(2)(3) 300 ns (2)(3) 250 ns (2) ns Output Low-voltage tof(1)(8) Ci Units Hysteresis of Schmitt Trigger Inputs tr(1)(8) tSP Max (1) Vhys VOL Min (1) (1)(8) (1)(8) Condition 0.05 VCC 3 mA sink current 0 Rise Time for both SDA and SCL Output Fall Time from VIHmin to VILmax 10 pF < Cb < 400 pF (2) (3) 20 + 0.1Cb Spikes Suppressed by Input Filter 0 Capacitance for each I/O Pin – 10 pF fCK (4)> max(16fSCL, 250kHz)(5) 0 400 kHz fSCL ≤ 100 kHz 4.0 – μs fSCL > 100 kHz 0.6 – μs fSCL SCL Clock Frequency tHD;STA Hold Time (repeated) START Condition 50 411 TPR0327AY–SMS–30Jan09 Table 31-3. Symbol 2-wire Serial Bus Requirements (Continued) Parameter Condition tLOW Low Period of the SCL Clock tHIGH High period of the SCL clock tSU;STA Set-up time for a repeated START condition tHD;DAT Data hold time tSU;DAT Data setup time tSU;STO Setup time for STOP condition tBUF Bus free time between a STOP and START condition Notes: Min Max Units (6) 4.7 – μs (7) 1.3 – μs fSCL ≤ 100 kHz 4.0 – μs fSCL > 100 kHz 0.6 – μs fSCL ≤ 100 kHz 4.7 – μs fSCL > 100 kHz 0.6 – μs fSCL ≤ 100 kHz 0 3.45 μs fSCL > 100 kHz 0 0.9 μs fSCL ≤ 100 kHz 250 – ns fSCL > 100 kHz 100 – ns fSCL ≤ 100 kHz 4.0 – μs fSCL > 100 kHz 0.6 – μs fSCL ≤ 100 kHz 4.7 – μs fSCL > 100 kHz 1.3 – μs fSCL ≤ 100 kHz fSCL > 100 kHz 1. In AT90SCR100, this parameter is characterized and not 100% tested. 2. Required only for fSCL > 100 kHz. 3. Cb = capacitance of one bus line in pF. 4. fCK = CPU clock frequency 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 tHIGH tLOW tr tLOW SCL tSU;STA tHD;STA SDA tHD;DAT tSU;DAT tSU;STO tBUF 31.5.2 412 High-Speed SPI Interface Characteristics TBD AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 31.5.3 SPI Timing Characteristics TBC/TBD See Figure 31-2 and Figure 31-3 for details. Table 31-4. SPI Timing Parameters(2) Description Mode 1 SCK period Master See Table 20-4 2 SCK high/low Master 50% duty cycle 3 Rise/Fall time Master 3.6 4 Setup Master 10 5 Hold Master 10 6 Out to SCK Master 0.5 • tsck 7 SCK to out Master 10 8 SCK to out high Master 10 9 SS low to out Slave 15 10 SCK period Slave 4 • tck 11 SCK high/low(1) Slave 2 • tck 12 Rise/Fall time Slave 13 Setup Slave 10 14 Hold Slave tck 15 SCK to out Slave 16 SCK to SS high Slave 17 SS high to tri-state Slave 18 SS low to SCK Slave Notes: Min Typ Max ns 1600 15 20 10 20 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 MISO (Data Input) 5 3 MSB ... LSB 7 MO SI (Data Output) MSB 8 ... LSB 413 TPR0327AY–SMS–30Jan09 Figure 31-3. SPI Interface Timing Requirements (Slave Mode) SS 10 9 16 SCK (CPOL = 0) 11 11 SCK (CPOL = 1) 13 MO SI (Data Input) 14 12 MSB ... LSB 17 15 MISO (Data Output) 31.6 MSB ... LSB X USB Interface Characteristics TBC/TBD Table 31-5. USB Electrical Parameters Symbol Parameter Condition Min. Typ. Max. Units VIH Input Level High (driven) 2.0 V VIHZ Input Level High (floating) 2.7 V VIL Input Level Low VDI Differential Input Sensitivity 0.2 VCM Differential Common Mode Range 0.8 VOL1 Static Output Low VOH1 Static Output High CIN Input Capacitance tr Rise Time Cout = 50 pF tf Fall Time Cout = 50 pF trfm Rise / Fall Time matching (tr/tr ) Zdrv Driver Output Resistance Steady State Drive tdrate Full Speed Data Rate Average Bit Rate tframe Frame Interval 414 0.8 V V 2.5 V 0.3 V 3.6 V 20 pF 4 20 ns 4 20 ns 90 110 % 28 44 ohm 11.97 12.03 Mb/s 0.9995 1.0005 ms 2.8 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 31.7 Smart Card Interface Characteristics ! Caution ! Caution Table 31-6. 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 Smart Card Class A, 5V (CVcc) Symbol Parameter Min Typ Max Unit Test Conditions CVCC Smart card voltage with Vcc = 2.7V to 2.85V with Vcc > 2.85V 4.6 4.6 5 5 5.4 5.4 V Load = 50mA Load = 60mA Spikes on CVCC TBD V Vcardok up Vcardok high level threshold TBD V Vcardok down Vcardok low level threshold TBD V TVHL CVCC valid to 0.4V TBD TBD μs TVLH CVCC 0 to valid TBD TBD μs Table 31-7. Smart Card Class B, 3V (CVcc) Symbol Parameter Min Typ Max Unit Test Conditions CVCC Smart card voltage with Vcc = 2.7V to 2.85V with Vcc > 2.85V 2.76 2.76 3 3 3.24 3.24 V Load = 50mA Load = 60mA Spikes on CVCC TBD V Vcardok up Vcardok high level threshold TBD V Vcardok down Vcardok low level threshold TBD V TVHL CVCC valid to 0.4V TBD TBD μs TVLH CVCC 0 to valid TBD TBD μs Min Typ Max Unit Test Conditions 1.66 1.8 1.944 V Load = 35mA Table 31-8. Smart Card C, 1.8V (CVcc) Symbol CVCC Vcardok up Parameter Smart card voltage Spikes on CVCC TBD V Vcardok high level threshold TBD V 415 TPR0327AY–SMS–30Jan09 Table 31-8. Smart Card C, 1.8V (CVcc) Symbol Vcardok down Parameter Min Vcardok low level threshold TBD TVHL CVCC valid to 0.4V TBD TVLH CVCC 0 to valid Table 31-9. Symbol Typ Max Unit Test Conditions V TBD TBD μs TBD TBD μs Typ Max Unit Smart Card Card Presence (CPRES) Parameter Min 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 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page (0xFF) SCICR Name RESET CARDDET VCARD1 VCARD0 UART WTEN CREP CONV 190 (0xFE) SCCON CLK - CARDC8 CARDC4 CARDIO CARDCLK CARDRST CARDVCC 192 (0xFD) SCISR SCTBE CARDIN - VCARDOK SCWTO SCTC SCRC SCPE 193 (0xFC) SCIIR SCTBI - - VCARDERR SCWTI SCTI SCRI SCPI 195 (0xFB) SCIER ESCTBI CARDINE - IVCARDER ESCWTI ESCTI ESCRI ESCPI 196 (0xFA) SCSR - BGTEN - CREPSEL CPRESRES - - - 196 (0xF9) SCIBUF (0xF8) SCETUH COMP - - - (0xF7) SCETUL (0xF6) SCGTH (0xF5) SCGTL (0xF4) SCIBUFD [7..0] 197 - ETU [10:8] 198 ETU [7:0] - - - - SCWT3 WT31 WT30 WT29 (0xF3) SCWT2 WT23 WT22 (0xF2) SCWT1 WT15 (0xF1) SCWT0 (0xF0) (0xEF) 198 - - - GT8 WT28 WT27 WT26 WT25 WT24 199 WT21 WT20 WT19 WT18 WT17 WT16 199 WT14 WT13 WT12 WT11 WT10 WT9 WT8 199 WT7 WT6 WT5 WT4 WT3 WT2 WT1 WT0 199 SCICLK XTSCS - SCICLK5 SCICLK4 SCICLK3 SCICLK2 SCICLK1 SCICLK0 199 DCCR DCON DCRDY DCBUSY - - - - - 203 - - - - - - - GT [7:0] 198 198 (0xEE) Reserved - (0xED) USBDMAB - (0xEC) USBDMADH - (0xEB) USBDMADL (0xEA) USBDMACS - EPS2 EPS1 EPS0 - DMAERR DMAIR DMAR 173 (0xE9) USBFNH - - - FNEND FNERR FN10 FN9 FN8 172 (0xE8) USBFNL FN7 FN6 FN5 FN4 FN3 FN2 FN1 FN0 172 (0xE7) USBFA - FADD6 FADD5 FADD4 FADD3 FADD2 FADD1 FADD0 171 (0xE6) USBGS - - - - RSMON RMWUE FCF FAF 171 (0xE5) USBRSTE RSTE4 RSTE6 RSTE5 RSTE4 RSTE3 RSTE2 RSTE1 RSTE0 170 (0xE4) USBEIM EP7IM EP7IM EP5IM EP4IM EP3IM EP2IM EP1IM EP0IM 167 (0xE3) USBEI EP7I EP6I EP5I EP4I EP4I EP2I EP1I EP0I 166 (0xE2) USBPIM - - - - SOFIM RMWUIM RESIM SUSIM 166 (0xE1) USBPI - - - FEURI SOFI RMWUI RESI SUSI 165 (0xE0) USBCR URMWU - UPUC - - - USBE - 164 - USBDMAB [6..0] - 176 USBDMAD [13..8] 175 USBDMAD [7..0] 175 (0xDF) HSSPIDMAB - - (0xDE) HSSPIDMADH - - HSSPIDMAB [4..0] 295 (0xDD) HSSPIDMADL (0xDC) HSSPIDMACS - - - - - DMAERR DMADIR DMAR (0xDB) HSSPICR - - - - - STTTO RETTO CS 290 (0xDA) HSSPIIR TIMEOUT BTD RCVOF NSSRE NSSFE - - - 288 (0xD9) HSSPICFG SPICKDIV2 SPICKDIV1 SPICKDIV0 DPRAM CPHA CPOL MSTR SPIEN 287 (0xD8) HSSPISR - - - DPRAMRDY NSS RXBUFF TXBUFE SPICKRDY 290 (0xD7) HSSPITDR HSSPITDD [7..0] 291 (0xD6) HSSPIRDR HSSPIRDD [7..0] 291 (0xD5) HSSPIGTR HSSPIGTD [7..0] (0xD4) HSSPIIER TIMEOUTIE BTDIE RCVOFIE (0xD3) HSSPICNT - - - (0xD2) HSSPITOH SPITIMEOUT[15:8] (0xD1) HSSPITOL SPITIMEOUT[7:0] (0xD0) Reserved - - - - - - - - HSSPIDMAD [13..8] 295 HSSPIDMAD [7..0] NSSIE 295 293 291 - - - - HSSPICNT [4..0] 289 291 292 292 (0xCF) Reserved - - - - - - - (0xCE) Reserved - - - - - - - - (0xCD) USBFCEX EPE - - - - EPDIR EPTYP1 EPTYP0 169 (0xCC) USBDBCEX BCT7 BCT6 BCT5 BCT4 BCT3 BCT2 BCT1 BCT0 169 (0xCB) USBCSEX - IERR FSTALL TXPB STSENT RXSETUP RCVD TXC 167 (0xCA) USBENUM - - - - ENUM3 ENUM2 ENUM1 ENUM0 167 (0xC9) Reserved - - - - - - - - (0xC8) Reserved - - - - - - - - (0xC7) Reserved - - - - - - - - (0xC6) UDR0 (0xC5) UBRR0H (0xC4) UBRR0L (0xC3) Reserved - - (0xC2) UCSR0C UMSEL01 UMSEL00 UPM01 UPM00 (0xC1) UCSR0B RXCIE0 TXCIE0 UDRIE0 RXEN0 (0xC0) UCSR0A RXC0 TXC0 UDRE0 FE0 DOR0 USART0 I/O Data Register - - - - 249 USART0 Baud Rate Register High Byte 253 USART0 Baud Rate Register Low Byte - - - 253 - - - USBS0 UCSZ01 UCSZ00 UCPOL0 251 TXEN0 UCSZ02 RXB80 TXB80 250 UPE0 U2X0 MPCM0 249 417 TPR0327AY–SMS–30Jan09 Address (0xBF) Name Reserved Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 - - - - - - - - Page (0xBE) Reserved - - - - - - - (0xBD) TWAMR TWAM6 TWAM5 TWAM4 TWAM3 TWAM2 TWAM1 TWAM0 - 328 (0xBC) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE 325 (0xBB) TWDR (0xBA) TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE 327 (0xB9) TWSR TWS7 TWS6 TWS5 TWS4 TWS3 - TWPS1 TWPS0 326 (0xB8) TWBR (0xB7) Reserved - - - - - - - - (0xB6) ASSR - EXCLK AS2 TCN2UB OCR2AUB OCR2BUB TCR2AUB TCR2BUB (0xB5) Reserved - - - - - - - - (0xB4) OCR2B Timer/Counter2 Output Compare Register B 150 (0xB3) OCR2A Timer/Counter2 Output Compare Register A 150 (0xB2) TCNT2 Timer/Counter2 (8 Bit) (0xB1) TCCR2B FOC2A FOC2B - - WGM22 CS22 CS21 CS20 148 (0xB0) TCCR2A COM2A1 COM2A0 COM2B1 COM2B0 - - WGM21 WGM20 145 FLERRE NAKEDE - PERRE TXSTPE TXOUTE RXSTALLE RXINE 229 - NBUSYB 225 ALLOC - 224 (0xAF) UPDATX (0xAE) UPIENX (0xAD) UPCFG2X (0xAC) UPSTAX 2-wire Serial Interface Data Register 327 2-wire Serial Interface Bit Rate Register 324 149 PDAT [7..0] 229 INTFRQ [7..0] CFGOK OVERFI DTSEQ [1..0] (0xAB) UPCFG1X (0xAA) UPCFG0X (0xA9) UPCRX - PFREEZE INMODE - RSTDT - - PEN (0xA8) UPRST - - - - P3RST P2RST P1RST P0RST 222 (0xA7) UPNUM - - - - - - PNUM1 PNUM0 222 (0xA6) UPINTX FIFOCON NAKEDI RWAL PERRI TXSPI TXOUTI RXSTALLI RXINI 227 (0xA5) UPINRQX INRQ [7..0] (0xA4) UHFLEN FLEN [7..0] (0xA3) UHFNUMH (0xA2) UHFNUML (0xA1) UHADDR - (0xA0) UHIEN - HWUPE HSOFE RXRSME RSMEDE RSTE DDISCE DCONNE 220 (0x9F) UHINT - HWUPI HSOFI RXRSMI RSMEDI RSTI DDISCI DCONNI 219 (0x9E) UHCR UHEN PAD [1..0] FRZCLK - RESUME RESET SOFEN 217 (0x9D) UPERRX - COUNTER [1..0] CRC16 TIMEOUT PID DATAPID DATATGL 226 (0x9C) UPBCXH - - - (0x9B) UPBCXL (0x9A) UPINT - - - - PINT3 PINT2 PINT1 PINT0 230 (0x99) UHSR - - - - SPEED - - - 218 (0x98) Reserved - - - - - - - - (0x97) Reserved - - - - - - - - (0x96) Reserved - - - - - - - - (0x95) RNGCR - - - - - - - ROSCE (0x94) LFSR3 LFSD [31..24] 336 (0x93) LFSR2 LFSD [23..16] 336 (0x92) LFSR1 LFSD [15..8] 336 (0x91) LFSR0 LFSD [7..0] 336 (0x90) RDWDR RDD [7..0] (0x8F) KBFR KBF7 KBF6 KBF5 KBF4 KBF3 KBF2 KBF1 KBF0 330 (0x8E) KBER KBE7 KBE6 KBE5 KBE4 KBE3 KBE2 KBE1 KBE0 331 (0x8D) KBLSR KBLS7 KBLS6 KBLS5 KBLS4 KBLS3 KBLS2 KBLS1 KBLS0 332 (0x8C) Reserved - - - - - - - - (0x8B) OCR1BH Timer/Counter1 - Output Compare Register B High Byte 131 (0x8A) OCR1BL Timer/Counter1 - Output Compare Register B Low Byte 131 (0x89) OCR1AH Timer/Counter1 - Output Compare Register A High Byte 131 (0x88) OCR1AL Timer/Counter1 - Output Compare Register A Low Byte 131 (0x87) ICR1H Timer/Counter1 - Input Capture Register High Byte 131 (0x86) ICR1L Timer/Counter1 - Input Capture Register Low Byte 131 (0x85) TCNT1H Timer/Counter1 - Counter Register High Byte 130 (0x84) TCNT1L Timer/Counter1 - Counter Register Low Byte (0x83) Reserved - - - (0x82) TCCR1C FOC1A FOC1B - - - - - - (0x81) TCCR1B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10 128 (0x80) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 - - WGM11 WGM10 126 (0x7F) Reserved - - - - - - - - (0x7E) Reserved - - - - - - - - 418 - 225 - UNDERFI 150 PSIZE [0..2] PTYPE [1..0] - PBK [0..1 PTOKEN [0..1] - - PEPNUM [0..3] - 223 226 221 - FNUM [10..8] 221 FNUM [7..0] 221 HADDR [6..0] - - 221 PBYTCT [10..8] 230 PBYTCT [7..0] - 222 230 336 337 - 130 - - 129 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Address Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 (0x7D) Reserved Name - - - - - - - - Page (0x7C) Reserved - - - - - - - - (0x7B) AESDR DATA [0..8] (0x7A) AESADDR ADDR [0..8] (0x79) AESACR (0x78) AESCR (0x77) (0x76) (0x75) LEDCR (0x74) Reserved - - - - - - - - (0x73) PCMSK3 PCINT31 PCINT30 PCINT29 PCINT28 PCINT27 PCINT26 PCINT25 PCINT24 (0x72) Reserved - - - - - - - - (0x71) Reserved - - - - - - - - (0x70) TIMSK2 - - - - - OCIE2B OCIE2A TOIE2 153 (0x6F) TIMSK1 - - ICIE1 - - OCIE1B OCIE1A TOIE1 132 (0x6E) TIMSK0 - - - - - OCIE0B OCIE0A TOIE0 103 (0x6D) PCMSK2 PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 73 (0x6C) PCMSK1 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 PCINT8 73 (0x6B) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 73 (0x6A) Reserved - - - - - - - - (0x69) EICRA ISC31 ISC30 ISC21 ISC20 ISC11 ISC10 ISC01 ISC00 69 (0x68) PCICR - - - - PCIE3 PCIE2 PCIE1 PCIE0 71 (0x67) Reserved - - - - - - - - (0x66) OSCCAL CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 (0x65) PRR1 - - PRKB PRAES PRSCI PRHSSPI PRUSB PRSCUSB 46 (0x64) PRR0 PRTWI PRTIM2 PRTIM0 - PRTIM1 PRSPI PRUSART0 - 45 (0x63) SMONCR SMONIF SMONIE - - - - - SMONEN 60 (0x62) PLLCR PLLMUX - - - - - LOCK ON/OFF 40 (0x61) CLKPR - - - - CLKPS3 CLKPS2 CLKPS1 CLKPS0 40 (0x60) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 61 I T H S V N Z C 15 343 343 - - - - XOR MANINC AUTOINC KD 342 AESIE AESIF AUTOKEY KEYGN KS - ENCRYPT AESGO 341 Reserved - - - - - - - - Reserved - - - - - - - LED3 LED2 LED1 LED0 77 73 39 0x3F (0x5F) SREG 0x3E (0x5E) SPH SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 17 0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 17 0x3C (0x5C) Reserved - - - - - - - - 0x3B (0x5B) Reserved - - - - - - - - 0x3A (0x5A) Reserved - - - - - - - - 0x39 (0x59) Reserved - - - - - - - - 0x38 (0x58) Reserved - - - - - - - - 0x37 (0x57) SPMCSR SPMIE RWWSB SIGRD RWWSRE BLBSET PGWRT PGERS SPMEN 0x36 (0x56) Reserved - - - - - - - - 0x35 (0x55) MCUCR JTD - - PUD - - IVSEL IVCE 67, 82, 356 0x34 (0x54) MCUSR - - - JTRF WDRF BORF EXTRF PORF 60 0x33 (0x53) SMCR - - - - SM2 SM1 SM0 SE 45 0x32 (0x52) Reserved - - - - - - - - 0x31 (0x51) OCDR D7/IDRD D6 D5 D4 D3 D2 D1 D0 0x30 (0x50) Reserved - - - - - - - - - - - - - - - - 367 352 0x2F (0x4F) Reserved 0x2E (0x4E) SPDR 0x2D (0x4D) SPSR SPIF WCOL - - - - - SPI2X 274 0x2C (0x4C) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 272 0x2B (0x4B) GPIOR2 General Purpose I/O Register 2 0x2A (0x4A) GPIOR1 General Purpose I/O Register 1 0x29 (0x49) Reserved 0x28 (0x48) OCR0B Timer/Counter0 Output Compare Register B 103 0x27 (0x47) OCR0A Timer/Counter0 Output Compare Register A 103 0x26 (0x46) TCNT0 Timer/Counter0 (8 Bit) 0x25 (0x45) TCCR0B FOC0A FOC0B - - WGM02 CS02 CS01 CS00 0x24 (0x44) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 - - WGM01 WGM00 98 0x23 (0x43) GTCCR TSM - - - - - PSRASY PSRSYNC 155 0x22 (0x42) EEARH - - - - 0x21 (0x41) EEARL SPI 0 Data Register - - - - 274 29 29 - - - - 102 EEARH [11:8] 24 EEARL [7:0] 0x20 (0x40) EEDR 0x1F (0x3F) EECR 0x1E (0x3E) GPIOR0 0x1D (0x3D) EIMSK - - - - 0x1C (0x3C) EIFR - - - - 24 EEPROM Data Register - - EEPM1 EEPM0 EERIE 101 24 EEMPE EEPE EERE INT3 INT2 INT1 INT0 70 INTF3 INTF2 INTF1 INTF0 70 General Purpose I/O Register 0 24 30 419 TPR0327AY–SMS–30Jan09 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page 0x1B (0x3B) Address PCIFR Name - - - - PCIF3 PCIF2 PCIF1 PCIF0 72 0x1A (0x3A) EIRR - - - - INTD3 INTD2 - - 71 0x19 (0x39) Reserved - - - - - - - - 0x18 (0x38) Reserved - - - - - - - - 0x17 (0x37) TIFR2 - - - - - OCF2B OCF2A TOV2 153 0x16 (0x36) TIFR1 - - ICF1 - - OCF1B OCF1A TOV1 132 0x15 (0x35) TIFR0 - - - - - OCF0B OCF0A TOV0 104 0x14 (0x34) Reserved - - - - - - - - 0x13 (0x33) Reserved - - - - - - - - 0x12 (0x32) Reserved - - - - - - - - 0x11 (0x31) Reserved - - - - - - - - 0x10 (0x30) Reserved - - - - - - - - 0x0F (0x2F) Reserved - - - - - - - - 0x0E (0x2E) PORTE PORTE7 PORTE6 PORTE5 PORTE4 PORTE3 PORTE2 PORTE1 PORTE0 84 0x0D (0x2D) DDRE DDE7 DDE6 DDE5 DDE4 DDE3 DDE2 DDE1 DDE0 85 0x0C (0x2C) PINE PINE7 PINE6 PINE5 PINE4 PINE3 PINE2 PINE1 PINE0 85 0x0B (0x2B) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 84 0x0A (0x2A) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 84 0x09 (0x29) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 84 0x08 (0x28) PORTC - - PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 84 0x07 (0x27) DDRC - - DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 84 0x06 (0x26) PINC - - PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 84 0x05 (0x25) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 83 0x04 (0x24) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 83 0x03 (0x23) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 83 0x02 (0x22) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 83 0x01 (0x21) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 83 0x00 (0x20) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 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. ! Caution 420 All ‘Reserved’ registers must not be read or written. Writing or Reading these registers may generate unhandled state. AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 33. Instruction Set Summary Mnemonics Operands Description Operation Flags #Clocks 1 ARITHMETIC AND LOGIC INSTRUCTIONS ADD Rd, Rr Add two Registers Rd ← Rd + Rr Z,C,N,V,H ADC Rd, Rr Add with Carry two Registers Rd ← Rd + Rr + C Z,C,N,V,H 1 ADIW Rdl,K Add Immediate to Word Rdh:Rdl ← Rdh:Rdl + K Z,C,N,V,S 2 SUB Rd, Rr Subtract two Registers Rd ← Rd - Rr Z,C,N,V,H 1 SUBI Rd, K Subtract Constant from Register Rd ← Rd - K Z,C,N,V,H 1 SBC Rd, Rr Subtract with Carry two Registers Rd ← Rd - Rr - C Z,C,N,V,H 1 SBCI Rd, K Subtract with Carry Constant from Reg. Rd ← Rd - K - C Z,C,N,V,H 1 SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl ← Rdh:Rdl - K Z,C,N,V,S 2 AND Rd, Rr Logical AND Registers Rd ← Rd • Rr Z,N,V 1 ANDI Rd, K Logical AND Register and Constant Rd ← Rd • K Z,N,V 1 OR Rd, Rr Logical OR Registers Rd ← Rd v Rr Z,N,V 1 ORI Rd, K Logical OR Register and Constant Rd ← Rd v K Z,N,V 1 EOR Rd, Rr Exclusive OR Registers Rd ← Rd ⊕ Rr Z,N,V 1 COM Rd One’s Complement Rd ← 0xFF − Rd Z,C,N,V 1 NEG Rd Two’s Complement Rd ← 0x00 − Rd Z,C,N,V,H 1 SBR Rd,K Set Bit(s) in Register Rd ← Rd v K Z,N,V 1 CBR Rd,K Clear Bit(s) in Register Rd ← Rd • (0xFF - K) Z,N,V 1 INC Rd Increment Rd ← Rd + 1 Z,N,V 1 1 DEC Rd Decrement Rd ← Rd − 1 Z,N,V TST Rd Test for Zero or Minus Rd ← Rd • Rd Z,N,V 1 CLR Rd Clear Register Rd ← Rd ⊕ Rd Z,N,V 1 SER Rd Set Register Rd ← 0xFF None 1 MUL Rd, Rr Multiply Unsigned R1:R0 ← Rd x Rr Z,C 2 MULS Rd, Rr Multiply Signed R1:R0 ← Rd x Rr Z,C 2 MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 ← Rd x Rr Z,C 2 FMUL Rd, Rr Fractional Multiply Unsigned Z,C 2 Z,C 2 Z,C 2 FMULS Rd, Rr Fractional Multiply Signed FMULSU Rd, Rr Fractional Multiply Signed with Unsigned R1:R0 ← (Rd x Rr) << 1 R1:R0 ← (Rd x Rr) << 1 R1:R0 ← (Rd x Rr) << 1 BRANCH INSTRUCTIONS RJMP k IJMP Relative Jump PC ← PC + k + 1 None 2 Indirect Jump to (Z) PC ← Z None 2 3 JMP k Direct Jump PC ← k None RCALL k Relative Subroutine Call PC ← PC + k + 1 None 4 Indirect Call to (Z) PC ← Z None 4 ICALL CALL k RET RETI CPSE Rd,Rr Direct Subroutine Call PC ← k None 5 Subroutine Return PC ← STACK None 5 Interrupt Return PC ← STACK I 5 Compare, Skip if Equal if (Rd = Rr) PC ← PC + 2 or 3 None 1/2/3 CP Rd,Rr Compare Rd − Rr Z, N,V,C,H 1 CPC Rd,Rr Compare with Carry Rd − Rr − C Z, N,V,C,H 1 CPI Rd,K Compare Register with Immediate Rd − K Z, N,V,C,H 1 SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC ← PC + 2 or 3 None 1/2/3 SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC ← PC + 2 or 3 None 1/2/3 SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC ← PC + 2 or 3 None 1/2/3 SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC ← PC + 2 or 3 None 1/2/3 BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC←PC+k + 1 None 1/2 BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC←PC+k + 1 None 1/2 BREQ k Branch if Equal if (Z = 1) then PC ← PC + k + 1 None 1/2 BRNE k Branch if Not Equal if (Z = 0) then PC ← PC + k + 1 None 1/2 BRCS k Branch if Carry Set if (C = 1) then PC ← PC + k + 1 None 1/2 BRCC k Branch if Carry Cleared if (C = 0) then PC ← PC + k + 1 None 1/2 BRSH k Branch if Same or Higher if (C = 0) then PC ← PC + k + 1 None 1/2 BRLO k Branch if Lower if (C = 1) then PC ← PC + k + 1 None 1/2 BRMI k Branch if Minus if (N = 1) then PC ← PC + k + 1 None 1/2 BRPL k Branch if Plus if (N = 0) then PC ← PC + k + 1 None 1/2 BRGE k Branch if Greater or Equal, Signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1/2 BRLT k Branch if Less Than Zero, Signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1/2 BRHS k Branch if Half Carry Flag Set if (H = 1) then PC ← PC + k + 1 None 1/2 BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC ← PC + k + 1 None 1/2 BRTS k Branch if T Flag Set if (T = 1) then PC ← PC + k + 1 None 1/2 BRTC k Branch if T Flag Cleared if (T = 0) then PC ← PC + k + 1 None 1/2 BRVS k Branch if Overflow Flag is Set if (V = 1) then PC ← PC + k + 1 None 1/2 BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC ← PC + k + 1 None 1/2 421 TPR0327AY–SMS–30Jan09 Mnemonics Operands Description Operation Flags BRIE k Branch if Interrupt Enabled if ( I = 1) then PC ← PC + k + 1 None #Clocks 1/2 BRID k Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2 SBI P,b Set Bit in I/O Register I/O(P,b) ← 1 None 2 CBI P,b Clear Bit in I/O Register I/O(P,b) ← 0 None 2 LSL Rd Logical Shift Left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z,C,N,V 1 LSR Rd Logical Shift Right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z,C,N,V 1 1 BIT AND BIT-TEST INSTRUCTIONS ROL Rd Rotate Left Through Carry Rd(0)←C,Rd(n+1)← Rd(n),C←Rd(7) Z,C,N,V ROR Rd Rotate Right Through Carry Rd(7)←C,Rd(n)← Rd(n+1),C←Rd(0) Z,C,N,V 1 ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 Z,C,N,V 1 SWAP Rd Swap Nibbles Rd(3..0)←Rd(7..4),Rd(7..4)←Rd(3..0) None 1 BSET s Flag Set SREG(s) ← 1 SREG(s) 1 BCLR s Flag Clear SREG(s) ← 0 SREG(s) 1 BST Rr, b Bit Store from Register to T T ← Rr(b) T 1 BLD Rd, b Bit load from T to Register Rd(b) ← T None 1 SEC Set Carry C←1 C 1 CLC Clear Carry C←0 C 1 SEN Set Negative Flag N←1 N 1 CLN Clear Negative Flag N←0 N 1 SEZ Set Zero Flag Z←1 Z 1 CLZ Clear Zero Flag Z←0 Z 1 SEI Global Interrupt Enable I←1 I 1 CLI Global Interrupt Disable I←0 I 1 SES Set Signed Test Flag S←1 S 1 CLS Clear Signed Test Flag S←0 S 1 SEV Set Twos Complement Overflow. V←1 V 1 CLV Clear Twos Complement Overflow V←0 V 1 SET Set T in SREG T←1 T 1 CLT Clear T in SREG T←0 T 1 SEH Set Half Carry Flag in SREG H←1 H 1 CLH Clear Half Carry Flag in SREG H←0 H 1 DATA TRANSFER INSTRUCTIONS MOV Rd, Rr Move Between Registers Rd ← Rr None 1 MOVW Rd, Rr Copy Register Word Rd+1:Rd ← Rr+1:Rr None 1 LDI Rd, K Load Immediate Rd ← K None 1 LD Rd, X Load Indirect Rd ← (X) None 2 LD Rd, X+ Load Indirect and Post-Inc. Rd ← (X), X ← X + 1 None 2 LD Rd, - X Load Indirect and Pre-Dec. X ← X - 1, Rd ← (X) None 2 2 LD Rd, Y Load Indirect Rd ← (Y) None LD Rd, Y+ Load Indirect and Post-Inc. Rd ← (Y), Y ← Y + 1 None 2 LD Rd, - Y Load Indirect and Pre-Dec. Y ← Y - 1, Rd ← (Y) None 2 LDD Rd,Y+q Load Indirect with Displacement Rd ← (Y + q) None 2 LD Rd, Z Load Indirect Rd ← (Z) None 2 LD Rd, Z+ Load Indirect and Post-Inc. Rd ← (Z), Z ← Z+1 None 2 LD Rd, -Z Load Indirect and Pre-Dec. Z ← Z - 1, Rd ← (Z) None 2 LDD Rd, Z+q Load Indirect with Displacement Rd ← (Z + q) None 2 LDS Rd, k Load Direct from SRAM Rd ← (k) None 2 ST X, Rr Store Indirect (X) ← Rr None 2 ST X+, Rr Store Indirect and Post-Inc. (X) ← Rr, X ← X + 1 None 2 ST - X, Rr Store Indirect and Pre-Dec. X ← X - 1, (X) ← Rr None 2 ST Y, Rr Store Indirect (Y) ← Rr None 2 ST Y+, Rr Store Indirect and Post-Inc. (Y) ← Rr, Y ← Y + 1 None 2 ST - Y, Rr Store Indirect and Pre-Dec. Y ← Y - 1, (Y) ← Rr None 2 STD Y+q,Rr Store Indirect with Displacement (Y + q) ← Rr None 2 ST Z, Rr Store Indirect (Z) ← Rr None 2 ST Z+, Rr Store Indirect and Post-Inc. (Z) ← Rr, Z ← Z + 1 None 2 ST -Z, Rr Store Indirect and Pre-Dec. Z ← Z - 1, (Z) ← Rr None 2 STD Z+q,Rr Store Indirect with Displacement (Z + q) ← Rr None 2 STS k, Rr LPM (k) ← Rr None 2 R0 ← (Z) None 3 LPM Rd, Z Load Program Memory Rd ← (Z) None 3 LPM Rd, Z+ Load Program Memory and Post-Inc Rd ← (Z), Z ← Z+1 None 3 ELPM Rd, Z Extended Load Program Memory Rd ← (Z) None 3 Store Program Memory (Z) ← R1:R0 None - SPM 422 Store Direct to SRAM Load Program Memory IN Rd, P In Port Rd ← P None 1 OUT P, Rr Out Port P ← Rr None 1 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 Mnemonics Operands Description Operation Flags PUSH Rr Push Register on Stack STACK ← Rr None #Clocks 2 POP Rd Pop Register from Stack Rd ← STACK None 2 MCU CONTROL INSTRUCTIONS NOP No Operation None 1 SLEEP Sleep (see specific descr. for Sleep function) None 1 WDR Watchdog Reset (see specific descr. for WDR/timer) None 1 BREAK Break For On-chip Debug Only None N/A 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 Block Diagram .......................................................................................... 3 2 Pin List Configuration ............................................................................. 5 3 Resources ................................................................................................. 9 4 About Code Examples ........................................................................... 11 5 AVR CPU Core ........................................................................................ 13 6 7 8 9 5.1 Introduction ......................................................................................................13 5.2 Architectural Overview .....................................................................................13 5.3 ALU – Arithmetic Logic Unit .............................................................................14 5.4 Status Register ................................................................................................15 5.5 General Purpose Register File ........................................................................16 5.6 Stack Pointer ...................................................................................................17 5.7 Instruction Execution Timing ...........................................................................17 5.8 Reset and Interrupt Handling ...........................................................................18 AT90SCR100 Memories ......................................................................... 21 6.1 In-System Reprogrammable Flash Program Memory .....................................21 6.2 SRAM Data Memory ........................................................................................22 6.3 EEPROM Data Memory ..................................................................................23 6.4 I/O Memory ......................................................................................................29 Clock System ......................................................................................... 31 7.1 Overview ..........................................................................................................31 7.2 Clock Sources .................................................................................................33 7.3 Clock Output Buffer .........................................................................................40 7.4 Clock System Registers ..................................................................................40 Power Management and Sleep Modes ................................................. 43 8.1 Power Modes Descriptions ..............................................................................43 8.2 Power Reduction Register ...............................................................................45 8.3 Important note about: Entering and Leaving low consumption modes ............47 8.4 Minimizing Power Consumption ......................................................................48 System Control and Reset .................................................................... 51 9.1 TPR0327AY–SMS–30Jan09 Resetting the AVR ...........................................................................................51 427 9.2 Reset Sources .................................................................................................51 9.3 Internal Voltage Reference ..............................................................................55 9.4 Supply monitor .................................................................................................56 9.5 Watchdog Timer ..............................................................................................57 9.6 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 Standard IO Ports ............................................................................................75 12.2 Specific Low Speed Keyboard Output .............................................................76 12.3 LED ..................................................................................................................76 12.4 Ports as General Digital I/O .............................................................................77 12.5 Register Description for I/O-Ports ....................................................................83 13 Timers ..................................................................................................... 87 13.1 8-bit Timer/Counter0 with PWM ......................................................................87 13.2 16-bit Timer/Counter1 with PWM ..................................................................105 13.3 8-bit Timer/Counter2 with PWM and Asynchronous Operation (RTC) ..........134 13.4 Timer/Counter Prescaler ...............................................................................154 14 USB Device Interface ........................................................................... 157 14.1 Features ........................................................................................................157 14.2 Overview ........................................................................................................157 14.3 Endpoints Description ....................................................................................159 14.4 Attachment Procedure ...................................................................................160 14.5 USB Interrupts ...............................................................................................160 14.6 Suspend and Resume Modes .......................................................................161 14.7 Double Buffering ............................................................................................163 14.8 USB Device Registers Description ................................................................164 14.9 USBDMA Controller .......................................................................................172 15 Smart Card Interface Block (SCIB) ..................................................... 177 428 15.1 Features ........................................................................................................177 15.2 Overview ........................................................................................................177 15.3 Block Diagram ...............................................................................................177 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 15.4 Definitions ......................................................................................................178 15.5 Functional Description ...................................................................................180 15.6 Additional Features ........................................................................................187 15.7 Smart Card Interface Block Registers ...........................................................190 16 DC/DC Converter .................................................................................. 201 16.1 Overview ........................................................................................................201 16.2 Features ........................................................................................................201 16.3 Description .....................................................................................................201 16.4 Summary: State Machine ..............................................................................202 16.5 DC/DC Registers ...........................................................................................203 17 USB Host Controller ............................................................................ 205 17.1 Features ........................................................................................................205 17.2 USB Host Smart Card Interface Description .................................................205 17.3 USB-IC Design ..............................................................................................206 17.4 Memory Management ....................................................................................207 17.5 USB Host Controller Description ...................................................................208 17.6 Interrupt system .............................................................................................216 17.7 USB Host Controller Registers ......................................................................217 18 USART ................................................................................................... 231 18.1 Features ........................................................................................................231 18.2 USART0 ........................................................................................................231 18.3 Overview ........................................................................................................231 18.4 Clock Generation ...........................................................................................232 18.5 Frame Formats ..............................................................................................235 18.6 USART Initialization .......................................................................................236 18.7 Data Transmission – The USART Transmitter ..............................................238 18.8 Data Reception – The USART Receiver .......................................................240 18.9 Asynchronous Data Reception ......................................................................244 18.10 Multi-processor Communication Mode ..........................................................247 18.11 USART Register Description .........................................................................249 18.12 Examples of Baud Rate Setting .....................................................................254 19 USART in SPI Mode ............................................................................. 257 19.1 Features ........................................................................................................257 19.2 Overview ........................................................................................................257 19.3 Clock Generation ...........................................................................................257 429 TPR0327AY–SMS–30Jan09 19.4 SPI Data Modes and Timing ..........................................................................258 19.5 Frame Formats ..............................................................................................259 19.6 Data Transfer .................................................................................................260 19.7 USART MSPIM Register Description ............................................................262 19.8 AVR USART MSPIM vs. AVR SPI ................................................................265 20 SPI - Serial Peripheral Interface .......................................................... 267 20.1 Features ........................................................................................................267 20.2 Description .....................................................................................................267 20.3 SS Pin Functionality ......................................................................................272 20.4 SPI Registers .................................................................................................272 20.5 Data Modes ...................................................................................................275 21 High-Speed SPI Controller .................................................................. 277 21.1 Features ........................................................................................................277 21.2 Description .....................................................................................................277 21.3 HSSS line Functionality .................................................................................286 21.4 Data Modes ...................................................................................................286 21.5 HSSPI Interface Registers .............................................................................287 21.6 HSSPIDMA Controller ...................................................................................292 22 2-wire Serial Interface _ TWI ............................................................... 297 22.1 Features ........................................................................................................297 22.2 TWI Serial Interface Bus Definition ................................................................297 22.3 Data Transfer and Frame Format ..................................................................298 22.4 Multi-master Bus Systems, Arbitration and Synchronization .........................301 22.5 Overview of the TWI Module .........................................................................302 22.6 Using the TWI ................................................................................................305 22.7 Transmission Modes .....................................................................................308 22.8 Multi-master Systems and Arbitration ............................................................323 22.9 TWI Register Description ...............................................................................324 23 Keyboard Interface .............................................................................. 329 23.1 Features ........................................................................................................329 23.2 General Description .......................................................................................329 23.3 Keyboard Register Description ......................................................................330 24 Random Number Generator ................................................................ 335 24.1 430 Features ........................................................................................................335 AT90SCR100 TPR0327AY–SMS–30Jan09 AT90SCR100 24.2 RNG Definition ...............................................................................................335 24.3 Random Number Generator Registers ..........................................................336 25 AES 128/256 Engine ............................................................................. 339 25.1 Features ........................................................................................................339 25.2 Overview ........................................................................................................339 25.3 AES Registers description .............................................................................341 25.4 Example. Code Sample .................................................................................343 26 JTAG Interface and On-chip Debug System ..................................... 347 26.1 Features ........................................................................................................347 26.2 Overview ........................................................................................................347 26.3 TAP – Test Access Port ................................................................................347 26.4 TAP Controller ...............................................................................................349 26.5 Using the Boundary-scan Chain ....................................................................350 26.6 Using the On-chip Debug System .................................................................350 26.7 On-chip Debug Specific JTAG Instructions ...................................................351 26.8 On-chip Debug Related Register in I/O Memory ...........................................352 26.9 Using the JTAG Programming Capabilities ...................................................352 26.10 Bibliography ...................................................................................................352 27 IEEE 1149.1 (JTAG) Boundary-scan ................................................... 353 27.1 Features ........................................................................................................353 27.2 System Overview ...........................................................................................353 27.3 Data Registers ...............................................................................................353 27.4 Boundary-scan Specific JTAG Instructions ...................................................355 27.5 Boundary-scan Related Register in I/O Memory ...........................................356 27.6 Boundary-scan Chain ....................................................................................357 27.7 AT90SCR100 Boundary-scan Order .............................................................360 27.8 Boundary-scan Description Language Files ..................................................362 28 Boot Loader Support - Read-While-Write Self-Programming .......... 363 28.1 Boot Loader Features ....................................................................................363 28.2 Application and Boot Loader Flash Sections .................................................363 28.3 Read-While-Write and No Read-While-Write Flash Sections ........................364 28.4 Boot Loader Lock Bits ...................................................................................366 28.5 Entering the Boot Loader Program ................................................................367 28.6 Addressing the Flash During Self-Programming ...........................................369 28.7 Self-Programming the Flash ..........................................................................370 431 TPR0327AY–SMS–30Jan09 29 Memory Programming ......................................................................... 377 29.1 Program And Data Memory Lock Bits ...........................................................377 29.2 Fuse Bits ........................................................................................................379 29.3 Signature Bytes .............................................................................................380 29.4 Calibration Byte .............................................................................................381 29.5 Page Size ......................................................................................................381 29.6 Serial Downloading ........................................................................................381 29.7 Serial Programming Instruction set ...............................................................383 29.8 Programming via the JTAG Interface ............................................................385 30 Application Information ....................................................................... 399 30.1 Ordering Information ......................................................................................399 30.2 Typical Application .........................................................................................400 30.3 Pinout ............................................................................................................402 30.4 Mechanical Information .................................................................................405 31 Electrical Characteristics .................................................................... 409 31.1 Scope ............................................................................................................409 31.2 DC Characteristics TBC/TBD ........................................................................410 31.3 PORT .............................................................................................................410 31.4 Clocks ............................................................................................................411 31.5 Communication Interfaces .............................................................................411 31.6 USB Interface Characteristics TBC/TBD ......................................................414 31.7 Smart Card Interface Characteristics ............................................................415 31.8 USB Host Controller Characteristics .............................................................416 32 Register Summary ............................................................................... 417 33 Instruction Set Summary .................................................................... 421 34 Datasheet Revision History ................................................................ 425 34.1 Rev. AY-30Jan09 ..........................................................................................425 34.2 Rev. AX-13Nov08 ..........................................................................................425 Table of Contents.................................................................................. 427 432 AT90SCR100 TPR0327AY–SMS–30Jan09 Headquarters International Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131 USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600 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 Technical Support [email protected] Sales Contact www.atmel.com/contacts Product Contact Web Site www.atmel.com 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. © Atmel Corporation 2008. All Rights Reserved. Atmel ®, Atmel logo and combinations thereof, AVR ® and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others. TPR0327AY–SMS–30Jan09