| The Datasheet Archive - 100 Million Datasheets from 7500 Manufacturers. |
8-bit Microcontroller with 128K Bytes In-System Programmable Flash ATm
Top Searches for this datasheet8-bit Microcontroller with 128K Bytes In-System Programmable Flash ATmega128 ATmega128L Rev. 2467L-AVR-05/04 Configurations Figure Pinout ATmega128 AVCC AREF (ADC0) (ADC1) (ADC2) (ADC3) (ADC4/TCK) (ADC5/TMS) (ADC6/TDO) (ADC7/TDI) (AD0) (AD1) (AD2) Overview ATmega128 low-power CMOS 8-bit microcontroller based enhanced RISC architecture. executing powerful instructions single clock cycle, ATmega128 achieves throughputs approaching MIPS allowing system designer optimize power consumption versus processing speed. ATmega128 2467L-AVR-05/04 (OC2/OC1C) TOSC2/PG3 TOSC1/1PG4 RESET XTAL2 XTAL1 (SCL/INT0) (SDA/INT1) (RXD1/INT2) (TXD1/INT3) (ICP1) (XCK1) (T1) (T2) RXD0/(PDI) (TXD0/PDO) (XCK0/AIN0) (OC3A/AIN1) (OC3B/INT4) (OC3C/INT5) (T3/INT6) (ICP3/INT7) (SS) (SCK) (MOSI) (MISO) (OC0) (OC1A) (OC1B) (AD3) (AD4) (AD5) (AD6) (AD7) PG2(ALE) (A15) (A14) (A13) (A12) (A11) (A10) (A9) (A8) PG1(RD) PG0(WR) ATmega128 Block Diagram Figure Block Diagram PORTF DRIVERS PORTA DRIVERS PORTC DRIVERS DATA REGISTER PORTF DATA DIR. REG. PORTF DATA REGISTER PORTA DATA DIR. REG. PORTA DATA REGISTER PORTC DATA DIR. REG. PORTC 8-BIT DATA AVCC AGND AREF PROGRAM COUNTER STACK POINTER WATCHDOG TIMER INTERNAL OSCILLATOR CALIB. OSCILLATOR JTAG OSCILLATOR ON-CHIP DEBUG PROGRAM FLASH SRAM CONTROL REGISTER TIMING CONTROL BOUNDARYSCAN INSTRUCTION REGISTER GENERAL PURPOSE REGISTERS TIMER/ COUNTERS PROGRAMMING LOGIC INSTRUCTION DECODER INTERRUPT UNIT CONTROL LINES EEPROM STATUS REGISTER USART0 USART1 TWO-WIRE SERIAL INTERFACE ANALOG COMPARATOR DATA REGISTER PORTE DATA DIR. REG. PORTE DATA REGISTER PORTB DATA DIR. REG. PORTB DATA REGISTER PORTD DATA DIR. REG. PORTD DATA REG. PORTG DATA DIR. REG. PORTG PORTE DRIVERS PORTB DRIVERS PORTD DRIVERS PORTG DRIVERS RESET XTAL1 XTAL2 2467L-AVR-05/04 core combines rich instruction with general purpose working registers. registers directly connected Arithmetic Logic Unit (ALU), allowing independent registers accessed single instruction executed clock cycle. resulting architecture more code efficient while achieving throughputs times faster than conventional CISC microcontrollers. ATmega128 provides following features: 128K bytes In-System Programmable Flash with Read-While-Write capabilities, bytes EEPROM, bytes SRAM, general purpose lines, general purpose working registers, Real Time Counter (RTC), four flexible Timer/Counters with compare modes PWM, USARTs, byte oriented Two-wire Serial Interface, 8-channel, 10-bit with optional differential input stage with programmable gain, programmable Watchdog Timer with Internal Oscillator, serial port, IEEE std. 1149.1 compliant JTAG test interface, also used accessing On-chip Debug system programming software selectable power saving modes. Idle mode stops while allowing SRAM, Timer/Counters, port, interrupt system continue functioning. Powerdown mode saves register contents freezes Oscillator, disabling other chip functions until next interrupt Hardware Reset. Power-save mode, asynchronous timer continues run, allowing user maintain timer base while rest device sleeping. Noise Reduction mode stops modules except Asynchronous Timer ADC, minimize switching noise during conversions. Standby mode, Crystal/Resonator Oscillator running while rest device sleeping. This allows very fast start-up combined with power consumption. Extended Standby mode, both main Oscillator Asynchronous Timer continue run. device manufactured using Atmel's high-density nonvolatile memory technology. On-chip Flash allows program memory reprogrammed in-system through serial interface, conventional nonvolatile memory programmer, On-chip Boot program running core. boot program interface download application program application Flash memory. Software Boot Flash section will continue while Application Flash section updated, providing true Read-While-Write operation. combining 8-bit RISC with In-System Self-Programmable Flash monolithic chip, Atmel ATmega128 powerful microcontroller that provides highly flexible cost effective solution many embedded control applications. ATmega128 supported with full suite program system development tools including: compilers, macro assemblers, program debugger/simulators, in-circuit emulators, evaluation kits. ATmega103 ATmega128 Compatibility ATmega128 highly complex microcontroller where number locations supersedes locations reserved instruction set. ensure backward compatibility with ATmega103, locations present ATmega103 have same location ATmega128. Most additional locations added Extended space starting from $FF, (i.e., ATmega103 internal space). These locations reached using LD/LDS/LDD ST/STS/STD instructions only, using instructions. relocation internal space still problem ATmega103 users. Also, increased number interrupt vectors might problem code uses absolute addresses. solve these problems, ATmega103 compatibility mode selected programming fuse M103C. this mode, none functions Extended space use, internal located ATmega103. Also, Extended Interrupt vectors removed. ATmega128 2467L-AVR-05/04 ATmega128 ATmega128 100% compatible with ATmega103, replace ATmega103 current Printed Circuit Boards. application note "Replacing ATmega103 ATmega128" describes what user should aware replacing ATmega103 ATmega128. ATmega103 Compatibility Mode programming M103C fuse, ATmega128 will compatible with ATmega103 regards RAM, pins interrupt vectors described above. However, some features ATmega128 available this compatibility mode, these features listed below: USART instead two, Asynchronous mode only. Only eight least significant bits Baud Rate Register available. bits Timer/Counter with compare registers instead 16-bit Timer/Counters with three compare registers. Two-wire serial interface supported. Port output only. Port serves alternate functions only (not general port). Port serves digital input only addition analog input ADC. Boot Loader capabilities supported. possible adjust frequency internal calibrated Oscillator. External Memory Interface release Address pins general I/O, neither configure different wait-states different External Memory Address sections. addition, there some other minor differences make more compatible ATmega103: Only EXTRF PORF exists MCUCSR. Timed sequence required Watchdog Time-out change. External Interrupt pins serve level interrupt only. USART FIFO buffer, data overrun comes earlier. Unused bits ATmega103 should written ensure same operation ATmega128. Descriptions Port (PA7.PA0) Digital supply voltage. Ground. Port 8-bit bi-directional port with internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. Port also serves functions various special features ATmega128 listed page Port (PB7.PB0) Port 8-bit bi-directional port with internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source 2467L-AVR-05/04 current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. Port also serves functions various special features ATmega128 listed page Port (PC7.PC0) Port 8-bit bi-directional port with internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. Port also serves functions special features ATmega128 listed page ATmega103 compatibility mode, Port output only, port pins tri-stated when reset condition becomes active. Port (PD7.PD0) Port 8-bit bi-directional port with internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. Port also serves functions various special features ATmega128 listed page Port (PE7.PE0) Port 8-bit bi-directional port with internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. Port also serves functions various special features ATmega128 listed page Port (PF7.PF0) Port serves analog inputs Converter. Port also serves 8-bit bi-directional port, Converter used. Port pins provide internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. JTAG interface enabled, pull-up resistors pins PF7(TDI), PF5(TMS), PF4(TCK) will activated even Reset occurs. tri-stated unless states that shift data entered. Port also serves functions JTAG interface. ATmega103 compatibility mode, Port input Port only. Port (PG4.PG0) Port 5-bit bi-directional port with internal pull-up resistors (selected each bit). Port output buffers have symmetrical drive characteristics with both high sink source capability. inputs, Port pins that externally pulled will source current pull-up resistors activated. Port pins tri-stated when reset condition becomes active, even clock running. Port also serves functions various special features. ATmega128 2467L-AVR-05/04 ATmega128 port pins tri-stated when reset condition becomes active, even clock running. ATmega103 compatibility mode, these pins only serves strobes signals external memory well input Oscillator, pins initialized asynchronously when reset condition becomes active, even clock running. oscillator pins. RESET Reset input. level this longer than minimum pulse length will generate reset, even clock running. minimum pulse length given Table page Shorter pulses guaranteed generate reset. Input inverting Oscillator amplifier input internal clock operating circuit. Output from inverting Oscillator amplifier. AVCC supply voltage Port Converter. should externally connected VCC, even used. used, should connected through low-pass filter. AREF analog reference Converter. programming enable Serial Programming mode. holding this during Power-on Reset, device will enter Serial Programming mode. function during normal operation. This datasheet contains simple code examples that briefly show various parts device. These code examples assume that part specific header file included before compilation. aware that compiler vendors include definitions header files interrupt handling compiler dependent. Please confirm with compiler documentation more details. XTAL1 XTAL2 AVCC AREF About Code Examples 2467L-AVR-05/04 Core Introduction This section discusses core architecture general. main function core ensure correct program execution. must therefore able access memories, perform calculations, control peripherals handle interrupts. Figure Block Diagram Architecture Data 8-bit Architectural Overview Flash Program Memory Program Counter Status Control Instruction Register General Purpose Registrers Interrupt Unit Unit Watchdog Timer Indirect Addressing Instruction Decoder Direct Addressing Control Lines Analog Comparator Module1 Data SRAM Module Module EEPROM Lines order maximize performance parallelism, uses Harvard architecture with separate memories buses program data. Instructions program memory executed with single level pipelining. While instruction being executed, next instruction pre-fetched from program memory. This concept enables instructions executed every clock cycle. program memory InSystem Reprogrammable Flash memory. fast-access Register file contains 8-bit general purpose working registers with single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. typical operation, operands output from Register file, operation executed, result stored back Register file clock cycle. registers used three 16-bit indirect address register pointers Data Space addressing enabling efficient address calculations. these address pointers also used address pointer look tables Flash Program memory. These added function registers 16-bit X-register, Y-register Z-register, described later this section. supports arithmetic logic operations between registers between constant register. Single register operations also executed ALU. After ATmega128 2467L-AVR-05/04 ATmega128 arithmetic operation, Status Register updated reflect information about result operation. Program flow provided conditional unconditional jump call instructions, able directly address whole address space. Most instructions have single 16-bit word format. Every program memory address contains 32-bit instruction. Program Flash memory space divided sections, Boot Program section Application Program section. Both sections have dedicated Lock bits write read/write protection. instruction that writes into Application Flash Memory section must reside Boot Program section. During interrupts subroutine calls, return address Program Counter (PC) stored Stack. Stack effectively allocated general data SRAM, consequently stack size only limited total SRAM size usage SRAM. user programs must initialize reset routine (before subroutines interrupts executed). Stack Pointer read/write accessible space. data SRAM easily accessed through five different addressing modes supported architecture. memory spaces architecture linear regular memory maps. flexible interrupt module control registers space with additional global interrupt enable Status Register. interrupts have separate interrupt vector interrupt vector table. interrupts have priority accordance with their interrupt vector position. lower interrupt vector address, higher priority. memory space contains addresses which accessed directly, Data Space locations following those Register file, $5F. addition, ATmega128 Extended space from SRAM where only ST/STS/STD LD/LDS/LDD instructions used. Arithmetic Logic Unit high-performance operates direct connection with general purpose working registers. Within single clock cycle, arithmetic operations between general purpose registers between register immediate executed. operations divided into three main categories arithmetic, logical, bit-functions. Some implementations architecture also provide powerful multiplier supporting both signed/unsigned multiplication fractional format. "Instruction Set" section detailed description. Status Register contains information about result most recently executed arithmetic instruction. This information used altering program flow order perform conditional operations. Note that Status Register updated after operations, specified Instruction Reference. This will many cases remove need using dedicated compare instructions, resulting faster more compact code. status register automatically stored when entering interrupt routine restored when returning from interrupt. This must handled software. status Register SREG defined Read/Write Initial Value SREG Status Register Global Interrupt Enable 2467L-AVR-05/04 Global Interrupt Enable must interrupts enabled. individual interrupt enable control then performed separate control registers. Global Interrupt Enable Register cleared, none interrupts enabled independent individual interrupt enable settings. I-bit cleared hardware after interrupt occurred, RETI instruction enable subsequent interrupts. Ibit also cleared software with instructions, described instruction reference. Copy Storage Copy instructions (Bit LoaD) (Bit STore) T-bit source destination operated bit. from register Register file copied into instruction, copied into register Register file instruction. Half Carry Flag Half Carry Flag indicates half carry some arithmetic operations. Half carry useful arithmetic. "Instruction Description" detailed information. Sign Bit, S-bit always exclusive between negative flag two's complement overflow flag "Instruction Description" detailed information. Two's Complement Overflow Flag Two's Complement Overflow Flag supports two's complement arithmetics. "Instruction Description" detailed information. Negative Flag Negative Flag indicates negative result arithmetic logic operation. "Instruction Description" detailed information. Zero Flag Zero Flag indicates zero result arithmetic logic operation. "Instruction Description" detailed information. Carry Flag Carry Flag indicates carry arithmetic logic operation. "Instruction Description" detailed information. General Purpose Register File Register file optimized Enhanced RISC instruction set. order achieve required performance flexibility, following input/output schemes supported Register file: 8-bit output operand 8-bit result input 8-bit output operands 8-bit result input 8-bit output operands 16-bit result input 16-bit output operand 16-bit result input Figure shows structure general purpose working registers CPU. Figure General Purpose Working Registers Addr. ATmega128 2467L-AVR-05/04 ATmega128 General Purpose Working Registers X-register Byte X-register High Byte Y-register Byte Y-register High Byte Z-register Byte Z-register High Byte Most instructions operating Register file have direct access registers, most them single cycle instructions. shown Figure each register also assigned data memory address, mapping them directly into first locations user Data Space. Although being physically implemented SRAM locations, this memory organization provides great flexibility access registers, Z-pointer Registers index register file. X-register, Y-register, Zregister registers R26.R31 have some added functions their general purpose usage. These registers 16-bit address pointers indirect addressing Data Space. three indirect address registers described Figure Figure Z-registers register ($1B) ($1A) register ($1D) ($1C) register ($1F) ($1E) different addressing modes these address registers have functions fixed displacement, automatic increment, automatic decrement (see Instruction Reference details). 2467L-AVR-05/04 Stack Pointer Stack mainly used storing temporary data, storing local variables storing return addresses after interrupts subroutine calls. Stack Pointer Register always points Stack. Note that Stack implemented growing from higher memory locations lower memory locations. This implies that Stack PUSH command decreases Stack Pointer. Stack Pointer points data SRAM stack area where Subroutine Interrupt Stacks located. This Stack space data SRAM must defined program before subroutine calls executed interrupts enabled. Stack Pointer must point above $60. Stack Pointer decremented when data pushed onto Stack with PUSH instruction, decremented when return address pushed onto Stack with subroutine call interrupt. Stack Pointer incremented when data popped from Stack with instruction, incremented when data popped from Stack with return from subroutine return from interrupt RETI. Stack Pointer implemented 8-bit registers space. number bits actually used implementation dependent. Note that data space some implementations architecture small that only needed. this case, Register will present. SP15 Read/Write Initial Value SP14 SP13 SP12 SP11 SP10 Page Select Register RAMPZ RAMPZ0 RAMPZ Read/Write Initial Value Bits Res: Reserved Bits These reserved bits will always read zero. When writing this address location, write these bits zero compatibility with future devices. RAMPZ0: Extended Page Z-pointer RAMPZ Register normally used select which Page accessed Z-pointer. ATmega128 does support more than SRAM memory, this register used only select which page program memory accessed when ELPM/SPM instruction used. different settings RAMPZ0 have following effects: RAMPZ0 RAMPZ0 Program memory address $0000 $7FFF (lower bytes) accessed ELPM/SPM Program memory address $8000 $FFFF (higher bytes) accessed ELPM/SPM Note that affected RAMPZ setting. ATmega128 2467L-AVR-05/04 ATmega128 Instruction Execution Timing This section describes general access timing concepts instruction execution. driven clock clkCPU, directly generated from selected clock source chip. internal clock division used. Figure shows parallel instruction fetches instruction executions enabled Harvard architecture fast-access Register file concept. This basic pipelining concept obtain MIPS with corresponding unique results functions cost, functions clocks, functions power-unit. Figure Parallel Instruction Fetches Instruction Executions clkCPU Instruction Fetch Instruction Execute Instruction Fetch Instruction Execute Instruction Fetch Instruction Execute Instruction Fetch Figure shows internal timing concept Register file. single clock cycle operation using register operands executed, result stored back destination register. Figure Single Cycle Operation clkCPU Total Execution Time Register Operands Fetch Operation Execute Result Write Back Reset Interrupt Handling provides several different interrupt sources. These interrupts separate reset vector each have separate program vector program memory space. interrupts assigned individual enable bits which must written logic together with Global Interrupt Enable Status Register order enable interrupt. Depending Program Counter value, interrupts automatically disabled when Boot Lock bits BLB02 BLB12 programmed. This feature improves software security. section "Memory Programming" page details. lowest addresses program memory space default defined Reset Interrupt vectors. complete list vectors shown "Interrupts" page list also determines priority levels different interrupts. lower address higher priority level. RESET highest priority, next INT0 External Interrupt Request interrupt vectors moved start boot Flash section setting IVSEL Control Register (MCUCR). Refer "Interrupts" page more information. Reset vector also moved start boot Flash section programming BOOTRST fuse, "Boot Loader Support Read-While-Write Self-Programming" page 275. 2467L-AVR-05/04 When interrupt occurs, Global Interrupt Enable I-bit cleared interrupts disabled. user software write logic I-bit enable nested interrupts. enabled interrupts then interrupt current interrupt routine. I-bit automatically when Return from Interrupt instruction RETI executed. There basically types interrupts. first type triggered event that sets interrupt flag. these interrupts, Program Counter vectored actual interrupt vector order execute interrupt handling routine, hardware clears corresponding interrupt flag. Interrupt flags also cleared writing logic flag position(s) cleared. interrupt condition occurs while corresponding interrupt enable cleared, interrupt flag will remembered until interrupt enabled, flag cleared software. Similarly, more interrupt conditions occur while global interrupt enable cleared, corresponding interrupt flag(s) will remembered until global interrupt enable set, will then executed order priority. second type interrupts will trigger long interrupt condition present. These interrupts necessarily have interrupt flags. interrupt condition disappears before interrupt enabled, interrupt will triggered. When exits from interrupt, will always return main program execute more instruction before pending interrupt served. Note that Status Register automatically stored when entering interrupt routine, restored when returning from interrupt routine. This must handled software. When using instruction disable interrupts, interrupts will immediately disabled. interrupt will executed after instruction, even occurs simultaneously with instruction. following example shows this used avoid interrupts during timed EEPROM write sequence. Assembly Code Example r16, SREG EECR, EEMWE EECR, EEWE SREG, restore SREG value (I-bit) store SREG value start EEPROM write disable interrupts during timed sequence Code Example char cSREG; cSREG SREG; store SREG value disable interrupts during timed sequence _disable_interrupt(); EECR (1<<EEMWE); start EEPROM write EECR (1<<EEWE); SREG cSREG; restore SREG value (I-bit) ATmega128 2467L-AVR-05/04 ATmega128 When using instruction enable interrupts, instruction following will executed before pending interrupts, shown this example. Assembly Code Example global interrupt enable sleep; enter sleep, waiting interrupt note: will enter sleep before pending interrupt(s) Code Example _enable_interrupt(); global interrupt enable _sleep(); enter sleep, waiting interrupt note: will enter sleep before pending interrupt(s) Interrupt Response Time interrupt execution response enabled interrupts four clock cycles minimum. After four clock cycles, program vector address actual interrupt handling routine executed. During this 4-clock cycle period, Program Counter pushed onto Stack. vector normally jump interrupt routine, this jump takes three clock cycles. interrupt occurs during execution multi-cycle instruction, this instruction completed before interrupt served. interrupt occurs when Sleep mode, interrupt execution response time increased four clock cycles. This increase comes addition start-up time from selected sleep mode. return from interrupt handling routine takes four clock cycles. During these 4-clock cycles, Program Counter (two bytes) popped back from Stack, Stack Pointer incremented two, I-bit SREG set. 2467L-AVR-05/04 ATmega128 Memories In-System Reprogrammable Flash Program Memory This section describes different memories ATmega128. architecture main memory spaces, Data Memory Program Memory space. addition, ATmega128 features EEPROM Memory data storage. three memory spaces linear regular. ATmega128 contains 128K bytes On-chip In-System Reprogrammable Flash memory program storage. Since instructions bits wide, Flash organized software security, Flash Program memory space divided into sections, Boot Program section Application Program section. Flash memory endurance least 10,000 write/erase cycles. ATmega128 Program Counter (PC) bits wide, thus addressing program memory locations. operation Boot Program section associated Boot Lock bits software protection described detail "Boot Loader Support ReadWhile-Write Self-Programming" page 275. "Memory Programming" page contains detailed description Flash programming SPI, JTAG, Parallel Programming mode. Constant tables allocated within entire program memory address space (see Load Program Memory ELPM Extended Load Program Memory instruction description). Timing diagrams instruction fetch execution presented "Instruction Execution Timing" page Figure Program Memory Program Memory $0000 Application Flash Section Boot Flash Section $FFFF ATmega128 2467L-AVR-05/04 ATmega128 SRAM Data Memory ATmega128 supports different configurations SRAM data memory listed Table Table Memory Configurations Configuration Normal mode ATmega103 Compatibility mode Internal SRAM Data Memory 4096 4000 External SRAM Data Memory Figure shows ATmega128 SRAM Memory organized. ATmega128 complex microcontroller with more peripheral units than supported within location reserved Opcode instructions. Extended space from SRAM, only ST/STS/STD LD/LDS/LDD instructions used. Extended space does exist when ATmega128 ATmega103 compatibility mode. normal mode, first 4352 Data Memory locations address both Register file, Memory, Extended Memory, internal data SRAM. first locations address Register file, next location standard memory, then locations Extended memory, next 4096 locations address internal data SRAM. ATmega103 compatibility mode, first 4096 Data Memory locations address both Register file, Memory internal data SRAM. first locations address Register file, next location standard memory, next 4000 locations address internal data SRAM. optional external data SRAM used with ATmega128. This SRAM will occupy area remaining address locations address space. This area starts address following internal SRAM. Register file, I/O, Extended Internal SRAM occupies lowest 4352 bytes normal mode, lowest 4096 bytes ATmega103 compatibility mode (Extended present), when using 64KB (65536 bytes) External Memory, 61184 Bytes External Memory available normal mode, 61440 Bytes ATmega103 compatibility mode. "External Memory Interface" page details take advantage external memory map. When addresses accessing SRAM memory space exceeds internal data memory locations, external data SRAM accessed using same instructions internal data memory access. When internal data memories accessed, read write strobe pins (PG0 PG1) inactive during whole access cycle. External SRAM operation enabled setting MCUCR Register. Accessing external SRAM takes additional clock cycle byte compared access internal SRAM. This means that commands LDS, STS, LDD, STD, PUSH, take additional clock cycle. Stack placed external SRAM, interrupts, subroutine calls returns take three clock cycles extra because two-byte program counter pushed popped, external memory access does take advantage internal pipe-line memory access. When external SRAM interface used with wait-state, one-byte external access takes two, three, four additional clock cycles one, two, three wait-states respectively. Interrupts, subroutine calls returns will need five, seven, nine clock cycles more than specified instruction manual one, two, three wait-states. 2467L-AVR-05/04 five different addressing modes data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, Indirect with Post-increment. Register file, registers feature indirect addressing pointer registers. direct addressing reaches entire data space. Indirect with Displacement mode reaches address locations from base address given Z-register. When using register indirect addressing modes with automatic pre-decrement postincrement, address registers decremented incremented. general purpose working registers, registers, 4096 bytes internal data SRAM ATmega128 accessible through these addressing modes. Register file described "General Purpose Register File" page Figure Data Memory Memory Configuration Data Memory Registers Registers Reg. Internal SRAM (4096 $10FF $1100 External SRAM External SRAM $0000 $001F $0020 $005F $0060 $00FF $0100 Memory Configuration Data Memory Registers Registers Internal SRAM (4000 $0FFF $1000 $0000 $001F $0020 $005F $0060 $FFFF $FFFF ATmega128 2467L-AVR-05/04 ATmega128 Data Memory Access Times This section describes general access timing concepts internal memory access. internal data SRAM access performed clkCPU cycles described Figure Figure On-chip Data SRAM Access Cycles clkCPU Address Data Data Compute Address Address valid Memory access instruction Next instruction EEPROM Data Memory ATmega128 contains bytes data EEPROM memory. organized separate data space, which single bytes read written. EEPROM endurance least 100,000 write/erase cycles. access between EEPROM described following, specifying EEPROM Address Registers, EEPROM Data Register, EEPROM Control Register. "Memory Programming" page contains detailed description EEPROM programming SPI, JTAG, Parallel Programming mode EEPROM Read/Write Access EEPROM access registers accessible space. write access time EEPROM given Table self-timing function, however, lets user software detect when next byte written. user code contains instructions that write EEPROM, some precautions must taken. heavily filtered power supplies, likely rise fall slowly Power-up/down. This causes device some period time voltage lower than specified minimum clock frequency used. "Preventing EEPROM Corruption" page details avoid problems these situations. order prevent unintentional EEPROM writes, specific write procedure must followed. Refer description EEPROM Control Register details this. When EEPROM read, halted four clock cycles before next instruction executed. When EEPROM written, halted clock cycles before next instruction executed. EEPROM Address Register EEARH EEARL EEAR7 EEAR6 EEAR5 EEAR4 EEAR11 EEAR3 EEAR10 EEAR2 Read Write EEAR9 EEAR1 EEAR8 EEAR0 EEARH EEARL Read/Write Initial Value Bits 15.12 Res: Reserved Bits 2467L-AVR-05/04 These reserved bits will always read zero. When writing this address location, write these bits zero compatibility with future devices. Bits 11.0 EEAR11.0: EEPROM Address EEPROM Address Registers EEARH EEARL specify EEPROM address bytes EEPROM space. EEPROM data bytes addressed linearly between 4096. initial value EEAR undefined. proper value must written before EEPROM accessed. EEPROM Data Register EEDR EEDR Read/Write Initial Value Bits EEDR7.0: EEPROM Data EEPROM write operation, EEDR Register contains data written EEPROM address given EEAR Register. EEPROM read operation, EEDR contains data read from EEPROM address given EEAR. EEPROM Control Register EECR EERIE EEMWE EEWE EERE EECR Read/Write Initial Value Bits Res: Reserved Bits These bits reserved bits ATmega128 will always read zero. EERIE: EEPROM Ready Interrupt Enable Writing EERIE enables EEPROM Ready Interrupt I-bit SREG set. Writing EERIE zero disables interrupt. EEPROM Ready interrupt generates constant interrupt when EEWE cleared. EEMWE: EEPROM Master Write Enable EEMWE determines whether setting EEWE causes EEPROM written. When EEMWE written one, writing EEWE within four clock cycles will write data EEPROM selected address. EEMWE zero, writing EEWE will have effect. When EEMWE been written software, hardware clears zero after four clock cycles. description EEWE EEPROM write procedure. EEWE: EEPROM Write Enable EEPROM Write Enable Signal EEWE write strobe EEPROM. When address data correctly EEWE must write value into EEPROM. EEMWE must when logical written EEWE, otherwise EEPROM write takes place. following procedure should followed when writing EEPROM (the order steps essential): Wait until EEWE becomes zero. Wait until SPMEN SPMCSR becomes zero. Write EEPROM address EEAR (optional). Write EEPROM data EEDR (optional). ATmega128 2467L-AVR-05/04 ATmega128 Write logical EEMWE while writing zero EEWE EECR. Within four clock cycles after setting EEMWE, write logical EEWE. EEPROM programmed during write Flash memory. software must check that Flash programming completed before initiating EEPROM write. Step only relevant software contains boot loader allowing program Flash. Flash never being updated CPU, step omitted. "Boot Loader Support Read-While-Write Self-Programming" page details about boot programming. Caution: interrupt between step step will make write cycle fail, since EEPROM Master Write Enable will time-out. interrupt routine accessing EEPROM interrupting another EEPROM access, EEAR EEDR Register will modified, causing interrupted EEPROM access fail. recommended have global interrupt flag cleared during four last steps avoid these problems. When write access time elapsed, EEWE cleared hardware. user software poll this wait zero before writing next byte. When EEWE been set, halted cycles before next instruction executed. EERE: EEPROM Read Enable EEPROM Read Enable Signal EERE read strobe EEPROM. When correct address EEAR Register, EERE must written logic trigger EEPROM read. EEPROM read access takes instruction, requested data available immediately. When EEPROM read, halted four cycles before next instruction executed. user should poll EEWE before starting read operation. write operation progress, neither possible read EEPROM, change EEAR Register. calibrated Oscillator used time EEPROM accesses. Table lists typical programming time EEPROM access from CPU. Table EEPROM Programming Time Symbol EEPROM Write (from CPU) Note: Number Calibrated Oscillator Cycles(1) 8448 Programming Time Uses clock, independent CKSEL-fuse settings. 2467L-AVR-05/04 following code examples show assembly function writing EEPROM. examples assume that interrupts controlled (e.g., disabling interrupts globally) that interrupts will occur during execution these functions. examples also assume that flash boot loader present software. such code present, EEPROM write function must also wait ongoing command finish. Assembly Code Example EEPROM_write: Wait completion previous write sbic EECR,EEWE rjmp EEPROM_write address (r18:r17) address register EEARH, EEARL, Write data (r16) data register EEDR,r16 Write logical EEMWE EECR,EEMWE Start eeprom write setting EEWE EECR,EEWE Code Example void EEPROM_write(unsigned uiAddress, unsigned char ucData) Wait completion previous write while(EECR (1<<EEWE)) address data registers EEAR uiAddress; EEDR ucData; Write logical EEMWE EECR (1<<EEMWE); Start eeprom write setting EEWE EECR (1<<EEWE); ATmega128 2467L-AVR-05/04 ATmega128 next code examples show assembly functions reading EEPROM. examples assume that interrupts controlled that interrupts will occur during execution these functions. Assembly Code Example EEPROM_read: Wait completion previous write sbic EECR,EEWE rjmp EEPROM_read address (r18:r17) address register EEARH, EEARL, Start eeprom read writing EERE EECR,EERE Read data from data register r16,EEDR Code Example unsigned char EEPROM_read(unsigned uiAddress) Wait completion previous write while(EECR (1<<EEWE)) address register EEAR uiAddress; Start eeprom read writing EERE EECR (1<<EERE); Return data from data register return EEDR; EEPROM Write During Powerdown Sleep Mode When entering Power-down sleep mode while EEPROM write operation active, EEPROM write operation will continue, will complete before write access time passed. However, when write operation completed, Oscillator continues running, consequence, device does enter Power-down entirely. therefore recommended verify that EEPROM write operation completed before entering Power-down. During periods VCC, EEPROM data corrupted because supply voltage EEPROM operate properly. These issues same board level systems using EEPROM, same design solutions should applied. EEPROM data corruption caused situations when voltage low. First, regular write sequence EEPROM requires minimum voltage operate correctly. Secondly, itself execute instructions incorrectly, supply voltage low. EEPROM data corruption easily avoided following this design recommendation: Preventing EEPROM Corruption 2467L-AVR-05/04 Keep RESET active (low) during periods insufficient power supply voltage. This done enabling internal Brown-out Detector (BOD). detection level internal does match needed detection level, external Reset Protection circuit used. reset occurs while write operation progress, write operation will completed provided that power supply voltage sufficient. Memory space definition ATmega128 shown "Register Summary" page 364. ATmega128 I/Os peripherals placed space. locations accessed LD/LDS/LDD ST/STS/STD instructions, transferring data between general purpose working registers space. registers within address range directly bit-accessible using instructions. these registers, value single bits checked using SBIS SBIC instructions. Refer instruction section more details. When using specific commands OUT, addresses must used. When addressing registers data space using instructions, must added these addresses. ATmega128 complex microcontroller with more peripheral units than supported within location reserved Opcode instructions. Extended space from SRAM, only ST/STS/STD LD/LDS/LDD instructions used. Extended space replaced with SRAM locations when ATmega128 ATmega103 compatibility mode. compatibility with future devices, reserved bits should written zero accessed. Reserved memory addresses should never written. Some status flags cleared writing logical them. Note that instructions will operate bits register, writing back into flag read set, thus clearing flag. instructions work with registers only. peripherals control registers explained later sections. External Memory Interface With features External Memory Interface provides, well suited operate interface memory devices such External SRAM Flash, peripherals such LCD-display, A/D, D/A. main features are: Four different wait-state settings (including wait-state). Independent wait-state setting different extErnal Memory sectors (configurable sector size). number bits dedicated address high byte selectable. Bus-keepers data lines minimize current consumption (optional). Overview When eXternal MEMory (XMEM) enabled, address space outside internal SRAM becomes available using dedicated External Memory pins (see Figure page Table page Table page Table page 82). memory configuration shown Figure ATmega128 2467L-AVR-05/04 ATmega128 Figure External Memory with Sector Select Memory Configuration 0x0000 Memory Configuration 0x0000 Internal memory Internal memory 0x0FFF 0x1000 0x10FF 0x1100 Lower sector SRW01 SRW00 SRW10 External Memory (0-60K SRL[2.0] External Memory (0-60K Upper sector SRW11 SRW10 0xFFFF 0xFFFF Note: ATmega128 ATmega103 compatibility mode: Memory Configuration available (Memory Configuration N/A) ATmega128 ATmega103 compatibility mode: Memory Configuration available (Memory Configuration N/A) ATmega103 Compatibility Both External Memory Control Registers (XMCRA XMCRB) placed Extended space. ATmega103 compatibility mode, these registers available, features selected these registers available. device still ATmega103 compatible, these features exist ATmega103. limitations ATmega103 compatibility mode are: Only wait-states settings available (SRW1n 0b00 SRW1n 0b01). number bits that assigned address high byte fixed. External Memory section divided into sectors with different waitstate settings. Bus-keeper available. pins output only (Port ATmega128). Using External Memory Interface interface consists AD7:0: Multiplexed low-order address data bus. A15:8: High-order address (configurable number bits). ALE: Address latch enable. Read strobe. Write strobe. 2467L-AVR-05/04 control bits External Memory Interface located three registers, Control Register MCUCR, External Memory Control Register XMCRA, External Memory Control Register XMCRB. When XMEM interface enabled, XMEM interface will override setting data direction registers that corresponds ports dedicated XMEM interface. details about port override, alternate functions section "I/O Ports" page XMEM interface will auto-detect whether access internal external. access external, XMEM interface will output address, data, control signals ports according Figure (this figure shows wave forms without wait-states). When goes from high-to-low, there valid address AD7:0. during data transfer. When XMEM interface enabled, also internal access will cause activity address, data ports, strobes will toggle during internal access. When External Memory Interface disabled, normal data direction settings used. Note that when XMEM interface disabled, address space above internal SRAM boundary mapped into internal SRAM. Figure illustrates connect external SRAM using octal latch (typically 573" equivalent) which transparent when high. Address Latch Requirements high-speed operation XRAM interface, address latch must selected with care system frequencies above 2.7V. When operating conditions above these frequencies, typical style 74HC series latch becomes inadequate. External Memory Interface designed compliance 74AHC series latch. However, most latches used long they comply with main timing parameters. main parameters address latch are: propagation delay (tPD). Data setup time before (tSU). Data (address) hold time after (TH). External Memory Interface designed guaranty minimum address hold time after asserted Refer tLAXX_LD/tLLAXX_ST "External Data Memory Timing" Tables through Tables pages 332. D-to-Q propagation delay (tPD) must taken into consideration when calculating access time requirement external component. data setup time before must exceed address valid (tAVLLC) minus wiring delay (dependent capacitive load). Figure External SRAM Connected D[7:0] AD7:0 A[7:0] A15:8 SRAM A[15:8] ATmega128 2467L-AVR-05/04 ATmega128 Pull-up Bus-keeper pull-ups AD7:0 ports activated corresponding Port register written one. reduce power consumption sleep mode, recommended disable pull-ups writing Port register zero before entering sleep. XMEM interface also provides bus-keeper AD7:0 lines. bus-keeper disabled enabled software described "External Memory Control Register XMCRB" page When enabled, bus-keeper will ensure defined logic level (zero one) AD7:0 when these lines would otherwise tri-stated XMEM interface. Timing External Memory devices have different timing requirements. meet these requirements, ATmega128 XMEM interface provides four different wait-states shown Table important consider timing specification External Memory device before selecting wait-state. most important parameters access time external memory compared set-up requirement ATmega128. access time External Memory defined time from receiving chip select/address until data this address actually driven bus. access time cannot exceed time from pulse must asserted until data stable during read sequence (See tLLRL+ tRLRH tDVRH Tables through Tables pages 332). different wait-states software. additional feature, possible divide external memory space sectors with individual wait-state settings. This makes possible connect different memory devices with different timing requirements same XMEM interface. XMEM interface timing details, please refer Table Table Figure Figure "External Data Memory Timing" page 330. Note that XMEM interface asynchronous that waveforms following figures related internal system clock. skew between internal external clock (XTAL1) guarantied (varies between devices temperature, supply voltage). Consequently, XMEM interface suited synchronous operation. Figure External Data Memory Cycles without Wait-state (SRWn1=0 SRWn0=0) System Clock (CLKCPU A15:8 Prev. addr. Address DA7:0 Prev. data Address Data DA7:0 (XMBK Prev. data Address Data DA7:0 (XMBK Prev. data Address XXXXX Data XXXXXXXX Note: SRWn1 SRW11 (upper sector) SRW01 (lower sector), SRWn0 SRW10 (upper sector) SRW00 (lower sector). pulse period only present next instruction accesses (internal external). 2467L-AVR-05/04 Read Write Figure External Data Memory Cycles with SRWn1 SRWn0 1(1) System Clock (CLKCPU A15:8 Prev. addr. Address DA7:0 Prev. data Address Data DA7:0 (XMBK Prev. data Address Data DA7:0 (XMBK Prev. data Address Data Note: SRWn1 SRW11 (upper sector) SRW01 (lower sector), SRWn0 SRW10 (upper sector) SRW00 (lower sector). pulse period only present next instruction accesses (internal external). Figure External Data Memory Cycles with SRWn1 SRWn0 0(1) System Clock (CLKCPU A15:8 Prev. addr. Address Read Write DA7:0 Prev. data Address Data DA7:0 (XMBK Prev. data Address Data DA7:0 (XMBK Prev. data Address Data Note: SRWn1 SRW11 (upper sector) SRW01 (lower sector), SRWn0 SRW10 (upper sector) SRW00 (lower sector). pulse period only present next instruction accesses (internal external). ATmega128 2467L-AVR-05/04 Read Write ATmega128 Figure External Data Memory Cycles with SRWn1 SRWn0 1(1) System Clock (CLKCPU A15:8 Prev. addr. Address DA7:0 Prev. data Address Data DA7:0 (XMBK Prev. data Address Data DA7:0 (XMBK Prev. data Address Data Note: SRWn1 SRW11 (upper sector) SRW01 (lower sector), SRWn0 SRW10 (upper sector) SRW00 (lower sector). pulse period only present next instruction accesses (internal external). XMEM Register Description Control Register MCUCR SRW10 IVSEL IVCE MCUCR Read/Write Initial Value SRE: External SRAM/XMEM Enable Writing enables External Memory Interface.The functions AD7:0, A15:8, ALE, activated alternate functions. overrides direction settings respective data direction registers. Writing zero, disables External Memory Interface normal data direction settings used. SRW10: Wait-state Select detailed description non-ATmega103 compatibility mode, common description SRWn bits below (XMCRA description). ATmega103 compatibility mode, writing SRW10 enables wait-state extra cycle added during read/write strobe shown Figure External Memory Control Register XMCRA SRL2 SRL1 SRL0 SRW01 SRW00 SRW11 XMCRA Read/Write Initial Value Res: Reserved This reserved will always read zero. When writing this address location, write this zero compatibility with future devices. SRL2, SRL1, SRL0: Wait-state Sector Limit 2467L-AVR-05/04 Read Write possible configure different wait-states different External Memory addresses. external memory address space divided sectors that have separate wait-state bits. SRL2, SRL1, SRL0 bits select split sectors, Table Figure default, SRL2, SRL1, SRL0 bits zero entire external memory address space treated sector. When entire SRAM address space configured sector, wait-states configured SRW11 SRW10 bits. Table Sector limits with different settings SRL2.0 SRL2 SRL1 SRL0 Sector Limits Lower sector Upper sector 0x1100 0xFFFF Lower sector 0x1100 0x1FFF Upper sector 0x2000 0xFFFF Lower sector 0x1100 0x3FFF Upper sector 0x4000 0xFFFF Lower sector 0x1100 0x5FFF Upper sector 0x6000 0xFFFF Lower sector 0x1100 0x7FFF Upper sector 0x8000 0xFFFF Lower sector 0x1100 0x9FFF Upper sector 0xA000 0xFFFF Lower sector 0x1100 0xBFFF Upper sector 0xC000 0xFFFF Lower sector 0x1100 0xDFFF Upper sector 0xE000 0xFFFF MCUCR SRW11, SRW10: Wait-state Select Bits Upper Sector SRW11 SRW10 bits control number wait-states upper sector external memory address space, Table SRW01, SRW00: Wait-state Select Bits Lower Sector SRW01 SRW00 bits control number wait-states lower sector external memory address space, Table Table Wait States(1) SRWn1 Note: SRWn0 Wait States wait-states Wait cycle during read/write strobe Wait cycles during read/write strobe Wait cycles during read/write wait cycle before driving address (lower/upper sector). further details timing wait-states External Memory Interface, Figures through Figures setting bits affects timing. Res: Reserved This reserved will always read zero. When writing this address location, write this zero compatibility with future devices. ATmega128 2467L-AVR-05/04 ATmega128 External Memory Control Register XMCRB XMBK XMM2 XMM1 XMM0 XMCRB Read/Write Initial Value XMBK: External Memory Bus-keeper Enable Writing XMBK enables keeper AD7:0 lines. When keeper enabled, will ensure defined logic level (zero one) AD7:0 when they would otherwise tri-stated. Writing XMBK zero disables keeper. XMBK qualified with SRE, even XMEM interface disabled, keepers still activated long XMBK one. Res: Reserved Bits These reserved bits will always read zero. When writing this address location, write these bits zero compatibility with future devices. XMM2, XMM1, XMM0: External Memory High Mask When External Memory enabled, Port pins default used high address byte. full 60KB address space required access External Memory, some, all, Port pins released normal Port function described Table described "Using 64KB Locations External Memory" page possible XMMn bits access 64KB locations External Memory. Table Port Pins Released Normal Port Pins when External Memory Enabled XMM2 XMM1 XMM0 Bits External Memory Address (Full space) Address high bits Released Port Pins None Full Port Using Locations External Memory Smaller than Since external memory mapped after internal memory shown Figure external memory addressed when addressing first 4,352 bytes data space. appear that first 4,352 bytes external memory inaccessible (external memory addresses 0x0000 0x10FF). However, when connecting external memory smaller than example these locations easily accessed simply addressing from address 0x8000 0x90FF. Since External Memory Address connected external memory, addresses 0x8000 0x90FF will appear addresses 0x0000 0x10FF external memory. Addressing above address 0x90FF recommended, since this will address external memory location that already accessed another (lower) address. Application software, external memory will appear linear address space from 0x1100 0x90FF. This illustrated Figure Memory configuration refers ATmega103 compatibility mode, configuration non-compatible mode. 2467L-AVR-05/04 When device ATmega103 compatibility mode, internal address space 4,096 bytes. This implies that first 4,096 bytes external memory accessed addresses 0x8000 0x8FFF. Application software, external memory will appear linear address space from 0x1000 0x8FFF. Figure Address with External Memory Memory Configuration Memory External SRAM Memory Configuration Memory External SRAM 0x0000 Internal Memory 0x10FF 0x1100 0x0000 0x0000 0x0FFF 0x1000 Internal Memory 0x0000 0x0FFF 0x1000 0x10FF 0x1100 0x7FFF 0x8000 External Memory 0x7FFF 0x7FFF 0x8000 External Memory 0x7FFF 0x90FF 0x9100 0x8FFF 0x9000 (Unused) (Unused) 0xFFFF 0xFFFF ATmega128 2467L-AVR-05/04 ATmega128 Using 64KB Locations External Memory Since External Memory mapped after Internal Memory shown Figure only 60KB External Memory available default (address space 0x0000 0x10FF reserved internal memory). However, possible take advantage entire External Memory masking higher address bits zero. This done using XMMn bits control software most significant bits address. setting Port output 0x00, releasing most significant bits normal Port operation, Memory Interface will address 0x0000 0x1FFF. following code examples. Assembly Code Example(1) OFFSET defined 0x2000 ensure external memory access Configure Port (address high byte) output 0x00 when pins released normal Port operation r16, 0xFF DDRC, r16, 0x00 PORTC, release PC7:5 r16, (1<<XMM1)|(1<<XMM0) XMCRB, write 0xAA address 0x0001 external memory r16, 0xaa 0x0001+OFFSET, re-enable PC7:5 external memory r16, (0<<XMM1)|(0<<XMM0) XMCRB, store 0x55 address (OFFSET external memory r16, 0x55 0x0001+OFFSET, Code Example(1) #define OFFSET 0x2000 void XRAM_example(void) unsigned char (unsigned char (OFFSET DDRC 0xFF; PORTC 0x00; XMCRB (1<<XMM1) (1<<XMM0); 0xaa; XMCRB 0x00; 0x55; Note: example code assumes that part specific header file included. Care must exercised using this option most memory masked away. 2467L-AVR-05/04 System Clock Clock Options Clock Systems their Distribution Figure presents principal clock systems their distribution. clocks need active given time. order reduce power consumption, clocks modules being used halted using different sleep modes, described "Power Management Sleep Modes" page clock systems detailed below. Figure Clock Distribution Asynchronous Timer/Counter General modules Core Flash EEPROM clkADC clkI/O clkASY clkCPU clkFLASH Clock Control Unit Reset Logic Watchdog Timer Source clock Clock Multiplexer Watchdog clock Watchdog Oscillator Timer/Counter Oscillator External Oscillator External clock Crystal Oscillator Low-Frequency Crystal Oscillator Calibrated Oscillator Clock clkCPU clock routed parts system concerned with operation core. Examples such modules General Purpose Register File, Status Register data memory holding Stack Pointer. Halting clock inhibits core from performing general operations calculations. clock used majority modules, like Timer/Counters, SPI, USART. clock also used External Interrupt module, note that some external interrupts detected asynchronous logic, allowing such interrupts detected even clock halted. Also note that address recognition module carried asynchronously when clkI/O halted, enabling address reception sleep modes. Flash clock controls operation Flash interface. Flash clock usually active simultaneously with clock. Clock clkI/O Flash Clock clkFLASH ATmega128 2467L-AVR-05/04 ATmega128 Asynchronous Timer Clock clkASY Clock clkADC Asynchronous Timer clock allows Asynchronous Timer/Counter clocked directly from external clock crystal. dedicated clock domain allows using this Timer/Counter real-time counter even when device sleep mode. provided with dedicated clock domain. This allows halting clocks order reduce noise generated digital circuitry. This gives more accurate conversion results. device following clock source options, selectable Flash fuse bits shown below. clock from selected source input clock generator, routed appropriate modules. Table Device Clocking Options Select Device Clocking Option External Crystal/Ceramic Resonator External Low-frequency Crystal External Oscillator Calibrated Internal Oscillator External Clock Note: CKSEL3.0(1) 1111 1010 1001 1000 0101 0100 0001 0000 Clock Sources fuses means unprogrammed while means programmed. various choices each clocking option given following sections. When wakes from Power-down Power-save, selected clock source used time start-up, ensuring stable Oscillator operation before instruction execution starts. When starts from reset, there additional delay allowing power reach stable level before commencing normal operation. Watchdog Oscillator used timing this real-time part start-up time. number Oscillator cycles used each time-out shown Table frequency Watchdog Oscillator voltage dependent shown "ATmega128 Typical Characteristics" page 335. Table Number Watchdog Oscillator Cycles Typical Time-out (VCC 5.0V) Typical Time-Out (VCC 3.0V) Number Cycles (4,096) (65,536) Default Clock Source device shipped with CKSEL "0001" "10". default clock source setting therefore Internal Oscillator with longest startup time. This default setting ensures that users make their desired clock source setting using InSystem Parallel Programmer. 2467L-AVR-05/04 Crystal Oscillator XTAL1 XTAL2 input output, respectively, inverting amplifier which configured On-chip Oscillator, shown Figure Either quartz crystal ceramic resonator used. CKOPT fuse selects between different Oscillator Amplifier modes. When CKOPT programmed, Oscillator output will oscillate will full rail-to-rail swing output. This mode suitable when operating very noisy environment when output from XTAL2 drives second clock buffer. This mode wide frequency range. When CKOPT unprogrammed, Oscillator smaller output swing. This reduces power consumption considerably. This mode limited frequency range used drive other clock buffers. resonators, maximum frequency with CKOPT unprogrammed with CKOPT programmed. should always equal both crystals resonators. optimal value capacitors depends crystal resonator use, amount stray capacitance, electromagnetic noise environment. Some initial guidelines choosing capacitors with crystals given Table ceramic resonators, capacitor values given manufacturer should used. Figure Crystal Oscillator Connections XTAL2 XTAL1 Oscillator operate three different modes, each optimized specific frequency range. operating mode selected fuses CKSEL3.1 shown Table Table Crystal Oscillator Operating Modes CKOPT Note: CKSEL3.1 101(1) 101, 110, Frequency Range (MHz) Recommended Range Capacitors with Crystals This option should used with crystals, only with ceramic resonators. CKSEL0 fuse together with SUT1.0 fuses select start-up times shown Table ATmega128 2467L-AVR-05/04 ATmega128 Table Start-up Times Crystal Oscillator Clock Selection Start-up Time from Power-down Power-save CKSEL0 Notes: SUT1.0 Additional Delay from Reset (VCC 5.0V) Recommended Usage Ceramic resonator, fast rising power Ceramic resonator, slowly rising power Ceramic resonator, enabled Ceramic resonator, fast rising power Ceramic resonator, slowly rising power Crystal Oscillator, enabled Crystal Oscillator, fast rising power Crystal Oscillator, slowly rising power CK(1) CK(2) CK(2) CK(2) These options should only used when operating close maximum frequency device, only frequency stability start-up important application. These options suitable crystals. These options intended with ceramic resonators will ensure frequency stability start-up. They also used with crystals when operating close maximum frequency device, frequency stability start-up important application. Low-frequency Crystal Oscillator 32.768 watch crystal clock source device, Low-frequency Crystal Oscillator must selected setting CKSEL fuses "1001". crystal should connected shown Figure programming CKOPT fuse, user enable internal capacitors XTAL1 XTAL2, thereby removing need external capacitors. internal capacitors have nominal value When this Oscillator selected, start-up times determined fuses shown Table Table Start-up Times Low-frequency Crystal Oscillator Clock Selection Start-up Time from Power-down Power-save SUT1.0 Note: Additional Delay from Reset (VCC 5.0V) Reserved Recommended Usage Fast rising power enabled Slowly rising power Stable frequency start-up These options should only used frequency stability start-up important application. 2467L-AVR-05/04 External Oscillator timing insensitive applications, External configuration shown Figure used. frequency roughly estimated equation 1/(3RC). should least programming CKOPT fuse, user enable internal capacitor between XTAL1 GND, thereby removing need external capacitor. more information Oscillator operation details choose refer External Oscillator application note. Figure External Configuration XTAL2 XTAL1 Oscillator operate four different modes, each optimized specific frequency range. operating mode selected fuses CKSEL3.0 shown Table Table External Oscillator Operating Modes CKSEL3.0 0101 0110 0111 1000 Frequency Range (MHz) 12.0 When this Oscillator selected, start-up times determined fuses shown Table Table Start-Up Times External Oscillator Clock Selection Start-up Time from Power-down Power-save SUT1.0 Note: Additional Delay from Reset (VCC 5.0V) Recommended Usage enabled Fast rising power Slowly rising power Fast rising power enabled This option should used when operating close maximum frequency device. ATmega128 2467L-AVR-05/04 ATmega128 Calibrated Internal Oscillator Calibrated Internal Oscillator provides fixed 1.0, 2.0, 4.0, clock. frequencies nominal values 25°C. This clock selected system clock programming CKSEL fuses shown Table selected, will operate with external components. CKOPT fuse should always unprogrammed when using this clock option. During Reset, hardware loads calibration byte into OSCCAL Register thereby automatically calibrates Oscillator. 25°C Oscillator frequency selected, this calibration gives frequency within nominal frequency. Using calibration methods described application notes available www.atmel.com/avr possible achieve accuracy given Temperature. When this Oscillator used chip clock, Watchdog Oscillator will still used Watchdog Timer Reset Time-out. more information pre-programmed calibration value, section "Calibration Byte" page 291. Table Internal Calibrated Oscillator Operating Modes CKSEL3.0 0001(1) 0010 0011 0100 Note: device shipped with this option selected. Nominal Frequency (MHz) When this Oscillator selected, start-up times determined fuses shown Table XTAL1 XTAL2 should left unconnected (NC). Table Start-up Times Internal Calibrated Oscillator Clock Selection SUT1.0 Start-up Time from Powerdown Power-save Additional Delay from Reset (VCC 5.0V) Reserved Recommended Usage enabled Fast rising power Slowly rising power Note: device shipped with this option selected. Oscillator Calibration Register OSCCAL CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 OSCCAL Read/Write Initial Value Device Specific Calibration Value Note: OSCCAL Register available ATmega103 compatibility mode. Bits CAL7.0: Oscillator Calibration Value Writing calibration byte this address will trim Internal Oscillator remove process variations from Oscillator frequency. During Reset, calibration value which located signature high byte (address 0x00) automatically loaded into OSCCAL Register. internal used other frequencies, calibration values must loaded manually. This done first reading signature programmer, then store calibration values Flash EEPROM. Then value read software loaded into OSCCAL Register. When OSCCAL 2467L-AVR-05/04 zero, lowest available frequency chosen. Writing non-zero values this register will increase frequency Internal Oscillator. Writing register gives highest available frequency. calibrated Oscillator used time EEPROM Flash access. EEPROM Flash written, calibrate more than above nominal frequency. Otherwise, EEPROM Flash write fail. Note that Oscillator intended calibration 1.0, 2.0, 4.0, MHz. Tuning other values guaranteed, indicated Table Table Internal Oscillator Frequency Range. OSCCAL Value Frequency Percentage Nominal Frequency Frequency Percentage Nominal Frequency External Clock drive device from external clock source, XTAL1 should driven shown Figure device external clock, CKSEL fuses must programmed "0000". programming CKOPT fuse, user enable internal capacitor between XTAL1 GND. Figure External Clock Drive Configuration EXTERNAL CLOCK SIGNAL When this clock source selected, start-up times determined fuses shown Table Table Start-up Times External Clock Selection SUT1.0 Start-up Time from Powerdown Power-save Additional Delay from Reset (VCC 5.0V) Reserved Recommended Usage enabled Fast rising power Slowly rising power When applying external clock, required avoid sudden changes applied clock frequency ensure stable operation MCU. variation frequency more than from clock cycle next lead unpredictable behavior. required ensure that kept Reset during such changes clock frequency. ATmega128 2467L-AVR-05/04 ATmega128 Timer/Counter Oscillator microcontrollers with Timer/Counter Oscillator pins (TOSC1 TOSC2), crystal connected directly between pins. external capacitors needed. Oscillator optimized with 32.768 watch crystal. Applying external clock source TOSC1 recommended. XTAL Divide Control Register used divide Source clock frequency number range 129. This feature used decrease power consumption when requirement processing power low. XDIVEN Read/Write Initial Value XDIV6 XDIV5 XDIV4 XDIV3 XDIV2 XDIV1 XDIV0 XDIV XTAL Divide Control Register XDIV XDIVEN: XTAL Divide Enable When XDIVEN written one, clock frequency peripherals (clkI/O, clkADC, clkCPU, clkFLASH) divided factor defined setting XDIV6 XDIV0. This written run-time vary clock frequency suitable application. Bits XDIV6.XDIV0: XTAL Divide Select Bits These bits define division factor that applies when XDIVEN (one). value these bits denoted following formula defines resulting peripherals clock frequency fCLK: Source clock -129 value these bits only changed when XDIVEN zero. When XDIVEN written one, value written simultaneously into XDIV6.XDIV0 taken division factor. When XDIVEN written zero, value written simultaneously into XDIV6.XDIV0 rejected. divider divides master clock input MCU, speed peripherals reduced when division factor used. Note: When system clock divided, Timer/Counter0 used with Asynchronous clock only. frequency asynchronous clock must lower than 1/4th frequency scaled down Source clock. Otherwise, interrupts lost, accessing Timer/Counter0 registers fail. 2467L-AVR-05/04 Power Management Sleep Modes Sleep modes enable application shut down unused modules MCU, thereby saving power. provides various sleep modes allowing user tailor power consumption application's requirements. enter sleep modes, MCUCR must written logic SLEEP instruction must executed. SM2, SM1, bits MCUCR Register select which sleep mode (Idle, Noise Reduction, Power-down, Power-save, Standby, Extended Standby) will activated SLEEP instruction. Table summary. enabled interrupt occurs while sleep mode, wakes then halted four cycles addition start-up time, executes interrupt routine, resumes execution from instruction following SLEEP. contents register file SRAM unaltered when device wakes from sleep. reset occurs during sleep mode, wakes executes from Reset Vector. Figure page presents different clock systems ATmega128, their distribution. figure helpful selecting appropriate sleep mode. Control Register MCUCR Control Register contains control bits power management. Read/Write Initial Value SRW10 IVSEL IVCE MCUCR Sleep Enable must written logic make enter Sleep mode when SLEEP instruction executed. avoid entering Sleep mode unless programmers purpose, recommended write Sleep Enable (SE) just before execution SLEEP instruction clear immediately after waking Bits SM2.0: Sleep Mode Select Bits These bits select between available sleep modes shown Table Table Sleep Mode Select Note: Sleep Mode Idle Noise Reduction Power-down Power-save Reserved Reserved Standby(1) Extended Standby(1) Standby mode Extended Standby mode only available with external crystals resonators. ATmega128 2467L-AVR-05/04 ATmega128 Idle Mode When SM2.0 bits written 000, SLEEP instruction makes enter Idle mode, stopping allowing SPI, USART, Analog Comparator, ADC, Twowire Serial Interface, Timer/Counters, Watchdog, interrupt system continue operating. This sleep mode basically halts clkCPU clkFLASH, while allowing other clocks run. Idle mode enables wake from external triggered interrupts well internal ones like Timer Overflow USART Transmit Complete interrupts. wake-up from Analog Comparator interrupt required, Analog Comparator powered down setting Analog Comparator Control Status Register ACSR. This will reduce power consumption Idle mode. enabled, conversion starts automatically when this mode entered. Noise Reduction Mode When SM2.0 bits written 001, SLEEP instruction makes enter Noise Reduction mode, stopping allowing ADC, External Interrupts, Two-wire Serial Interface address watch, Timer/Counter0 Watchdog continue operating enabled). This sleep mode basically halts I/O, clkCPU, clkFLASH, while allowing other clocks run. This improves noise environment ADC, enabling higher resolution measurements. enabled, conversion starts automatically when this mode entered. Apart form Conversion Complete interrupt, only External Reset, Watchdog Reset, Brown-out Reset, Two-wire Serial Interface address match interrupt, Timer/Counter0 interrupt, SPM/EEPROM ready interrupt, External Level Interrupt INT7:4, External Interrupt INT3:0 wake from Noise Reduction mode. Power-down Mode When SM2.0 bits written 010, SLEEP instruction makes enter Power-down mode. this mode, External Oscillator stopped, while External Interrupts, Two-wire Serial Interface address watch, Watchdog continue operating enabled). Only External Reset, Watchdog Reset, Brown-out Reset, Two-wire Serial Interface address match interrupt, External Level Interrupt INT7:4, External Interrupt INT3:0 wake MCU. This sleep mode basically halts generated clocks, allowing operation asynchronous modules only. Note that level triggered interrupt used wake-up from Power-down mode, changed level must held some time wake MCU. Refer "External Interrupts" page details. When waking from Power-down mode, there delay from wake-up condition occurs until wake-up becomes effective. This allows clock restart become stable after having been stopped. wake-up period defined same CKSEL fuses that define Reset Time-out period, described "Clock Sources" page Power-save Mode When SM2.0 bits written 011, SLEEP instruction makes enter Power-save mode. This mode identical Power-down, with exception: Timer/Counter0 clocked asynchronously, i.e., ASSR set, Timer/Counter0 will during sleep. device wake from either Timer Overflow tput Comp event from er/Coun ter0 corre Timer/Counter0 interrupt enable bits TIMSK, global interrupt enable SREG set. Asynchronous Timer clocked asynchronously, Power-down mode recommended instead Power-save mode because contents registers 2467L-AVR-05/04 asynchronous timer should considered undefined after wake-up Power-save mode This sleep mode basically halts clocks except clkASY, allowing operation only asynchronous modules, including Timer/Counter0 clocked asynchronously. Standby Mode When SM2.0 bits External Crystal/Resonator clock option selected, SLEEP instruction makes enter Standby mode. This mode identical Power-down with exception that Oscillator kept running. From Standby mode, device wakes clock cycles. When SM2.0 bits external crystal/resonator clock option selected, SLEEP instruction makes enter Extended Standby mode. This mode identical Power-save mode with exception that Oscillator kept running. From Extended Standby mode, device wakes clock cycles. Extended Standby Mode Table Active Clock Domains Wake Sources Different Sleep Modes Active Clock Domains Sleep Mode Idle Noise Reduction Powerdown Powersave Standby(1) Extended Standby(1) Notes: X(2) X(2) X(2) X(2) Oscillators Main Clock Source Enabled Timer Enabled X(2) X(2) Address Match Wake Sources SPM/ EEPROM Ready Other clkCPU clkFLASH clkIO clkADC clkASY INT7:0 X(3) Timer X(3) X(3) X(3) X(3) X(2) X(2) External Crystal resonator selected clock source ASSR Only INT3:0 level interrupt INT7:4 ATmega128 2467L-AVR-05/04 ATmega128 Minimizing Power Consumption There several issues consider when trying minimize power consumption controlled system. general, sleep modes should used much possible, sleep mode should selected that possible device's functions operating. functions needed should disabled. particular, following modules need special consideration when trying achieve lowest possible power consumption. enabled, will enabled sleep modes. save power, should disabled before entering sleep mode. When turned again, next conversion will extended conversion. Refer "Analog Digital Converter" page details operation. When entering Idle mode, Analog Comparator should disabled used. When entering Noise Reduction mode, Analog Comparator should disabled. other sleep modes, Analog Comparator automatically disabled. However, Analog Comparator Internal Voltage Reference input, Analog Comparator should disabled sleep modes. Otherwise, Internal Voltage Reference will enabled, independent sleep mode. Refer "Analog Comparator" page details configure Analog Comparator. Brown-out Detector needed application, this module should turned off. Brown-out Detector enabled BODEN fuse, will enabled sleep modes, hence, always consume power. deeper sleep modes, this will contribute significantly total current consumption. Refer "Brown-out Detector" page details configure Brown-out Detector. Internal Voltage Reference will enabled when needed Brown-out Detector, Analog Comparator ADC. these modules disabled described sections above, internal voltage reference will disabled will consuming power. When turned again, user must allow reference start before output used. reference kept sleep mode, output used immediately. Refer "Internal Voltage Reference" page details start-up time. Watchdog Timer needed application, this module should turned off. Watchdog Timer enabled, will enabled sleep modes, hence, always consume power. deeper sleep modes, this will contribute significantly total current consumption. Refer "Watchdog Timer" page details configure Watchdog Timer. When entering sleep mode, port pins should configured minimum power. most important thing then ensure that pins drive resistive loads. sleep modes where both clock (clkI/O) clock (clkADC) stopped, input buffers device will disabled. This ensures that power consumed input logic when needed. some cases, input logic needed detecting wake-up conditions, will then enabled. Refer section "Digital Input Enable Sleep Modes" page details which pins enabled. input buffer enabled input signal left floating have analog signal level close VCC/2, input buffer will excessive power. Analog Digital Converter Analog Comparator Brown-out Detector Internal Voltage Reference Watchdog Timer Port Pins 2467L-AVR-05/04 JTAG Interface On-chip Debug System On-chip debug system enabled OCDEN Fuse chip enter Power down Power save sleep mode, main clock source remains enabled. these sleep modes, this will contribute significantly total current consumption. There three alternative ways avoid this: Disable OCDEN Fuse. Disable JTAGEN Fuse. Write MCUCSR. left floating when JTAG interface enabled while JTAG controller shifting data. hardware connected does pull logic level, power consumption will increase. Note that next device scan chain contains pull-up that avoids this problem. Writing MCUCSR register leaving JTAG fuse unprogrammed disables JTAG interface. ATmega128 2467L-AVR-05/04 ATmega128 System Control Reset Resetting During Reset, registers their initial values, program starts execution from Reset Vector. instruction placed Reset Vector must absolute jump instruction reset handling routine. program never enables interrupt source, interrupt vectors used, regular program code placed these locations. This also case Reset Vector Application section while interrupt vectors Boot section vice versa. circuit diagram Figure shows reset logic. Table defines electrical parameters reset circuitry. ports immediately reset their initial state when reset source goes active. This does require clock source running. After reset sources have gone inactive, delay counter invoked, stretching internal reset. This allows power reach stable level before normal operation starts. time-out period delay counter defined user through CKSEL fuses. different selections delay period presented "Clock Sources" page Reset Sources ATmega128 five sources reset: Power-on Reset. reset when supply voltage below Power-on Reset threshold (VPOT). External Reset. reset when level present RESET longer than minimum pulse length. Watchdog Reset. reset when Watchdog Timer period expires Watchdog enabled. Brown-out Reset. reset when supply voltage below Brown-out Reset threshold (VBOT) Brown-out Detector enabled. JTAG Reset. reset long there logic Reset Register, scan chains JTAG system. Refer section "IEEE 1149.1 (JTAG) Boundary-scan" page details. 2467L-AVR-05/04 Figure Reset Logic DATA Control Status Register (MCUCSR) PORF BORF EXTRF WDRF JTRF Brown-Out Reset Circuit Reset Circuit Pull-up Resistor Power-On Reset Circuit BODEN BODLEVEL Pull-up Resistor RESET SPIKE FILTER JTAG Reset Register Watchdog Timer Watchdog Oscillator Clock Generator Delay Counters TIMEOUT CKSEL[3:0] SUT[1:0] Table Reset Characteristics Symbol Parameter Power-on Reset Threshold Voltage (rising) VPOT Power-on Reset Threshold Voltage (falling)(1) RESET Threshold Voltage Pulse width RESET Brown-out Reset Threshold Voltage(2) Minimum voltage period Brown-out Detection Brown-out Detector hysteresis BODLEVEL BODLEVEL BODLEVEL BODLEVEL Condition Units COUNTER RESET VRST tRST VBOT 0.85 tBOD VHYST Notes: Power-on Reset will work unless supply voltage been below VPOT (falling) ATmega128 2467L-AVR-05/04 ATmega128 VBOT below nominal minimum operating voltage some devices. devices where this case, device tested down VBOT during production test. This guarantees that Brown-out Reset will occur before drops voltage where correct operation microcontroller longer guaranteed. test performed using BODLEVEL=1 ATmega128L BODLEVEL=0 ATmega128. BODLEVEL=1 applicable ATmega128. Power-on Reset Power-on Reset (POR) pulse generated On-chip detection circuit. detection level defined Table activated whenever below detection level. circuit used trigger Start-up Reset, well detect failure supply voltage. Power-on Reset (POR) circuit ensures that device reset from Power-on. Reaching Power-on Reset threshold voltage invokes delay counter, which determines long device kept RESET after rise. RESET signal activated again, without delay, when decreases below detection level. Figure Start-up, RESET Tied VCC. VPOT RESET VRST TIME-OUT tTOUT INTERNAL RESET Figure Start-up, RESET Extended Externally VPOT RESET VRST TIME-OUT tTOUT INTERNAL RESET External Reset External Reset generated level RESET pin. Reset pulses longer than minimum pulse width (see Table will generate reset, even clock running. Shorter pulses guaranteed generate reset. When applied signal reaches Reset Threshold Voltage VRST positive edge, delay counter starts after Time-out period tTOUT expired. 2467L-AVR-05/04 Figure External Reset During Operation Brown-out Detection ATmega128 On-chip Brown-out Detection (BOD) circuit monitoring level during operation comparing fixed trigger level. trigger level selected fuse BODLEVEL 2.7V (BODLEVEL unprogrammed), 4.0V (BODLEVEL programmed). trigger level hysteresis ensure spike free Brown-out Detection. hysteresis detection level should interpreted VBOT+ VBOT VHYST/2 VBOT- VBOT VHYST/2. circuit enabled/disabled fuse BODEN. When enabled (BODEN programmed), decreases value below trigger level (VBOT- Figure 26), Brown-out Reset immediately activated. When increases above trigger level (VBOT+ Figure 26), delay counter starts after time-out period tTOUT expired. circuit will only detect drop voltage stays below trigger level longer than tBOD given Table Figure Brown-out Reset During Operation VBOTVBOT+ RESET TIME-OUT tTOUT INTERNAL RESET ATmega128 2467L-AVR-05/04 ATmega128 Watchdog Reset When Watchdog times out, will generate short reset pulse cycle duration. falling edge this pulse, delay timer starts counting Time-out period tTOUT. Refer page details operation Watchdog Timer. Figure Watchdog Reset During Operation Control Status Register MCUCSR Control Status Register provides information which reset source caused reset. Read/Write Initial Value JTRF WDRF BORF EXTRF PORF MCUCSR Description Note that only EXTRF PORF available ATmega103 compatibility mode. JTRF: JTAG Reset Flag This reset being caused logic JTAG Reset Register selected JTAG instruction AVR_RESET. This reset Power-on Reset, writing logic zero flag. WDRF: Watchdog Reset Flag This Watchdog Reset occurs. reset Power-on Reset, writing logic zero flag. BORF: Brown-out Reset Flag This Brown-out Reset occurs. reset Power-on Reset, writing logic zero flag. EXTRF: External Reset Flag This External Reset occurs. reset Power-on Reset, writing logic zero flag. PORF: Power-On Reset Flag This Power-on Reset occurs. reset only writing logic zero flag. make reset flags identify reset condition, user should read then reset MCUCSR early possible program. register cleared before another reset occurs, source reset found examining reset flags. 2467L-AVR-05/04 Internal Voltage Reference Voltage Reference Enable Signals Start-up Time ATmega128 features internal bandgap reference. This reference used Brownout Detection, used input Analog Comparator ADC. 2.56V reference generated from internal bandgap reference. voltage reference start-up time that influence should used. start-up time given Table save power, reference always turned reference during following situations: When enabled programming BODEN fuse). When bandgap reference connected Analog Comparator setting ACBG ACSR). When enabled. Thus, when enabled, after setting ACBG enabling ADC, user must always allow reference start before output from Analog Comparator used. reduce power consumption Power-down mode, user avoid three conditions above ensure that reference turned before entering Power-down mode. Table Internal Voltage Reference Characteristics Symbol Parameter Bandgap reference voltage Bandgap reference start-up time Bandgap reference current consumption 1.15 1.23 1.40 Units Watchdog Timer Watchdog Timer clocked from separate On-chip Oscillator which runs Mhz. This typical value characterization data typical values other levels. controlling Watchdog Timer prescaler, Watchdog Reset interval adjusted shown Table page Watchdog Reset instruction resets Watchdog Timer. Watchdog Timer also reset when disabled when Chip Reset occurs. Eight different clock cycle periods selected determine reset period. reset period expires without another Watchdog Reset, ATmega128 resets executes from Reset Vector. timing details Watchdog Reset, refer page prevent unintentional disabling Watchdog unintentional change time-out period, different safety levels selected Fuses M103C WDTON shown Table Safety level corresponds setting ATmega103. There restriction enabling safety levels. Refer "Timed Sequences Changing Configuration Watchdog Timer" page details. ATmega128 2467L-AVR-05/04 ATmega128 Table Configuration Function Fuse Settings M103C WDTON. Safety Level Initial State Disabled Enabled Disabled Enabled Disable Timed sequence Always enabled Timed sequence Always enabled Change Time-out Timed sequence Timed sequence restriction Timed sequence M103C Unprogrammed Unprogrammed Programmed Programmed WDTON Unprogrammed Programmed Unprogrammed Programmed Figure Watchdog Timer WATCHDOG OSCILLATOR Watchdog Timer Control Register WDTCR WDCE WDP2 WDP1 WDP0 WDTCR Read/Write Initial Value Bits Res: Reserved Bits These bits reserved bits ATmega128 will always read zero. WDCE: Watchdog Change Enable This must when written logic zero. Otherwise, Watchdog will disabled. Once written one, hardware will clear this after four clock cycles. Refer description Watchdog disable procedure. Safety Level this must also when changing prescaler bits. "Timed Sequences Changing Configuration Watchdog Timer" page WDE: Watchdog Enable When written logic one, Watchdog Timer enabled, written logic zero, Watchdog Timer function disabled. only cleared WDCE logic level one. disable enabled Watchdog Timer, following procedure must followed: 2467L-AVR-05/04 same operation, write logic WDCE WDE. logic must written even though before disable operation starts. Within next four clock cycles, write logic WDE. This disables Watchdog. safety level possible disable Watchdog Timer, even with algorithm described above. "Timed Sequences Changing Configuration Watchdog Timer" page Bits WDP2, WDP1, WDP0: Watchdog Timer Prescaler WDP2, WDP1, WDP0 bits determine Watchdog Timer prescaling when Watchdog Timer enabled. different prescaling values their corresponding Timeout Periods shown Table Table Watchdog Timer Prescale Select WDP2 WDP1 WDP0 Number Oscillator Cycles (16,384) (32,768) (65,536) 128K (131,072) 256K (262,144) 512K (524,288) 1,024K (1,048,576) 2,048K (2,097,152) Typical Time-out 3.0V 14.8 29.6 59.1 0.12 0.24 0.47 0.95 Typical Time-out 5.0V 14.0 28.1 56.2 0.11 0.22 0.45 ATmega128 2467L-AVR-05/04 ATmega128 following code example shows assembly function turning WDT. example assumes that interrupts controlled (e.g. disabling interrupts globally) that interrupts will occur during execution these functions. Assembly Code Example WDT_off: Reset r16, WDTCR Write logical WDCE r16, (1<<WDCE)|(1<<WDE) WDTCR, Turn r16, (0<<WDE) WDTCR, Code Example void WDT_off(void) Reset WDT*/ _watchdog_reset(); Write logical WDCE WDTCR (1<<WDCE) (1<<WDE); Turn WDTCR 0x00; Timed Sequences Changing Configuration Watchdog Timer sequence changing configuration differs slightly between three safety levels. Separate procedures described each level. Safety Level This mode compatible with Watchdog operation found ATmega103. Watchdog Timer initially disabled, enabled writing without restriction. time-out period changed time without restriction. disable enabled Watchdog Timer, procedure described page (WDE description) must followed. this mode, Watchdog Timer initially disabled, enabled writing without restriction. timed sequence needed when changing Watchdog Time-out period disabling enabled Watchdog Timer. disable enabled Watchdog Timer, and/or changing Watchdog Time-out, following procedure must followed: same operation, write logic WDCE WDE. logic must written regardless previous value bit. Within next four clock cycles, same operation, write bits desired, with WDCE cleared. Safety Level 2467L-AVR-05/04 Safety Level this mode, Watchdog Timer always enabled, will always read one. timed sequence needed when changing Watchdog Time-out period. change Watchdog Time-out, following procedure must followed: same operation, write logical WDCE WDE. Even though always set, must written start timed sequence. Within next four clock cycles, same operation, write bits desired, with WDCE cleared. value written irrelevant. ATmega128 2467L-AVR-05/04 ATmega128 Interrupts This section describes specifics interrupt handling performed ATmega128. general explanation interrupt handling, refer "Reset Interrupt Handling" page Interrupt Vectors ATmega128 Table Reset Interrupt Vectors Vector Program Address(2) $0000(1) $0002 $0004 $0006 $0008 $000A $000C $000E $0010 $0012 $0014 $0016 $0018 $001A $001C $001E $0020 $0022 $0024 $0026 $0028 $002A $002C $002E $0030(3) $0032 $0034 $0036 Source RESET INT0 INT1 INT2 INT3 INT4 INT5 INT6 INT7 TIMER2 COMP TIMER2 TIMER1 CAPT TIMER1 COMPA TIMER1 COMPB TIMER1 TIMER0 COMP TIMER0 SPI, USART0, USART0, UDRE USART0, READY ANALOG COMP TIMER1 COMPC TIMER3 CAPT TIMER3 COMPA TIMER3 COMPB TIMER3 COMPC TIMER3 Interrupt Definition External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, JTAG Reset External Interrupt Request External Interrupt Request External Interrupt Request External Interrupt Request External Interrupt Request External Interrupt Request External Interrupt Request External Interrupt Request Timer/Counter2 Compare Match Timer/Counter2 Overflow Timer/Counter1 Capture Event Timer/Counter1 Compare Match Timer/Counter1 Compare Match Timer/Counter1 Overflow Timer/Counter0 Compare Match Timer/Counter0 Overflow Serial Transfer Complete USART0, Complete USART0 Data Register Empty USART0, Complete Conversion Complete EEPROM Ready Analog Comparator Timer/Countre1 Compare Match Timer/Counter3 Capture Event Timer/Counter3 Compare Match Timer/Counter3 Compare Match Timer/Counter3 Compare Match Timer/Counter3 Overflow $0038(3) $003A 2467L-AVR-05/04 Table Reset Interrupt Vectors (Continued) Vector Notes: Program Address(2) $003C(3) $003E(3) $0040 $0042 Source USART1, USART1, UDRE USART1, READY Interrupt Definition USART1, Complete USART1 Data Register Empty USART1, Complete Two-wire Serial Interface Store Program Memory Ready $0044(3) When BOOTRST fuse programmed, device will jump Boot Loader address reset, "Boot Loader Support Read-While-Write Self-Programming" page 275. When IVSEL MCUCR set, interrupt vectors will moved start Boot Flash section. address each interrupt vector will then address this table added start address boot Flash section. Interrupts address $0030 $0044 exist ATmega103 compatibility mode. Table shows Reset interrupt vectors placement various combinations BOOTRST IVSEL settings. program never enables interrupt source, interrupt vectors used, regular program code placed these locations. This also case Reset Vector Application section while interrupt vectors Boot section vice versa. Table Reset Interrupt Vectors Placement BOOTRST Note: IVSEL Reset Address $0000 $0000 Boot Reset Address Boot Reset Address Interrupt Vectors Start Address $0002 Boot Reset Address $0002 $0002 Boot Reset Address $0002 Boot Reset Address shown Table page 286. BOOTRST fuse means unprogrammed while means programmed. ATmega128 2467L-AVR-05/04 ATmega128 most typical general program setup Reset Interrupt Vector Addresses ATmega128 Address LabelsCode $0000 $0002 $0004 $0006 $0008 $000A $000C $000E $0010 $0012 $0014 $0016 $0018 $001A $001C $001E $0020 $0022 $0024 $0026 $0028 $002A $002C $002E $0030 $0032 $0034 $0036 $0038 $003A $003C $003E $0040 $0042 Handler $0044 $0046 $0047 $0048 $0049 $004A $004B RESET:ldir16, high(RAMEND); Main program start SPH,r16 SPL,r16 Enable interrupts stack pointer r16, low(RAMEND) RESET EXT_INT0 EXT_INT1 EXT_INT2 EXT_INT3 EXT_INT4 EXT_INT5 EXT_INT6 EXT_INT7 TIM2_OVF Comments Reset Handler IRQ0 Handler IRQ1 Handler IRQ2 Handler IRQ3 Handler IRQ4 Handler IRQ5 Handler IRQ6 Handler IRQ7 Handler Timer2 Overflow Handler TIM2_COMP Timer2 Compare Handler TIM1_CAPT Timer1 Capture Handler TIM1_COMPA; Timer1 CompareA Handler TIM1_COMPB; Timer1 CompareB Handler TIM1_OVF TIM0_OVF SPI_STC Timer1 Overflow Handler Timer0 Overflow Handler Transfer Complete Handler TIM0_COMP Timer0 Compare Handler USART0_RXC; USART0 Complete Handler USART0_DRE; USART0,UDR Empty Handler USART0_TXC; USART0 Complete Handler EE_RDY ANA_COMP Conversion Complete Handler EEPROM Ready Handler Analog Comparator Handler TIM1_COMPC; Timer1 CompareC Handler TIM3_CAPT Timer3 Capture Handler TIM3_COMPA; Timer3 CompareA Handler TIM3_COMPB; Timer3 CompareB Handler TIM3_COMPC; Timer3 CompareC Handler TIM3_OVF Timer3 Overflow Handler USART1_RXC; USART1 Complete Handler USART1_DRE; USART1,UDR Empty Handler USART1_TXC; USART1 Complete Handler SPM_RDY Two-wire Serial Interface Interrupt Ready Handler <instr> 2467L-AVR-05/04 When BOOTRST fuse unprogrammed, Boot section size bytes IVSEL MCUCR Register before interrupts enabled, most typical general program setup Reset Interrupt Vector Addresses Address LabelsCode $0000 $0001 $0002 $0003 $0004 $0005 .org $F002 $F002 $F004 $F044 EXT_INT0 EXT_INT1 SPM_RDY IRQ0 Handler IRQ1 Handler Store Program Memory Ready Handler RESET:ldi SPH,r16 SPL,r16 Enable interrupts Comments r16,high(RAMEND); Main program start stack pointer r16,low(RAMEND) <instr> When BOOTRST fuse programmed Boot section size bytes, most typical general program setup Reset Interrupt Vector Addresses Address .org $0002 $0002 $0004 $0044 .org $F000 $F000 RESET: $F001 $F002 $F003 $F004 $F005 r16,high(RAMEND); Main program start SPH,r16 SPL,r16 Enable interrupts stack pointer r16,low(RAMEND) EXT_INT0 EXT_INT1 SPM_RDY IRQ0 Handler IRQ1 Handler Store Program Memory Ready Handler LabelsCode Comments <instr> When BOOTRST fuse programmed, Boot section size bytes IVSEL MCUCR Register before interrupts enabled, most typical general program setup Reset Interrupt Vector Addresses Address .org $F000 $F000 $F002 $F004 $F044 $F046 $F047 $F048 RESET: RESET EXT_INT0 EXT_INT1 Reset handler IRQ0 Handler IRQ1 Handler Labels Code Comments SPM_RDY Store Program Memory Ready Handler r16,high(RAMEND); Main program start SPH,r16 stack pointer r16,low(RAMEND) ATmega128 2467L-AVR-05/04 ATmega128 $F049 $F04A $F04B SPL,r16 Enable interrupts <instr> Moving Interrupts Between Application Boot Space Control Register MCUCR General Interrupt Control Register controls placement interrupt vector table. SRW10 IVSEL IVCE MCUCR Read/Write Initial Value IVSEL: Interrupt Vector Select When IVSEL cleared (zero), interrupt vectors placed start Flash memory. When this (one), interrupt vectors moved beginning Boot Loader section flash. actual address start Boot Flash section determined BOOTSZ fuses. Refer section "Boot Loader Support Read-While-Write Self-Programming" page details. avoid unintentional changes interrupt vector tables, special write procedure must followed change IVSEL bit: Write Interrupt Vector Change Enable (IVCE) one. Within four cycles, write desired value IVSEL while writing zero IVCE. Interrupts will automatically disabled while this sequence executed. Interrupts disabled cycle IVCE set, they remain disabled until after instruction following write IVSEL. IVSEL written, interrupts remain disabled four cycles. I-bit Status Register unaffected automatic disabling. Note: interrupt vectors placed Boot Loader section Boot Lock BLB02 programmed, interrupts disabled while executing from Application section. interrupt vectors placed Application section Boot Lock BLB12 programed, interrupts disabled while executing from Boot Loader section. Refer section "Boot Loader Support Read-While-Write Self-Programming" page details Boot Lock bits. 2467L-AVR-05/04 IVCE: Interrupt Vector Change Enable IVCE must written logic enable change IVSEL bit. IVCE cleared hardware four cycles after written when IVSEL written. Setting IVCE will disable interrupts, explained IVSEL description above. Code Example below. Assembly Code Example Move_interrupts: Enable change interrupt vectors r16, (1<<IVCE) MCUCR, Move interrupts boot flash section r16, (1<<IVSEL) MCUCR, Code Example void Move_interrupts(void) Enable change interrupt vectors MCUCR (1<<IVCE); Move interrupts boot flash section MCUCR (1<<IVSEL); ATmega128 2467L-AVR-05/04 ATmega128 Ports Introduction ports have true Read-Modify-Write functionality when used general digital ports. This means that direction port changed without unintentionally changing direction other with instructions. same applies when changing drive value configured output) enabling/disabling pull-up resistors configured input). Each output buffer symmetrical drive characteristics with both high sink source capability. driver strong enough drive displays directly. port pins have individually selectable pull-up resistors with supply-voltage invariant resistance. pins have protection diodes both Ground indicated Figure Refer "Electrical Characteristics" page complete list parameters. Figure Equivalent Schematic Logic CPIN Figure "General Digital I/O" Details registers references this section written general form. lower case represents numbering letter port, lower case represents number. However, when using register defines program, precise form must used. example, PORTB3 Port here documented generally PORTxn. physical registers locations listed "Register Description Ports" page Three memory address locations allocated each port, each Data Register PORTx, Data Direction Register DDRx, Port Input Pins PINx. Port Input Pins location read only, while Data Register Data Direction Register read/write. addition, Pull-up Disable SFIOR disables pull-up function pins ports when set. Using port General Digital described "Ports General Digital I/O" page Most port pins multiplexed with alternate functions peripheral features device. each alternate function interferes with port described "Alternate Port Functions" page Refer individual module sections full description alternate functions. Note that enabling alternate function some port pins does affect other pins port General Digital I/O. 2467L-AVR-05/04 Ports General Digital ports bi-directional ports with optional internal pull-ups. Figure shows functional description port pin, here generically called Pxn. Figure General Digital I/O(1) DDxn RESET PORTxn RESET SLEEP SYNCHRONIZER PINxn PUD: SLEEP: clkI/O: PULLUP DISABLE SLEEP CONTROL CLOCK WDx: RDx: WPx: RRx: RPx: WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx Note: WPx, WDx, RRx, RPx, common pins within same port. clkI/O, SLEEP, common ports. Configuring Each port consists three Register bits: DDxn, PORTxn, PINxn. shown "Register Description Ports" page DDxn bits accessed DDRx address, PORTxn bits PORTx address, PINxn bits PINx address. DDxn DDRx Register selects direction this pin. DDxn written logic one, configured output pin. DDxn written logic zero, configured input pin. PORTxn written logic when configured input pin, pull-up resistor activated. switch pull-up resistor off, PORTxn written logic zero configured output pin. port pins tri-stated when Reset condition becomes active, even clocks running. PORTxn written logic when configured output pin, port driven high (one). PORTxn written logic zero when configured output pin, port driven (zero). ATmega128 2467L-AVR-05/04 DATA ATmega128 When switching between tri-state ({DDxn, PORTxn} 0b00) output high ({DDxn, PORTxn} 0b11), intermediate state with either pull-up enabled ({DDxn, PORTxn} 0b01) output ({DDxn, PORTxn} 0b10) must occur. Normally, pull-up enabled state fully acceptable, high-impedant environment will notice difference between strong high driver pull-up. this case, SFIOR Register written disable pull-ups ports. Switching between input with pull-up output generates same problem. user must either tri-state ({DDxn, PORTxn} 0b00) output high state ({DDxn, PORTxn} 0b11) intermediate step. Table summarizes control signals value. Table Port Configurations DDxn PORTxn SFIOR) Input Input Input Output Output Pull-up Comment Tri-state (Hi-Z) will source current ext. pulled low. Tri-state (Hi-Z) Output (Sink) Output High (Source) Reading Value Independent setting Data Direction DDxn, port read through PINxn Register bit. shown Figure PINxn Register preceding latch constitute synchronizer. This needed avoid metastability physical changes value near edge internal clock, also introduces delay. Figure shows timing diagram synchronization when reading externally applied value. maximum minimum propagation delays denoted tpd,max tpd,min respectively. Figure Synchronization when Reading Externally Applied Value SYSTEM INSTRUCTIONS SYNC LATCH PINxn 0x00 tpd, tpd, 0xFF r17, PINx 2467L-AVR-05/04 Consider clock period starting shortly after first falling edge system clock. latch closed when clock low, goes transparent when clock high, indicated shaded region "SYNC LATCH" signal. signal value latched when system clock goes low. clocked into PINxn Register succeeding positive clock edge. indicated arrows tpd,max tpd,min, single signal transition will delayed between system clock period depending upon time assertion. When reading back software assigned value, instruction must inserted indicated Figure instruction sets "SYNC LATCH" signal positive edge clock. this case, delay through synchronizer system clock period. Figure Synchronization when Reading Software Assigned Value SYSTEM INSTRUCTIONS SYNC LATCH PINxn 0x00 0xFF PORTx, 0xFF r17, PINx ATmega128 2467L-AVR-05/04 ATmega128 following code example shows port pins high, low, define port pins from input with pull-ups assigned port pins resulting values read back again, previously discussed, instruction included able read back value recently assigned some pins. Assembly Code Example(1) Define pull-ups outputs high Define directions port pins Read port pins r16,PINB PORTB,r16 DDRB,r17 Insert synchronization Code Example(1) unsigned char Define pull-ups outputs high Define directions port pins PORTB DDRB Insert synchronization*/ _no_operation(); Read port pins PINB; Note: assembly program, temporary registers used minimize time from pull-ups pins until direction bits correctly set, defining redefining bits strong high drivers. Digital Input Enable Sleep Modes shown Figure digital input signal clamped ground input schmitt-trigger. signal denoted SLEEP figure, Sleep Controller Power-down mode, Power-save mode, Standby mode, Extended Standby mode avoid high power consumption some input signals left floating, have analog signal level close VCC/2. SLEEP overridden port pins enabled External Interrupt pins. External Interrupt Request enabled, SLEEP active also these pins. SLEEP also overridden various other alternate functions described "Alternate Port Functions" page logic high level ("one") present Asynchronous External Interrupt configured "Interrupt Rising Edge, Falling Edge, Logic Change Pin" while external interrupt enabled, corresponding External Interrupt Flag will when resuming from above mentioned sleep modes, clamping these sleep modes produces requested logic change. 2467L-AVR-05/04 Unconnected pins some pins unused, recommended ensure that these pins have defined level. Even though most digital inputs disabled deep sleep modes described above, floating inputs should avoided reduce current consumption other modes where digital inputs enabled (Reset, Active mode Idle mode). simplest method ensure defined level unused pin, enable internal pull-up. this case, pull-up will disabled during reset. power consumption during reset important, recommended external pull-up pull-down. Connecting unused pins directly recommended, since this cause excessive currents accidentally configured output. Alternate Port Functions Most port pins have alternate functions addition being general digital I/Os. Figure shows port control signals from simplified Figure overridden alternate functions. overriding signals present port pins, figure serves generic description applicable port pins microcontroller family. Figure Alternate Port Functions(1) PUOExn PUOVxn DDOExn DDOVxn DDxn PVOExn PVOVxn RESET PORTxn DIEOExn DIEOVxn RESET SLEEP SYNCHRONIZER PINxn DIxn AIOxn PUOExn: PUOVxn: DDOExn: DDOVxn: PVOExn: PVOVxn: DIEOExn: DIEOVxn: SLEEP: PULL-UP OVERRIDE ENABLE PULL-UP OVERRIDE VALUE DATA DIRECTION OVERRIDE ENABLE DATA DIRECTION OVERRIDE VALUE PORT VALUE OVERRIDE ENABLE PORT VALUE OVERRIDE VALUE DIGITAL INPUT-ENABLE OVERRIDE ENABLE DIGITAL INPUT-ENABLE OVERRIDE VALUE SLEEP CONTROL PUD: WDx: RDx: RRx: WPx: RPx: clkI/O: DIxn: AIOxn: PULLUP DISABLE WRITE DDRx READ DDRx READ PORTx REGISTER WRITE PORTx READ PORTx CLOCK DIGITAL INPUT PORTx ANALOG INPUT/OUTPUT PORTx Note: WPx, WDx, RLx, RPx, common pins within same port. clkI/O, SLEEP, common ports. other signals unique each pin. ATmega128 2467L-AVR-05/04 DATA ATmega128 Table summarizes function overriding signals. port indexes from Figure shown succeeding tables. overriding signals generated internally modules having alternate function. Table Generic Description Overriding Signals Alternate Functions. Signal Name PUOE Full Name Pull-up Override Enable Pull-up Override Value Data Direction Override Enable Data Direction Override Value Port Value Override Enable Description this signal set, pull-up enable controlled PUOV signal. this signal cleared, pull-up enabled when {DDxn, PORTxn, PUD} 0b010. PUOE set, pull-up enabled/disabled when PUOV set/cleared, regardless setting DDxn, PORTxn, Register bits. this signal set, Output Driver Enable controlled DDOV signal. this signal cleared, Output driver enabled DDxn Register bit. DDOE set, Output Driver enabled/disabled when DDOV set/cleared, regardless setting DDxn Register bit. this signal Output Driver enabled, port value controlled PVOV signal. PVOE cleared, Output Driver enabled, port Value controlled PORTxn Register bit. PVOE set, port value PVOV, regardless setting PORTxn Register bit. this set, Digital Input Enable controlled DIEOV signal. this signal cleared, Digital Input Enable determined MCU-state (Normal mode, Sleep modes). DIEOE set, Digital Input enabled/disabled when DIEOV set/cleared, regardless state (Normal mode, Sleep modes). This Digital Input alternate functions. figure, signal connected output schmitt trigger before synchronizer. Unless Digital Input used clock source, module with alternate function will synchronizer. This Analog Input/output to/from alternate functions. signal connected directly pad, used bi-directionally. PUOV DDOE DDOV<b Other recent searchesTSS721A - TSS721A TSS721A Datasheet TMS320VC5441 - TMS320VC5441 TMS320VC5441 Datasheet TC74VCX16721FT - TC74VCX16721FT TC74VCX16721FT Datasheet NCV33272A - NCV33272A NCV33272A Datasheet NCV33274A - NCV33274A NCV33274A Datasheet MCH6415 - MCH6415 MCH6415 Datasheet LTC3538 - LTC3538 LTC3538 Datasheet IDT74FCTL2257T - IDT74FCTL2257T IDT74FCTL2257T Datasheet CMXT7090L - CMXT7090L CMXT7090L Datasheet BYG21 - BYG21 BYG21 Datasheet AT49F512 - AT49F512 AT49F512 Datasheet
Privacy Policy | Disclaimer |