![]() |
|
If you can't view the Datasheet, Please click here to try to view without PDF Reader . |
|
Datasheet File OCR Text: |
features ? high-performance, low-power atmel ? avr ? 8-bit microcontroller ? advanced risc architecture ? 133 powerful instructions ? most single clock cycle execution ? 32 8 general purpose working regist ers + peripheral control registers ? fully static operation ? up to 16mhz throughput at 16mips ? on-chip 2-cycle multiplier ? high endurance non-volatile memory segments ? 128kbytes of in-system self-programmable flash program memory ? 4kbytes eeprom ? 4kbytes internal sram ? write/erase cycles: 10,000 flash/100,000 eeprom ? data retention: 20 years at 85 c/100 years at 25 c (1) ? optional boot code section with independent lock bits in-system programming by on-chip boot program true read-while-w rite operation ? up to 64 kbytes optional external memory space ? programming lock for software security ? spi interface for in -system programming ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan capabilities a ccording to the jtag standard ? extensive on-chip debug support ? programming of flash, eeprom, fuses and lock bits through the jtag interface ? peripheral features ? two 8-bit timer/counters with se parate prescalers and compare modes ? two expanded 16-bit timer/counters wi th separate prescaler, compare mode and capture mode ? real time counter with separate oscillator ? two 8-bit pwm channels ? 6 pwm channels with programmabl e resolution from 2 to 16 bits ? output compare modulator ? 8-channel, 10-bit adc 8 single-ended channels 7 differential channels 2 differential channels with prog rammable gain at 1x, 10x, or 200x ? byte-oriented two-wi re serial interface ? dual programmable serial usarts ? master/slave spi serial interface ? programmable watchdog timer with on-chip oscillator ? on-chip analog comparator ? special microcontroller features ? power-on reset and programmable brown-out detection ? internal calibrated rc oscillator ? external and internal interrupt sources ? six sleep modes: idle, adc noise reduction, power-save, power-down, standby, and extended standby ? software selectable clock frequency ? atmega103 compatibility mode selected by a fuse ? global pull-up disable ? i/o and packages ? 53 programmable i/o lines ? 64-lead tqfp and 64-pad qfn/mlf ? operating voltages ? 2.7v - 5.5v ? speed grades ?0 - 16mhz 8-bit microcontroller with 128kbytes in-system programmable flash atmega128a rev. 8151h?avr?02/11
2 8151h?avr?02/11 atmega128a 1. pin configurations figure 1-1. pinout atmega128a note: the pinout figure applies to both tqfp an d mlf packages. the bottom pad under the qfn/mlf package should be soldered to ground. 2. overview the atmel ? avr ? atmega128a is a low-power cmos 8-bit microcontroller based on the avr enhanced risc architecture. by executing powerful instructions in a single clock cycle, the atmega128a achieves throughputs approaching 1mips per mhz allowing the system designer to optimize power consumption versus processing speed. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 pen rxd0/(pdi) pe0 (txd0/pdo) pe1 (xck0/ain0) pe2 (oc3a/ain1) pe3 (oc3b/int4) pe4 (oc3c/int5) pe5 (t3/int6) pe6 (icp3/int7) pe7 (ss) pb0 (sck) pb1 (mosi) pb2 (miso) pb3 (oc0) pb4 (oc1a) pb5 (oc1b) pb6 pa3 (ad3) pa4 (ad4) pa5 (ad5) pa6 (ad6) pa7 (ad7) pg2(ale) pc7 (a15) pc6 (a14) pc5 (a13) pc4 (a12) pc3 (a11) pc2 (a10) pc1 (a9) pc0 (a8) pg1(rd) pg0(wr) 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 (oc2/oc1c) pb7 tosc2/pg3 tosc1/pg4 reset vcc gnd xtal2 xtal1 (scl/int0) pd0 (sda/int1) pd1 (rxd1/int2) pd2 (txd1/int3) pd3 (icp1) pd4 (xck1) pd5 (t1) pd6 (t2) pd7 avcc gnd aref pf0 (adc0) pf1 (adc1) pf2 (adc2) pf3 (adc3) pf4 (adc4/tck) pf5 (adc5/tms) pf6 (adc6/tdo) pf7 (adc7/tdi) gnd vcc pa0 (ad0) pa1 (ad1) pa2 (ad2) 3 8151h?avr?02/11 atmega128a 2.1 block diagram figure 2-1. block diagram program counter internal oscillator watchdog timer stack pointer program flash mcu control register sram general purpose registers instruction register timer/ counters instruction decoder data dir. reg. portb data dir. reg. porte data dir. reg. porta data dir. reg. portd data register portb data register porte data register porta data register portd timing and control oscillator oscillator interrupt unit eeprom spi usart0 status register z y x alu portb drivers porte drivers porta drivers portf drivers portd drivers portc drivers pb0 - pb7 pe0 - pe7 pa0 - pa7 pf0 - pf7 reset vcc agnd gnd aref xtal1 xtal2 control lines + - analog comparator pc0 - pc7 8-bit data bus avcc usart1 calib. osc data dir. reg. portc data register portc on-chip debug jtag tap programming logic pen boundary- scan data dir. reg. portf data register portf adc pd0 - pd7 data dir. reg. portg data reg. portg portg drivers pg0 - pg4 two-wire serial interface 4 8151h?avr?02/11 atmega128a the atmel ? avr ? core combines a rich instruction set with 32 general purpose working registers. all the 32 registers are directly connected to the arithmetic logic unit (alu), allowing two inde- pendent registers to be accessed in one single in struction executed in one clock cycle. the resulting architecture is more code efficient wh ile achieving throughputs up to ten times faster than conventional cisc microcontrollers. the atmega128a provides the following features: 128 kbytes of in-system programmable flash with read-while-write capabilities, 4 kb ytes eeprom, 4 kbytes sram, 53 general pur- pose i/o lines, 32 general purpose working registers, real time counter (rtc), four flexible timer/counters with compare modes and pwm, 2 usarts, a byte oriented two-wire serial interface, an 8-channel, 10-bit adc with optional differential input stage with programmable gain, programmable watchdog timer with internal oscillator, an spi serial port, ieee std. 1149.1 compliant jtag test interface, also used for accessing the on-chip debug system and programming and six software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counters, spi por t, and interrupt system to continue function- ing. the power-down mode saves the register contents but freezes the oscillator, disabling all other chip functions until the next interrupt or hardware reset. in power-save mode, the asyn- chronous timer continues to run, allowing the user to maintain a timer base while the rest of the device is sleeping. the adc noise reduction mode stops the cpu and all i/o modules except asynchronous timer and adc, to minimize switch ing noise during adc conversions. in standby mode, the crystal/resonator oscillator is runn ing while the rest of the device is sleeping. this allows very fast start-up combined with low power consumption. in extended standby mode, both the main oscillato r and the asynch ronous timer continue to run. the device is manufactured using atmel?s high- density nonvolatile memory technology. the on- chip isp flash allows the prog ram memory to be repr ogrammed in-system th rough an spi serial interface, by a conventional nonvolatile memory programmer, or by an on-chip boot program running on the avr core. the boot program can use any interface to download the application program in the applicatio n flash memory. software in the boot flash section will continue to run while the application flash section is updated, providing true read-while-write operation. by combining an 8-bit risc cpu with in-system self-programmable flash on a monolithic chip, the atmel atmega128a is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. the atmega128a avr is supported with a full suite of program and system development tools including: c compilers, macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits. 2.2 atmega103 and atmega128a compatibility the atmega128a is a highly complex microcontroller where the number of i/o locations super- sedes the 64 i/o locations reserved in the avr instruction set. to ensure backw ard compatibility with the atmega103, all i/o locations present in atmega103 have the same location in atmega128a. most additional i/o locations are added in an extended i/o space starting from $60 to $ff, (that is, in the atmega103 internal ram space). these locations can be reached by using ld/lds/ldd and st/sts/std instructions only, not by using in and out instructions. the relocation of the internal ram space may still be a prob lem for atmega103 users. also, the increased number of interrupt vectors might be a problem if the code uses absolute addresses. to solve these problems, an atmega103 compatibility mode can be selected by programming the fuse m103c. in this mode, none of the functions in the extended i/o space are in use, so the internal ram is located as in atmega103. also, the extended interrupt vectors are removed. 5 8151h?avr?02/11 atmega128a the atmel ? avr ? atmega128a is 100% pin compatible with atmega103, and can replace the atmega103 on current printed circuit boards. the application note ?replacing atmega103 by atmega128a? describes what the user should be aware of replacing the atmega103 by an atmega128a. 2.2.1 atmega103 compatibility mode by programming the m103c fuse, the atmega128a will be compatible with the atmega103 regards to ram, i/o pins and interrupt vectors as described above. however, some new fea- tures in atmega128a are not available in this compatibility mode, these features are listed below: ? one usart instead of two, asynchronous mode only. only the eight least significant bits of the baud rate register is available. ? one 16 bits timer/counter with two compare registers instead of two 16-bit timer/counters with three compare registers. ? two-wire serial interface is not supported. ? port c is output only. ? port g serves alternate functions only (not a general i/o port). ? port f serves as digital input only in addition to analog input to the adc. ? boot loader capabilit ies is not supported. ? it is not possible to adjust the frequency of the internal calibrated rc oscillator. ? the external memory interface can not release any address pins for general i/o, neither configure different wait-states to different external memory address sections. ? in addition, there are some other minor differences to make it more compatible to atmega103: ? only extrf and porf exists in mcucsr. ? timed sequence not required for watchdog time-out change. ? external interrupt pins 3 - 0 serve as level interrupt only. ? usart has no fifo buffer, so data overrun comes earlier. unused i/o bits in atmega103 should be wri tten to 0 to ensure same operation in atmega128a. 2.3 pin descriptions 2.3.1 vcc digital supply voltage. 2.3.2 gnd ground. 2.3.3 port a (pa7:pa0) port a is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port a output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port a pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port a pins are tri-stated when a reset condition becomes active, even if the clock is not running. 6 8151h?avr?02/11 atmega128a port a also serves the functions of various special features of the atmega128a as listed on page 73 . 2.3.4 port b (pb7:pb0) port b is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port b output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port b pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b also serves the functions of various special features of the atmega128a as listed on page 74 . 2.3.5 port c (pc7:pc0) port c is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port c output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port c pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. the port c pins are tri-stated when a reset condition becomes active, even if the clock is not running. port c also serves the functions of special features of the atmega128a as listed on page 76 . in atmega103 compatibility mode , port c is output only, and the port c pins are not tri-stated when a reset condition becomes active. note: the atmel ? avr ? atmega128a is by default shipped in atmega103 compatibility mode. thus, if the parts are not programmed before they are put on the pcb, portc will be output during first power up, and until the atmega103 compatibility mode is disabled. 2.3.6 port d (pd7:pd0) port d is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port d output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port d pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d also serves the functions of various special features of the atmega128a as listed on page 78 . 2.3.7 port e (pe7:pe0) port e is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port e output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port e pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port e pins are tri-stated when a reset condition becomes active, even if the clock is not running. port e also serves the functions of various special features of the atmega128a as listed on page 81 . 2.3.8 port f (pf7:pf0) port f serves as the analog inputs to the a/d converter. port f also serves as an 8-bit bi-directional i/o port, if the a/d converter is not used. port pins can provide internal pull-up resistors (selected for each bit). the port f output buffers have sym- 7 8151h?avr?02/11 atmega128a metrical drive characteristics with both high sink and source capa bility. as inputs, port f pins that are externally pulled low will source current if the pull-up resistors are ac tivated. the port f pins are tri-stated when a reset condition becomes active, even if the clock is not running. if the jtag interface is enabled, the pull-up resistors on pins pf7( tdi), pf5(tms), and pf4(tck) will be activated even if a reset occurs. the tdo pin is tri-stated unless tap states that shift out data are entered. port f also serves the functions of the jtag interface. in atmega103 compatibilit y mode, port f is an input port only. 2.3.9 port g (pg4:pg0) port g is a 5-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port g output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port g pins that are extern ally pulled low will sour ce current if the pull-up resistors are activated. the port g pins are tri-stated when a reset condition becomes active, even if the clock is not running. port g also serves the functions of various special features. the port g pins are tri-stated when a reset condi tion becomes active, even if the clock is not running. in atmel ? avr ? atmega103 compatibility mode, these pins on ly serves as strobes signals to the external memory as well as input to the 32khz oscillator, and the pins are initialized to pg0 = 1, pg1 = 1, and pg2 = 0 asynchronously when a reset condition becomes active, even if the clock is not running. pg3 and pg4 are oscillator pins. 2.3.10 reset reset input. a low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not runni ng. the minimum pulse length is given in ?system and reset characteristics? on page 324 . shorter pulses are not guaranteed to generate a reset. 2.3.11 xtal1 input to the inverting oscillato r amplifier and input to the in ternal clock operating circuit. 2.3.12 xtal2 output from the invert ing oscillator amplifier. 2.3.13 avcc avcc is the supply voltage pin for port f and the a/d converter. it should be externally con- nected to v cc , even if the adc is not used. if the adc is used, it should be connected to v cc through a low-pass filter. 2.3.14 aref aref is the analog reference pin for the a/d converter. 2.3.15 pen pen is a programming enable pin for the spi seri al programming mode, and is internally pulled high . by holding this pin low during a power-on reset, the device will enter the spi serial pro- gramming mode. pen has no function during normal operation. 8 8151h?avr?02/11 atmega128a 3. resources a comprehensive set of development tools, application notes, and datasheets are available for download on http:// www.atmel.com/avr. note: 1. 4. data retention reliability qualification results show that the pr ojected data retention failure rate is much less than 1 ppm over 20 years at 85c or 100 years at 25c. 5. about code examples this datasheet contains simple code examples that briefly show how to use various parts of the device. these code examples assume that the part specific header file is included before compi- lation. be aware that not all c compiler vendors include bit definitions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documentation for more details. for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructio ns that allow access to extended i/o. typically ?lds? and ?sts? combined with ? sbrs?, ?sbrc?, ?sbr?, and ?cbr?. 9 8151h?avr?02/11 atmega128a 6. avr cpu core 6.1 introduction this section discusses the atmel ? avr ? core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, contro l peripherals and handle interrupts. 6.2 architectural overview figure 6-1. block diagram of the avr architecture in order to maximize performance and parallelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a single level pipelining. while one instruction is being executed, the next instruc- tion is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in-system reprogrammable flash memory. the fast-access register file contains 32 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle ar ithmetic logic unit (alu ) operation. in a typ- ical alu operation, two operands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. six of the 32 registers can be used as three 16-b it indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control i/o lines eeprom data bus 8-bit data sram direct addressing indirect addressing interrupt unit spi unit watchdog timer analog comparator i/o module 2 i/o module1 i/o module n 10 8151h?avr?02/11 atmega128a can also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16-bit x-register, y-register and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic opera- tion, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and uncon ditional jump and call instructions, able to directly address the whole address space. most avr instructions have a single 16-bit word for- mat. every program memory address contains a 16-bit or 32-bit instruction. program flash memory space is divided in two sections, the boot program section and the application program section. both sections have dedicated lock bits for write and read/write protection. the spm instruction that writes into the application flash memory section must reside in the boot program section. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in the general data sram, and consequently the stack size is only limited by the to tal sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer ? sp ? is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control registers in the i/o space with an additional global interrupt enable bit in the status register. all interrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector posi- tion. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresses wh ich can be accessed directly, or as the data space locations following those of the register file, $20 - $5f. in addition, the atmega128a has extended i/o space from $60 - $ff in sram where only the st/sts/std and ld/lds/ldd instructions can be used. 6.3 alu ? arithm etic logic unit the high-performance avr alu operates in dire ct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-functions. some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruction set? section for a detailed description. 6.4 status register the status register contains information about the result of the most recently executed arithme- tic instruction. this information can be used for altering program flow in order to perform conditional operations. note that the status register is updated after all alu operations, as specified in the instruction set reference. this will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically st ored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software. 11 8151h?avr?02/11 atmega128a 6.4.1 sreg - avr status register ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for th e interrupts to be enabled. the individual inter- rupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i-bit can also be set and cleared in software with the sei and cli instructions, as described in the instruction set reference. ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (b it store) use the t-bit as source or desti- nation for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicates a half carry in some arithmetic operations. half carry is useful in bcd arithmetic. see the ?instruction set description? for detailed information. ? bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or between the negative flag n and the two?s complement over- flow flag v. see the ?instruction set description? for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v suppor ts two?s complement arithmetics. see the ?instruction set description? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmetic or logic operation. see the ?instruction set description? for de tailed information. 6.5 general purpose register file the register file is optimized for the avr enhanced risc instruction set. in order to achieve the required performance and flexib ility, the followin g input/output schemes are supported by the register file: bit 76543210 ithsvnzcsreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 12 8151h?avr?02/11 atmega128a ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 6-2 on page 12 shows the structure of the 32 general purpose working registers in the cpu. figure 6-2. atmel ? avr ? cpu general purpose working registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 6-2 , each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user data space. although not being physically imple- mented as sram locations, this memory organization provides great flexibility in access of the registers, as the x-, y-, and z-pointer registers can be set to index any register in the file. 6.5.1 x-register, y-register, and z-register the registers r26:r31 have some added functions to their general purpose usage. these regis- ters are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are described in figure 6-3 . 7 0 addr. r0 $00 r1 $01 r2 $02 ? r13 $0d general r14 $0e purpose r15 $0f working r16 $10 registers r17 $11 ? r26 $1a x-register low byte r27 $1b x-register high byte r28 $1c y-register low byte r29 $1d y-register high byte r30 $1e z-register low byte r31 $1f z-register high byte 13 8151h?avr?02/11 atmega128a figure 6-3. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the instruction set reference for details). 6.6 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. note that the stack is implemented as growing from higher to lower memory locations. the stack pointer register always points to the top of the stack. the stack pointer points to the data sram stack area where the subroutine and interrupt stacks are loca ted. a stack push command will decrease the stack pointer. the stack in the data sram must be defined by the program before any subroutine calls are executed or interrupts are enabled. initial stack pointer value equals the last address of the internal sram and the stack pointer must be set to point above start of the sram, see figure 7-2 on page 20 . see table 6-1 for stack pointer details. the atmel ? avr ? stack pointer is implemented as two 8-bit registers in the i/o space. the num- ber of bits actually used is implementation dependent. note that the data space in some implementations of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. 15 xh xl 0 x - register 7 0 7 0 r27 ($1b) r26 ($1a) 15 yh yl 0 y - register 7 0 7 0 r29 ($1d) r28 ($1c) 15 zh zl 0 z - register 7 0 7 0 r31 ($1f) r30 ($1e) table 6-1. stack pointer instructions instruction stack pointer description push decremented by 1 data is pushed onto the stack call icall rcall decremented by 2 return address is pushed onto the stack with a subroutine call or interrupt pop incremented by 1 data is popped from the stack ret reti incremented by 2 return address is popped from the stack with return from subroutine or return from interrupt 14 8151h?avr?02/11 atmega128a 6.6.1 sph and spl - stack pointer high and low register 6.6.2 rampz - ram page z select register ? bits 7:1 ? reserved these are reserved bits and will always read as zero. when writing to this address location, write these bits to zero for compatibility with future devices. ? bit 0 ? rampz0: extended ram page z-pointer the rampz register is normally used to sele ct which 64k ram page is accessed by the z- pointer. as the atmel ? avr ? atmega128a does not support more than 64k of sram memory, this register is used only to select which page in the program memory is accessed when the elpm/spm instruction is used. the different se ttings of the rampz0 bit have the following effects: note that lpm is not affected by the rampz setting. 6.7 instruction execution timing this section describes the general access timi ng concepts for instruction execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no internal clo ck division is used. figure 6-4 shows the parallel instruction fetches and instruction executions enabled by the har- vard architecture and the fast-access register f ile concept. this is t he basic pipelining concept to obtain up to 1mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. bit 151413121110 9 8 sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 sph sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/write r/w r/w r/w r/w r/w r/w r/w r/w r/wr/wr/wr/wr/wr/wr/wr/w initial value 00000000 00000000 bit 76543 2 1 0 ? ? ? ? ? ? ? rampz0 rampz read/write r r r r r r r r/w initial value 0 0 0 0 0 0 0 0 rampz0 = 0: program memory address $0000 - $7fff (lower 64kbytes) is accessed by elpm/spm rampz0 = 1: program memory address $8000 - $ffff (higher 64kbytes) is accessed by elpm/spm 15 8151h?avr?02/11 atmega128a figure 6-4. the parallel instruction fetches and instruction executions figure 6-5 shows the internal timing concept for the re gister file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destina- tion register. figure 6-5. single cycle alu operation 6.8 reset and inte rrupt handling the atmel ? avr ? provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in order to enable the interrupt. depending on the pro- gram counter value, interrupts may be automatically disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security. see the section ?memory pro- gramming? on page 291 for details. the lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 59 . the list also determines the priority levels of the different interrupts. the lower the address the higher is the priority level. reset has the highest priority, and next is int0 ? the external interrupt request 0. the interrupt vectors can be moved to the start of the boot flash section by setting the ivsel bit in the mcu control r egister (mcucr). refer to ?interrupts? on page 59 for more information. the reset vector can also be moved to the start of the boot flash section by programming the bootrst fuse, see ?boot loader support ? read-while-write self-programming? on page 277 . when an interrupt occurs, the global interrupt enable i-bit is cleared and all interrupts are dis- abled. the user software can write logic one to the i-bit to enable nested interrupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instruction ? reti ? is executed. there are basically two types of interrupts. the fi rst type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vector clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu 16 8151h?avr?02/11 atmega128a in order to execute the interrupt handling rout ine, and hardware clears the corresponding inter- rupt flag. interrupt flags can also be cleared by wr iting a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and re membered until the inte rrupt is enabled, or the flag is cleared by software. similarly, if one or more interrup t conditions occur while the global interrupt enable bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the global interrupt enable bit is set, and will then be executed by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears before the interrupt is enabled, the in terrupt will not be triggered. when the atmel ? avr ? exits from an interrupt, it will always return to the main prog ram and exe- cute one more instruction before any pending interrupt is served. note that the status register is not automatica lly stored when entering an interrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable interrupts, the interrup ts will be immediately disabled. no interrupt will be executed af ter the cli instruction, even if it occurs simultaneously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence. when using the sei instruction to enable interr upts, the instruction following sei will be exe- cuted before any pending interrupts, as shown in this example. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eemwe ; start eeprom write sbi eecr, eewe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ __disable_interrupt(); eecr |= (1< 18 8151h?avr?02/11 atmega128a 7. memories this section describes the different memories in the atmel ? avr ? atmega128a. the avr archi- tecture has two main memory spaces, the data memory and the program memory space. in addition, the atme ga128a features an eepr om memory for data st orage. all three memory spaces are linear and regular. 7.1 in-system reprogrammable flash program memory the atmega128a contains 128kbytes on-chip in-system reprogrammable flash memory for program storage. since all avr instructions are 16 bits or 32 bits wide, the flash is organized as 64k 16. for software security, the flash progra m memory space is divided into two sections, boot program section and application program section. the flash memory has an endurance of at least 10,000 write/erase cycles. the atmega128a program counter (pc) is 16 bits wide, thus addressing the 64k program memory locations. the operation of boot program section and associated boot lock bits for software protection are described in detail in ?boot loader support ? read-while-write self-programming? on page 277 . ?memory programming? on page 291 contains a detailed description on flash programming in spi, jtag, or para llel programming mode. constant tables can be allocated within the entire program memory address space (see the lpm ? load program memory and elpm ? extended load program memory instruction description). timing diagrams for instruction fetch and execution are presented in ?instruction execution tim- ing? on page 14 . figure 7-1. program memory map $0000 $ffff program memory application flash section boot flash section 19 8151h?avr?02/11 atmega128a 7.2 sram data memory the atmel ? avr ? atmega128a supports two different configurations for the sram data memory as listed in table 7-1 . figure 7-2 shows how the atmega128a sram memory is organized. the atmega128a is a complex microcontroller with more peripheral units than can be sup- ported within the 64 location reserved in the opcode for the in and out instructions. for the extended i/o space from $60 - $ff in sram, only the st/sts/std and ld/lds/ldd instruc- tions can be used. the extended i/o space does not exist when the atmega128a is in the atmega103 com patibility mode. in normal mode, the first 4352 data memory locations address both the register file, the i/o memory, extended i/o memory, and the internal data sram. the first 32 locations address the register file, the next 64 location the standard i/o memory, then 160 locations of extended i/o memory, and the next 4096 locations address the internal data sram. in atmega103 compatibilit y mode, the first 4096 data memory locations address both the reg- ister file, the i/o memory and the internal data sram. the first 32 locations address the register file, the next 64 location the standard i/o memory, and the next 4000 locations address the inter- nal data sram. an optional external data sram can be used with the atmega128a. this sram will occupy an area in the remaining address locations in the 64k address space. this area starts at the address following the internal sram. the register file, i/o, extended i/o and internal sram occupies the lowest 4352bytes in normal mode, and the lowest 4096bytes in the atmega103 compatibility mode (extended i/o not present), so when using 64 kbytes (65536 bytes) of exter- nal memory, 61184bytes of external memory are available in normal mode, and 61440bytes in atmega103 compatibility mode. see ?external memory interface? on page 22 for details on how to take advantage of the external memory map. when the addresses accessing the sram memory space exceeds the internal data memory locations, the external data sram is accessed using the same instructions as for the internal data memory access. when the internal data memories are accessed, the read and write strobe pins (pg0 and pg1 ) are inactive during the whole access cycle. external sram operation is enabled by setting the sre bit in the mcucr register. accessing external sram takes one additional clock cycle per byte compared to access of the internal sram. this means that the commands ld, st, lds, sts, ldd, std, push, and pop take one additional clock cycle. if the stack is placed in external sram, interrupts, subroutine calls and returns take three clock cycles extra because the two-byte program counter is pushed and popped, and external memory access does not take advantage of the internal pipe-line memory access. when external sram interface is used with wait-state, one-byte external access takes two, three, or four additional cl ock cycles for one, two, and three wait-states respectively. interrupts, subroutine calls and returns will need five, seven, or nine clock cycles more than specified in the instruction set manual for one, two, and three wait-states. table 7-1. memory configurations configuration internal sram data memory external sram data memory normal mode 4096 up to 64k atmega103 compatibility mode 4000 up to 64k 20 8151h?avr?02/11 atmega128a the five different addressing modes for the data memory cover: direct, indirect with displace- ment, indirect, indirect with pre-decrement, and indirect with post-increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locations from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post-incre- ment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i/o registers, and the 4096bytes of internal data sram in the atmel ? avr ? atmega128a are all accessible th rough all these addressing modes. the register file is described in ?general purpose register file? on page 11 . figure 7-2. data memory map 7.2.1 data memory access times this section describes the general access timi ng concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 7-3 . memory configuration b 32 registers 64 i/o registers internal sram (4000 x 8) $0000 - $001f $0020 - $005f $1000 $0fff $ffff $0060 data memory external sram (0 - 64k x 8) memory configuration a 32 registers 64 i/o registers internal sram (4096 x 8) $0000 - $001f $0020 - $005f $1100 $10ff $ffff $0060 - $00ff data memory external sram (0 - 64k x 8) 160 ext i/o reg. $0100 21 8151h?avr?02/11 atmega128a figure 7-3. on-chip data sram access cycles 7.3 eeprom data memory the atmel ? avr ? atmega128a contains 4kbyte s of data eeprom memory . it is organized as a separate data space, in which single bytes can be read and written. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the following, specif ying the eeprom address registers, the eeprom data register, and the eeprom control register. ?memory programming? on page 291 contains a detailed description on eeprom programming in spi, jtag, or para llel programming mode 7.3.1 eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time for the eeprom is given in table 7-2 . a self-timing function, however, lets the user software detect when the next byte can be written. if the user code contains instruc- tions that write the eeprom, some precautions must be taken. in heavily filtered power supplies, v cc is likely to rise or fall slowly on po wer-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see ?preventing eeprom co rruption? on page 21. for details on how to avoid problems in these situations. in order to prevent unintentional eeprom writes, a specific write procedure must be followed. refer to the description of the eeprom control regist er for details on this. when the eeprom is read, the cpu is halted for fo ur clock cycles before the next in struction is executed. when the eeprom is written, the cp u is halted for two clock cycles before the next instruction is executed. 7.3.2 eeprom write during power-down sleep mode when entering power-down sleep mode whil e an eeprom write operation is active, the eeprom write operation will c ontinue, and will complete before the write access time has passed. however, when the writ e operation is completed, the oscillator continues running, and as a consequence, the device does not enter power-down entirely. it is therefore recommended to verify that the eeprom wr ite operation is completed before entering power-down. 7.3.3 preventing eeprom corruption during periods of low v cc, the eeprom data can be corrupted because the supply voltage is too low for the cpu and the eeprom to operate properly. these issues are the same as for board level systems using eepr om, and the same design so lutions should be applied. clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction 22 8151h?avr?02/11 atmega128a an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate correctly. sec- ondly, the cpu itself can execute instructions incorrectly, if the supp ly voltage is too low. eeprom data corruption can ea sily be avoided by followin g this design recommendation: keep the avr reset active (low) during periods of insufficient power su pply voltage. this can be done by enabling the internal brown-out detector (bod). if a reset occurs while a write oper- ation is in progress, th e write operation will be completed prov ided that the power supply voltage is sufficient. 7.4 i/o memory the i/o space definition of the atmel ? avr ? atmega128a is shown in ?register summary? on page 367 . all atmega128a i/os and peripherals are placed in the i/o space. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range $00 - $1f are directly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be checked by using the sbis and sbic instructions. refer to the instruction set section for more details. when using the i/o specific commands in and out, the i/o addresses $00 - $3f must be used. when addressing i/o registers as data space using ld and st instructions, $20 must be added to these addresses. the atmega128a is a complex micro- controller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for t he extended i/o space from $60 - $ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. the extended i/o space is replaced with sram locations when the atmega128a is in th e atmega103 comp atibility mode. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note that the cbi and sbi instructions will operat e on all bits in the i/o register, writ ing a one back into any flag read as set, thus clearing the flag. the cbi and sbi instructions work with registers $00 to $1f only. the i/o and peripherals control registers are explained in later sections. 7.5 external memory interface 7.5.1 features ? four different wait-state settin gs (including no wait-state). ? independent wait-s tate setting for different external me mory sectors (configurable sector size). ? the number of bits dedicated to address high byte is selectable. ? bus-keepers on data lines to minimi ze current consumption (optional). 7.5.2 overview with all the features the external memory interf ace provides, it is well suited to operate as an interface to memory devices such as external sram and flash, and peripherals such as lcd- display, a/d, and d/a. when the external memory (xmem) is enabled, address space outside the internal sram becomes available using the dedicated external memory pins (see figure 1- 1 on page 2 , table 12-2 on page 73 , table 12-8 on page 77 , and table 12-20 on page 85 ). the memory configuration is shown in figure 7-4 . 23 8151h?avr?02/11 atmega128a figure 7-4. external memory with sector select note: atmel ? avr ? atmega128a in non atmega103 compatibil ity mode: memory configuration a is available (memory configuration b n/a) atmega128a in atmega103 compatibility mode: memory configuration b is available (memory configuration a n/a) 7.5.3 atmega103 compatibility both external memory control registers (xmc ra and xmcrb) are placed in extended i/o space. in atmega103 compatibilit y mode, these regist ers are not availabl e, and the features selected by these registers are not available. the device is still atmega103 compatible, as these features did not exist in atmega103. the limitations in atmega103 compatibility mode are: ? only two wait-states settings are available (srw1n = 0b00 and srw1n = 0b01). ? the number of bits that are assigned to address high byte are fixed. ? the external memory section can not be divided into sectors with different wait-state settings. ? bus-keeper is not available. ?rd , wr and ale pins are output only (port g in atmega128a). 7.5.4 using the external memory interface the interface consists of: ? ad7:0: multiplexed low-orde r address bus and data bus. ? a15:8: high-order address bus (configurable number of bits). ? ale: address latch enable. memory configuration a 0x0000 0x10ff external memory (0-60k x 8) 0xffff internal memory srl[2..0] srw11 srw10 srw01 srw00 lower sector upper sector 0x1100 memory configuration b 0x0000 external memory (0-60k x 8) 0xffff internal memory srw10 0x0fff 0x1000 24 8151h?avr?02/11 atmega128a ?rd : read strobe. ?wr : write strobe. the control bits for the external memory interface are located in three registers, the mcu con- trol register ? mcucr, the ex ternal memory cont rol register a ? xmcra, and the external memory control register b ? xmcrb. when the xmem interface is enabled, the xmem interface will override th e setting in the data direction registers that corresponds to the ports dedicated to the xmem interface. for details about the port override, see the alternate functions in section ?i/o ports? on page 65 . the xmem interface will auto-detect wh ether an access is internal or extern al. if the access is external, the xmem interface will output address, data, and the control si gnals on the ports according to fig- ure 7-6 (this figure shows the wave forms without wait-states). when ale goes from high-to-low, there is a valid address on ad7:0. ale is low during a data transfer. when the xmem interface is enabled, also an internal access will caus e activity on address, data and ale ports, but the rd and wr strobes will not toggle duri ng internal access . when the external memory interface is disabled, the normal pin and data direction settings are used. note that when the xmem inter- face is disabled, the address space above the internal sram boundary is not mapped into the internal sram. figure 7-5 illustrates how to connect an exte rnal sram to the avr using an octal latch (typically ?74 573? or equiva lent) which is transpar ent when g is high. 7.5.5 address latch requirements due to the high-speed operation of the xram interface, the address latch must be selected with care for system frequencies above 8mhz @ 4v and 4mhz @ 2.7v. when operating at condi- tions above these frequencies, the typical old style 74hc series latch becomes inadequate. the external memory interface is designed in compliance to the 74ahc series latch. however, most latches can be used as long they comply with the main timing parameters. the main parameters for the address latch are: ? d to q propagation delay (t pd ). ? data setup time before g low (t su ). ? data (address) hold time after g low ( th ). the external memory interface is designed to guaranty minimum address hold time after g is asserted low of t h = 5 ns. refer to t laxx_ld /t llaxx_st in ?external data memory timing? tables 27- 9 through tables 27-16 on pages 332 - 335. the d-to-q propagation delay (t pd ) must be taken into consideration when calculating the access time requirement of the external component. the data setup time before g low (t su ) must not exceed address valid to ale low (t avllc ) minus pcb wiring delay (dependent on the capacitive load). figure 7-5. external sram connected to the atmel ? avr ? d[7:0] a[7:0] a[15:8] rd wr sram dq g ad7:0 ale a15:8 rd wr avr 25 8151h?avr?02/11 atmega128a 7.5.6 pull-up and bus-keeper the pull-ups on the ad7:0 ports may be activated if the corresponding port register is written to one. to reduce power consumption in sleep mode, it is recommended to disable the pull-ups by writing the port register to zero before entering sleep. the xmem interface also provides a bus-keeper on the ad7:0 lines. the bus-keeper can be dis- abled and enabled in software as described in ?xmcrb - external memory control register b? on page 35 . when enabled, the bus-kee per will ensure a defined logic level (zero or one) on the ad7:0 bus when these lines would otherwise be tri-stated by the xmem interface. 7.5.7 timing external memory devices have different timing requirements. to meet these requirements, the atmel ? avr ? atmega128a xmem interface provides four different wait-states as shown in table 7-4 . it is important to consider the timing s pecification of the external memory device before selecting the wait-state. the most important parameters are the access time for the exter- nal memory compared to the set-up requirement of the atmega128a. the access time for the external memory is defined to be the time from receiving the chip select/address until the data of this address actually is driven on the bus. the ac cess time cannot exceed the time from the ale pulse must be asserted low until data is stable during a read sequence (see t llrl + t rlrh - t dvrh in tables 27-9 through tables 27-16 on pages 332 - 335). the different wait-states are set up in software. as an additional feature, it is possib le to divide the external memory space in two sec- tors with individual wait-state settings. this ma kes it possible to connect two different memory devices with different timing requirements to the same xmem interface. for xmem interface tim- ing details, please refer to table 27-9 to table 27-16 and figure 27-9 to figure 27-12 in the ?external data memory timing? on page 332 . note that the xmem interface is asynchronous and that the waveforms in the following figures are related to the internal system clock. t he skew between the internal and external clock (xtal1) is not guarantied (varies between devices temperature, and supply voltage). conse- quently, the xmem interface is not suited for synchronous operation. figure 7-6. external data memory cycles without wait-state (srwn1=0 and srwn0=0) ale t1 t2 t3 write read wr t4 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) xxxxx xxxxxxxx 26 8151h?avr?02/11 atmega128a note: 1. srwn1 = srw11 (upper sector) or srw01 (lower sector), srwn0 = srw10 (upper sector) or srw00 (lower sector). the ale pulse in period t4 is only present if the next instruction accesses the ram (internal or external). figure 7-7. external data memory cycles with srwn1 = 0 and srwn0 = 1 (1) note: 1. srwn1 = srw11 (upper sector) or srw01 (lower sector), srwn0 = srw10 (upper sector) or srw00 (lower sector). the ale pulse in period t5 is only present if the next instruction accesses the ram (internal or external). figure 7-8. external data memory cycles with srwn1 = 1 and srwn0 = 0 (1) note: 1. srwn1 = srw11 (upper sector) or srw01 (lower sector), srwn0 = srw10 (upper sector) or srw00 (lower sector). the ale pulse in period t6 is only present if the next instruction accesses the ram (internal or external). ale t1 t2 t3 write read wr t5 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) t4 ale t1 t2 t3 write read wr t6 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) t4 t5 27 8151h?avr?02/11 atmega128a figure 7-9. external data memory cycles with srwn1 = 1 and srwn0 = 1 (1) note: 1. srwn1 = srw11 (upper sector) or srw01 (lower sector), srwn0 = srw10 (upper sector) or srw00 (lower sector). the ale pulse in period t7 is only present if the next instruction accesses the ram (internal or external). 7.5.8 using all locations of external memory smaller than 64 kbytes since the external memory is mapped after the internal memory as shown in figure 7-4 , the external memory is not addressed when addressi ng the first 4,352bytes of data space. it may appear that the first 4,352bytes of the extern al memory are inaccessible (external memory addresses 0x0000 to 0x10ff). however, when connecting an external memory smaller than 64kbytes, for example 32kbytes, these locations are easily accessed simply by addressing from address 0x8000 to 0x90ff. since the external me mory address bit a15 is not connected to the external memory, addr esses 0x8000 to 0x90ff will appear as addresses 0x0000 to 0x10ff for the external memory. addressi ng above address 0x90 ff is not recommend ed, since this will address an external memory location that is al ready accessed by another (lower) address. to the application software, the external 32kbytes memory w ill appear as one linear 32kbytes address space from 0x1100 to 0x 90ff. this is illustrated in figure 7-10 . memory configuration b refers to the atmega103 compat ibility mode, configuration a to the non-compatible mode. when the device is set in atmel ? avr ? atmega103 compatibility mode , the internal address space is 4,096bytes. this implies that the fi rst 4,096bytes of the external memory can be accessed at addresses 0x8000 to 0x8fff. to the application software, the external 32kbytes memory will appear as one lin ear 32kbytes address spac e from 0x1000 to 0x8fff. ale t1 t2 t3 write read wr t7 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) t4 t5 t6 28 8151h?avr?02/11 atmega128a figure 7-10. address map with 32kbytes external memory 7.5.9 using all 64 kbytes locations of external memory since the external memory is mapped after the internal memory as shown in figure 7-4 , only 60kbytes of external memory is available by default (address space 0x0000 to 0x10ff is reserved for internal memory). however, it is possible to take advantage of the entire external memory by masking the higher address bits to zero. this can be done by using the xmmn bits and control by software the most significant bits of the address. by setting port c to output 0x00, and releasing the most si gnificant bits for normal port pin operation, the memory interface will address 0x0000 - 0x1fff. see the following code examples. 0x0000 0x10ff 0xffff 0x1100 0x7fff 0x8000 0x 9 0ff 0x 9 100 0x0000 0x10ff 0x1100 0x7fff memory configuration a memory configuration b internal memory (unused) avr memory map external 32k sram external memory 0x0000 0x0fff 0xffff 0x1000 0x7fff 0x8000 0x8fff 0x 9 000 0x0000 0x0fff 0x1000 0x7fff internal memory (unused) avr memory map external 32k sram external memory 29 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8. care must be exercised using this option as most of the memory is masked away. assembly code example (1) ; offset is defined to 0x2000 to ensure ; external memory access ; configure port c (address high byte) to ; output 0x00 when the pins are released ; for normal port pin operation ldi r16, 0xff out ddrc, r16 ldi r16, 0x00 out portc, r16 ; release pc7:5 ldi r16, (1< 31 8151h?avr?02/11 atmega128a ? bit 2 ? eemwe: eeprom master write enable the eemwe bit determines whether setting eewe to one causes the eeprom to be written. when eemwe is written to one, writing eewe to one within four clock cycles will write data to the eeprom at the selected address. if eemwe is zero, writing eewe to one will have no effect. when eemwe has been written to one by software, hardware clears the bit to zero after four clock cycles. see the description of the eewe bit for an eeprom write procedure. ? bit 1 ? eewe: eeprom write enable the eeprom write enable signal eewe is the write strobe to the eeprom. when address and data are correctly set up, the eewe bit must be set to write the value into the eeprom. the eemwe bit must be set when the logical o ne is written to eewe, otherwise no eeprom write takes place. the following procedure shoul d be followed when writing the eeprom (the order of steps 3 and 4 is not essential): 1. wait until eewe becomes zero. 2. wait until spmen in spmcsr becomes zero. 3. write new eeprom address to eear (optional). 4. write new eeprom data to eedr (optional). 5. write a logical one to the eemwe bit while writing a zero to eewe in eecr. 6. within four clock cycles after sett ing eemwe, write a logical one to eewe. the eeprom can not be programmed during a cpu write to the flash memory. the software must check that the flash programming is co mpleted before initiating a new eeprom write. step 2 is only relevant if the software contains a boot loader allowing the cpu to program the flash. if the flash is never being updated by the cpu, step 2 can be omitted. see ?boot loader support ? read-while-write self-programming? on page 277 for details about boot programming. caution: an interrupt between step 5 and step 6 will make the write cycle fail, since the eeprom master write enable will time-out. if an interrupt routine accessing the eeprom is interrupting another eeprom acce ss, the eear or eedr register will be modified, causing the interrupted eeprom access to fail. it is recommended to have the global interrupt flag cleared during the four last steps to avoid these problems. when the write access time has elapsed, the eewe bit is cleared by hardware. the user soft- ware can poll this bit and wait for a zero before writing the next byte. when eewe has been set, the cpu is halted for two cycles before the next instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the re ad strobe to the eeprom. when the correct address is set up in the eear register, the eere bit must be written to a logic one to trigger the eeprom read. the eeprom read access takes one instruction, and th e requested data is available immediately. when t he eeprom is read, the cpu is ha lted for four cycles before the next instruction is executed. the user should poll the eewe bit before starti ng the read operation. if a write operation is in progress, it is neither possi ble to read the eeprom, nor to change the eear register. 32 8151h?avr?02/11 atmega128a the calibrated oscillator is used to time the eeprom accesses. table 7-2 lists the typical pro- gramming time for eeprom access from the cpu. note: 1. uses 1mhz clock, independent of cksel-fuse settings. the following code examples show one assembly and one c function for writing to the eeprom. the examples assume that interrupts ar e controlled (for example, by disabling inter- rupts globally) so that no inte rrupts will occur during execution of these functi ons. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait fo r any ongoing spm co mmand to finish. table 7-2. eeprom programming time symbol number of calibrated rc oscillator cycles (1) typ programming time eeprom write (from cpu) 8448 8.5ms assembly code example eeprom_write: ; wait for completion of previous write sbic eecr,eewe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eemwe sbi eecr,eemwe ; start eeprom write by setting eewe sbi eecr,eewe ret c code example void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 35 8151h?avr?02/11 atmega128a note: 1. n = 0 or 1 (lower/upper sector). for further details of the timing and wait-state s of the external memory interface, see figures 7-6 through figures 7-9 for how the sett ing of the srw bits affects the timing. ? bit 0 ? res: reserved bit this is a reserved bit and will always read as zero. when writing to this address location, write this bit to zero for comp atibility with future devices. 7.6.6 xmcrb - external memory control register b ? bit 7? xmbk: external memory bus-keeper enable writing xmbk to one enables the bus keeper on the ad7:0 lines. when the bus keeper is enabled, it will ensure a defined logic level (zero or one) on ad 7:0 when they would otherwise be tri-stated. writing xmbk to zero disables the bus keeper. xmbk is not qualified with sre, so even if the xmem interface is disabled, the bu s keepers are still activated as long as xmbk is one. ? bit 6:4 ? reserved these are reserved bits and will always read as zero. when writing to this address location, write these bits to zero for compatibility with future devices. ? bit 2:0 ? xmm2, xmm1, xmm0: external memory high mask when the external memory is enabled, all port c pins are default used for the high address byte. if the full 60kbytes address space is not required to access the external memory, some, or all, port c pins can be released for normal port pin function as described in table 7-5 . as described in ?using all 64 kbytes locations of external memory? on page 28 , it is possible to use the xmmn bits to access all 64kbytes locations of the external memory. table 7-4. wait states (1) srwn1 srwn0 wait states 0 0 no wait-states 0 1 wait one cycle during read/write strobe 1 0 wait two cycles during read/write strobe 1 1 wait two cycles during read/write and wait one cycle before driving out new address bit 76543210 xmbk????xmm2xmm1xmm0xmcrb read/writer/wrrrrr/wr/wr/w initial value00000000 table 7-5. port c pins released as normal port pi ns when the external memory is enabled xmm2 xmm1 xmm0 # bits for external memory address released port pins 0 0 0 8 (full 60 kbytes space) none 0017 pc7 0106 pc7 - pc6 0115 pc7 - pc5 36 8151h?avr?02/11 atmega128a 1004 pc7 - pc4 1013 pc7 - pc3 1102 pc7 - pc2 1 1 1 no address high bits full port c table 7-5. port c pins released as normal port pi ns when the external memory is enabled xmm2 xmm1 xmm0 # bits for external memory address released port pins 37 8151h?avr?02/11 atmega128a 8. system clock and clock options 8.1 clock systems and their distribution figure 8-1 presents the principal clock systems in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in ?power manage- ment and sleep modes? on page 46 . the clock systems are detailed below. figure 8-1. clock distribution 8.1.1 cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the atmel ? avr ? core. examples of such modules are the general purpose register file, the status register and the data memory holding the stac k pointer. halting the cpu cloc k inhibits the core from per- forming general operations and calculations. 8.1.2 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like timer/counters, spi, and usart.? the i/o clock is also used by the external inte rrupt module, but note that some external inter- rupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. also note that address recognition in the twi module is carried out asynchro- nously when clk i/o is halted, enabling twi address reception in all sleep modes. general i/o modules asynchronous timer/counter adc cpu core ram clk i/o clk asy avr clock control unit clk cpu flash and eeprom clk flash clk adc source clock watchdog timer watchdog oscillator reset logic clock multiplexer watchdog clock calibrated rc oscillator timer/counter oscillator crystal oscillator low-frequency crystal oscillator external rc oscillator external clock 38 8151h?avr?02/11 atmega128a 8.1.3 flash clock ? clk flash the flash clock controls operatio n of the flash interface. the flash clock is us ually active simultaneously with the cpu clock. 8.1.4 asynchronous timer clock ? clk asy the asynchronous timer clock al lows the asynchronous timer/c ounter to be clocked directly from an external 32khz clock crystal. the dedica ted clock domain allows using this timer/coun- ter as a real-time counter even when the device is in sleep mode. 8.1.5 adc clock ? clk adc the adc is provided with a dedicated clock domain. this allows halting the cpu and i/o clocks in order to reduce noise generated by digital circuitry. this gives more accurate adc conversion results. 8.1.6 xdiv - xtal divi de control register the xtal divide control register is used to divide the source clock frequency by a number in the range 2 - 129. this feature can be used to decrease power consumption when the require- ment for processing power is low. ? bit 7 ? xdiven: xtal divide enable when the xdiven bit is written one, the cloc k frequency of the cpu and all peripherals (clk i/o , clk adc , clk cpu , clk flash ) is divided by the factor defined by the setting of xdiv6 - xdiv0. this bit can be written run-time to vary the clock frequency as suitable to the application. ? bits 6:0 ? xdiv6:xdiv0: xtal divide select bits 6 - 0 these bits define the division factor that applies when the xdiven bit is set (one). if the value of these bits is denoted d , the following formula defines the resulting cpu and peripherals clock frequency f clk : the value of these bits can only be changed when xdiven is zero. when xdiven is written to one, the value written simultaneously into xdiv 6:xdiv0 is taken as the division factor. when xdiven is written to zero, the va lue written simultaneously into xdiv6:xdiv0 is rejected. as the divider divides the master clock input to the mcu, the speed of all peripherals is reduced when a division factor is used. when the system clock is divided, timer/counte r0 can be used with a synchronous clock only. the frequency of the asynchronous clock must be lower than 1/4th of the frequency of the scaled down source clock. otherwise, interrupts may be lost, and accessing the timer/counter0 registers may fail. bit 7 6543210 xdiven xdiv6 xdiv5 xdiv4 xdiv3 xdiv2 xdiv1 xdiv0 xdiv read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0000000 f clk source clock 129 d ? --------------------------------- - = 39 8151h?avr?02/11 atmega128a 8.2 clock sources the device has the following clock source opti ons, selectable by flash fuse bits as shown below. the clock from the selected source is input to the atmel ? avr ? clock generator, and routed to the appropriate modules. note: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. the various choices for each clocking option is given in the following sections. when the cpu wakes up from power-down or power-save, the selected clock source is used to time the start- up, ensuring stable osc illator operation bef ore instruction execution st arts. when the cpu starts from reset, there is as an additional delay allowing the power to reach a stable level before com- mencing normal operation. the watchdog oscillator is used for timing this real-time part of the start-up time. the number of wdt oscillator cycles used for each time-out is shown in table 8- 2 . the frequency of the watchdog oscillator is voltage dependent as shown in the ?typical characteristics? on page 338 . 8.3 default clock source the device is shipped with cksel = ?0001? and sut = ?10?. the default clock source setting is therefore the internal rc oscillator with longest startup ti me. this default setting ensures that all users can make their desired clock source setting using an in-system or parallel programmer. 8.4 crystal oscillator xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be con- figured for use as an on-chip oscillator, as shown in figure 8-2 . either a quartz crystal or a ceramic resonator may be used. the ckopt fuse selects between two different oscillator amplifier modes. when ckopt is programmed, the oscillator ou tput will oscillate will a full rail- to-rail swing on the output. this mode is suitable when operating in a very noisy environment or when the output from xtal2 drives a second clock buffer. this mode has a wide frequency range. when ckopt is unprogrammed, the oscillator has a sm aller output swin g. this reduces power consumption considerably. this mode has a limited frequency range and it can not be used to drive other clock buffers. for resonators, the maximum frequency is 8mhz with ckopt unprogrammed and 16mhz with ckopt programmed. c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray table 8-1. device clocking options select device clocking option cksel3:0 (1) external crystal/ceramic resonator 1111 - 1010 external low-frequency crystal 1001 external rc oscillator 1000 - 0101 calibrated internal rc oscillator 0100 - 0001 external clock 0000 table 8-2. number of watchdog oscillator cycles typical time-out (v cc = 5.0v) typical time-out (v cc = 3.0v) number of cycles 4.1ms 4.3ms 4k (4,096) 65ms 69ms 64k (65,536) 40 8151h?avr?02/11 atmega128a capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use wi th crystals are given in table 8-3 . for ceramic resonators, the capacitor values given by the manufacturer should be used. figure 8-2. crystal oscillator connections the oscillator can operate in three different mo des, each optimized for a specific frequency range. the op erating mode is selected by t he fuses cksel3:1 as shown in table 8-3 . note: 1. this option should not be used with crystals, only with ceramic resonators. the cksel0 fuse together with the sut1:0 fuses se lect the start-up times as shown in table 8- 4 . table 8-3. crystal oscillator operating modes ckopt cksel3:1 frequency range (mhz) recommended range for capacitors c1 and c2 for use with crystals 1 101 (1) 0.4 - 0.9 ? 1 110 0.9 - 3.0 12 - 22pf 1 111 3.0 - 8.0 12 - 22pf 0 101, 110, 111 1.0 - 12 - 22pf table 8-4. start-up times for the crysta l oscillator clock selection cksel0 sut1:0 start-up time from power-down and power- save additional delay from reset (v cc = 5.0v) recommended usage 0 00 258 ck (1) 4.1ms ceramic resonator, fast rising power 0 01 258 ck (1) 65ms ceramic resonator, slowly rising power 0 10 1k ck (2) ? ceramic resonator, bod enabled 0 11 1k ck (2) 4.1ms ceramic resonator, fast rising power 1 00 1k ck (2) 65ms ceramic resonator, slowly rising power xtal2 xtal1 gnd c2 c1 41 8151h?avr?02/11 atmega128a notes: 1. these options should only be used when not operating close to the maximum frequency of the device, and only if frequency stability at start- up is not important for the application. these options are not suitable for crystals. 2. these options are intended for use with cerami c resonators and will ensure frequency stability at start-up. they can also be used with crystal s when not operating close to the maximum fre- quency of the device, and if frequency stability at start-up is not important for the application. 8.5 low-frequency crystal oscillator to use a 32.768 khz watch crystal as the clock source for the device, the low-frequency crystal oscillator must be selected by setting the cksel fuses to ?1001?. the crystal should be con- nected as shown in figure 8-2 . by programming the ckopt fuse, the user can enable internal capacitors on xtal1 and xtal2, thereby removing the need for external capacitors. the inter- nal capacitors have a nominal value of 36pf. when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 8-5 . note: 1. these options should only be used if frequen cy stability at start-up is not important for the application. 8.6 external rc oscillator for timing insensitive applications, the external rc configuration shown in figure 8-3 can be used. the frequency is roughly estimated by the equation f = 1/(3rc). c should be at least 22pf. by programming the ckopt fuse, the user can enable an internal 36 pf capacitor between xtal1 and gnd, thereby removing the need for an external capacitor. for more infor- mation on oscillator operation and details on how to choose r and c, refer to the external rc oscillator application note. 1 01 16k ck ? crystal oscillator, bod enabled 1 10 16k ck 4.1ms crystal oscillator, fast rising power 1 11 16k ck 65ms crystal oscillator, slowly rising power table 8-4. start-up times for the crystal osc illator clock select ion (continued) cksel0 sut1:0 start-up time from power-down and power- save additional delay from reset (v cc = 5.0v) recommended usage table 8-5. start-up times for the lo w-frequency crystal os cillator clock selection sut1:0 start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 1k ck (1) 4.1ms fast rising power or bod enabled 01 1k ck (1) 65ms slowly rising power 10 32k ck 65ms stable frequency at start-up 11 reserved 42 8151h?avr?02/11 atmega128a figure 8-3. external rc configuration the oscillator can operat e in four different mo des, each optimized for a specific frequency range. the op erating mode is selected by t he fuses cksel3:0 as shown in table 8-6 . when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 8-7 . note: 1. this option should not be used when operating close to the maximum frequency of the device. 8.7 calibrated internal rc oscillator the calibrated internal rc oscillator provides a fixed 1.0mhz, 2.0mhz, 4.0mhz, or 8.0mhz clock. all frequencies are nominal values at 5v and 25 c. this clock may be selected as the sys- tem clock by programming the cksel fuses as shown in table 8-8 . if selected, it will operate with no external components. the ckopt fuse should always be unprogrammed when using this clock option. during reset, hardware loads the calibration byte for the 1mhz oscillator into the osccal register and thereby automatically calibrates the rc oscillator. at 5v, 25 c and 1.0mhz oscillator frequency selected, this calibrati on gives a frequency wi thin 3% of the nomi- nal frequency. using calibration methods as described in application notes available at www.atmel.com/avr it is possible to achieve 1% accuracy at any given v cc and temperature. when this oscillator is used as the chip clock, the watchdog oscillator will still be used for the table 8-6. external rc oscillator operating modes cksel3:0 frequency range (mhz) 0101 0.1 - 0.9 0110 0.9 - 3.0 0111 3.0 - 8.0 1000 8.0 - 12.0 table 8-7. start-up times for t he external rc oscillator clock selection sut1:0 start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 18ck ? bod enabled 01 18ck 4.1ms fast rising power 10 18ck 65ms slowly rising power 11 6ck (1) 4.1ms fast rising power or bod enabled xtal2 xtal1 gnd c r v cc nc 43 8151h?avr?02/11 atmega128a watchdog timer and for the reset time-out. for more information on the pre-programmed cali- bration value, see the section ?calibration byte? on page 294 . note: 1. the device is shipped with this option selected. when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 8-9 . xtal1 and xtal2 should be left unconnected (nc). notes: 1. the device is shipped with this option selected. 8.8 external clock to drive the device from an external clock source, xtal1 should be driven as shown in figure 8-4 . to run the device on an external clock, the cksel fuse s must be progra mmed to ?0000?. by programming the ckopt fuse, the user can enable an internal 36pf capacitor between xtal1 and gnd. figure 8-4. external clock drive configuration table 8-8. internal calibrated rc o scillator operating modes cksel3:0 nominal frequency (mhz) 0001 (1) 1.0 0010 2.0 0011 4.0 0100 8.0 table 8-9. start-up times for the internal calib rated rc oscillato r clock selection sut1:0 start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 6 ck ? bod enabled 01 6 ck 4.1ms fast rising power 10 (1) 6 ck 65ms slowly rising power 11 reserved external clock signal 44 8151h?avr?02/11 atmega128a when this clock source is selected, start-up times are determined by the sut fuses as shown in table 8-10 . when applying an external clock, it is required to avoid sudden changes in the applied clock fre- quency to ensure stable operation of the mcu. a variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. it is required to en sure that the mcu is kept in reset during such changes in the clock frequency. 8.9 timer/counter oscillator for avr microcontrollers with timer/counter osc illator pins (tosc1 and tosc2), the crystal is connected directly between the pins. no external capacitors are needed. the oscillator is opti- mized for use with a 32.768khz watch crystal. applying an external clock source to tosc1 is not recommended. note: the timer/counter oscillator uses the same type of crystal o scillator as low-frequency oscillator and the internal capacitors have the same nominal value of 36pf. 8.10 register description 8.10.1 osccal - oscillator calibration register note: osccal register is not available in atmega103 compatibility mode. ? bits 7:0 ? cal7:0: oscillator calibration value writing the calibration byte to th is address will trim the internal os cillator to remove process vari- ations from the oscillator frequency. during rese t, the 1mhz calibration value which is located in the signature row high byte (address 0x00) is automatically loaded into the osccal register. if the internal rc is used at other frequencies, the calibration values must be loaded manually. this can be done by first reading the signature row by a programmer, and then store the calibra- tion values in the flash or eeprom. then the value can be read by software and loaded into the osccal register. when osccal is zero, the lowest available frequ ency is chosen. writing non-zero values to this register will increase the freque ncy of the internal o scillator. writing $ff to the register gives the highest available frequency. the calibrated oscillator is used to time eeprom and flash access . if eeprom or flash is written, do not calibrate to more than 10% above the nominal frequency. otherwise, the eeprom or flash write may fail. note that the table 8-10. start-up times for the external clock selection sut1:0 start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 6ck ? bod enabled 01 6ck 4.1ms fast rising power 10 6ck 65ms slowly rising power 11 reserved bit 76543210 cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value device spec ific calibration value 45 8151h?avr?02/11 atmega128a oscillator is intended for calibration to 1.0mhz, 2.0mhz, 4.0mhz, or 8.0 mhz. tuning to other values is not guaranteed, as indicated in table 8-11 . table 8-11. internal rc oscilla tor frequency range. osccal value min frequency in percentage of nominal frequency (%) max frequency in percentage of nominal frequency (%) $00 50 100 $7f 75 150 $ff 100 200 46 8151h?avr?02/11 atmega128a 9. power management and sleep modes 9.1 overview sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the atmel ? avr ? provides various sleep modes allowi ng the user to tailor the power con- sumption to the application?s requirements. 9.2 sleep modes figure 8-1 on page 37 presents the different clock systems in the atmega128a, and their distri- bution. the figure is helpful in selecting an appropriate sleep mode. table 9-1 shows the different sleep modes and their wake-up sources. notes: 1. external crystal or resonator selected as clock source 2. if as 0 bit in assr is set 3. only int3:0 or level interrupt int7:4 to enter any of the six sleep modes, the se bi t in mcucr must be written to logic one and a sleep instruction must be executed. the sm2, sm1, and sm0 bits in the mcucr register select which sleep mode (idle, adc noise re duction, power-down, power-save, standby, or extended standby) will be activate d by the sleep instruction. see table 9-2 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then halted for four cycles in addition to the start-up time, it executes the interrupt routine, and resumes execution from the instruction following sleep. the contents of the register file and sram are unaltered when the device wakes up from sleep. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector. table 9-1. active clock domains and wake up sources in the different sleep modes active clock domains oscillators wake up sources sleepmode clk cpu clk flash clk io clk adc clk asy main clock source enabled timer osc enabled int7:0 twi address match timer 0 spm/ eeprom ready adc other i/o idle x x x x x (2) xxx x xx adc noise reduction x x x x (2) x (3) xx x x power-down x (3) x power-save x (2) x (2) x (3) xx (2) standby (1) xx (3) x extended standby (1) x (2) xx (2) x (3) xx (2) 47 8151h?avr?02/11 atmega128a 9.3 idle mode when the sm2:0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing spi, usart, anal og comparator, adc, two-wire serial inter- face, timer/counters, watchdog, and the interrupt system to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the ot her clocks to run. idle mode enables the mcu to wake up from external triggered interrupts as well as internal ones like the timer overflow and usart transmit complete interrupts. if wake-up from the analog comparator interrupt is not required, the analog comparator can be powered down by setting the acd bit in the analog comparator control and status register ? acsr. this will reduce power consumption in idle mode. if t he adc is enabled, a conversion starts automati- cally when this mode is entered. 9.4 adc noise reduction mode when the sm2:0 bits are written to 001, the sleep instruction makes the mcu enter adc noise reduction mode, stopping the cpu but allowing the adc, the external interrupts, the two-wire serial interface address watch, timer/counter0 and the watchdog to continue operat- ing (if enabled). this sleep mode basically halts clk i/o , clk cpu , and clk flash , while allowing the other clocks to run. this improves the noise environment for the ad c, enabling higher resolution measurements. if the adc is enabled, a conversion starts automatically when this mode is entered. apart form the adc conversion complete interrupt, only an external reset, a watchdog reset, a brown-out reset, a two-wire serial interface address match interrupt, a timer/counter0 interrupt, an spm/eeprom ready interrupt, an external level interrupt on int7:4, or an external interrupt on int3:0 can wake up the mcu from adc noise reduction mode. 9.5 power-down mode when the sm2:0 bits are written to 010, the sleep instruction makes the mcu enter power- down mode. in this mode, the external oscillator is stopped, while the external interrupts, the two-wire serial interface address watch, and the watchdog continue operating (if enabled). only an external reset, a watchdog reset, a brown-out reset, a two-wire serial interface address match interrupt, an external level interr upt on int7:4, or an external interrupt on int3:0 can wake up the mcu. this sleep mode basically halts all gener ated clocks, allowing operation of asynchronous modules only. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to ?external interrupts? on page 90 for details. when waking up from power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the reset time-out period, as described in ?clock sources? on page 39 . 9.6 power-save mode when the sm2:0 bits are written to 011, the sleep instruction makes the mcu enter power- save mode. this mode is identical to power-down, with one exception: if timer/counter0 is clocked asyn chronously, that is, the as0 bi t in assr is set, timer/counter0 will run during sleep. the device can wake up from either timer overflow or output compare 48 8151h?avr?02/11 atmega128a event from timer/counter0 if the corresponding timer/counter0 interrupt enable bits are set in timsk, and the global interrupt enable bit in sreg is set. if the asynchronous timer is not clocked asynchronously, power-down mode is recommended instead of power-save mode because the contents of the registers in the asynchronous timer should be considered undefined after wake-up in power-save mode if as0 is 0. this sleep mode basically halts all clocks except clk asy , allowing operation only of asynchronous modules, including timer/counter0 if clocked asynchronously. 9.7 standby mode when the sm2:0 bits are 110 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the oscillator is kept running. fr om standby mode, the device wakes up in 6 clock cycles. 9.8 extended standby mode when the sm2:0 bits are 111 and an external crystal/resonator clock option is selected, the sleep instruction makes the m cu enter extended standby mode . this mode is identical to power-save mode with th e exception that the oscillator is kept running. from extended standby mode, the device wakes up in six clock cycles. 9.9 minimizing power consumption there are several issues to consider when trying to minimize the power consumption in an avr controlled system. in general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possi ble of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consideration when trying to achieve the lowest possible po wer consumption. see also section 8. ?system clock and clock options? on page 37 . 9.9.1 analog to digital converter if enabled, the adc will be enabled in all sleep modes. to save power, the adc should be dis- abled before entering any sleep mode. when the adc is turned off and on again, the next conversion will be an extended conversion. refer to ?analog to digital converter? on page 233 for details on adc operation. 9.9.2 analog comparator when entering idle mode, the analog comparator should be disabled if not used. when entering adc noise reduction mode, the analog comparat or should be disabled. in the other sleep modes, the analog comparator is automatically di sabled. however, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be dis- abled in all sleep modes. ot herwise, the internal volt age reference will be enabled, independent of sleep mode. refer to ?analog comparator? on page 230 for details on how to configure the analog comparator. 9.9.3 brown-out detector if the brown-out detector is not needed in the application, this module should be turned off. if the brown-out detector is enabled by the boden fuse, it will be enabled in all sleep modes, and hence, always consume power. in the deeper slee p modes, this will contribute significantly to 49 8151h?avr?02/11 atmega128a the total current consumption. refer to ?brown-out detector? on page 48 for details on how to configure the brown-out detector. 9.9.4 internal voltage reference the internal voltage referenc e will be enabled when needed by the brown-out detector, the analog comparator or the adc. if these modules are disabled as described in the sections above, the internal voltage refe rence will be disabled and it w ill not be consuming power. when turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to ?internal volt- age reference? on page 54 for details on the start-up time. 9.9.5 watchdog timer if the watchdog timer is not needed in the application, this module should be turned off. if the watchdog timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. in the deeper slee p modes, this will contribute signific antly to the total current consump- tion. refer to ?watchdog timer? on page 55 for details on how to configure the watchdog timer. 9.9.6 port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important thing is then to ensure that no pins drive resistive loads. in sleep modes where the both the i/o clock (clk i/o ) and the adc clock (clk adc ) are stopped, the input buffers of the device will be disabled. this ensures that no power is consumed by the input logic when not needed. in some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. refer to the section ?digital input enable and sleep modes? on page 70 for details on which pins are enabled. if the input buffer is enabled and the input signal is left floating or have an analog signal level close to v cc /2, the input buffer will use excessive power. 9.9.7 jtag interface and on-chip debug system if the on-chip debug system is enabled by the ocden fuse and the chip enter power down or power save sleep mode, the main clock source remains enabled. in these sl eep modes, this will contribute significantly to the total current c onsumption. there are three alternative ways to avoid this: ? disable ocden fuse. ? disable jtagen fuse. ? write one to the jtd bit in mcucsr. the tdo pin is left floating when the jtag interf ace is enabled while th e jtag tap controller is not shifting data. if the hardware connected to t he tdo pin does not pull up the logic level, power consumption will increase. note that the tdi pin fo r the next device in the scan chain con- tains a pull-up that avoids this problem. writi ng the jtd bit in the mcucsr register to one or leaving the jtag fuse unprogrammed disables the jtag interface. 50 8151h?avr?02/11 atmega128a 9.10 register description 9.10.1 mcucr - mcu control register the mcu control register contains control bits for power management. ? bit 5 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the sleep mode unle ss it is the pro- grammers purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep instru ction and to clear it imme diately after waking up. ? bits 4:2 ? sm2:0: sleep mode select bits 2, 1, and 0 these bits select betw?een the six available sleep modes as shown in table 9-2 . note: 1. standby mode and extended standby mode are only available with external crystals or resonators. bit 76543210 sre srw10 se sm1 sm0 sm2 ivsel ivce mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 9-2. sleep mode select sm2 sm1 sm0 sleep mode 000idle 0 0 1 adc noise reduction 010power-down 011power-save 100reserved 101reserved 110standby (1) 1 1 1 extended standby (1) 51 8151h?avr?02/11 atmega128a 10. system control and reset 10.1 resetting the avr during reset, all i/o registers are set to their initial values, and the program starts execution from the reset vector. the instruction placed at the reset vector must be a jmp ? absolute jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the app lication section while the interrupt vectors are in the boot section or vice versa. the circuit diagram in figure 10-1 shows the reset logic. the the electrical parameters of the reset circuitry are defined in ?system and reset char- acteristics? on page 324 . the i/o ports of the atmel ? avr ? are immediately reset to their initial state when a reset source goes active. this does not requir e any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay counter is defined by the user th rough the cksel fuses. the different selec- tions for the delay period are presented in ?clock sources? on page 39 . 10.2 reset sources the atmega128a has five sources of reset: ? power-on reset. the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ). ? external reset. the mcu is reset when a low level is present on the reset pin for longer than the minimum pulse length. ? watchdog reset. the mcu is reset when the watchdog timer period expires and the watchdog is enabled. ? brown-out reset. the mcu is re set when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled. ? jtag avr reset. the mcu is reset as long as there is a logic one in the reset register, one of the scan chains of the jtag system. refer to the section ?ieee 1149.1 (jtag) boundary- scan? on page 255 for details. 52 8151h?avr?02/11 atmega128a figure 10-1. reset logic 10.2.1 power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detection level is defined in ?system and reset characteristics? on page 324 . the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a fa ilure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reaching the power-on reset threshold voltage invokes the delay counter, which determines how long the device is kept in reset after v cc rise. the reset signal is acti vated again, without any delay, when v cc decreases below the detection level. figure 10-2. mcu start-up, reset tied to v cc . mcu control and status register (mcucsr) brown-out reset circuit boden bodlevel delay counters cksel[3:0] ck timeout wdrf borf extrf porf data bus clock generator spike filter pull-up resistor jtrf jtag reset register watchdog oscillator sut[1:0] counter reset watchdog timer reset pull-up resistor pen reset circuit l dq q power-on reset circuit v reset time-out internal reset t tout v pot v rst cc 53 8151h?avr?02/11 atmega128a figure 10-3. mcu start-up, reset extended externally 10.2.2 external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see ?system and reset characteristics? on page 324 ) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst on its positive edge, the delay counter starts the mcu after the time-out period t tout has expired. figure 10-4. external reset during operation 10.2.3 brown-out detection atmel ? avr ? atmega128a has an on-chip brown-out detection (bod) circuit for monitoring the v cc level during operation by comparing it to a fixed trigger level. the trigger level for the bod can be selected by the fuse bodlevel to be 2.7v (bod level unprogra mmed), or 4.0v (bodlevel programmed). the trig ger level has a hysteresis to ensure spike free brown-out detection. the hysteresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. the bod circuit can be enabled/ disabled by the fuse boden. when the bod is enabled (boden programmed), and v cc decreases to a value below the trigger level (v bot- in figure 10- 5 ), the brown-out reset is immediately activated. when v cc increases above the trigger level (v bot+ in figure 10-5 ), the delay counter starts the mcu after the time-out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for lon- ger than t bod given in ?system and reset characteristics? on page 324 . reset time-out internal reset t tout v pot v rst v cc cc 54 8151h?avr?02/11 atmega128a figure 10-5. brown-out reset during operation 10.2.4 watchdog reset when the watchdog times out, it will generate a short rese t pulse of 1 ck cycle duration. on the falling edge of this pulse, the delay time r starts counting the time-out period t tout . refer to ?watchdog timer? on page 55 for details on operation of the watchdog timer. figure 10-6. watchdog reset during operation 10.3 internal voltage reference atmel ? avr ? atmega128a features an internal bandgap reference. this reference is used for brown-out detection, and it can be used as an input to the analog comparator or the adc. the 2.56v reference to the adc is generated from the internal bandgap reference. 10.3.1 voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in ?system and reset characteristics? on page 324 . to save power, the reference is not always turned on. the reference is on during the following situations: 1. when the bod is enabled (by programming the boden fuse). 2. when the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). 3. when the adc is enabled. thus, when the bod is not enabled, after setting the acbg bit or enabling the adc, the user must always allow the reference to start up before the output from the analog comparator or v cc reset time-out internal reset v bot- v bot+ t tout ck cc 55 8151h?avr?02/11 atmega128a adc is used. to reduce power consumption in power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering power-down mode. 10.4 watchdog timer the watchdog timer is clocked fr om a separate on-chip oscillato r which runs at 1mhz. this is the typical value at v cc = 5v. see characterization data for typical values at other v cc levels. by controlling the watchdog timer prescaler, the watchdog reset interval can be adjusted as shown in table 10-2 on page 58 . the wdr ? watchdog reset ? instruction resets the watch- dog timer. the watchdog timer is also reset when it is disabled and when a chip reset occurs. eight different clock cycle periods can be selected to determine the reset period. if the reset period expires without another watchdog reset, the atmega128a resets and executes from the reset vector. see ?watchdog reset? on page 54 for timing details. to prevent unintentional disabling of the watchdog or unintentional change of time-out period, 3 different safety levels are selected by the fuses m103c and wdton as shown in table 10-1. safety level 0 corresponds to the setting in atmega103. there is no restriction on enabling the wdt in any of the safety levels. refer to ?timed sequences for changing the configuration of the watchdog timer? on page 55 for details. figure 10-7. watchdog timer 10.5 timed sequences for c hanging the configuration of the watchdog timer the sequence for changing configuration differs s lightly between the three safety levels. sepa- rate procedures are described for each level. table 10-1. wdt configuration as a function of the fuse settings of m103c and wdton. m103c wdton safety level wdt initial state how to disable the wdt how to change time-out unprogrammed unprogrammed 1 disabled timed sequence timed sequence unprogrammed programmed 2 enabled always enabled timed sequence programmed unprogrammed 0 disabled timed sequence no restriction programmed programmed 2 enabled always enabled timed sequence watchdog oscillator 56 8151h?avr?02/11 atmega128a 10.5.1 safety level 0 this mode is compatible with the watchdog operation found in atmega103. the watchdog timer is initially disabled, but can be enabled by writing the wde bit to 1 without any restriction. the time-out period can be changed at any time without restriction. to disable an enabled watchdog timer, the procedure described on page 57 (wde bit description) must be followed. 10.5.2 safety level 1 in this mode, the watchdog time r is initially disabled, but can be enabled by writing the wde bit to 1 without any restriction. a timed sequence is needed when changing the watchdog time-out period or disabling an enabled watchdog time r. to disable an enabled watchdog timer, and/or changing the watchdog time-out, the following procedure must be followed: 1. in the same operation, write a logic one to wdce and wde. a logic one must be writ- ten to wde regardless of the previous value of the wde bit. 2. within the next four clock cycles, in the same operation, write the wde and wdp bits as desired, but with the wdce bit cleared. 10.5.3 safety level 2 in this mode, the watchdog time r is always enabled, and the wde bit will always read as one. a timed sequence is needed when changing the watchdog time-out period. to change the watchdog time-out, the following procedure must be followed: 1. in the same operation, write a logical one to wdce and wde. even though the wde always is set, the wde must be written to one to start the timed sequence. 2. within the next four clock cycles, in the same operation, write the wdp bits as desired, but with the wdce bit cleared. the value written to the wde bit is irrelevant. 10.6 register description 10.6.1 mcucsr - mcu cont rol and status register the mcu control and status register provides information on which reset source caused an mcu reset. note that only extrf and porf are ava ilable in atmega103 compatibility mode. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. ? bit 3 ? wdrf: watchdog reset flag this bit is set if a watchdog re set occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bi t is reset by a power-on reset, or by writing a logic zero to the flag. bit 76543210 jtd ? ? jtrf wdrf borf extrf porf mcucsr read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description 57 8151h?avr?02/11 atmega128a ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcucsr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 10.6.2 wdtcr - watchdog timer control register ? bits 7:5 ? reserved these bits are reserved in the at mega128a and will always read as zero. ? bit 4 ? wdce: watchdog change enable this bit must be set when the wde bit is writte n to logic zero. otherwis e, the watchdog will not be disabled. once written to one, hardware will clear this bit after four clock cycles. refer to the description of the wde bit for a watchdog disable procedure. in safety level 1 and 2, this bit must also be set when changing the prescaler bits. see ?timed sequences for changing the configuration of the watchdog timer? on page 55. ? bit 3 ? wde: watchdog enable when the wde is written to logic one, the watchdog timer is enabled, and if the wde is written to logic zero, the watchdog timer function is di sabled. wde can only be cleared if the wdce bit has logic level one. to disable an enabled watchdog timer, the following procedure must be followed: 1. in the same operation, write a logic one to wdce and wde. a logic one must be writ- ten to wde even though it is set to one before the disable operation starts. 2. within the next four clock cycles, write a logic 0 to wde. this disables the watchdog. in safety level 2, it is not possible to disable the watchdog timer, even with the algorithm described above. see ?timed sequences for changing the configuration of the watchdog timer? on page 55. ? bits 2:0 ? wdp2, wdp1, wdp0: watchdog timer prescaler 2, 1, and 0 the wdp2, wdp1, and wdp0 bits determine the watchdog timer prescaling when the watch- dog timer is enabled. the different prescaling values and their corresponding timeout periods are shown in table 10-2 . bit 76543210 ? ? ? wdce wde wdp2 wdp1 wdp0 wdtcr read/write r r r r/w r/w r/w r/w r/w initial value00000000 58 8151h?avr?02/11 atmega128a the following code example shows one assembly and one c function for turning off the wdt. the example assumes that interrupts are controlled (for example by disabling interrupts globally) so that no interrupts will occur duri ng execution of these functions. table 10-2. watchdog timer prescale select wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 3.0v typical time-out at v cc = 5.0v 0 0 0 16k (16,384) 14.8ms 14.0ms 0 0 1 32k (32,768) 29.6ms 28.1ms 0 1 0 64k (65,536) 59.1ms 56.2ms 0 1 1 128k (131,072) 0.12s 0.11s 1 0 0 256k (262,144) 0.24s 0.22s 1 0 1 512k (524,288) 0.47s 0.45s 1 1 0 1,024k (1,048,576) 0.95s 0.9s 1 1 1 2,048k (2,097,152) 1.9s 1.8s assembly code example wdt_off: ; reset wdt wdr in r16, wdtcr ; write logical one to wdce and wde ori r16, (1< 60 8151h?avr?02/11 atmega128a notes: 1. when the bootrst fuse is programmed, th e device will jump to the boot loader address at reset, see ?boot loader support ? read-while-write self-programming? on page 277 . 2. when the ivsel bit in mcucr is set, interrupt vectors will be moved to the start of the boot flash section. the address of each interrupt vector will then be address in this table added to the start address of the boot flash section. 3. the interrupts on address $0030 - $0044 do not exist in atmega103 compatibility mode. table 11-2 shows reset and interrupt vectors placement for the various combinations of bootrst and ivsel settings. if the program never enables an in terrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the application sect ion while the interrupt vectors are in the boot section or vice versa. note: the boot reset address is shown in table 25-6 on page 288 . for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. the most typical and general program setup for the reset and interrupt vector addresses in atmega128a is: address labelscode comments $0000 jmp reset ; reset handler $0002 jmp ext_int0 ; irq0 handler $0004 jmp ext_int1 ; irq1 handler $0006 jmp ext_int2 ; irq2 handler $0008 jmp ext_int3 ; irq3 handler $000a jmp ext_int4 ; irq4 handler $000c jmp ext_int5 ; irq5 handler $000e jmp ext_int6 ; irq6 handler $0010 jmp ext_int7 ; irq7 handler $0012 jmp tim2_comp ; timer2 compare handler 28 $0036 (3) timer3 compb timer/count er3 compare match b 29 $0038 (3) timer3 compc timer/count er3 compare match c 30 $003a (3) timer3 ovf timer/counter3 overflow 31 $003c (3) usart1, rx usart1, rx complete 32 $003e (3) usart1, udre usart1 data register empty 33 $0040 (3) usart1, tx usart1, tx complete 34 $0042 (3) twi two-wire serial interface 35 $0044 (3) spm ready store program memory ready table 11-2. reset and interrupt vectors placement bootrst ivsel reset address interrupt vectors start address 1 0 $0000 $0002 1 1 $0000 boot reset address + $0002 0 0 boot reset address $0002 0 1 boot reset address boot reset address + $0002 table 11-1. reset and interrupt vectors (continued) vector no. program address (2) source interrupt definition 61 8151h?avr?02/11 atmega128a $0014 jmp tim2_ovf ; timer2 overflow handler $0016 jmp tim1_capt ; timer1 capture handler $0018 jmp tim1_compa; timer1 comparea handler $001a jmp tim1_compb; timer1 compareb handler $001c jmp tim1_ovf ; timer1 overflow handler $001e jmp tim0_comp ; timer0 compare handler $0020 jmp tim0_ovf ; timer0 overflow handler $0022 jmp spi_stc ; spi transfer complete handler $0024 jmp usart0_rxc; usart0 rx complete handler $0026 jmp usart0_dre; usart0,udr empty handler $0028 jmp usart0_txc; usart0 tx complete handler $002a jmp adc ; adc conversion complete handler $002c jmp ee_rdy ; eeprom ready handler $002e jmp ana_comp ; analog comparator handler $0030 jmp tim1_compc; timer1 comparec handler $0032 jmp tim3_capt ; timer3 capture handler $0034 jmp tim3_compa; timer3 comparea handler $0036 jmp tim3_compb; timer3 compareb handler $0038 jmp tim3_compc; timer3 comparec handler $003a jmp tim3_ovf ; timer3 overflow handler $003c jmp usart1_rxc; usart1 rx complete handler $003e jmp usart1_dre; usart1,udr empty handler $0040 jmp usart1_txc; usart1 tx complete handler $0042 jmp twi ; two-wire serial interface interrupt handler $0044 jmp spm_rdy ; spm ready handler ; $0046 reset:ldir16, high(ramend); main program start $0047 out sph,r16 ; set stack pointer to top of ram $0048 ldi r16, low(ramend) $0049 out spl,r16 $004a sei ; enable interrupts $004b 62 8151h?avr?02/11 atmega128a $f004 jmp ext_int1 ; irq1 handler :. :. :. ; $f044 jmp spm_rdy ; store program memory ready handler when the bootrst fuse is programmed and the boot section size set to 8 kbytes, the most typical and general program setup for the reset and interrupt vector addresses is: address labelscode comments .org $0002 $0002 jmp ext_int0 ; irq0 handler $0004 jmp ext_int1 ; irq1 handler :. :. :. ; $0044 jmp spm_rdy ; store program memory ready handler ; .org $f000 $f000 reset: ldi r16,high(ramend); main program start $f001 out sph,r16 ; set stack pointer to top of ram $f002 ldi r16,low(ramend) $f003 out spl,r16 $f004 sei ; enable interrupts $f005 63 8151h?avr?02/11 atmega128a 11.2 register description 11.2.1 mcucr - mcu control register ? bit 1 ? ivsel: interrupt vector select when the ivsel bit is cleared (zero), the interrupt vectors are placed at the start of the flash memory. when this bit is set (one), the interrupt vectors are moved to the beginning of the boot loader section of the flash. the actual address of the start of the boot flash section is deter- mined by the bootsz fuses. refer to the section ?boot loader support ? read-while-write self-programming? on page 277 for details. to avoid unintentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit: 1. write the interrupt vector change enable (ivce) bit to one. 2. within four cycles, write the desired valu e to ivsel while writing a zero to ivce. interrupts will automatically be di sabled while this sequence is executed. interrupts are disabled in the cycle ivce is set, and they remain disabl ed until after the instru ction following the write to ivsel. if ivsel is not written, interrupts remain disabled for four cycles. the i-bit in the status register is unaffected by the automatic disabling. note: if interrupt vectors are placed in the boot loa der section and boot lock bit blb02 is programmed, interrupts are disabled while executing from the ap plication section. if interrupt vectors are placed in the application section and boot lock bit blb 12 is programed, interrupts are disabled while executing from the boot loader section. refer to the section ?boot loader support ? read-while- write self-programming? on page 277 for details on boot lock bits. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be written to logic one to enable change of the ivsel bit. ivce is cleared by hardware four cyc les after it is written or when ivsel is written. sett ing the ivce bit will disable interrupts, as explained in the ivsel description above. see code example below. bit 76543210 sre srw10 se sm1 sm0 sm2 ivsel ivce mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 64 8151h?avr?02/11 atmega128a assembly code example move_interrupts: ; enable change of interrupt vectors ldi r16, (1< 66 8151h?avr?02/11 atmega128a functions? on page 71 . refer to the individual module sectio ns for a full description of the alter- nate functions. note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. 12.2 ports as gener al digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 12-2 shows a func- tional description of one i/o port pin, here generically called pxn. figure 12-2. general digital i/o (1) note: 1. wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 12.2.1 configuring the pin each port pin consists of three register bits: ddxn, portxn, and pinxn. as shown in ?register description? on page 86 , the ddxn bits are accessed at the ddrx i/o address, the portxn bits at the portx i/o address, and the pinxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direct ion of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero, pxn is configured as an input pin. clk rpx rrx wpx rdx wdx pud synchronizer wdx: write ddrx wpx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data bus sleep sleep: sleep control pxn i/o 67 8151h?avr?02/11 atmega128a if portxn is written logic one when the pin is c onfigured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when a reset condition becomes active, even if no clocks are running. if portxn is written logic one when the pin is conf igured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). when switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled ({ddxn, portxn} = 0b01) or output low ({ddxn, portxn} = 0b10) must occur. norma lly, the pull-up enabled state is fully accept- able, as a high-impedant enviro nment will not notice the differenc e between a strong high driver and a pull-up. if this is not the case, the pud bit in the sfior register can be written to one to disable all pull-ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b11) as an intermediate step. table 12-3 summarizes the control signals for the pin value. 12.2.2 reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pinxn register bit. as shown in figure 12-2 , the pinxn register bit and the preceding latch con- stitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 12-4 shows a timing dia- gram of the synchronization when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. figure 12-3. port pin configurations ddxn portxn pud (in sfior) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source) 68 8151h?avr?02/11 atmega128a figure 12-4. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of th e system clock. the latch is closed when the clock is low, and goes transpa rent when the clock is high, as indicated by the shaded region of the ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn register at the succeeding positive clock edge. as indi- cated by the two arrows t pd,max and t pd,min , a single signal transiti on on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in figure 12-5 . the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay t pd through the synchronizer is one system clock period. system clk instructions sync latch pinxn r17 in r17, pinx 0xff 0x00 t pd, max xxx xxx t pd, min 69 8151h?avr?02/11 atmega128a figure 12-5. synchronization when reading a software assigned pin value the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. nop in r17, pinx 0xff 0x00 0xff t pd out portx, r16 system clk r16 instructions sync latch pinxn r17 70 8151h?avr?02/11 atmega128a note: 1. for the assembly program, two temporary registers are used to minimize the time from pull- ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. 12.2.3 digital input enable and sleep modes as shown in figure 12-2 , the digital input signal can be clamped to ground at the input of the schmitt-trigger. the signal denot ed sleep in the figure, is set by the mcu sleep controller in power-down mode, power-save mode, standby mode, and extended standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as exte rnal interrupt pins. if the external interrupt request is not enabled, sleep is active also fo r these pins. sleep is also overridden by vari- ous other alternate functions as described in ?alternate port functions? on page 71 . if a logic high level (?one?) is present on an asynchronous external interrupt pin configured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding external interrupt flag will be set when resuming from the above mentioned sleep modes, as the clamping in these sleep modes produces the requested logic change. assembly code example (1) :. ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 72 8151h?avr?02/11 atmega128a note: 1. wpx, wdx, rlx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. table 12-1 summarizes the function of the overriding signals. the pin and port indexes from fig- ure 12-6 are not shown in the succeeding tables. the overriding signals are generated internally in the modules having the alternate function. the following subsections shortly describes the alte rnate functions for each port, and relates the overriding signals to the alternate function. refer to the alternate function description for further details. table 12-1. generic description of overriding signals for alternate functions. signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, t he port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is clea red, the digital input enable is determined by mcu-state (normal mode, sleep modes). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regard less of the mcu state (normal mode, sleep modes). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/from alternate functions. the signal is connected directly to the pad, and can be used bi- directionally. 73 8151h?avr?02/11 atmega128a 12.3.1 alternate functions of port a the port a has an alternate function as the address low byte and data lines for the external memory interface. table 12-3 and table 12-4 relates the alternate functions of port a to the overriding signals shown in figure 12-6 on page 71 . note: 1. ada is short for address active and represents the time when address is output. see ?exter- nal memory interface? on page 22 for details. table 12-2. port a pins alternate functions port pin alternate function pa7 ad7 (external memory interface address and data bit 7) pa6 ad6 (external memory interface address and data bit 6) pa5 ad5 (external memory interface address and data bit 5) pa4 ad4 (external memory interface address and data bit 4) pa3 ad3 (external memory interface address and data bit 3) pa2 ad2 (external memory interface address and data bit 2) pa1 ad1 (external memory interface address and data bit 1) pa0 ad0 (external memory interface address and data bit 0) table 12-3. overriding signals for alternate functions in pa7:pa4 signal name pa7/ad7 pa6/ad6 pa5/ad5 pa4/ad4 puoe sre sre sre sre puov ~(wr | ada (1) ) ? porta7 ? pud ~(wr | ada) ? porta6 ? pud ~(wr | ada) ? porta5 ? pud ~(wr | ada) ? porta4 ? pud ddoe sre sre sre sre ddov wr | ada wr | ada wr | ada wr | ada pvoe sre sre sre sre pvov a7 ? ada | d7 output ? wr a6 ? ada | d6 output ? wr a5 ? ada | d5 output ? wr a4 ? ada | d4 output ? wr dieoe0000 dieov0000 di d7 input d6 input d5 input d4 input aio???? 74 8151h?avr?02/11 atmega128a 12.3.2 alternate functions of port b the port b pins with alternate functions are shown in table 12-5 . note: 1. oc1c not applicable in atmega103 compatibility mode. the alternate pin configuration is as follows: ? oc2/oc1c, bit 7 oc2, output compare match output: the pb7 pin can serve as an external output for the timer/counter2 output compare. the pin has to be configured as an output (ddb7 set ?one?) to serve this function. the oc2 pin is also t he output pin for the pwm mode timer function. oc1c, output compare match c output: the pb7 pi n can serve as an external output for the timer/counter1 output compare c. the pin has to be configured as an output (ddb7 set (one)) to serve this function. the oc1c pin is also the output pin for the pwm mode timer function. table 12-4. overriding signals for alternate functions in pa3:pa0 signal name pa3/ad3 pa2/ad2 pa1/ad1 pa0/ad0 puoe sre sre sre sre puov ~(wr | ada) ? porta3 ? pud ~(wr | ada) ? porta2 ? pud ~(wr | ada) ? porta1 ? pud ~(wr | ada) ? porta0 ? pud ddoe sre sre sre sre ddov wr | ada wr | ada wr | ada wr | ada pvoe sre sre sre sre pvov a3 ? ada | d3 output ? wr a2? ada | d2 output ? wr a1 ? ada | d1 output ? wr a0 ? ada | d0 output ? wr dieoe0000 dieov0000 di d3 input d2 input d1 input d0 input aio???? table 12-5. port b pins alternate functions port pin alternate functions pb7 oc2/oc1c (1) (output compare and pwm output for timer/counter2 or output compare and pwm output c for timer/counter1) pb6 oc1b (output compare and pwm output b for timer/counter1) pb5 oc1a (output compare and pwm output a for timer/counter1) pb4 oc0 (output compare and pwm output for timer/counter0) pb3 miso (spi bus master input/slave output) pb2 mosi (spi bus master output/slave input) pb1 sck (spi bus serial clock) pb0 ss (spi slave select input) 75 8151h?avr?02/11 atmega128a ? oc1b, bit 6 oc1b, output compare match b output: the pb6 pin can serve as an external output for the timer/counter1 output compare b. the pin has to be configured as an output (ddb6 set (one)) to serve this function. the oc1b pin is also the output pin for the pwm mode timer function. ? oc1a, bit 5 oc1a, output compare match a output: the pb5 pin can serve as an external output for the timer/counter1 output compare a. the pin has to be configured as an output (ddb5 set (one)) to serve this function. the oc1a pin is also the output pin for the pwm mode timer function. ? oc0, bit 4 oc0, output compare match output: the pb4 pin can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddb4 set (one)) to serve this function. the oc0 pin is also t he output pin for the pwm mode timer function. ? miso ? port b, bit 3 miso: master data input, slave data output pin for spi channel. when the spi is enabled as a master, this pin is configured as an input r egardless of the setting of ddb3. when the spi is enabled as a slave, the data direction of this pi n is controlled by ddb3. when the pin is forced to be an input, the pull- up can still be controlled by the portb3 bit. ? mosi ? port b, bit 2 mosi: spi master data output, slave data input for spi channel. when the spi is enabled as a slave, this pin is configured as an input regar dless of the setting of ddb2. when the spi is enabled as a master, the data direction of this pi n is controlled by ddb2. when the pin is forced to be an input, the pull-up can st ill be controlled by the portb2 bit. ? sck ? port b, bit 1 sck: master clock output, slave clock input pin for spi channel. when the spi is enabled as a slave, this pin is configured as an input regar dless of the setting of ddb1. when the spi is enabled as a master, the data direction of this pi n is controlled by ddb1. when the pin is forced to be an input, the pull-up can st ill be controlled by the portb1 bit. ?ss ? port b, bit 0 ss : slave port select input. when the spi is enab led as a slave, this pin is configured as an input regardless of the setting of ddb0. as a slav e, the spi is activated when this pin is driven low. when the spi is enabled as a master, the data di rection of this pin is controlled by ddb0. when the pin is forced to be an input, the pull-up can still be controlled by the portb0 bit. table 12-6 and table 12-7 relate the alternate functions of port b to the overriding signals shown in figure 12-6 on page 71 . spi mstr input and spi sl ave output constitute the miso signal, while mosi is divided in to spi mstr output and spi slave input. 76 8151h?avr?02/11 atmega128a note: 1. see ?output compare modulator (ocm1c2)? on page 163 for details. oc1c does not exist in atmega103 compatibility mode. 12.3.3 alternate functions of port c in atmega103 comp atibility mode, port c is output only. the atmega128a is by default shipped in compatibility mode. thus , if the parts are not programm ed before they are put on the pcb, portc will be output during first power up, and until the atme ga103 compatibility mode is disabled. the port c has an alternate function as the address high byte for the external mem- ory interface. table 12-6. overriding signals for alternate functions in pb7:pb4 signal name pb7/oc2/oc1c pb6/oc1b pb5/oc1a pb4/oc0 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc2/oc1c enable (1) oc1b enable oc1a enable oc0 enable pvov oc2/oc1c (1) oc1b oc1a oc0b dieoe 0 0 0 0 dieov 0 0 0 0 di ? ? ? ? aio ? ? ? ? table 12-7. overriding signals for alternate functions in pb3:pb0 signal name pb3/miso pb2/mosi pb1/sck pb0/ss puoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr puov portb3 ? pud portb2 ? pud portb1 ? pud portb0 ? pud ddoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr ddov 0 0 0 0 pvoe spe ? mstr spe ? mstr spe ? mstr 0 pvov spi slave output spi mstr output sck output 0 dieoe 0 0 0 0 dieov 0 0 0 0 di spi mstr input spi slave input sck input spi ss aio ? ? ? ? 77 8151h?avr?02/11 atmega128a table 12-9 and table 12-10 relate the alternate functions of port c to the overriding signals shown in figure 12-6 on page 71 . note: 1. xmm = 0 in atmega103 compatibility mode. table 12-8. port c pins alternate functions port pin alternate function pc7 a15 pc6 a14 pc5 a13 pc4 a12 pc3 a11 pc2 a10 pc1 a9 pc0 a8 table 12-9. overriding signals for alte rnate functions in pc7:pc4 signal name pc7/a15 pc6/a14 pc5/a13 pc4/a12 puoe sre ? (xmm (1) <1) sre ? (xmm<2) sre ? (xmm<3) sre ? (xmm<4) puov0 000 ddoe sre ? (xmm<1) sre ? (xmm<2) sre ? (xmm<3) sre ? (xmm<4) ddov 1 1 1 1 pvoe sre ? (xmm<1) sre ? (xmm<2) sre ? (xmm<3) sre ? (xmm<4) pvov a15 a14 a13 a12 dieoe0 000 dieov0 000 di? ??? aio? ??? 78 8151h?avr?02/11 atmega128a note: 1. xmm = 0 in atmega103 compatibility mode. 12.3.4 alternate functions of port d the port d pins with alternate functions are shown in table 12-11 . note: 1. xck1, txd1, rxd1, sda, and scl not applicable in atmega103 compatibility mode. the alternate pin configuration is as follows: ? t2 ? port d, bit 7 t2, timer/counter2 counter source. ? t1 ? port d, bit 6 t1, timer/counter1 counter source. ? xck1 ? port d, bit 5 xck1, usart1 external clock. th e data direction register (ddd4) controls whether the clock is output (ddd4 set) or input (ddd4 cleared). the xck1 pin is active only when the usart1 operates in synchronous mode. table 12-10. overriding signals for alte rnate functions in pc3:pc0 (1) signal name pc3/a11 pc2/a10 pc1/a9 pc0/a8 puoe sre ? (xmm<5) sre ? (xmm<6) sre ? (xmm<7) sre ? (xmm<7) puov0000 ddoe sre ? (xmm<5) sre ? (xmm<6) sre ? (xmm<7) sre ? (xmm<7) ddov 1 1 1 1 pvoe sre ? (xmm<5) sre ? (xmm<6) sre ? (xmm<7) sre ? (xmm<7) pvov a11 a10 a9 a8 dieoe0000 dieov0000 di???? aio???? table 12-11. port d pins alternate functions port pin alternate function pd7 t2 (timer/counter2 clock input) pd6 t1 (timer/counter1 clock input) pd5 xck1 (1) (usart1 external clock input/output) pd4 icp1 (timer/counter1 input capture pin) pd3 int3 /txd1 (1) (external interrupt3 input or uart1 transmit pin) pd2 int2/rxd1 (1) (external interrupt2 input or uart1 receive pin) pd1 int1 /sda (1) (external interrupt1 input or twi serial data) pd0 int0 /scl (1) (external interrupt0 input or twi serial clock) 79 8151h?avr?02/11 atmega128a ? icp1 ? port d, bit 4 icp1 ? input capture pin1: the pd4 pin can act as an input capture pin for timer/counter1. ?int3 /txd1 ? port d, bit 3 int3, external interrupt source 3: the pd3 pin c an serve as an external interrupt source to the mcu. txd1, transmit data (data output pin for t he usart1). when the usart1 transmitter is enabled, this pin is configured as an output regardless of the value of ddd3. ?int2 /rxd1 ? port d, bit 2 int2, external interrupt source 2. the pd2 pin can serve as an external interrupt source to the mcu. rxd1, receive data (data input pin for the u sart1). when the usart1 receiver is enabled this pin is configured as an input regardless of the value of ddd2. when the usart forces this pin to be an input, the pull-up can still be controlled by the portd2 bit. ?int1 /sda ? port d, bit 1 int1, external interrupt source 1. the pd1 pin c an serve as an external interrupt source to the mcu. sda, two-wire serial interface data: when the twen bit in twcr is set (one) to enable the two-wire serial interface, pin pd1 is disconnected from the port and becomes the serial data i/o pin for the two-wire serial interface. in this mode, there is a spike filter on the pin to sup- press spikes shorter than 50 ns on the input signal , and the pin is driven by an open drain driver with slew-rate limitation. ?int0 /scl ? port d, bit 0 int0, external interrupt source 0. the pd0 pin c an serve as an external interrupt source to the mcu. scl, two-wire serial interface clock: when the twen bit in twcr is set (one) to enable the two-wire serial interface, pin pd0 is disconnec ted from the port and bec omes the serial clock i/o pin for the two-wire serial interface. in this mode, there is a spike filter on the pin to sup- press spikes shorter than 50 ns on the input signal , and the pin is driven by an open drain driver with slew-rate limitation. table 12-12 and table 12-13 relates the alternate functions of port d to the overriding signals shown in figure 12-6 on page 71 . 80 8151h?avr?02/11 atmega128a note: 1. when enabled, the two-wire serial interfac e enables slew-rate controls on the output pins pd0 and pd1. this is not shown in this table. in addition, spike filters are connected between the aio outputs shown in the port figure and the digital logic of the twi module. table 12-12. overriding signals for alternate functions pd7:pd4 signal name pd7/t2 pd 6/t1 pd5/xck1 pd4/icp1 puoe000 0 puov000 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 0 umsel1 0 pvov 0 0 xck1 output 0 dieoe000 0 dieov000 0 di t2 input t1 input xck1 input icp1 input aio ??? ? table 12-13. overriding signals for alte rnate functions in pd3:pd0 (1) signal name pd3/int3/t xd1 pd2/int2/rxd1 pd1/int1/sda pd0/int0/scl puoe txen1 rxen1 twen twen puov 0 portd2 ? pud portd1 ? pud portd0 ? pud ddoe txen1 rxen1 twen twen ddov 1 0 sda_out scl_out pvoe txen1 0 twen twen pvov txd1 0 0 0 dieoe int3 enable int2 enab le int1 enable int0 enable dieov 1 1 1 1 di int3 input int2 input/rxd1 int1 input int0 input aio ? ? sda input scl input 81 8151h?avr?02/11 atmega128a 12.3.5 alternate functions of port e the port e pins with alternate functions are shown in table 12-14 . note: 1. icp3, t3, oc3c, oc3b, oc3b, oc3a, and xck0 not applicable in atmega103 compatibility mode. ? int7/icp3 ? port e, bit 7 int7, external interrupt source 7: the pe7 pin can serve as an external interrupt source. icp3 ? input capture pin3: the pe7 pin can ac t as an input capture pin for timer/counter3. ? int6/t3 ? port e, bit 6 int6, external interrupt source 6: the pe6 pin can serve as an external interrupt source. t3, timer/counter3 counter source. ? int5/oc3c ? port e, bit 5 int5, external interrupt source 5: the pe5 pin can serve as an external interrupt source. oc3c, output compare match c output: the pe5 pin can serve as an external output for the timer/counter3 output compare c. the pin has to be configured as an output (dde5 set ?one?) to serve this function. the oc3c pin is also the output pin for the pwm mode timer function. int4/oc3b ? port e, bit 4 int4, external interrupt source 4: the pe4 pin can serve as an external interrupt source. oc3b, output compare match b output: the pe4 pin can serve as an external output for the timer/counter3 output compare b. the pin has to be configured as an output (dde4 set (one)) to serve this function. the oc3b pin is also the output pin for the pwm mode timer function. ? ain1/oc3a ? port e, bit 3 ain1 ? analog comparator negative input. this pi n is directly connected to the negative input of the analog comparator. oc3a, output compare match a output: the pe3 pin can serve as an external output for the timer/counter3 output compare a. the pin has to be configured as an output (dde3 set ?one?) to serve this function. the oc3a pin is also the output pin for the pwm mode timer function. table 12-14. port e pins alternate functions port pin alternate function pe7 int7/icp3 (1) (external interrupt 7 input or timer/counter3 input capture pin) pe6 int6/ t3 (1) (external interrupt 6 input or timer/counter3 clock input) pe5 int5/oc3c (1) (external interrupt 5 input or ou tput compare and pwm output c for timer/counter3) pe4 int4/oc3b (1) (external interrupt4 input or ou tput compare and pwm output b for timer/counter3) pe3 ain1/oc3a (1) (analog comparator negative input or output compare and pwm output a for timer/counter3) pe2 ain0/xck0 (1) (analog comparator positive input or usart0 external clock input/output) pe1 pdo/txd0 (programming data output or uart0 transmit pin) pe0 pdi/rxd0 (programming data input or uart0 receive pin) 82 8151h?avr?02/11 atmega128a ? ain0/xck0 ? port e, bit 2 ain0 ? analog comparator positive input. this pin is directly connected to the positive input of the analog comparator. xck0, usart0 external clock. th e data direction register (dde2) controls whether the clock is output (dde2 set) or input (dde2 cleared) . the xck0 pin is active only when the usart0 operates in synchronous mode. ? pdo/txd0 ? port e, bit 1 pdo, spi serial programming data output. duri ng serial program downloading, this pin is used as data output line for the atmega128a. txd0, uart0 transmit pin. ? pdi/rxd0 ? port e, bit 0 pdi, spi serial programming data input. during serial program downloading, this pin is used as data input line for the atmega128a. rxd0, usart0 receive pin. receive data (data input pin for the usart0). when the usart0 receiver is enabled this pin is configur ed as an input regardless of the value of ddre0. when the usart0 forces this pi n to be an input, a logical one in porte0 will turn on the inter- nal pull-up. table 12-15 and table 12-16 relates the alternate functions of port e to the overriding signals shown in figure 12-6 on page 71 . table 12-15. overriding signals for alternate functions pe7:pe4 signal name pe7/int7/icp3 pe6/int6/t3 pe5/int5/oc3c pe4/int4/oc3b puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 0 oc3c enable oc3b enable pvov 0 0 oc3c oc3b dieoe int7 enable int6 enabl e int5 enable int4 enable dieov 1 1 1 1 di int7 input/icp3 input int7 input/t3 input int5 input int4 input aio ? ? ? ? 83 8151h?avr?02/11 atmega128a 12.3.6 alternate functions of port f the port f has an alternate function as analog input for the adc as shown in table 12-17 . if some port f pins are configured as outputs, it is essential that these do not switch when a con- version is in progress. this might corrupt the result of the conversion. in atmega103 compatibility mode port f is input only. if the jtag interface is enabled, the pull- up resistors on pinspf7(tdi), pf5(tms), and pf4(tck) will be activated even if a reset occurs. ? tdi, adc7 ? port f, bit 7 adc7, analog to digital converter, channel 7 . tdi, jtag test data in: serial input data to be shifted in to the instruction register or data reg- ister (scan chains). when the jtag interface is enabled, this pin can not be used as an i/o pin. ? tdo, adc6 ? port f, bit 6 adc6, analog to digital converter, channel 6 . tdo, jtag test data out: serial output data from instruction register or data register. when the jtag interface is enabled, this pin can not be used as an i/o pin. the tdo pin is tri-stated unless tap states that shift out data are entered. table 12-16. overriding signals for alternate functions in pe3:pe0 signal name pe3/ain1/oc3a pe2/ain 0/xck0 pe1/pdo/txd0 pe0/pdi/rxd0 puoe 0 0 txen0 rxen0 puov 0 0 0 porte0 ? pud ddoe 0 0 txen0 rxen0 ddov 0 0 1 0 pvoe oc3b enable umsel0 txen0 0 pvov oc3b xck0 output txd0 0 dieoe 0 0 0 0 dieov 0 0 0 0 di 0 xck0 input ? rxd0 aio ain1 input ain0 input ? ? table 12-17. port f pins alternate functions port pin alternate function pf7 adc7/tdi (adc input channel 7 or jtag test data input) pf6 adc6/tdo (adc input channel 6 or jtag test data output) pf5 adc5/tms (adc input channel 5 or jtag test mode select) pf4 adc4/tck (adc input channel 4 or jtag test clock) pf3 adc3 (adc input channel 3) pf2 adc2 (adc input channel 2) pf1 adc1 (adc input channel 1) pf0 adc0 (adc input channel 0) 84 8151h?avr?02/11 atmega128a ? tms, adc5 ? port f, bit 5 adc5, analog to digital converter, channel 5 . tms, jtag test mode select: this pin is used fo r navigating through the tap-controller state machine. when the jtag interface is enabled, this pin can not be used as an i/o pin. ? tck, adc4 ? port f, bit 4 adc4, analog to digital converter, channel 4 . tck, jtag test clock: jtag operation is synch ronous to tck. when the jtag interface is enabled, this pin can not be used as an i/o pin. ? adc3 ? adc0 ? port f, bit 3:0 analog to digital converter, channel 3:0. table 12-18. overriding signals for alternate functions in pf7:pf4 signal name pf7/adc7/tdi pf6/adc6/tdo pf5/adc5/tms pf4/adc4/tck puoe jtagen jtagen jtagen jtagen puov 1 0 1 1 d d o e j tag e n j tag e n j tag e n j tag e n ddov 0 shift_ir + shift_dr 00 pvoe 0 jtagen 0 0 pvov 0 tdo 0 0 d i e o e j tag e n j tag e n j tag e n j tag e n dieov 0 0 0 0 di ? ? ? ? aio tdi/adc7 input adc6 input tms/adc5 input tckadc4 input table 12-19. overriding signals for alternate functions in pf3:pf0 signal name pf3/adc3 pf2/adc2 pf1/adc1 pf0/adc0 puoe0000 puov0000 ddoe0000 ddov0000 pvoe0000 pvov0000 dieoe0000 dieov0000 di???? aio adc3 input adc2 input adc1 input adc0 input 85 8151h?avr?02/11 atmega128a 12.3.7 alternate functions of port g in atmega103 compatibility mode, only the alternate functions are the defaults for port g, and port g cannot be used as general digital port pi ns. the alternate pin configuration is as follows: ? tosc1 ? port g, bit 4 tosc1, timer oscillator pin 1: when the as0 bit in assr is se t (one) to enabl e asynchronous clocking of timer/counter0, pin pg4 is disconnected from the port, and becomes the input of the inverting oscillator amplifier. in this mode, a cr ystal oscillator is connected to this pin, and the pin can not be used as an i/o pin. ? tosc2 ? port g, bit 3 tosc2, timer oscillator pin 2: when the as0 bit in assr is se t (one) to enabl e asynchronous clocking of timer/counter0, pin pg3 is disconnected from the port, and becomes the inverting output of the oscillator amplifier. in this mode , a crystal oscillator is connected to this pin, and the pin can not be used as an i/o pin. ? ale ? port g, bit 2 ale is the external data memory address latch enable signal. ?rd ? port g, bit 1 rd is the external data memory read control strobe. ?wr ? port g, bit 0 wr is the external data memory write control strobe. table 12-20. port g pins alternate functions port pin alternate function pg4 tosc1 (rtc oscillator timer/counter0) pg3 tosc2 (rtc oscillator timer/counter0) pg2 ale (address latch enable to external memory) pg1 rd (read strobe to external memory) pg0 wr (write strobe to external memory) 86 8151h?avr?02/11 atmega128a table 12-21 and table 12-22 relates the alternate functions of port g to the overriding signals shown in figure 12-6 on page 71 . 12.4 register description 12.4.1 sfior - special function io register ? bit 2 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see ?con- figuring the pin? on page 66 for more details about this feature. table 12-21. overriding signals for alternate functions in pg4:pg1 signal name pg4/tosc1 pg3/tosc2 pg2/ale pg1/rd puoe as0 as0 sre sre puov 0 0 0 0 ddoe as0 as0 sre sre ddov 0 0 1 1 pvoe 0 0 sre sre pvov 0 0 ale rd dieoe as0 as0 0 0 dieov 0 0 0 0 di ? ? ? ? aio t/c0 osc input t/c0 osc output ? ? table 12-22. overriding signals for alternate functions in pg0 signal name pg0/wr puoe sre puov 0 ddoe sre ddov 1 pvoe sre pvov wr dieoe 0 dieov 0 di ? aio ? bit 7 6 5 4 3 2 1 0 tsm ? ? ? acme pud psr0 psr321 sfior read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 87 8151h?avr?02/11 atmega128a 12.4.2 porta - port a data register 12.4.3 ddra - port a da ta direction register 12.4.4 pina - port a input pins address 12.4.5 portb - port b data register 12.4.6 ddrb - port b da ta direction register 12.4.7 pinb - port b input pins address 12.4.8 portc - port c data register 12.4.9 ddrc - port c da ta direction register bit 76543210 porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 porta read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 dda7 dda6 dda5 dda4 dda3 dda2 dda1 dda0 ddra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 7 6543210 pina7 pina6 pina5 pina4 pina3 pina2 pina1 pina0 pina read/writer rrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 pinb read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portc7 portc6 portc5 portc4 portc3 portc2 portc1 portc0 portc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ddc7 ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 ddrc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 88 8151h?avr?02/11 atmega128a 12.4.10 pinc - port c input pins address in atmega103 compatibilit y mode, ddrc and pinc registers are initialized to being push-pull zero output. the port pins assumes their initial value, even if the clock is not running. note that the ddrc and pinc registers are available in atmega103 compatibility mode, and should not be used for 100% back-ward compatibility. 12.4.11 portd - port d data register 12.4.12 ddrd - port d da ta direction register 12.4.13 pind - port d input pins address 12.4.14 porte - port e data register 12.4.15 ddre - port e data direction register 12.4.16 pine - port e input pins address bit 76543210 pinc7 pinc6 pinc5 pinc4 pi nc3 pinc2 pinc1 pinc0 pinc read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 portd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 pind read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 porte7 porte6 porte5 porte4 porte3 porte2 porte1 porte0 porte read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 dde7 dde6 dde5 dde4 dde3 dde2 dde1 dde0 ddre read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pine7 pine6 pine5 pine4 pine3 pine2 pine1 pine0 pinf read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a 89 8151h?avr?02/11 atmega128a 12.4.17 portf - port f data register 12.4.18 ddrf - port f data direction register 12.4.19 pinf - port f input pins address note that portf and ddrf registers are no t available in atmega103 compatibility mode where port f serves as digital input only. 12.4.20 portg - port g data register 12.4.21 ddrg - port g data direction register 12.4.22 ping - port g input pins address note that portg, ddrg, and ping are not av ailable in atme ga103 compatibility mode. in the atmega103 compatibility mode po rt g serves its alternate fu nctions only (tosc1, tosc2, wr , rd and ale). bit 76543210 portf7 portf6 portf5 portf4 portf3 portf2 portf1 portf0 portf read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddf7 ddf6 ddf5 ddf4 ddf3 ddf2 ddf1 ddf0 ddrf read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pinf7 pinf6 pinf5 pinf4 pinf3 pinf2 pinf1 pinf0 pinf read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 ??? portg4 portg3 portg2 portg1 portg0 portg read/write r r r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ? ? ? ddg4 ddg3 ddg2 ddg1 ddg0 ddrg read/write r r r r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ? ? ? ping4 ping3 ping2 ping1 ping0 ping read/writerrrrrrrr initial value 0 0 0 n/a n/a n/a n/a n/a 90 8151h?avr?02/11 atmega128a 13. external interrupts the external interrupts are triggered by the int7:0 pins. observe that, if enabled, the interrupts will trigger even if th e int7:0 pins are configur ed as outputs. this feat ure provides a way of gen- erating a software interrupt. the external interrupts can be triggered by a falling or rising edge or a low level. this is set up as indicated in the specification for the external interrupt control reg- isters ? eicra (int3:0) and eicrb (int7:4) . when the external interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. note that recognition of falling or rising edge interrupts on int7:4 requires the presence of an i/o clock, described in ?clock systems and their distribution? on page 37 . low level interrupts and the edge interrupt on int3:0 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. this makes the mcu less sensitive to noise. the changed level is sampled twice by the watchdog oscillator clock. the period of the watchdog oscillator is 1 s (nominal) at 5.0v and 25 c. the frequency of the watchdog oscilla- tor is voltage dependent as shown in the ?electrical characteristics? on page 321 . the mcu will wake up if the input has the required level during this sampling or if it is held until the end of the start-up time. the start-up time is defined by the sut fuses as described in ?clock systems and their distribution? on page 37 . if the level is sampled twice by the watchdog osc illator clock but disappears before the end of th e start-up time, the mcu will stil l wake up, but no interrupt will be generated. the required level must be held long enough for the mcu to complete the wake up to trigger the level interrupt. 13.1 register description 13.1.1 eicra - external interrupt control register a this register can not be reach ed in atmega103 compat ibility mode, but the in itial value defines int3:0 as low level interrupts, as in atmega103. ? bits 7:0 ? isc31, isc30 ? isc00, isc00: external interrupt 3 - 0 sense control bits the external interrupts 3 - 0 are activated by the external pins int3:0 if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 13-1 . edges on int3:int0 are registered asynchro- nously. pulses on int3:0 pins wider than the minimum pulse width given in table 13-2 will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. if enabled, a level triggered interrupt will generate an inter- rupt request as long as the pin is held low. when changing the iscn bit, an interrupt can occur. therefore, it is recommended to first disable intn by clearing its interrupt enable bit in the eimsk register. then, the iscn bit can be changed. finally, the intn interrupt flag should be bit 76543210 isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 eicra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 91 8151h?avr?02/11 atmega128a cleared by writing a logical one to its interrupt flag bit (intfn) in the eifr register before the interrupt is re-enabled. note: 1. n = 3, 2, 1or 0. when changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. 13.1.2 eicrb - external interrupt control register b ? bits 7:0 ? isc71, isc70 - isc41, isc40: external interrupt 7 - 4 sense control bits the external interrupts 7 - 4 are activated by the external pins int7:4 if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 13-3 . the value on the int7:4 pins are sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an inter- rupt. observe that cpu clock frequency can be lower than the xtal frequency if the xtal divider is enabled. if low level interrupt is se lected, the low level must be held until the comple- tion of the currently executing instruction to generate an interrupt. if enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. note: 1. n = 7, 6, 5 or 4. when changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. table 13-1. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of intn generates an interrupt request. 01reserved 1 0 the falling edge of intn generates asynchronously an interrupt request. 1 1 the rising edge of intn generates asynchronously an interrupt request. table 13-2. asynchronous external interrupt characteristics symbol parameter condition min typ max units t int minimum pulse width for asynchronous external interrupt 50 ns bit 76543210 isc71 isc70 isc61 isc60 isc51 isc50 isc41 isc40 eicrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 13-3. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of intn generates an interrupt request. 0 1 any logical change on intn generates an interrupt request 1 0 the falling edge between two samples of intn generates an interrupt request. 1 1 the rising edge between two samples of intn generates an interrupt request. 92 8151h?avr?02/11 atmega128a 13.1.3 eimsk - external interrupt mask register ? bits 7:0 ? int7 ? int0: external interrupt request 7 - 0 enable when an int7 ? int0 bit is written to one and the i-bit in the status register (sreg) is set (one), the corresponding external pin interrupt is enabled. the interrupt sense control bits in the external interrupt control registers ? eicra an d eicrb ? defines whether the external inter- rupt is activated on risi ng or falling edge or level sensed. acti vity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. this provides a way of generating a software interrupt. 13.1.4 eifr - external interrupt flag register ? bits 7:0 ? intf7 - intf0: external interrupt flags 7 - 0 when an edge or logic change on the int7:0 pin triggers an interrupt request, intf7:0 becomes set (one). if the i-bit in sreg and the corresponding interrupt enable bit, int7:0 in eimsk, are set (one), the mcu will jump to the interrupt vector . the flag is cleared wh en the interr upt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. these flags are always cleared when int7:0 are configured as level interrupt. note that when entering sleep mode with the int3:0 inte rrupts disabled, the input buffers on these pins will be disabled. this may cause a logic change in internal si gnals which will set the intf3:0 flags. see ?digital input enable and sleep modes? on page 70 for more information. bit 76543210 int7 int6 int5 int4 int3 int2 int1 iint0 eimsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 intf7 intf6 intf5 intf4 intf3 intf2 intf1 iintf0 eifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 93 8151h?avr?02/11 atmega128a 14. 8-bit timer/counter0 with pwm and asynchronous operation 14.1 features ? single channel counter ? clear timer on compar e match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? frequency generator ? 10-bit clock prescaler ? overflow and compare match interrupt sources (tov0 and ocf0) ? allows clocking from external 32khz watc h crystal independent of the i/o clock 14.2 overview timer/counter0 is a general purpose, single channel, 8-bit timer/counter module. a simplified block diagram of the 8-bit timer/counter is shown in figure 14-1 . for the actual placement of i/o pins, refer to ?pin configurations? on page 2 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?register description? on page 106 . figure 14-1. 8-bit timer/counter block diagram timer/counter data b u s = tcntn waveform generation ocn = 0 control logic = 0xff top bottom count clear direction tovn (int.req.) ocn (int.req.) synchronization unit ocrn tccrn assrn status flags clk i/o clk asy synchronized status flags asynchronous mode select (asn) tosc1 t/c oscillator tosc2 prescaler clk tn clk i/o 94 8151h?avr?02/11 atmega128a 14.2.1 registers the timer/counter (tcnt0) and output compare register (ocr0) are 8-bit registers. interrupt request (shorten as int.req.) signals are all visible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (timsk). tifr and timsk are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or asynchronously clocked from the tosc1/2 pins, as detailed later in this section. the asynchronous operation is controlled by the asynchronous status regist er (assr). the clock select lo gic block controls which clock source the timer/counter uses to increment (or de crement) its value. the timer/counter is inac- tive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t0 ). the double buffered output compare register (ocr0) is compared with the timer/counter value at all times. the result of the compare can be used by the waveform generator to generate a pwm or variable frequency output on the output compare pin (oc0). see ?output compare unit? on page 95. for details. the compare match event will also set the compare flag (ocf0) which can be used to generate an output compare interrupt request. 14.2.2 definitions many register and bit references in this document are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. however, when using the register or bit defines in a program, the precise form must be used (that is, tcnt0 for accessing timer/counter0 counter value and so on). the definitions in table 14-1 are also used extensively throughout the document. 14.3 timer/counter clock sources the timer/counter can be clocked by an internal synchronous or an external asynchronous clock source. the clock source clk t0 is by default equal to the mcu clock, clk i/o . when the as0 bit in the assr register is written to logic one, the clock source is taken from the timer/counter oscillator connected to tosc1 and tosc2. fo r details on asynchronous operation, see ?assr - asynchronous status register? on page 109 . for details on clock sources and prescaler, see ?timer/counter prescaler? on page 106 . 14.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 14-2 shows a block diagram of the counter and its surrounding environment. table 14-1. definitions bottom the counter reaches the bottom when it becomes zero (0x00). max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0 register. the assignment is dependent on the mode of operation. 95 8151h?avr?02/11 atmega128a figure 14-2. counter unit block diagram signal description (internal signals): count increment or decrement tcnt0 by 1. direction selects between increment and decrement. clear clear tcnt0 (set all bits to zero). clk t 0 timer/counter clock. top signalizes that tcnt0 has reached maximum value. bottom signalizes that tcnt0 has reached minimum value (zero). depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs02:0). when no clock source is selected (cs02:0 = 0) the timer is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr0). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare output oc0. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 98 . the timer/counter overflow (tov0) flag is set according to the mode of operation selected by the wgm01:0 bits. tov0 can be used for generating a cpu interrupt. 14.5 output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare register (ocr0). whenever tcnt0 equals ocr0, the comparator signals a match. a match will set the output compare flag (ocf0) at the next timer clock cycle. if enabled (ocie0 = 1), the output compare flag generates an output compare interrupt. the ocf0 flag is automatically cleared when the interrupt is executed. alternatively, t he ocf0 flag can be cleared by software by writ- ing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the wgm01:0 bits and compare output mode (com01:0) bits. the max and bottom signals are used by the waveform generator for han- dling the special cases of the extreme values in some modes of operation ( ?modes of operation? on page 98 ). figure 14-3 shows a block diagram of the output compare unit. data b u s tcntn control logic count tovn (int.req.) top bottom direction clear tosc1 t/c oscillator tosc2 prescaler clk i/o clk tn 96 8151h?avr?02/11 atmega128a figure 14-3. output compare unit, block diagram the ocr0 register is double buffered when us ing any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buff- ering is disabled. the double buffering synchron izes the update of the ocr0 compare register to either top or bottom of the counting sequenc e. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0 register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocr0 buffer register, and if double buffering is disabled the cpu will access the ocr0 directly. 14.5.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc0) bit. forcing compare match will not set the ocf0 flag or reload/clear the timer, but the oc0 pin will be updated as if a real compare match had occurred (the com01:0 bits settings define whether the oc0 pin is set, cleared or toggled). 14.5.2 compare match bloc king by tcnt0 write all cpu write operations to the tcnt0 register will block any compare matc h that occurs in the next timer clock cycle, even when the timer is st opped. this feature allows ocr0 to be initialized to the same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. 14.5.3 using the output compare unit since writing tcnt0 in any mode of operation will block all comp are matches for one timer clock cycle, there are risks involved when changi ng tcnt0 when using the output compare channel, independently of whether the timer/counter is running or not. if the value written to tcnt0 equals the ocr0 value, the compare match will be missed, re sulting in incorrect waveform gen- ocfn (int.req.) = (8-bit comparator ) ocrn ocxy data b u s tcntn wgmn1:0 waveform generator top focn comn1:0 bottom 97 8151h?avr?02/11 atmega128a eration. similarly, do not write the tcnt0 value equal to bottom when the counter is downcounting. the setup of the oc0 should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0 value is to use the force output compare (foc0) strobe bit in normal mode. the oc0 register keeps its value even when changing between waveform generation modes. be aware that the com01:0 bits are not double buffered together with the compare value. changing the com01:0 bits will take effect immediately. 14.6 compare match output unit the compare output mode (com01:0) bits have two functions. the waveform generator uses the com01:0 bits for defining the output compare (oc0) state at the next compare match. also, the com01:0 bits control the oc0 pin output source. figure 14-4 shows a simplified schematic of the logic affected by the com01:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com01:0 bits are shown. when referring to the oc0 state, the reference is for the internal oc0 register, not the oc0 pin. figure 14-4. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0) from the waveform generator if either of the com01:0 bits are set. however, the oc0 pin direction (input or output) is still controlled by the data direction register (ddr) for the port pin. the data direction regis- ter bit for the oc0 pin (ddr_oc0) must be set as output before the oc0 value is visible on the pin. the port override function is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc0 state before the out- put is enabled. note that some com01:0 bit settings are reserved for certain modes of operation. see ?register description? on page 106. port ddr dq dq ocn pin ocn dq waveform generator comn1 comn0 0 1 data b u s focn clk i/o 98 8151h?avr?02/11 atmega128a 14.6.1 compare output mode and waveform generation the waveform generator uses the com01:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com01:0 = 0 tells the waveform generator that no action on the oc0 register is to be performed on the next compare match. for compare output actions in the non- pwm modes refer to table 14-3 on page 107 . for fast pwm mode, refer to table 14-4 on page 108 , and for phase correct pwm refer to table 14-5 on page 108 . a change of the com01:0 bits state will have effect at the first compare ma tch after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the foc0 strobe bits. 14.7 modes of operation the mode of operation, that is, the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm01:0) and compare out- put mode (com01:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com01:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com01:0 bits control whether the output should be set, cleared, or toggled at a compare match ( see ?compare match output unit? on page 97. ). for detailed timing information refer to ?timer/counter timing diagrams? on page 102 . 14.7.1 normal mode the simplest mode of operation is the normal mode (wgm01:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal operation the timer/counter overflow flag ( tov0 ) will be set in the same timer clock cycle as the tcnt0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the norma l mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to gener ate waveforms in normal mode is no t recommended, since this will occupy too much of the cpu time. 14.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm01:0 = 2), the ocr0 register is used to manip- ulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt0) matches the ocr0. the ocr0 defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also sim- plifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 14-5 . the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0, and then counter (tcnt0) is cleared. 99 8151h?avr?02/11 atmega128a figure 14-5. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0 flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0 is lower than the current value of tcnt0, the counter will miss the compar e match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0 output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com01:0 = 1). the oc0 value will no t be visible on the port pin unl ess the data direction for the pin is set to output. the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0 is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). as for the normal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 14.7.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm01:0 = 3) provides a high frequency pwm waveform generation option. the fast pwm di ffers from the other pwm option by its sin- gle-slope operation. the counter counts from bottom to max then restarts from bottom. in non-inverting compare output mode, the output compare (oc0) is cleared on the compare match between tcnt0 and ocr0, and set at bottom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that uses dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac app lications. high frequency a llows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the max value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 14-6 . the tcnt0 value is in the timing diagram shown as a his- tcntn ocn (toggle) ocn interrupt flag set 1 4 period 2 3 (comn1:0 = 1) f ocn f clk_i/o 2 n 1 ocrn + () ?? ---------------------------------------------- - = 100 8151h?avr?02/11 atmega128a togram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0 and tcnt0. figure 14-6. fast pwm mode, timing diagram the timer/counter overflow flag ( tov0 ) is set each time the counter reaches max if the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc0 pin. set- ting the com01:0 bits to 2 will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com01:0 to 3 (see table 14-4 on page 108 ). the actual oc0 value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc0 register at the compare match between ocr0 and tcnt0, and clearing (or setting) the oc0 register at the timer clock cycle the coun- ter is cleared (changes from max to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr0 register represent special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0 is set equal to bottom, the output will be a narrow spike for each max+1 ti mer clock cycle. setting the ocr0 equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com01:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting oc0 to toggle its logical level on each compare match (com01:0 = 1). the waveform generated will have a ma ximum frequency of f oc0 = f clk_i/o /2 when ocr0 is set to zero. this fea- ture is similar to the oc0 toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. tcntn ocrn update and tovn interrupt flag set 1 period 2 3 ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn interrupt flag set 4 5 6 7 f ocnpwm f clk_i/o n 256 ? ------------------ = 101 8151h?avr?02/11 atmega128a 14.7.4 phase correct pwm mode the phase correct pwm mode (wgm01:0 = 1) pr ovides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter counts repeatedly from bottom to max and then from max to bottom. in non- inverting compare output mode, the output compare (oc0) is cleared on the compare match between tcnt0 and ocr0 while counting up, and set on the compare match while downcount- ing. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmet- ric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode is fixed to 8 bits. in phase correct pwm mode the counter is incremented until the counter value matches max when the counter reaches max, it changes the count direction. the tcnt0 value will be equal to max for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 14-7 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0 and tcnt0. figure 14-7. phase correct pwm mode, timing diagram the timer/counter overflow flag ( tov0 ) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0 pin. setting the com01:0 bi ts to 2 will produce a non-invert ed pwm. an inverted pwm out- put can be generated by setting the com01:0 to 3 (see table 14-5 on page 108 ). the actual oc0 value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the oc0 register at the compare match between ocr0 and tcnt0 when the counter increments, and setting (or clearing) the oc0 register at compare match between ocr0 and tcnt0 when the counter decrements. the tovn interrupt flag set ocn interrupt flag set 1 2 3 tcntn period ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn update 102 8151h?avr?02/11 atmega128a pwm frequency for the output when using phase correct pwm can be calculated by the follow- ing equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr0 register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr0 is set equal to bottom, the out- put will be continuously low and if set equal to max the output will be continuously high for non- inverted pwm mode. for inverted pwm the output will have the opposite logic values. at the very start of period 2 in figure 14-7 ocn has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bot- tom. there are two cases that give a transition without compare match: ? ocr0 changes its valu e from max, like in figure 14-7 . when the ocr0 value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up- counting compare match. ? the timer starts counting from a higher value than the one in ocr0, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 14.8 timer/counter timing diagrams figure 14-8 and figure 14-9 contain timing data for the timer/counter operation. the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal. the figure shows the count sequence close to the max value. figure 14-10 and figure 14-11 show the same timing data, but with the prescaler enabled. the figures illustrate when interrupt flags are set. the following figures show the timer/counter in synchronous mode, and the timer clock (clk t0 ) is therefore shown as a clock enable signal. in asynchronous mode, clk i/o should be replaced by the timer/counter oscillator clock. the figures include informati on on when interrupt flags are set. figure 14-8 contains timing data for basic timer/ counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 14-8. timer/counter timing dia gram, no prescaling f ocnpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1 103 8151h?avr?02/11 atmega128a figure 14-9 shows the same timing data, but with the prescaler enabled. figure 14-9. timer/counter timing dia gram, with prescaler (f clk_i/o /8) figure 14-10 shows the setting of ocf0 in all modes except ctc mode. figure 14-10. timer/counter timing diagram, setti ng of ocf0, with prescaler (f clk_i/o /8) figure 14-11 shows the setting of ocf0 and the clearing of tcnt0 in ctc mode. tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfn ocrn tcntn ocrn value ocrn - 1 ocrn ocrn + 1 ocrn + 2 clk i/o clk tn (clk i/o /8) 104 8151h?avr?02/11 atmega128a figure 14-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) 14.9 asynchronous operati on of timer/counter0 when timer/counter0 operates asynchronously, some considerations must be taken. ? warning: when switching between asynchronous and synchronous clocking of timer/counter0, the timer registers tcnt0, ocr0, and tccr0 might be corrupted. a safe procedure for switching clock source is: 1. disable the timer/counter0 interrupts by clearing ocie0 and toie0. 2. select clock source by setting as0 as appropriate. 3. write new values to tcnt0, ocr0, and tccr0. 4. to switch to asynchronous operation: wait for tcn0ub, ocr0ub, and tcr0ub. 5. clear the timer/counter0 interrupt flags. 6. enable interrupts, if needed. ? the oscillator is optimized for use with a 32.768 khz watch crystal. applying an external clock to the tosc1 pin may result in incorrect timer/counter0 operation. the cpu main clock frequency must be more than four times the oscillator frequency. ? when writing to one of the registers tcnt0, ocr0, or tccr0, the value is transferred to a temporary register, and latched after two positive edges on tosc1. the user should not write a new value before the contents of the temporary register have been transferred to its destination. each of the three mentioned registers have their individual temporary register, which means that, for example, writing to tcnt0 does not disturb an ocr0 write in progress. to detect that a transfer to the destination register has taken place, the asynchronous status register ? assr has been implemented. ? when entering power-save or extended standby mode after having written to tcnt0, ocr0, or tccr0, the user must wait until th e written register ha s been u pdated if timer/counter0 is used to wake up the device. otherwise, the mcu will enter sleep mode before the changes are effective. this is particularly important if the output compare0 interrupt is used to wake up the device, since the output compare function is disabled during writing to ocr0 or tcnt0. if the write cycle is not finished, and the mcu enters sleep mode before the ocr0ub bit returns to zero, the device will never receive a compare match interrupt, and the mcu will not wake up. ocfn ocrn tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) 105 8151h?avr?02/11 atmega128a ? if timer/counter0 is used to wake the device up from power-save or extended standby mode, precautions must be taken if the user wants to re-enter one of these modes: the interrupt logic needs one tosc1 cycle to be reset. if the time between wake-up and re- entering sleep mo de is less than one tosc1 cycle, th e interrupt will not occur, and the device will fail to wake up. if the user is in doubt whether the time before re-entering power- save or extended standby mode is sufficient, the following algorithm can be used to ensure that one tosc1 cycle has elapsed: 1. write a value to tccr0, tcnt0, or ocr0. 2. wait until the correspo nding update busy flag in assr returns to zero. 3. enter power-save or extended standby mode. ? when the asynchronous operatio n is selected, the 32.768khz oscillator for timer/counter0 is always running, except in power-down and standby modes. after a power-up reset or wake-up from power-down or standby mode, the user should be aware of the fact that this oscillator might take as long as one second to stabilize. the user is advised to wait for at least one second before using timer/counter0 after power-up or wake-up from power-down or standby mode. the contents of all timer/coun ter0 registers must be considered lost after a wake-up from power-down or standby mode due to unstable clock signal upon start-up, no matter whether the oscillator is in use or a clock signal is applied to the tosc1 pin. ? description of wake up from power-save or extended standby mode when the timer is clocked asynchronously: when the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value. after wake-up, the mcu is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction following sleep. ? reading of the tcnt0 register shortly after wake-up from power-save may give an incorrect result. since tcnt0 is clocked on the asynchronous tosc clock, reading tcnt0 must be done through a register synchronized to the internal i/o clock domain. synchronization takes place for every rising tosc1 edge. when waking up from power-save mode, and the i/o clock (clk i/o ) again becomes active, tcnt0 will read as the previous value (before entering sleep) until the next rising tosc1 edge. the phase of the tosc clock after waking up from power-save mode is essentially unpredictable, as it depends on the wake-up time. the recommended procedure for reading tcnt0 is thus as follows: 1. write any value to either of the registers ocr0 or tccr0. 2. wait for the corresponding update busy flag to be cleared. 3. read tcnt0. ? during asynchronous operation, the synchronization of the interrupt flags for the asynchronous timer takes three processor cycles plus one timer cycle. the timer is therefore advanced by at least one before the processor can read the timer value causing the setting of the interrupt flag. the output compare pin is changed on the timer clock and is not synchronized to the processor clock. 106 8151h?avr?02/11 atmega128a 14.10 timer/counter prescaler figure 14-12. prescaler for timer/counter0 the clock source for timer/counter0 is named clk t0 . clk t0 is by default connected to the main system clock clk i/o . by setting the as0 bit in assr, timer/counter0 is asynchronously clocked from the tosc1 pin. this enables use of timer/counter0 as a real time counter (rtc). when as0 is set, pins tosc1 and tosc2 are disconnected from port c. a crystal can then be con- nected between the tosc1 and tosc2 pins to serve as an independent clock source for timer/counter0. the oscillator is optimized for use with a 32.768kh z crystal. applying an exter- nal clock source to tosc1 is not recommended. for timer/counter0, the possible prescaled selections are: clk t0s /8, clk t0s /32, clk t0s /64, clk t0s /128, clk t0s /256, and clk t0s /1024. additionally, clk t0s as well as 0 (stop) may be selected. setting the psr0 bit in sfior resets the prescaler. this allows the user to operate with a pre- dictable prescaler. 14.11 register description 14.11.1 tccr0 - timer/c ounter control register ? bit 7 ? foc0: force output compare the foc0 bit is only active when the wgm bits specify a non-pwm mode. however, for ensur- ing compatibility with future devices, this bit must be set to zero when tccr0 is written when operating in pwm mode. when writing a logica l one to the foc0 bit, an immediate compare match is forced on the waveform generation unit. the oc0 output is changed according to its 10-bit t/c prescaler timer/counter0 clock source clk i/o clk t0s tosc1 as0 cs00 cs01 cs02 clk t0s /8 clk t0s /64 clk t0s /128 clk t0s /1024 clk t0s /256 clk t0s /32 0 psr0 clear clk t0 bit 7 6 5 4 3 2 1 0 foc0 wgm00 com01 com00 wgm01 cs02 cs01 cs00 tccr0 read/write w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 107 8151h?avr?02/11 atmega128a com01:0 bits setting. note that the foc0 bit is implemented as a strobe. therefore it is the value present in the com01:0 bits that determines the effect of the forced compare. a foc0 strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0 as top. the foc0 bit is always read as zero. ? bit 6, 3 ? wgm01:0: waveform generation mode these bits control the counting sequence of the counter, the source for the maximum (top) counter value, and what type of waveform generation to be used. modes of operation supported by the timer/counter unit are: normal mode, clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes. see table 14-2 and ?modes of operation? on page 98 . note: 1. the ctc0 and pwm0 bit definition names are now obsolete. use t he wgm01:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. ? bit 5:4 ? com01:0: compare match output mode these bits control the output compare pin (oc0) behavior. if one or both of the com01:0 bits are set, the oc0 output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction register (ddr) bit corresponding to oc0 pin must be set in order to enable the output driver. when oc0 is connected to the pin, the function of the com01:0 bits depends on the wgm01:0 bit setting. table 14-3 shows the com01:0 bit functionality when the wgm01:0 bits are set to a normal or ctc mode (non-pwm). table 14-2. waveform generation mode bit description mode wgm01 (1) (ctc0) wgm00 (1) (pwm0) timer/counter mode of operation top update of ocr0 at tov0 flag set on 0 0 0 normal 0xff immediate max 1 0 1 pwm, phase correct 0xff top bottom 2 1 0 ctc ocr0 immediate max 3 1 1 fast pwm 0xff bottom max table 14-3. compare output mode, non-pwm mode com01 com00 description 0 0 normal port operation, oc0 disconnected. 0 1 toggle oc0 on compare match 1 0 clear oc0 on compare match 1 1 set oc0 on compare match 108 8151h?avr?02/11 atmega128a table 14-4 shows the com01:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0 equals top and com01 is set. in this case, the compare match is ignored, but the set or clear is done at bottom. see ?fast pwm mode? on page 99 for more details. table 14-5 shows the com01:0 bit functionality when the wgm01:0 bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr0 equals top and com01 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 101 for more details. ? bit 2:0 ? cs02:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see table 14-6 . table 14-4. compare output mode, fast pwm mode (1) com01 com00 description 0 0 normal port operation, oc0 disconnected. 01reserved 1 0 clear oc0 on compare match, set oc0 at bottom, (non-inverting mode) 1 1 set oc0 on compare match, clear oc0 at bottom, (inverting mode) table 14-5. compare output mode, phase correct pwm mode (1) com01 com00 description 0 0 normal port operation, oc0 disconnected. 01reserved 1 0 clear oc0 on compare match when up-counting. set oc0 on compare match when downcounting. 1 1 set oc0 on compare match when up-c ounting. clear oc0 on compare match when downcounting. 109 8151h?avr?02/11 atmega128a 14.11.2 tcnt0 - timer/counter register the timer/counter register gives direct ac cess, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0 register. 14.11.3 ocr0 - output compare register the output compare register contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0 pin. 14.11.4 assr - asynchronous status register ? bit 3 ? as0: asynchronous timer/counter0 when as0 is written to zero, timer/counter0 is clocked from the i/o clock, clk i/o . when as0 is written to one, timer/counter is clocked from a crystal oscillato r connected to the timer oscilla- tor 1 (tosc1) pin. when the value of as0 is changed, the contents of tcnt0, ocr0, and tccr0 might be corrupted. table 14-6. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped) 001 clk t0s /(no prescaling) 010 clk t0s /8 (from prescaler) 011 clk t0s /32 (from prescaler) 100 clk t0s /64 (from prescaler) 101 clk t0s /128 (from prescaler) 110clk t 0 s /256 (from prescaler) 111clk t 0 s /1024 (from prescaler) bit 76543210 tcnt0[7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr0[7:0] ocr0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543 2 1 0 ? ? ? ? as0 tcn0ub ocr0ub tcr0ub assr read/writerrrrr/wr r r initial value00000 0 0 0 110 8151h?avr?02/11 atmega128a ? bit 2 ? tcn0ub: timer/counter0 update busy when timer/counter0 operates asynchronously and tcnt0 is written, this bit becomes set. when tcnt0 has been updated from the temporary storage register, this bit is cleared by hard- ware. a logical zero in this bit indicates that tcnt0 is ready to be updated with a new value. ? bit 1 ? ocr0ub: output co mpare register0 update busy when timer/counter0 operates asynchronously and ocr0 is written, this bit becomes set. when ocr0 has been updated from the temporary storage register, this bit is cleared by hard- ware. a logical zero in this bit indicates that ocr0 is ready to be updated with a new value. ? bit 0 ? tcr0ub: timer/counter control register0 update busy when timer/counter0 operates asynchronously and tccr0 is written, this bit becomes set. when tccr0 has been updated from the temporary storage register, this bit is cleared by hard- ware. a logical zero in this bit indicates that tccr0 is ready to be updated with a new value. if a write is performed to any of the three timer/counter0 registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur. the mechanisms for reading tcnt0, ocr0, and tccr0 are different. when reading tcnt0, the actual timer value is read. when reading oc r0 or tccr0, the value in the temporary stor- age register is read. 14.11.5 timsk - timer/counter interrupt mask register ? bit 1 ? ocie0: timer/counter0 output compare match interrupt enable when the ocie0 bit is written to one, and the i-bit in the status register is set (one), the timer/counter0 compare match interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs, that is , when the ocf0 bit is set in the timer/coun- ter interrupt flag register ? tifr. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, and the i-bit in the status register is set (one), the timer/counter0 overflow interrupt is enabled. the corresponding interrupt is executed if an overflow in timer/counter0 occurs, that is, when the tov0 bit is set in the timer/counter inter- rupt flag register ? tifr. 14.11.6 tifr - timer/counter interrupt flag register ? bit 1 ? ocf0: output compare flag 0 the ocf0 bit is set (one) when a compare match occurs between the timer/counter0 and the data in ocr0 ? output compare register0. ocf0 is cleared by hardware when executing the corresponding interrupt handling vector. alternativel y, ocf0 is cleared by writing a logic one to bit 7654 3210 ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 timsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 tifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 111 8151h?avr?02/11 atmega128a the flag. when the i-bit in sreg, ocie0 (timer/counter0 compare match interrupt enable), and ocf0 are set (one), the timer/counter0 compare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set (one) when an overflow occu rs in timer/counter0. tov0 is cleared by hard- ware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sr eg i-bit, toie0 (timer/counter0 overflow inter- rupt enable), and tov0 are set (one), the time r/counter0 overflow interrupt is executed. in pwm mode, this bit is set when timer/counter0 changes counting direction at $00. 14.11.7 sfior - special function io register ? bit 7 ? tsm: timer/counter synchronization mode writing the tsm bit to one activates the timer/counter synchronization mode. in this mode, the value that is written to the psr0 and psr 321 bits is kept, hence keeping the corresponding prescaler reset signals asserted. this ensures th at the corresponding timer/counters are halted and can be configured to the same value withou t the risk of one of them advancing during con- figuration. when the tsm bit is written to zero, the psr0 and psr321 bits are cleared by hardware, and the timer/counters start counting simultaneously. ? bit 1 ? psr0: prescaler reset timer/counter0 when this bit is one, the time r/counter0 prescaler will be rese t. this bit is normally cleared immediately by hardware. if this bit is written when timer/counter0 is operating in asynchronous mode, the bit will remain one until the presca ler has been reset. the bit will not be cleared by hardware if the tsm bit is set. bit 7 6 5 4 3 2 1 0 tsm ? ? ? acme pud psr0 psr321 sfior read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 112 8151h?avr?02/11 atmega128a 15. 16-bit timer/counter (timer/counter1 and timer/counter3) 15.1 features ? true 16-bit design (that is, allows 16-bit pwm) ? three independent output compare units ? double buffered outp ut compare registers ? one input capture unit ? input capture noise canceler ? clear timer on compare match (auto reload) ? glitch-free, phase correct pulse width modulator (pwm) ? variable pwm period ? frequency generator ? external event counter ? ten independent interrupt sources (tov1, ocf1a, ocf1b, ocf1c, icf1, tov3, ocf3a, ocf3b, ocf3c, and icf3) 15.1.1 restrictions in atmega103 compatibility mode note that in atmega103 compatibility mode, only one 16-bit timer/counter is available (timer/counter1). also note th at in atmega103 compatibility mo de, the timer/counter1 has two compare registers (compare a and compare b) only. 15.2 overview the 16-bit timer/counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. most register and bit references in this sec- tion are written in general form. a lower case ?n? replaces the timer/counter number, and a lower case ?x? replaces the output compare unit channel. however, when using the register or bit defines in a program, the precise form must be used, that is, tcnt1 for accessing timer/counter1 counter value and so on. a simplified block diagram of the 16-bit timer/counter is shown in figure 15-1 . for the actual placement of i/o pins, refer to ?pin configurations? on page 2 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit loca- tions are listed in the ?register description? on page 134 . 113 8151h?avr?02/11 atmega128a figure 15-1. 16-bit timer/counter block diagram note: refer to figure 1-1 on page 2 , table 12-5 on page 74 , and table 12-14 on page 81 for timer/counter1 and 3 pin placement and description. 15.2.1 registers the timer/counter (tcntn), output compare registers (ocrna/b/c), and input capture reg- ister (icrn) are all 16-bit registers. special procedures must be followed when accessing the 16- bit registers. these procedures are described in the section ?accessing 16-bit registers? on page 115 . the timer/counter control registers (tccrna/b/c) are 8-bit registers and have no cpu access restrictions. interrupt requests (short en as int.req.) signals are all visible in the timer interrupt flag register (tifr) and extended timer interrupt flag register (etifr). all interrupts are individually masked with the timer interrupt mask register (timsk) and extended timer interrupt mask register (etimsk). (e)tifr and (e)timsk are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the tn pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t n ). icfx (int.req.) tovx (int.req.) clock select timer/counter databus ocrxa ocrxb ocrxc icrx = = = tcntx waveform generation waveform generation waveform generation ocxa ocxb ocxc noise canceler icpx = fixed top values edge detector control logic = 0 top bottom count clear direction ocfxa (int.req.) ocfxb (int.req.) ocfxc (int.req.) tccrxa tccrxb tccrxc ( from analog comparator ouput ) tx edge detector ( from prescaler ) tclk 114 8151h?avr?02/11 atmega128a the double buffered output compare registers (ocrna/b/c) are compared with the timer/counter value at all time. the result of the compare can be used by the waveform gener- ator to generate a pwm or variable frequency output on the output compare pin (ocna/b/c). see ?output compare units? on page 122. the compare match event will also set the compare match flag (ocfna/b/c) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/ counter value at a given external (edge trig- gered) event on either the input capture pin (icpn) or on the analog comparator pins ( see ?analog comparator? on page 230. ) the input capture unit includes a digital filtering unit (noise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocrna register, the icrn regist er, or by a set of fixed values. when using ocrna as top value in a pwm mode, the ocrna register can not be used for generating a pwm output. however, the top value will in this case be do uble buffered allowing the top value to be changed in run time. if a fixed top value is required, the icrn register can be used as an alternative, freeing the ocrna to be used as pwm output. 15.2.2 definitions the following definitions are used extensively throughout the document: 15.2.3 compatibility the 16-bit timer/counter has been updated and impr oved from previous versions of the 16-bit avr timer/counter. this 16-bit timer/counter is fully compatible with the earlier version regarding: ? all 16-bit timer/counter related i/o register address locations, including timer interrupt registers. ? bit locations inside all 16-bit timer/counter registers, including timer interrupt registers. ? interrupt vectors. the following control bits have changed name, but have same functionality and register location: ? pwmn0 is changed to wgmn0. ? pwmn1 is changed to wgmn1. ? ctcn is changed to wgmn2. the following registers are added to the 16-bit timer/counter: ? timer/counter control register c (tccrnc). ? output compare register c, ocrnch and ocrncl, combined ocrnc. the following bits are added to the 16-bit timer/counter control registers: ? com1c1:0 are added to tccr1a. table 15-1. definitions bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its max imum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stor ed in the ocrna or icrn register. the assignment is dependent of the mode of operation. 115 8151h?avr?02/11 atmega128a ? focna, focnb, and focnc are added in the new tccrnc register. ? wgmn3 is added to tccrnb. interrupt flag and mask bits for output compare unit c are added. the 16-bit timer/counter has improvements that will affect the compatibility in some special cases. 15.3 accessing 16-bit registers the tcntn, ocrna/b/c, and icrn are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write opera- tions. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16- bit access. the same temporary register is shared between all 16-bit registers within each 16- bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. when the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary regi ster for the high byte. reading the ocrna/b/c 16-bit registers does not involve using the temporary register. to do a 16-bit write, the high byte must be written before the low byte . for a 16-bit read, the low byte must be read before the high byte . the following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocrna/b/c and icrn registers. note that when using ?c?, the compiler handles the 16-bit access. 116 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8. the assembly code example returns the tcntn value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer regis- ters, then the result of the a ccess outside the interrupt will be corrupted. theref ore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tcntn register contents. reading any of the ocrna/b/c or icrn registers can be done by using the same principle. assembly code examples (1) :. ; set tcntn to 0x01ff ldi r17,0x01 ldi r16,0xff out tcntnh,r17 out tcntnl,r16 ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh :. c code examples (1) unsigned int i; :. /* set tcntn to 0x01ff */ tcntn = 0x1ff; /* read tcntn into i */ i = tcntn; :. 117 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8. the assembly code example returns the tcntn value in the r17:r16 register pair. the following code examples show how to do an atomic write of the tcntn register contents. writing any of the ocrna/b/c or icrn registers can be done by using the same principle. assembly code example (1) tim16_readtcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcntn( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* read tcntn into i */ i = tcntn; /* restore global interrupt flag */ sreg = sreg; return i; } 118 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8. the assembly code example requires that the r1 7:r16 register pair contains the value to be written to tcntn. 15.3.1 reusing the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described previously also applies in this case. 15.4 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (csn2:0) bits located in the timer/counter control register b (tccrnb). for details on cl ock sources an d prescaler, see ?timer/counter3, timer/counter2, and timer/counter1 prescalers? on page 145 . 15.5 counter unit the main part of the 16-bit timer/counter is th e programmable 16-bit bi-directional counter unit. figure 15-2 shows a block diagram of the counter and its surroundings. assembly code example (1) tim16_writetcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcntn to r17:r16 out tcntnh,r17 out tcntnl,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcntn( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* set tcntn to i */ tcntn = i; /* restore global interrupt flag */ sreg = sreg; } 119 8151h?avr?02/11 atmega128a figure 15-2. counter unit block diagram signal description (internal signals): count increment or decrement tcntn by 1. direction select between increment and decrement. clear clear tcntn (set all bits to zero). clk t n timer/counter clock. top signalize that tcntn has reached maximum value. bottom signalize that tcntn has re ached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcntnh) con- taining the upper 8 bits of the counter, and counter low (tcntnl) containing the lower 8 bits. the tcntnh register can only be indirectly accessed by the cpu. when the cpu does an access to the tcntnh i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tcntnh value when the tcntnl is read, and tcntnh is updated with the temporary regi ster value when tcntnl is written. this allows the cpu to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. it is important to notice that there are special cases of writing to the tcntn register when the counter is counting that will give un predictable results. the special cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t n ). the clk t n can be generated from an external or internal clock source, selected by the clock select bits (csn2:0). when no clock source is selected (csn2:0 = 0) the timer is stopped. however, the tcntn value can be accessed by the cpu, independent of whether clk t n is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits (wgmn3:0) located in the timer/counter control registers a and b (tccrna and tccrnb). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs ocnx. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 125 . the timer/counter overflow (tovn) flag is set according to the mode of operation selected by the wgmn3:0 bits. tovn can be used for generating a cpu interrupt. temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) control logic count clear direction tovn (int.req.) clock select top bottom tn edge detector ( from prescaler ) clk tn 120 8151h?avr?02/11 atmega128a 15.6 input capture unit the timer/counter incorporates an input capture unit that can capture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an event, or mul- tiple events, can be applied via the icpn pin or al ternatively, for the timer/counter1 only, via the analog comparator unit. the time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 15-3 . the elements of the block diagram that are not directly a part of the input capture unit are gray shaded. the small ?n? in register and bit names indicates the timer/counter number. figure 15-3. input capture unit block diagram note: the analog comparator output (aco) ca n only trigger the timer/counter1 icp ? not timer/counter3. when a change of the logic level (an event) occurs on the input capture pin (icpn), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge detector, a capture will be triggered. when a captur e is triggered, the 16-bit value of the counter (tcntn) is written to the input capture register (icrn). the input capture flag (icfn) is set at the same system clock as the tcntn value is c opied into icrn register. if enabled (ticien = 1), the input capture flag generates an input capture interrupt. the icfn flag is automatically cleared when the interrupt is executed. alternativ ely the icfn flag can be cleared by software by writing a logical one to its i/o bit location. reading the 16-bit value in the input capture register (icrn) is done by first reading the low byte (icrnl) and then the high byte (icrnh). when the low byte is read the high byte is copied into the high byte temporary register (temp). when the cpu reads the icrnh i/o location it will access the temp register. icfn (int.req.) analog comparator write icrn (16-bit register) icrnh (8-bit) noise canceler icpn edge detector temp (8-bit) data bus (8-bit) icrnl (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) acic* icnc ices aco* 121 8151h?avr?02/11 atmega128a the icrn register can only be written when us ing a waveform generation mode that utilizes the icrn register for defining the counter?s top value. in these cases the waveform genera- tion mode (wgmn3:0) bits must be set before the top value can be written to the icrn register. when writing the icrn re gister the high byte must be written to the icrnh i/o location before the low byte is written to icrnl. for more information on how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 115 . 15.6.1 input capture pin source the main trigger source for the input capture unit is the input capture pin (icpn). timer/counter1 can alternatively use the analog comparator output as trigger source for the input capture unit. the analog comparator is selected as trigger source by setting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can trigger a capture. the input capture flag must therefore be cleared after the change. both the input capture pin (icpn) and the analog comparator output (aco) inputs are sampled using the same technique as for the tn pin ( figure 16-1 on page 145 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases t he delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabl ed unless the timer/counter is set in a wave- form generation mode that uses icrn to define top. an input capture can be trigger ed by software by controlling the port of the icpn pin. 15.6.2 noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (icncn) bit in timer/counter control register b (tccrnb). when enabled the noise canceler introduces addi- tional four system clock cycles of delay from a change applied to the input, to the update of the icrn register. the noise canceler uses the sy stem clock and is therefore not affected by the prescaler. 15.6.3 using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is critical. if the processor has not read the captured value in th e icrn register before the nex t event occurs, the icrn will be overwritten with a new value. in this case the result of the ca pture will be incorrect. when using the input capture interrupt, the icrn register should be read as early in the inter- rupt handler routine as possible. even though the input capture interrupt has relatively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icrn 122 8151h?avr?02/11 atmega128a register has been read. after a change of the edge, the input capture flag (icfn) must be cleared by software (writing a logical one to the i/o bit location). for measuring frequency only, the clearing of the icfn flag is not required (if an interrupt handler is used). 15.7 output compare units the 16-bit comparator continuously compares tcntn with the output compare register (ocrnx). if tcnt equals ocrnx the comparator signals a match. a match will set the output compare flag (ocfnx) at the next timer clock cycle. if enabled (ocienx = 1), the output com- pare flag generates an output compare interrupt. the ocfnx flag is automatically cleared when the interrupt is executed. alternatively the ocfnx flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the waveform generation mode (wgmn3:0) bits and compare output mode (comnx1:0) bits. the top and bottom signals are used by the wave- form generator for handling the special cases of the extreme values in some modes of operation ( see ?modes of operation? on page 125. ) a special feature of output compare unit a allows it to define the timer/counter top value (that is, counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 15-4 shows a block diagram of the output compare unit. the small ?n? in the register and bit names indicates the device number (n = n for timer/counter n), and the ?x? indicates output compare unit (a/b/c). the elements of the block diagram that are not directly a part of the output compare unit are gray shaded. figure 15-4. output compare unit, block diagram ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf. (8-bit) ocnx temp (8-bit) data b u s (8-bit) ocrnxl buf. (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) comnx1:0 wgmn3:0 ocrnx (16-bit register) ocrnxh (8-bit) ocrnxl (8-bit) waveform generator top bottom 123 8151h?avr?02/11 atmega128a the ocrnx register is double buffered when using any of the twelve pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the dou- ble buffering is disabled. the double buffering synchronizes the update of the ocrnx compare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocrnx register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocrnx buffer register, and if double buffering is disabled the cpu will access the ocrnx directly. the conten t of the ocr1x (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automati- cally as the tcntn- and icrn register). therefore ocrnx is not read via the high byte temporary register (temp). however, it is a good practice to read the low byte first as when accessing other 16-bit registers. writing the ocrnx registers must be done via the temp regis- ter since the compare of all 16-bits is done continuously. the high byte (ocrnxh) has to be written first. when the high byte i/o location is written by the cpu, the temp register will be updated by the value written. then when the low byte (ocrnxl) is written to the lower 8-bit, the high byte will be copied into the upper 8 bits of either the ocrnx buffer or ocrnx compare register in the same system clock cycle. for more information of how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 115 . 15.7.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (focnx) bit. forcing compare match will not set the ocfnx flag or reload/clear the timer, but the ocnx pin will be updated as if a real compare match had occurred (the comnx1:0 bits settings de fine whether the ocnx pin is set, cleared or toggled). 15.7.2 compare match bloc king by tcntn write all cpu writes to the tcntn register will block any compare match that o ccurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocrnx to be initialized to the same value as tcntn without triggering an inte rrupt when the timer/counter clock is enabled. 15.7.3 using the output compare unit since writing tcntn in any mode of operation will block all comp are matches for one timer clock cycle, there are risks involved when changing tcntn when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcntn equals the ocrnx value, the compare matc h will be missed, resulting in incorrect wave- form generation. do not write the tcntn equal to top in pwm modes with variable top values. the compare match for the top will be ignored and the counte r will continue to 0xffff. similarly, do not write the tcntn value equal to bottom when the counter is downcounting. the setup of the ocnx should be performed before setting the data direction register for the port pin to output. the easiest way of setting the ocnx value is to use the force output compare (focnx) strobe bits in normal mode. the ocnx register keeps its value even when changing between waveform generation modes. be aware that the comnx1:0 bits are not doubl e buffered together with the compare value. changing the comnx1:0 bits will take effect immediately. 124 8151h?avr?02/11 atmega128a 15.8 compare match output unit the compare output mode (comnx1:0) bits have two functions. the waveform generator uses the comnx1:0 bits for defining the output compare (ocnx) state at the next compare match. secondly the comnx1:0 bits control the ocnx pin output source. figure 15-5 shows a simplified schematic of the logic affected by the comnx1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the comnx1:0 bits are shown. when referring to the ocnx state, the reference is for the internal ocnx register, not the ocnx pin. if a system reset occur, the ocnx register is reset to ?0?. figure 15-5. compare match output unit, schematic the general i/o port function is overridden by the output compare (ocnx) from the waveform generator if either of the comnx1:0 bits are set. however, the ocnx pin direction (input or out- put) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the ocnx pin (ddr_ocnx) must be set as output before th e ocnx value is visible on the pin. the port override function is generally independent of the waveform generation mode, but there are some exceptions. refer to table 15-2 , table 15-3 and table 15-4 for details. the design of the output compare pin logic allows initialization of the ocnx state before the out- put is enabled. note that some comnx1:0 bi t settings are reserved for certain modes of operation. see ?register description? on page 134. the comnx1:0 bits have no effect on the input capture unit. 15.8.1 compare output mode and waveform generation the waveform generator uses the comnx1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the comnx1:0 = 0 tells the waveform generator that no action on the ocnx register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 15-2 on page 135 . for fast pwm mode refer to table 15-3 on page 135 , and for phase correct and phase and frequency correct pwm refer to table 15-4 on page 136 . port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o 125 8151h?avr?02/11 atmega128a a change of the comnx1:0 bits st ate will have effect at the first compare matc h after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the focnx strobe bits. 15.9 modes of operation the mode of operation, that is, the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgmn3:0) and compare out- put mode (comnx1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the comnx1:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the comnx1:0 bits control whether the output should be set, cleared or toggle at a compare match ( see ?compare match output unit? on page 124. ) for detailed timing information refer to ?timer/counter timing diagrams? on page 132 . 15.9.1 normal mode the simplest mode of operation is the normal mode (wgmn3:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter overflow flag (tovn) will be set in the same timer clock cycle as the tcntn beco mes zero. the tovn flag in this case behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tovn flag, the timer resolution can be increased by soft- ware. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. however, observe that the maximum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generate interrupts at some given time. using the out- put compare to gener ate waveforms in normal mode is no t recommended, since this will occupy too much of the cpu time. 15.9.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgmn3:0 = 4 or 12), the ocrna or icrn register are used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcntn) matches either the ocrna (wgmn3:0 = 4) or the icrn (wgmn3:0 = 12). the ocrna or icrn define the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the opera- tion of counting external events. the timing diagram for the ctc mode is shown in figure 15-6 . the counter value (tcntn) increases until a compare match occurs with either ocrna or icrn, and then counter (tcntn) is cleared. 126 8151h?avr?02/11 atmega128a figure 15-6. ctc mode, timing diagram an interrupt can be generated at each time the counter value reaches the top value by either using the ocfna or icfn flag according to the register used to define the top value. if the inter- rupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a value close to bottom w hen the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocrna or icrn is lower than the current value of tcntn, the counter will miss the compare matc h. the counter will th en have to count to its maximum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is not desirable. an alternative will then be to use the fast pwm mode using ocrna for defining top (wgmn3:0 = 15) si nce the ocrna then will be double buffered. for generating a waveform output in ctc mode, the ocna output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (comna1:0 = 1). the ocna value will not be visible on the port pin unless the data direction for the pin is set to output (ddr_ocna = 1). th e waveform generated will have a maximum fre- quency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tovn flag is set in the same timer clock cycle that the counter counts from max to 0x0000. 15.9.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgmn3:0 = 5,6,7,14, or 15) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx, and setat bottom. in inverting compare output mode output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase cor- rect and phase and frequency correct pwm modes that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regula tion, rectification, and dac tcntn ocna (toggle) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 4 period 2 3 (comna1:0 = 1) f ocna f clk_i/o 2 n 1 ocrna + () ?? -------------------------------------------------- - = 127 8151h?avr?02/11 atmega128a applications. high frequency allows physically sm all sized external com ponents (coils, capaci- tors), hence reduces total system cost. the pwm resolution for fast pwm can be fixed to 8-bit, 9-bit, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the maximum resolution is 16-bit (icrn or ocrna set to max). the pwm resolution in bits can be calculated by using the following equation: in fast pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgmn3:0 = 5, 6, or 7), the value in icrn (wgmn3:0 = 14), or the value in ocrna (wgmn3:0 = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 15-7 . the figure shows fast pwm mode when ocrna or icrn is us ed to define top. the tcntn value is in the timing diagram shown as a histogram for illu strating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes represent compare matc hes between ocrnx and tcntn. the ocnx interrupt flag will be set when a compare match occurs. figure 15-7. fast pwm mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches top. in addition the ocna or icfn flag is set at the same timer clock cycle as tovn is set when either ocrna or icrn is used for defining the top value. if one of the interrupts are enabled, the interrupt han- dler routine can be used for updating the top and compare values. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the com- pare registers, a compare match will never occur between the tcntn and the ocrnx. note that when using fixed top values the unused bits are masked to zero when any of the ocrnx reg- isters are written. the procedure for updating icrn differs from updating ocrna when used for defining the top value. the icrn register is not double buffered. this means that if icrn is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new r fpwm top 1 + () log 2 () log ---------------------------------- - = tcntn ocrnx / top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 7 period 2 3 4 5 6 8 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) 128 8151h?avr?02/11 atmega128a icrn value written is lower than the current va lue of tcntn. the result will then be that the counter will miss the compare matc h at the top value. the counter will then have to count to the max value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. the ocrna register however, is double buffered. this feature allows the ocrna i/o location to be written anytime. when the ocrna i/o location is written the value written will be put into the ocrna buffer register. the ocrna compare register will then be updated with the value in the buffer register at the next timer clock cycle the tcntn matches top. the update is done at the same timer clock cycle as the tcntn is cleared and the tovn flag is set. using the icrn register for defining top work s well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a pwm output on ocna. however, if the base pwm frequency is actively change d (by changing the top value), using the ocrna as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow generation of pwm waveforms on the ocnx pins. setting the comnx1:0 bits to 2 will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to 3 (see table 15-3 on page 135 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn, and clearing (or setting) the ocnx register at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocrnx is set equal to bottom (0x0000) the out- put will be a narrow spike for eac h top+1 timer clock cycle. se tting the ocrnx equal to top will result in a const ant high or low output (depending on the polarity of the output set by the comnx1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting ocna to toggle its logical level on each compare match (comna1:0 = 1). this applies only if ocrna is used to define the top value (wgm n3:0 = 15). the wave form generated will have a maximum frequency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). this feature is similar to the ocna toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. 15.9.4 phase correct pwm mode the phase correct pulse width modulation or phase correct pwm mode (wgmn3:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency correct pwm mode, based on a dual- slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx while counting up, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. how- ever, due to the symmetric feature of the dual-s lope pwm modes, these modes are preferred for motor control applications. f ocnxpwm f clk_i/o n 1 top + () ? ---------------------------------- - = 129 8151h?avr?02/11 atmega128a the pwm resolution for the phase correct pwm mode can be fixed to 8-bit, 9-bit, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2 bit (icrn or ocrna set to 0x0003), and the maximum resolution is 16 bit (icrn or ocrna set to max). the pwm reso- lution in bits can be calculated by using the following equation: in phase correct pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgmn3:0 = 1, 2, or 3), the value in icrn (wgmn3:0 = 10), or the value in ocrna (wgmn3:0 = 11). the counter has then reached the top and changes the count direct ion. the tcntn value will be equa l to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 15-8 . the figure shows phase correct pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing diagram shown as a histogram for illustrati ng the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes represent compare matches between ocrnx and tcntn. the ocnx inter- rupt flag will be set when a compare match occurs. figure 15-8. phase correct pwm mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches bottom. when either ocrna or icrn is used for defining the top value, the ocna or icfn flag is set accord- ingly at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at top). the interrupt flags can be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the com- pare registers, a compare match will never occur between the tcntn and the ocrnx. note that when using fixed top values, the unused bits are masked to zero when any of the ocrnx reg- isters are written. as the third period shown in figure 15-8 illustrates, changi ng the top actively r pcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx / top update and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tovn interrupt flag set (interrupt on bottom) tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) 130 8151h?avr?02/11 atmega128a while the timer/counter is running in the phase correct mo de can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocrnx register. since the ocrnx update occurs at top, the pwm period starts and ends at top. this implies that the length of the falling slope is determined by the previous top va lue, while the length of the rising slope is determined by the new top value. when t hese two values differ the two slopes of the period will differ in length. the di fference in length gi ves the unsymmetrical re sult on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value while the timer/counter is running. when using a static top value there are practically no differences between the two modes of operation. in phase correct pwm mode, the compare units allow generation of pwm waveforms on the ocnx pins. setting the comnx1:0 bits to 2 will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to 3 (see table 15-4 on page 136 ). the actual ocnx value will only be visible on the port pi n if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx regis- ter at the compare match between ocrnx and tcntn when the counter increments, and clearing (or setting) the ocnx register at compare match between ocrnx and tcntn when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be continuously high for non-inverted pwm mode. for in verted pwm the output will have the opposite logic values. if ocna is used to define the top value (wgmn3:0 = 11) and comna1:0 = 1, the ocna output will toggle with a 50% duty cycle. 15.9.5 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency correct pwm mode (wgmn3:0 = 8 or 9) provides a high reso lution phase and frequency correct pwm wave- form generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx while counting up, and set on the compare match while downcounting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower maximum operation fre- quency compared to the single-slope operation. howe ver, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the main difference between the phase correct, and the phase and frequency correct pwm mode is the time the ocrnx register is updated by the ocrnx buffer register, (see figure 15- 8 and figure 15-9 ). the pwm resolution for the phase and frequency correct pwm mode can be defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the maximum resolution is 16-bit (icrn or ocrn a set to max). the pwm resolution in bits can be calculated using the following equation: f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------- - = 131 8151h?avr?02/11 atmega128a in phase and frequency correct pwm mode the counter is incremented until the counter value matches either the value in icrn (wgmn3:0 = 8), or the value in ocrna (wgmn3:0 = 9). the counter has then reac hed the top and ch anges the count di rection. the tcntn value will be equal to top for one timer clock cycle. the timing diagram for the phase correct and frequency correct pwm mode is shown on figure 15-9 . the figure shows phase and frequency correct pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing dia- gram shown as a histogram for illustrating the dual-slope operati on. the diagram includes non- inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes repre- sent compare matches between oc rnx and tcntn. the ocnx inte rrupt flag will be set when a compare match occurs. figure 15-9. phase and frequency correct pwm mode, timing diagram the timer/counter overflow flag (tovn) is set at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at bottom). when either ocrna or icrn is used for defining the top value, the ocna or icfn flag set when tcntn has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the com- pare registers, a compare match will neve r occur between the tcntn and the ocrnx. as figure 15-9 shows the output generated is, in contrast to the phase correct mode, symmetri- cal in all periods. since the ocrnx registers are updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and is therefore frequency correct. r pfcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx / top update and tovn interrupt flag set (interrupt on bottom) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) 132 8151h?avr?02/11 atmega128a using the icrn register for defining top work s well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a pwm output on ocna. however, if the base pwm frequency is actively changed by changing the top value, using the ocrna as top is clearly a better choice due to its double buffer feature. in phase and frequency correct pwm mode, the compare units allow generation of pwm wave- forms on the ocnx pins. setting the comnx1:0 bits to 2 will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to 3 (see table 15-4 on page 136 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn when the counter incre- ments, and clearing (or setting) the ocnx register at compare match between ocrnx and tcntn when the counter decrements. the pw m frequency for the output when using phase and frequency correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be set to high for non- inverted pwm mode. for inverted pwm the output will have the opposite logic values. if ocrna is used to define the top value (wgmn3:0 = 9) and comna1:0 = 1, the ocna output will toggle with a 50% duty cycle. 15.10 timer/counte r timing diagrams the timer/counter is a synchronous design and the timer clock (clk tn ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set, and when the ocrnx register is updated with the ocrnx buffer value (only for modes utilizing double buffering). figure 15-10 shows a timing diagram for the setting of ocfnx. figure 15-10. timer/counter timing diagram, setting of ocfnx, no prescaling figure 15-11 shows the same timing data, but with the prescaler enabled. f ocnxpfcpwm f clk_i/o 2 ntop ?? --------------------------- - = clk tn (clk i/o /1) ocfnx clk i/o ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 133 8151h?avr?02/11 atmega128a figure 15-11. timer/counter timing diagram, setting of ocfnx, with prescaler (f clk_i/o /8) figure 15-12 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode the ocrnx register is updated at bottom. the timing diagrams will be the same, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tovn flag at bottom. figure 15-12. timer/counter timing diagram, no prescaling figure 15-13 shows the same timing data, but with the prescaler enabled. ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk tn (clk i/o /1) clk i/o 134 8151h?avr?02/11 atmega128a figure 15-13. timer/counter timing dia gram, with prescaler (f clk_i/o /8) 15.11 register description 15.11.1 tccr1a - timer/counter1 control register a 15.11.2 tccr3a - timer/counter3 control register a ? bit 7:6 ? comna1:0: compare output mode for channel a ? bit 5:4 ? comnb1:0: compare output mode for channel b ? bit 3:2 ? comnc1:0: compare output mode for channel c the comna1:0, comnb1:0, and comnc1:0 control the output compare pins (ocna, ocnb, and ocnc respectively) behavior. if one or both of the comna1:0 bits are written to one, the ocna output overrides the normal port functionality of the i/o pin it is connected to. if one or both of the comnb1:0 bits are written to one, the ocnb output overrides the normal port func- tionality of the i/o pin it is connected to. if one or both of the comnc1:0 bits are written to one, the ocnc output overrides the normal port functionality of the i/o pin it is connected to. how- ever, note that the data direction register (ddr) bit corresponding to the ocna, ocnb or ocnc pin must be set in order to enable the output driver. when the ocna, ocnb or ocnc is connected to the pin, the function of the comnx1:0 bits is dependent of the wgmn3:0 bits setting. table 15-2 shows the comnx1:0 bit functionality when the wgmn3:0 bits are set to a normal or a ctc mode (non-pwm). tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) bit 76543210 com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 com3a1 com3a0 com3b1 com3b0 com3c1 com3c0 wgm31 wgm30 tccr3a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 135 8151h?avr?02/11 atmega128a table 15-3 shows the comnx1:0 bit functionality when the wgmn3:0 bits are set to the fast pwm mode note: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1/comnc1 is set. in this case t he compare match is ignored, but the set or clear is done at bottom. see ?fast pwm mode? on page 126. for more details. table 15-3 shows the comnx1:0 bit functionality when the wgmn3:0 bits are set to the phase correct and frequency correct pwm mode. table 15-2. compare output mode, non-pwm comna1/comnb1/ comnc1 comna0/comnb0/ comnc0 description 0 0 normal port operation, ocna/ocnb/ocnc disconnected. 0 1 toggle ocna/ocnb/ocnc on compare match. 1 0 clear ocna/ocnb/ocnc on compare match (set output to low level). 1 1 set ocna/ocnb/ocnc on compare match (set output to high level). table 15-3. compare output mode, fast pwm comna1/comnb1/ comnc1 comna0/comnb0/ comnc0 description 0 0 normal port operation, ocna/ocnb/ocnc disconnected. 0 1 wgmn3:0 = 15: toggle ocna on compare match, ocnb/ocnc disconnected (normal port operation). for all other wgmn settings, normal port operation, ocna/ocnb/ocnc disconnected. 1 0 clear ocna/ocnb/ocnc on compare match, set ocna/ocnb/ocnc at bottom, (non-inverting mode) 1 1 set ocna/ocnb/ocnc on compare match, clear ocna/ocnb/ocnc at bottom, (inverting mode) 136 8151h?avr?02/11 atmega128a note: 1. a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1//comnc1 is set. see ?phase correct pwm mode? on page 128. for more details. ? bit 1:0 ? wgmn1:0: waveform generation mode combined with the wgmn3:2 bits found in the tccrnb register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 15-5 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and three types of pulse width modulation (pwm) modes. ( see ?modes of operation? on page 125. ) table 15-4. compare output mode, phase correct and phase and frequency correct pwm comna1/comnb1/ comnc1 comna0/comnb0/ comnc0 description 0 0 normal port operation, ocna/ocnb/ocnc disconnected. 0 1 wgmn3:0 = 9 or 11: toggle ocna on compare match, ocnb/ocnc disconnected (normal port operation). for all other wgmn settings, normal port operation, ocna/ocnb/ocnc disconnected. 1 0 clear ocna/ocnb/ocnc on compare match when up-counting. set ocna/ocnb/ocnc on compare match when downcounting. 1 1 set ocna/ocnb/ocnc on compare match when up-counting. clear ocna/ocnb/ocnc on compare match when downcounting. table 15-5. waveform generation mode bit description mode wgmn3 wgmn2 (ctcn) wgmn1 (pwmn1) wgmn0 (pwmn0) timer/counter mode of operation (1) top update of ocrn x at tovn flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 3 0 0 1 1 pwm, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocrna immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff bottom top 6 0 1 1 0 fast pwm, 9-bit 0x01ff bottom top 7 0 1 1 1 fast pwm, 10-bit 0x03ff bottom top 8 1 0 0 0 pwm, phase and frequency correct icrn bottom bottom 9 1 0 0 1 pwm, phase and frequency correct ocrna bottom bottom 10 1 0 1 0 pwm, phase correct icrn top bottom 11 1 0 1 1 pwm, phase correct ocrna top bottom 137 8151h?avr?02/11 atmega128a note: 1. the ctcn and pwmn1:0 bit defi nition names are obsolete. use the wgm n2:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. 15.11.3 tccr1b - timer/counter1 control register b 15.11.4 tccr3b - timer/counter3 control register b ? bit 7 ? icncn: input capture noise canceler setting this bit (to one) activates the input ca pture noise canceler. when the noise canceler is activated, the input from the input capture pin (icpn) is filtered. the filter function requires four successive equal valued samples of the icpn pin for changing its output. the input capture is therefore delayed by four oscillator cycles when the noise canceler is enabled. ? bit 6 ? icesn: input capture edge select this bit selects which edge on the input capture pin (icpn) that is used to trigger a capture event. when the icesn bit is written to zero, a falling (negative) edge is used as trigger, and when the icesn bit is written to one, a risi ng (positive) edge w ill trigger the capture. when a capture is triggered according to the icesn setting, the counter value is copied into the input capture register (icrn). the event will also set the input capture flag (icfn), and this can be used to cause an input capture interrupt, if this interrupt is enabled. when the icrn is used as top value (see description of the wgmn3:0 bits located in the tccrna and the tccrnb register), the icpn is disconnected and consequently the input cap- ture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibility with future de vices, this bit must be written to zero when tccrnb is written. ? bit 4:3 ? wgmn3:2: waveform generation mode see tccrna register description. 12 1 1 0 0 ctc icrn immediate max 13 1 1 0 1 (reserved) ? ? ? 14 1 1 1 0 fast pwm icrn bottom top 15 1 1 1 1 fast pwm ocrna bottom top table 15-5. waveform generation mode bit description mode wgmn3 wgmn2 (ctcn) wgmn1 (pwmn1) wgmn0 (pwmn0) timer/counter mode of operation (1) top update of ocrn x at tovn flag set on bit 76543210 icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 icnc3 ices3 ? wgm33 wgm32 cs32 cs31 cs30 tccr3b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 138 8151h?avr?02/11 atmega128a ? bit 2:0 ? csn2:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see figure 15-10 and figure 15-11 . if external pin modes are used for the timer/countern, transitions on the tn pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 15.11.5 tccr1c - timer/counter1 control register c 15.11.6 tccr3c - timer/counter3 control register c ? bit 7 ? focna: force output compare for channel a ? bit 6 ? focnb: force output compare for channel b ? bit 5 ? focnc: force output compare for channel c the focna/focnb/focnc bits are only active when the wgmn3:0 bits specifies a non-pwm mode. when writing a logical one to the fo cna/focnb/focnc bit, an immediate compare match is forced on the waveform generation unit. the ocna/ocnb/ocnc output is changed according to its comnx1:0 bits setting. note that the focna/focnb/focnc bits are imple- mented as strobes. therefore it is the value present in the comnx1:0 bits that determine the effect of the forced compare. a focna/focnb/focnc strobe will no t generate any interrupt nor w ill it clear the timer in clear timer on compare match (ctc) mode using ocrna as top. the focna/focnb/focnb bits are always read as zero. table 15-6. clock select bit description csn2 csn1 csn0 description 0 0 0 no clock source. (timer/counter stopped) 001clk i/o /1 (no prescaling 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on tn pin. clock on falling edge 1 1 1 external clock source on tn pin. clock on rising edge bit 76543210 foc1a foc1b foc1c ? ? ? ? ? tccr1c read/write wwwrrrrr initial value 0 0 0 0 0 0 0 0 bit 76543210 foc3a foc3b foc3c ? ? ? ? ? tccr3c read/write wwwrrrrr initial value00000000 139 8151h?avr?02/11 atmega128a ? bit 4:0 ? reserved these bits are reserved for future use. for ensuring compatibility with future devices, these bits must be written to zero when tccrnc is written. 15.11.7 tcnt1h and tcnt1l - timer/counter1 15.11.8 tcnt3h and tcnt3ltimer/counter3 the two timer/counter i/o locations (tcntnh and tcntnl , combined tcntn) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is perfo rmed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16- bit registers? on page 115. modifying the counter (tcntn) while the counte r is running introduces a risk of missing a com- pare match between tcntn and one of the ocrnx registers. writing to the tcntn register blocks (removes) the compare match on the following timer clock for all compare units. 15.11.9 ocr1ah and ocr1al - ou tput compare register 1 a 15.11.10 ocr1bh and ocr1bl - ou tput compare register 1 b bit 76543210 tcnt1[15:8] tcnt1h tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 tcnt3[15:8] tcnt3h tcnt3[7:0] tcnt3l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ocr1a[15:8] ocr1ah ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ocr1b[15:8] ocr1bh ocr1b[7:0] ocr1bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 140 8151h?avr?02/11 atmega128a 15.11.11 ocr1ch and ocr1cl - ou tput compare register 1 c 15.11.12 ocr3ah and ocr3al - ou tput compare register 3 a 15.11.13 ocr3bh and ocr3bl - ou tput compare register 3 b 15.11.14 ocr3ch and ocr3cl - ou tput compare register 3 c the output compare registers contain a 16-bit value that is continuously compared with the counter value (tcntn). a match can be used to generate an output compare interrupt, or to generate a waveform output on the ocnx pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cp u writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 115. 15.11.15 icr1h and icr1l - input capture register 1 bit 76543210 ocr1c[15:8] ocr1ch ocr1c[7:0] ocr1cl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ocr3a[15:8] ocr3ah ocr3a[7:0] ocr3al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr3b[15:8] ocr3bh ocr3b[7:0] ocr3bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr3c[15:8] ocr3ch ocr3c[7:0] ocr3cl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 icr1[15:8] icr1h icr1[7:0] icr1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 141 8151h?avr?02/11 atmega128a 15.11.16 icr3h and icr3l - input capture register 3 the input capture is updated with the counter (tcntn) value each time an event occurs on the icpn pin (or optionally on the analog comparat or output for timer/counter1). the input cap- ture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these regi sters, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 115. 15.11.17 timsk - ti mer/counter interrupt mask register note: this register contains interrupt control bits fo r several timer/counters, but only timer1 bits are described in this section. the remaining bits are described in their respective timer sections. ? bit 5 ? ticie1: timer/counter1, input capture interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 input capture interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 59. ) is executed when the icf1 flag, located in tifr, is set. ? bit 4 ? ocie1a: timer/counter1, output compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 output compare a match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the ocf1a flag, located in tifr, is set. ? bit 3 ? ocie1b: timer/counter1, output compare b match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 output compare b match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the ocf1b flag, located in tifr, is set. ? bit 2 ? toie1: timer/counter1, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 overflow interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the tov1 flag, located in tifr, is set. bit 76543210 icr3[15:8] icr3h icr3[7:0] icr3l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 timsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 142 8151h?avr?02/11 atmega128a 15.11.18 etimsk - extended timer/ counter interrupt mask register note: this register is not available in atmega103 compatibility mode. ? bit 7:6 ? reserved these bits are reserved for future use. for ensuring compatibility with future devices, these bits must be set to zero when etimsk is written. ? bit 5 ? ticie3: timer/counter3, input capture interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter3 input capture interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the icf3 flag, located in etifr, is set. ? bit 4 ? ocie3a: timer/counter3, output compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter3 output compare a match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the ocf3a flag, located in etifr, is set. ? bit 3 ? ocie3b: timer/counter3, output compare b match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter3 output compare b match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the ocf3b flag, located in etifr, is set. ? bit 2 ? toie3: timer/counter3, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter3 overflow interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the tov3 flag, located in etifr, is set. ? bit 1 ? ocie3c: timer/counter3, output compare c match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter3 output compare c match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the ocf3c flag, located in etifr, is set. ? bit 0 ? ocie1c: timer/counter1, output compare c match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 output compare c match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 59) is executed when the ocf1c flag, located in etifr, is set. bit 76543210 ? ? ticie3 ocie3a ocie3b toie3 ocie3c ocie1c etimsk read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 143 8151h?avr?02/11 atmega128a 15.11.19 tifr - ti mer/counter interrupt flag register note: this register contains flag bits for several ti mer/counters, but only timer 1 bits are described in this section. the remaining bits are descr ibed in their respective timer sections. ? bit 5 ? icf1: timer/count er1, input capture flag this flag is set when a capture event occurs on the icp1 pin. when the input capture register (icr1) is set by the wgmn3:0 to be used as the top value, the icf1 flag is set when the coun- ter reaches the top value. icf1 is automatically cleared when the input capt ure interrupt vector is executed. alternatively, icf1 can be cleared by writing a logic one to its bit location. ? bit 4 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle afte r the counter (tcnt1) value matches the output compare register a (ocr1a). note that a forced outpu t compare (foc1a) strobe will not set the ocf1a flag. ocf1a is automatically cleared when the output compare match a interrupt vector is executed. alternatively, ocf1a can be cleared by writing a logic one to its bit location. ? bit 3 ? ocf1b: timer/counter1, output compare b match flag this flag is set in the timer clock cycle afte r the counter (tcnt1) value matches the output compare register b (ocr1b). note that a forced outpu t compare (foc1b) strobe will not set the ocf1b flag. ocf1b is automatically cleared when the output compare match b interrupt vector is executed. alternatively, ocf1b can be cleared by writing a logic one to its bit location. ? bit 2 ? tov1: timer/counter1, overflow flag the setting of this flag is dependent of the wgmn3:0 bits setting. in normal and ctc modes, the tov1 flag is set when the timer overflows. refer to table 15-5 on page 136 for the tov1 flag behavior when using another wgmn3:0 bit setting. ? tov1 is automatically cleared when the timer/counter1 overflow interrupt vector is executed. alternatively, tov1 can be cleared by writing a logic one to its bit location. 15.11.20 etifr - extended timer/co unter interrupt flag register ? bit 7:6 ? reserved these bits are reserved for future use. for ensuring compatibility with future devices, these bits must be set to zero when etifr is written. bit 76543210 ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 tifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ? ? icf3 ocf3a ocf3b tov3 ocf3c ocf1c etifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 144 8151h?avr?02/11 atmega128a ? bit 5 ? icf3: timer/count er3, input capture flag this flag is set when a capture event occurs on the icp3 pin. when the input capture register (icr3) is set by the wgm3:0 to be used as the top value, the icf3 flag is set when the counter reaches the top value. icf3 is automatically cleared when the input capt ure 3 interrupt vector is executed. alterna- tively, icf3 can be cleared by writing a logic one to its bit location. ? bit 4 ? ocf3a: timer/counter3, output compare a match flag this flag is set in the timer clock cycle afte r the counter (tcnt3) value matches the output compare register a (ocr3a). note that a forced outpu t compare (foc3a) strobe will not set the ocf3a flag. ocf3a is automatically cleared when the output compare match 3 a interrupt vector is exe- cuted. alternatively, ocf3a can be cleared by writing a logic one to its bit location. ? bit 3 ? ocf3b: timer/counter3, output compare b match flag this flag is set in the timer clock cycle afte r the counter (tcnt3) value matches the output compare register b (ocr3b). note that a forced outpu t compare (foc3b) strobe will not set the ocf3b flag. ocf3b is automatically cleared when the output compare match 3 b interrupt vector is exe- cuted. alternatively, ocf3b can be cleared by writing a logic one to its bit location. ? bit 2 ? tov3: timer/counter3, overflow flag the setting of this flag is dependent of the wgm3:0 bits setting. in normal and ctc modes, the tov3 flag is set when the timer overflows. refer to table 14-2 on page 107 for the tov3 flag behavior when using another wgm3:0 bit setting. tov3 is automatically cleared when the timer/counter3 overflow interrupt vector is executed. alternatively, tov3 can be cleared by writing a logic one to its bit location. ? bit 1 ? ocf3c: timer/counter3, output compare c match flag this flag is set in the timer clock cycle afte r the counter (tcnt3) value matches the output compare register c (ocr3c). note that a forced outpu t compare (foc3c) strobe will not set the ocf3c flag. ocf3c is automatically cleared when the output compare match 3 c interrupt vector is exe- cuted. alternatively, ocf3c can be cleared by writing a logic one to its bit location. ? bit 0 ? ocf1c: timer/counter1, output compare c match flag this flag is set in the timer clock cycle afte r the counter (tcnt1) value matches the output compare register c (ocr1c). note that a forced outpu t compare (foc1c) strobe will not set the ocf1c flag. ocf1c is automatically cleared when the output compare match 1 c interrupt vector is exe- cuted. alternatively, ocf1c can be cleared by writing a logic one to its bit location. 145 8151h?avr?02/11 atmega128a 16. timer/counter3, timer/counter2 , and timer/counter1 prescalers timer/counter3, timer/counter1, and timer/c ounter2 share the same prescaler module, but the timer/counters can have different prescaler settings. the description below applies to all of the mentioned timer/counters. 16.1 internal clock source the timer/counter can be clocked directly by the system clock (by setting the csn2:0 = 1). this provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the prescaler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. 16.2 prescaler reset the prescaler is free running, that is, operates independently of the clock select logic of the timer/counter, and it is shared by timer/counter1, timer/counter2, and timer/counter3. since the prescaler is not affected by the timer/counter?s clock select , the state of the prescaler will have implications for situations where a prescal ed clock is used. one example of prescaling arti- facts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycl es from when the timer is enable d to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for synchronizing the timer/counter to program execu- tion. however, care must be taken if the other timer/counter that shares the same prescaler also use prescaling. a prescaler re set will affect the prescaler peri od for all timer/ counters it is connected to. 16.3 external clock source an external clock source applied to the tn pin can be used as timer/counter clock (clk t1 /clk t2 /clk t3 ). the tn pin is sampled once every sy stem clock cycle by the pin synchroniza- tion logic. the synchronized (sampled) signal is then pass ed through the edge detector. figure 16-1 shows a functional equivalent block diagram of the tn synchronization and edge detector logic. the registers are clocked at the po sitive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk t1 /clk t 2 /clk t 3 pulse for each positive (csn2:0 = 7) or nega- tive (csn2:0 = 6) edge it detects. figure 16-1. tn pin sampling tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o 146 8151h?avr?02/11 atmega128a the synchronization and e dge detector logic introduces a de lay of 2.5 to 3.5 system clock cycles from an edge has been applied to the tn pin to the counter is updated. enabling and disabling of the clock input must be done when tn has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. each half period of the external clock applie d must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the sys- tem clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling fre- quency (nyquist sampling theorem). however, due to variation of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 16-2. prescaler for timer/counter1, timer/counter2, and timer/counter3 note: the synchronization logic on the input pins ( t3/t2/t1) is shown in figure 16-1 . 16.4 register description 16.4.1 sfior - special function io register ? bit 7 ? tsm: timer/counter synchronization mode writing the tsm bit to one activates the timer/counter synchronization mode. in this mode, the value that is written to the psr0 and psr 321 bits is kept, hence keeping the corresponding prescaler reset signals asserted. this ensures th at the corresponding timer/counters are halted and can be configured to the same value withou t the risk of one of them advancing during con- figuration. when the tsm bit is written to zero, the psr0 and psr321 bits are cleared by hardware, and the timer/counters start counting simultaneously. ? bit 0 ? psr321: prescaler reset timer/counter3, timer/counter2, and timer/counter1 when this bit is one, the time r/counter3, timer/counter1, an d timer/counter2 prescaler will be reset. this bit is normally cleared immediately by hardware, except if the tsm bit is set. note psr321 clear clk t2 timer/counter2 clock source 0 cs20 cs21 cs22 t2 clk t1 timer/counter1 clock source 0 cs10 cs11 cs12 t1 clk t3 timer/counter3 clock source 0 cs30 cs31 cs32 t3 10-bit t/c prescaler ck ck/8 ck/64 ck/256 ck/1024 bit 7 6 5 4 3 2 1 0 tsm ? ? ? acme pud psr0 psr321 sfior read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 147 8151h?avr?02/11 atmega128a that timer/counter3, timer/counter1, and timer/counter2 share the same prescaler and a reset of this prescaler will affect all three timers. 148 8151h?avr?02/11 atmega128a 17. 8-bit timer/counter2 with pwm 17.1 features ? single channel counter ? clear timer on compare match (auto reload) ? glitch-free, phase correct pulse width modulator (pwm) ? frequency generator ? external event counter ? 10-bit clock prescaler ? overflow and compare match inte rrupt sources (tov2 and ocf2) 17.2 overview timer/counter2 is a general purpose, single channel, 8-bit timer/counter module. a simplified block diagram of the 8-bit timer/counter is shown in figure 17-1 . for the actual placement of i/o pins, refer to ?pin configurations? on page 2 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?register description? on page 159 . figure 17-1. 8-bit timer/counter block diagram timer/counter data b u s = tcntn waveform generation ocn = 0 control logic = 0xff bottom count clear direction tovn (int.req.) ocrn tccrn clock select tn edge detector ( from prescaler ) clk tn top ocn (int.req.) 149 8151h?avr?02/11 atmega128a 17.2.1 registers the timer/counter (tcnt2) and output compare register (ocr2) are 8-bit registers. interrupt request (abbreviated to int.req. in the figure) si gnals are all visible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (timsk). tifr and timsk are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t2 pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t2 ). the double buffered output compare register (ocr2) is compared with the timer/counter value at all times. the result of the compare can be used by the waveform generator to generate a pwm or variable frequency output on the output compare pin (oc2). see ?output compare unit? on page 150. for details. the compare match event will also set the compare flag (ocf2) which can be used to generate an output compare interrupt request. 17.2.2 definitions many register and bit references in this document are written in general form. a lower case ?n? replaces the timer/counter number, in this case 2. however, when using the register or bit defines in a program, the precise form must be used (that is, tcnt2 for accessing timer/counter2 counter value and so on). the definitions in table 17-1 are also used extensively throughout the document. 17.3 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is co ntrolled by the clock select (cs22:0) bits located in the timer/counter control regi ster (tccr2). for details on clock sources and prescaler, see ?timer/counter3, timer/counter2, and timer/counter1 prescalers? on page 145 . 17.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 17-2 shows a block diagram of the counter and its surroundings. table 17-1. definitions bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum wh en it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr2 register. the assignment is dependent on the mode of operation. 150 8151h?avr?02/11 atmega128a figure 17-2. counter unit block diagram signal description (internal signals): count increment or decrement tcnt2 by 1. direction select between increment and decrement. clear clear tcnt2 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tcnt2 has reached maximum value. bottom signalize that tcnt2 has re ached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t2 ). clk t2 can be generated from an external or internal clock source, selected by the clock select bits (cs22:0). when no clock source is selected (cs22:0 = 0) the timer is stopped. however, the tcnt2 value can be accessed by the cpu, regardless of whether clk t2 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr2). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare output oc2. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 153 . the timer/counter overflow (tov2) flag is set according to the mode of operation selected by the wgm21:0 bits. tov2 can be used for generating a cpu interrupt. 17.5 output compare unit the 8-bit comparator continuously compares tcnt2 with the output compare register (ocr2). whenever tcnt2 equals ocr2, the comparator signals a match. a match will set the output compare flag (ocf2) at the next timer clock cycle. if enabled (ocie2 = 1 and global inter- rupt flag in sreg is set), the output compare flag generates an output compare interrupt. the ocf2 flag is automatically cleared when the interr upt is executed. alternatively, the ocf2 flag can be cleared by software by writing a logical one to its i/o bit location. the waveform genera- tor uses the match signal to generate an output according to operating mode set by the wgm21:0 bits and compare output mode (com21:0) bits. the max and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes data b u s tcntn control logic count tovn (int.req.) clock select top tn edge detector ( from prescaler ) clk tn bottom direction clear 151 8151h?avr?02/11 atmega128a of operation (see ?modes of operation? on page 153). figure 17-3 shows a block diagram of the output compare unit. figure 17-3. output compare unit, block diagram the ocr2 register is double buffered when us ing any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buff- ering is disabled. the double buffering synchron izes the update of the ocr2 compare register to either top or bottom of the counting sequenc e. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr2 register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocr2 buffer register, and if double buffering is disabled the cpu will access the ocr2 directly. 17.5.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force outp ut compare (foc2) bit. forcin g compare match will not set the ocf2 flag or reload/clear the timer, but the oc2 pin will be updated as if a real compare match had occurred (the com21:0 bits settings define whether the oc2 pin is set, cleared or toggled). 17.5.2 compare match bloc king by tcnt2 write all cpu write operations to th e tcnt2 register will block any co mpare match that occur in the next timer clock cycle, even when the timer is st opped. this feature allows ocr2 to be initialized to the same value as tcnt2 without triggering an interrupt when the timer/counter clock is enabled. 17.5.3 using the output compare unit since writing tcnt2 in any mode of operation will block all comp are matches for one timer clock cycle, there are risks involved when changi ng tcnt2 when using the output compare channel, independently of whether the timer/counter is running or not. if the value written to tcnt2 ocfn (int.req.) = (8-bit comparator ) ocrn ocn data b u s tcntn wgmn1:0 waveform generator top focn comn1:0 bottom 152 8151h?avr?02/11 atmega128a equals the ocr2 value, the compare match will be missed, re sulting in incorrect waveform gen- eration. similarly, do not write the tcnt2 value equal to bottom when the counter is downcounting. the setup of the oc2 should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc2 value is to use the force output compare (foc2) strobe bits in normal mode. the oc2 register keeps its value even when changing between waveform generation modes. be aware that the com21:0 bits are not double buffered together with the compare value. changing the com21:0 bits will take effect immediately. 17.6 compare match output unit the compare output mode (com21:0) bits have two functions. the waveform generator uses the com21:0 bits for defining the output compare (oc2) state at the next compare match. also, the com21:0 bits control the oc2 pin output source. figure 17-4 shows a simplified schematic of the logic affected by the com21:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com21:0 bits are shown. when referring to the oc2 state, the reference is for the internal oc2 register, not the oc2 pin. if a system reset occur, the oc2 register is reset to ?0?. figure 17-4. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc2) from the waveform generator if either of the com21:0 bits are set. however, the oc2 pin direction (input or output) is still controlled by the data direction register (ddr) for the port pin. the data direction regis- ter bit for the oc2 pin (ddr_oc2) must be set as output before the oc2 value is visible on the pin. the port override function is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc2 state before the out- put is enabled. note that some com21:0 bit settings are reserved for certain modes of operation. see ?register description? on page 159. port ddr dq dq ocn pin ocn dq waveform generator comn1 comn0 0 1 data b u s focn clk i/o 153 8151h?avr?02/11 atmega128a 17.6.1 compare output mode and waveform generation the waveform generator uses the com21:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com21:0 = 0 tells the waveform generator that no action on the oc2 register is to be performed on the next compare match. for compare output actions in the non- pwm modes refer to table 17-3 on page 160 . for fast pwm mode, refer to table 17-4 on page 160 , and for phase correct pwm refer to table 17-5 on page 161 . a change of the com21:0 bits state will have effect at the first compare ma tch after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the foc2 strobe bits. 17.7 modes of operation the mode of operation, that is, the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm21:0) and compare out- put mode (com21:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com21:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com21:0 bits control whether the output should be set, cleared, or toggled at a compare match (see ?compare match output unit? on page 152). for detailed timing information refer to figure 17-8 , figure 17-9 , figure 17-10 , and figure 17-11 in ?timer/counter timing diagrams? on page 157 . 17.7.1 normal mode the simplest mode of operation is the normal mode (wgm21:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal operation the timer/counter overflow flag ( tov 2) will be set in the same timer clock cycle as the tcnt2 becomes zero. the tov 2 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov 2 flag, the timer resolution can be increased by software. there are no special cases to consider in the norma l mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to gener ate waveforms in normal mode is no t recommended, since this will occupy too much of the cpu time. 17.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm21:0 = 2), the ocr2 register is used to manip- ulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt2) matches the ocr2. the ocr2 defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also sim- plifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 17-5 . the counter value (tcnt2) increases until a compare match occurs between tcnt2 and ocr2 and then counter (tcnt2) is cleared. 154 8151h?avr?02/11 atmega128a figure 17-5. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf2 flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr2 is lower than the current value of tcnt2, the counter will miss the compar e match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc2 output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com21:0 = 1). the oc2 value will no t be visible on the port pin unl ess the data direction for the pin is set to output. the waveform generated will have a maximum frequency of f oc2 = f clk_i/o /2 when ocr2 is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov2 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 17.7.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm21:0 = 3) provides a high frequency pwm waveform generation option. the fast pwm di ffers from the other pwm option by its sin- gle-slope operation. the counter counts from bottom to max then restarts from bottom. in non-inverting compare output mode, the output compare (oc2) is cleared on the compare match between tcnt2 and ocr2, and set at bottom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac app lications. high frequency a llows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the max value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 17-6 . the tcnt2 value is in the timing diagram shown as a his- tcntn ocn (toggle) ocn interrupt flag set 1 4 period 2 3 (comn1:0 = 1) f ocn f clk_i/o 2 n 1 ocrn + () ?? ---------------------------------------------- - = 155 8151h?avr?02/11 atmega128a togram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt2 slopes represent compare matches between ocr2 and tcnt2. figure 17-6. fast pwm mode, timing diagram the timer/counter overflow flag (tov2) is set each time the counter reaches max if the inter- rupt is enabled, the interrupt handler routine can be used for updating the compare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc2 pin. set- ting the com21:0 bits to 2 will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com21:0 to 3 (see table 17-4 on page 160 ). the actual oc2 value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc2 register at the compare match between ocr2 and tcnt2, and clearing (or setting) the oc2 register at the timer clock cycle the coun- ter is cleared (changes from max to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr2 register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr2 is set equal to bottom, the output will be a narrow spike for each max+1 ti mer clock cycle. setting the ocr2 equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com21:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting oc2 to toggle its logical level on each compare match (com21:0 = 1). the waveform generated will have a ma ximum frequency of f oc2 = f clk_i/o /2 when ocr2 is set to zero. this fea- ture is similar to the oc2 toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. tcntn ocrn update and tovn interrupt flag set 1 period 2 3 ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn interrupt flag set 4 5 6 7 f ocnpwm f clk_i/o n 256 ? ------------------ = 156 8151h?avr?02/11 atmega128a 17.7.4 phase correct pwm mode the phase correct pwm mode (wgm21:0 = 1) pr ovides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter counts repeatedly from bottom to max and then from max to bottom. in non- inverting compare output mode, the output compare (oc2) is cleared on the compare match between tcnt2 and ocr2 while counting up, and set on the compare match while downcount- ing. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmet- ric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode is fixed to 8 bits. in phase correct pwm mode the counter is incremented until the counter value matches max when the counter reaches max, it changes the count direction. the tcnt2 value will be equal to max for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 17-7 . the tcnt2 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt2 slopes represent compare matches between ocr2 and tcnt2. figure 17-7. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov2) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc2 pin. setting the com21:0 bi ts to 2 will produce a non-invert ed pwm. an inverted pwm out- put can be generated by setting the com21:0 to 3 (see table 17-5 on page 161 ). the actual oc2 value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the oc2 register at the compare tovn interrupt flag set ocn interrupt flag set 1 2 3 tcntn period ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn update 157 8151h?avr?02/11 atmega128a match between ocr2 and tcnt2 when the counter increments, and setting (or clearing) the oc2 register at compare match between ocr2 and tcnt2 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the follow- ing equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr2 register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr2 is set equal to bottom, the out- put will be continuously low and if set equal to max the output will be continuously high for non- inverted pwm mode. for inverted pwm the output will have the opposite logic values. at the very start of period 2 in figure 17-7 ocn has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bot- tom. there are two cases that give a transition without a compare match: ? ocr2a changes its value from max, like in figure 17-7 . when the ocr2a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up- counting compare match. ? the timer starts counting from a value higher than the one in ocr2a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 17.8 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t2 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set. figure 17-8 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max val ue in all modes other than phase correct pwm mode. figure 17-8. timer/counter timing diagram, no prescaling figure 17-9 shows the same timing data, but with the prescaler enabled. f ocnpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1 158 8151h?avr?02/11 atmega128a figure 17-9. timer/counter timing dia gram, with prescaler (f clk_i/o /8) figure 17-10 shows the setting of ocf2 in all modes except ctc mode. figure 17-10. timer/counter timing diagram, setti ng of ocf2, with prescaler (f clk_i/o /8) figure 17-11 shows the setting of ocf2 and the clearing of tcnt2 in ctc mode. tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfn ocrn tcntn ocrn value ocrn - 1 ocrn ocrn + 1 ocrn + 2 clk i/o clk tn (clk i/o /8) 159 8151h?avr?02/11 atmega128a figure 17-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) 17.9 register description 17.9.1 tccr2 - timer/counter control register ? bit 7 ? foc2: force output compare the foc2 bit is only active when the wgm20 bit specifies a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr2 is written when operating in pwm mode. when writing a logical one to the foc2 bit, an immediate com- pare match is forced on the waveform generati on unit. the oc2 output is changed according to its com21:0 bits setting. note that the foc2 bi t is implemented as a strobe. therefore it is the value present in the com21:0 bits that determines the effect of the forced compare. a foc2 strobe will not gene rate any interrupt, nor will it cl ear the timer in ctc mode using ocr2 as top. the foc2 bit is always read as zero. ? bit 6, 3 ? wgm21:0: waveform generation mode these bits control the counting sequence of the counter, the source for the maximum (top) counter value, and what type of waveform generation to be used. modes of operation supported by the timer/counter unit are: normal mode, clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes. see table 17-2 and ?modes of operation? on page 153 . ocfn ocrn tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) bit 76543210 foc2 wgm20 com21 com20 wgm21 cs22 cs21 cs20 tccr2 read/write w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 160 8151h?avr?02/11 atmega128a note: the ctc2 and pwm2 bit definition names are now obsolete. use the wgm21:0 definitions. how- ever, the functionality and location of these bits ar e compatible with previous versions of the timer. ? bit 5:4 ? com21:0: compare match output mode these bits control the output compare pin (oc2) behavior. if one or both of the com21:0 bits are set, the oc2 output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction register (ddr) bit corresponding to the oc2 pin must be set in order to enable the output driver. when oc2 is connected to the pin, the function of the com21:0 bits depends on the wgm21:0 bit setting. table 17-3 shows the com21:0 bit functionality when the wgm21:0 bits are set to a normal or ctc mode (non-pwm). table 17-4 shows the com21:0 bit functionality when the wgm21:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr2 equals top and com21 is set. in this case, the compare match is ignored, but the set or clear is done at bottom. see ?fast pwm mode? on page 154 for more details. table 17-2. waveform generation mode bit description mode wgm21 (ctc2) wgm20 (pwm2) timer/counter mode of operation top update of ocr2 at tov2 flag set on 0 0 0 normal 0xff immediate max 1 0 1 pwm, phase correct 0xff top bottom 2 1 0 ctc ocr2 immediate max 3 1 1 fast pwm 0xff bottom max table 17-3. compare output mode, non-pwm mode com21 com20 description 0 0 normal port operation, oc2 disconnected. 0 1 toggle oc2 on compare match 1 0 clear oc2 on compare match 1 1 set oc2 on compare match table 17-4. compare output mode, fast pwm mode (1) com21 com20 description 0 0 normal port operation, oc2 disconnected. 01reserved 1 0 clear oc2 on compare match, set oc2 at bottom, (non-inverting mode) 1 1 set oc2 on compare match, clear oc2 at bottom, (inverting mode) 161 8151h?avr?02/11 atmega128a table 17-5 shows the com21:0 bit functionality when the wgm21:0 bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr2 equals top and com21 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 156 for more details. ? bit 2:0 ? cs22:0: clock select the three clock select bits select the clock source to be used by the timer/counter. if external pin modes are used for the timer/counter2, transitions on the t2 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 17.9.2 tcnt2 - timer/counter register the timer/counter register gives direct ac cess, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt2 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt2) while the counter is running, introduces a risk of missing a compare match between tcnt2 and the ocr2 register. table 17-5. compare output mode, phase correct pwm mode (1) com21 com20 description 0 0 normal port operation, oc2 disconnected. 01reserved 1 0 clear oc2 on compare match when up -counting. set oc2 on compare match when downcounting. 1 1 set oc2 on compare match when up-c ounting. clear oc2 on compare match when downcounting. table 17-6. clock select bit description cs22 cs21 cs20 description 0 0 0 no clock source (timer/counter stopped) 001clk i/o /(no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t2 pin. clock on falling edge 1 1 1 external clock source on t2 pin. clock on rising edge bit 76543210 tcnt2[7:0] tcnt2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 162 8151h?avr?02/11 atmega128a 17.9.3 ocr2 - output compare register the output compare register contains an 8-bit value that is continuously compared with the counter value (tcnt2). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc2 pin. 17.9.4 timsk - timer/counter interrupt mask register ? bit 7 ? ocie2: timer/counter2 output compare match interrupt enable when the ocie2 bit is written to one, and the i-bit in the status register is set (one), the timer/counter2 compare match interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter2 occurs, that is , when the ocf2 bit is set in the timer/coun- ter interrupt flag register ? tifr. ? bit 6 ? toie2: timer/counter2 overflow interrupt enable when the toie2 bit is written to one, and the i-bit in the status register is set (one), the timer/counter2 overflow interrupt is enabled. the corresponding interrupt is executed if an overflow in timer/counter2 occurs, that is, when the tov2 bit is set in the timer/counter inter- rupt flag register ? tifr. 17.9.5 tifr - timer/counter interrupt flag register ? bit 7 ? ocf2: output compare flag 2 the ocf2 bit is set (one) when a compare match occurs between the timer/counter2 and the data in ocr2 ? output compare register2. ocf2 is cleared by hardware when executing the corresponding interrupt handling vector. alternativel y, ocf2 is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie2 (timer/counter2 compare match interrupt enable), and ocf2 are set (one), the timer/counter2 compare match interrupt is executed. ? bit 6 ? tov2: timer/counter2 overflow flag the bit tov2 is set (one) when an overflow occu rs in timer/counter2. tov2 is cleared by hard- ware when executing the corresponding interrupt handling vector. alternatively, tov2 is cleared by writing a logic one to the flag. when the sr eg i-bit, toie2 (timer/counter2 overflow inter- rupt enable), and tov2 are set (one), the timer/counter2 overflow interrupt is executed. in pwm mode, this bit is set when timer/counter2 changes counting direction at $00.np bit 76543210 ocr2[7:0] ocr2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 7654 3210 ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 timsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value0000 0000 bit 76543210 ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 tifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 163 8151h?avr?02/11 atmega128a 18. output compare modulator (ocm1c2) 18.1 overview the output compare modulator (ocm) allows generation of waveforms modulated with a carrier frequency. the modulator uses the outputs from the output compare unit c of the 16-bit timer/counter1 and the output compare unit of the 8-bit timer/counter2. for more details about these timer/counters see ?16-bit timer/counter (timer/counter1 and timer/counter3)? on page 112 and ?8-bit timer/counter2 with pwm? on page 148 . note that this feature is not available in atmeg a103 compatibility mode. figure 18-1. output compare modulator, block diagram when the modulator is enabled, the two output compare channels are modulated together as shown in the block diagram ( figure 18-1 ). 18.2 description the output compare unit 1c and output compare unit 2 shares the pb7 port pin for output. the outputs of the output compare units (oc1c and oc2) overrides the normal portb7 register when one of them is enabled (that is, when comnx1:0 is not equal to zero). when both oc1c and oc2 are enabled at the same time, the modulator is automatically enabled. the functional equivalent schematic of the modulator is shown on figure 18-2 . the schematic includes part of the timer/counter units and the port b pin 7 output driver circuit. oc1c pin oc1c / oc2 / pb7 timer/counter 1 timer/counter 2 oc2 164 8151h?avr?02/11 atmega128a figure 18-2. output compare modulator, schematic when the modulator is enabled the type of modulation (logical and or or) can be selected by the portb7 register. note that the ddrb7 controls the direction of the port independent of the comnx1:0 bit setting. 18.2.1 timing example figure 18-3 illustrates the modulator in ac tion. in this example the ti mer/counter1 is set to oper- ate in fast pwm mode (non-inverted) and timer/counter2 uses ctc waveform mode with toggle compare output mode (comnx1:0 = 1). figure 18-3. output compare modulator, timing diagram in this example, timer/counter2 provides the carrier, while the modulating signal is generated by the output compare unit c of the timer/counter1. the resolution of the pwm signal (oc1c) is reduced by the modulation. the reduction factor is equal to the number of system clock cycles of on e period of the carrier (oc2). in this example the resolution is reduced by a factor of two. the reason for the reduction is illustrated in figure 18-3 at the second and third period of the pb7 output when portb7 equals zero. the period 2 high time is one cycle longer than the period 3 high time, but the result on the pb7 output is equal in both periods. portb7 ddrb7 dq dq pin com21 com20 databus oc1c / oc2 / pb7 com1c1 com1c0 modulator 1 0 oc1c dq oc2 dq ( from waveform generator ) ( from waveform generator ) 0 1 vcc 1 2 oc2 (ctc mode) oc1c (fpwm mode) pb7 (portb7 = 0) pb7 (portb7 = 1) (period) 3 clk i/o 165 8151h?avr?02/11 atmega128a 19. serial peripheral interface ? spi 19.1 features ? full-duplex, three-wire synchronous data transfer ? master or slave operation ? lsb first or msb first data transfer ? seven programmable bit rates ? end of transmission interrupt flag ? write collision flag protection ? wake-up from idle mode ? double speed (ck/2) master spi mode 19.2 overview the serial peripheral interface (spi) allows hi gh-speed synchronous data transfer between the atmega128a and peripheral devices or between several avr devices. figure 19-1. spi block diagram note: 1. refer to figure 1-1 on page 2 and table 12-5 on page 74 for spi pin placement. the interconnection between master and slave cpus with spi is shown in figure 19-2 . the sys- tem consists of two shift registers, and a master clock generator. the spi master initiates the communication cycle when pu lling low the slave select ss pin of the desired slave. master and spi2x spi2x divider /2/4/8/16/32/64/128 166 8151h?avr?02/11 atmega128a slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the sck line to interchange data. data is always shifted from mas- ter to slave on the master out ? slave in, mosi, line, and from slave to master on the master in ? slave out, miso, line. after ea ch data packet, the master will synchronize the slave by pulling high the slave select, ss , line. when configured as a master, the spi interface has no automatic control of the ss line. this must be handled by user software before communication can start. when this is done, writing a byte to the spi data register starts the spi clock generator, and the hardware shifts the 8 bits into the slave. after shifting one byte, the spi clock generator stops, setting the end of transmis- sion flag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift the next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be kept in the buffer register for later use. when configured as a slave, the spi interface will remain sleeping with miso tri-stated as long as the ss pin is driven high. in this state, software may update the contents of the spi data register, spdr, but the data will not be shifted out by incoming clock pulses on the sck pin until the ss pin is driven low. as one byte has been completely shifted, the end of transmission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr register is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr before reading the incoming data. the last incomi ng byte will be kept in the buffer register for later use. figure 19-2. spi master-slave interconnection the system is single buffered in the transmit di rection and double buffered in the receive direc- tion. this means that bytes to be transmitted cannot be written to the spi data register before the entire shift cycle is complet ed. when receiving data, however, a received character must be read from the spi data register before the next character has been completely shifted in. oth- erwise, the first byte is lost. in spi slave mode, the control logic will sample the incoming signal of the sck pin. to ensure correct sampling of the clock signal, the minimum low and high period should be: low period: longer than 2 cpu clock cycles. high period: longer than 2 cpu clock cycles. when the spi is enabled, the data direction of the mosi, miso, sck, and ss pins is overridden according to table 19-1 . for more details on automatic port overrides, refer to ?alternate port functions? on page 71 . shift enable 167 8151h?avr?02/11 atmega128a note: 1. see ?alternate functions of port b? on page 74 for a detailed description of how to define the direction of the user defined spi pins. the following code examples show how to initialize the spi as a master and how to perform a simple transmission. ddr_spi in the examples must be replaced by the actual data direction register controlling the spi pins. dd_mosi, dd_miso and dd_sck must be replaced by the actual data direction bits for these pins. for example, if mosi is placed on pin pb5, replace dd_mosi with ddb5 and ddr_spi with ddrb. table 19-1. spi pin overrides (1) pin direction, master spi direction, slave spi mosi user defined input miso input user defined sck user defined input ss user defined input 168 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8 . assembly code example (1) spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< 171 8151h?avr?02/11 atmega128a figure 1. spi transfer format with cpha = 0 figure 2. spi transfer format with cpha = 1 19.5 register description 19.5.1 spcr - spi control register ? bit 7 ? spie: spi interrupt enable this bit causes the spi in terrupt to be executed if spif bit in the spsr register is set and the if the global interrupt enable bit in sreg is set. ? bit 6 ? spe: spi enable when the spe bit is written to one, the spi is enabled. this bit must be set to enable any spi operations. bit 1 bit 6 lsb msb sck (cpol = 0) mode 0 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 2 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 msb first (dord = 0) lsb first (dord = 1) sck (cpol = 0) mode 1 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 3 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 bit 1 bit 6 lsb msb msb first (dord = 0) lsb first (dord = 1) bit 76543210 spie spe dord mstr cpol cpha spr1 spr0 spcr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 172 8151h?avr?02/11 atmega128a ? bit 5 ? dord: data order when the dord bit is written to one, the lsb of the data word is transmitted first. when the dord bit is written to zero, the msb of the data word is transmitted first. ? bit 4 ? mstr: master/slave select this bit selects master spi mode when written to one, and slave spi mode when written logic zero. if ss is configured as an input and is driven low while mstr is set, mstr will be cleared, and spif in spsr will become set. the user will th en have to set mstr to re-enable spi mas- ter mode. ? bit 3 ? cpol: clock polarity when this bit is written to one, sck is high when idle. when cpol is written to zero, sck is low when idle. refer to figure 1 and figure 2 for an example. the cpol functionality is summarized below: ? bit 2 ? cpha: clock phase the settings of the clock phase bit (cpha) determine if data is sampled on the leading (first) or trailing (last) edge of sck. refer to figure 1 and figure 2 for an example. the cpha functional- ity is summarized below: ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the dev ice configured as a master. spr1 and spr0 have no effect on the slave. the relationship between sck and the oscillator clock frequency f osc is shown in the following table: table 19-2. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 19-3. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample table 19-4. relationship between sck and the oscillator frequency spi2x spr1 spr0 sck frequency 000 f osc / 4 001 f osc / 16 010 f osc / 64 011 f osc / 128 100 f osc / 2 173 8151h?avr?02/11 atmega128a 19.5.2 spsr - spi status register ? bit 7 ? spif: spi interrupt flag when a serial transfer is complete, the spif flag is set. an interrupt is generated if spie in spcr is set and global interrupts are enabled. if ss is an input and is dr iven low when the spi is in master mode, this will also set the spif flag. spif is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, the spif bit is cleared by first reading the spi status register with spif set, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the wcol bit is set if the spi data register (spdr) is written during a data transfer. the wcol bit (and the spif bit) are cleared by first reading the spi status register with wcol set, and then accessing the spi data register. ? bit 5:1 ? reserved these bits are reserved bits in the at mega128a and will always read as zero. ? bit 0 ? spi2x: double spi speed bit when this bit is written logi c one the spi speed (sck freque ncy) will be doubled when the spi is in master mode (see table 19-4 ). this means that the minimum sck period will be 2 cpu clock periods. when the spi is configured as slave, the spi is only guaranteed to work at f osc /4 or lower. the spi interface on the atmega128a is al so used for program memory and eeprom down- loading or uploading. see page 303 for spi serial programming and verification. 19.5.3 spdr - spi data register the spi data register is a read/write register used for data transfer between the register file and the spi shift register. writing to the register initiates data transmission. reading the regis- ter causes the shift register receive buffer to be read. 101 f osc / 8 110 f osc / 32 111 f osc / 64 table 19-4. relationship betw een sck and the oscillator frequency (continued) spi2x spr1 spr0 sck frequency bit 76543210 spifwcol?????spi2xspsr read/write rrrrrrrr/w initial value00000000 bit 76543210 msb lsb spdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value x x x x x x x x undefined 174 8151h?avr?02/11 atmega128a 20. usart 20.1 features ? full duplex operation (independent se rial receive and transmit registers) ? asynchronous or synchronous operation ? master or slave clocked synchronous operation ? high resolution baud rate generator ? supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits ? odd or even parity generation and parity check supported by hardware ? data overrun detection ? framing error detection ? noise filtering includes false start bit detection and digital low pass filter ? three separate interrupts on tx complete, tx data register empty, and rx complete ? multi-processor communication mode ? double speed asynchronous communication mode 20.1.1 dual usart the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device . the atmega128a has two usart?s, usart0 and usart1. the functionality for both usart?s is described below. usart0 and usart1 have different i/o registers as shown in ?register summary? on page 367 . note that in atmega103 compatibility mode, usart1 is not available, neither is the ubrr0h or ucrs0c registers. this means that in atmega103 compatibility mode, the atmega128a supports asynchronous operation of usart0 only. 20.2 overview a simplified block diagram of the usart transmitter is shown in figure 20-1 . cpu accessible i/o registers and i/o pins are shown in bold. 175 8151h?avr?02/11 atmega128a figure 20-1. usart block diagram note: refer to figure 1-1 on page 2 , table 12-11 on page 78 , and table 12-14 on page 81 for usart pin placement. the dashed boxes in the block diagram separate the three main parts of the usart (listed from the top): clock generator, transmitter, and receiver. control registers are shared by all units. the clock generation logic consists of synchronizati on logic for external clock input used by syn- chronous slave operation, and the baud rate generator. the xck (transfer clock) pin is only used by synchronous transfer mode. the transmitter consists of a single write buffer, a serial shift register, parity generator and control logic for handling different serial frame formats. the write buffer allows a continuous transfer of data without any delay between frames. the receiver is the most complex part of the usart module due to its clock and data recovery units. the recovery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, co ntrol logic, a shift register and a two level receive buffer (udr). the receiver supports the same frame formats as the transmitter, and can detect frame error, data overrun and parity errors. 20.2.1 avr usart vs. avr uart ? compatibility the usart is fully compatible with the avr uart regarding: ? bit locations inside all usart registers ? baud rate generation parity generator ubrr[h:l] udr (transmit) ucsra ucsrb ucsrc baud rate generator transmit shift register receive shift register rxd txd pin control udr (receive) pin control xck data recovery clock recovery pin control tx control rx control parity checker databus osc sync logic clock generator transmitter receiver 176 8151h?avr?02/11 atmega128a ? transmitter operation ? transmit buffer functionality ? receiver operation however, the receive bu ffering has two improvements that will affect the comp atibility in some special cases: ? a second buffer register has been added. the two buffer registers operate as a circular fifo buffer. therefore the udr must only be read once for each incoming data! more important is the fact that the error flags (fe and dor) and the ninth data bit (rxb8) are buffered with the data in the receive buffer. therefore the status bits must always be read before the udr register is read. othe rwise the error status will be lost since the buffer state is lost. ? the receiver shift register can now act as a th ird buffer level. this is done by allowing the received data to remain in the serial shift register (see figure 20-1 ) if the buffer registers are full, until a new start bit is detected. the usart is therefore more resistant to data overrun (dor) error conditions. the following control bits have changed name, but have same functionality and register location: ? chr9 is changed to ucsz2 ? or is changed to dor 20.3 clock generation the clock generation logic generates the base clock for the transmitter and receiver. the usart supports four modes of clock operation: normal asynchronous, double speed asyn- chronous, master synchronous, and slave synchronous mode. the umsel bit in usart control and status register c (ucsrc) selects between asynchronous and synchronous oper- ation. double speed (asynchronous mode only) is controlled by the u2x found in the ucsra register. when using synchronous mode (umsel = 1), the data direction register for the xck pin (ddr_xck) controls whether the clock source is internal (master mode) or external (slave mode). the xck pin is only active when using synchronous mode. figure 20-2 shows a block diagram of the clock generation logic. figure 20-2. clock generation logic, block diagram prescaling down-counter / 2 ubrr / 4 / 2 fosc ubrr+1 sync register osc xck pin txclk u2x umsel ddr_xck 0 1 0 1 xcki xcko ddr_xck rxclk 0 1 1 0 edge detector ucpol 177 8151h?avr?02/11 atmega128a signal description: txclk transmitter clock. (internal signal) rxclk receiver base clock. (internal signal) xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal). used for synchronous master operation. fosc xtal pin frequency (system clock). 20.3.1 internal clock generation ? the baud rate generator internal clock generation is used for the as ynchronous and the synchronous master modes of operation. the description in this section refers to figure 20-2 . the usart baud rate register (ubrr) and the down-counter connected to it function as a programmable prescaler or baud rate generator. the down-counter, running at system clock (fosc), is loaded with the ubrr value each time the counter has counted down to zero or when the ubrrl register is written. a clock is gener ated each time the counter reaches zero. this clock is the baud rate generator clock output (= fosc/(ubrr+1)). the transmitter divides the baud rate generator clock output by 2, 8, or 16 depending on mode. the baud rate generator output is used directly by the receiver?s clock and data recovery units. however, the recovery units use a state machine that uses 2, 8, or 16 states depending on mode set by the state of the umsel, u2x and ddr_xck bits. table 20-1 contains equations for calculating the baud rate (in bits per second) and for calculat- ing the ubrr value for each mode of operation using an internally generated clock source. note: 1. the baud rate is defined to be the transfer rate in bit per second (bps). baud baud rate (in bits per second, bps) fosc system oscillator clock frequency ubrr contents of the ubrrh and ub rrl registers, (0 - 4095) some examples of ubrr values for so me system clock frequencies are found in table 20-9 (see page 198 ). 20.3.2 double speed operation (u2x) the transfer rate can be doubled by setting the u2x bit in ucsra. setting this bit only has effect for the asynchronous operation. set this bi t to zero when using synchronous operation. table 20-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrr value asynchronous normal mode (u2x = 0) asynchronous double speed mode (u2x = 1) synchronous master mode baud f osc 16 ubrr 1 + () -------------------------------------- - = ubrr f osc 16 baud ----------------------- - 1 ? = baud f osc 8 ubrr 1 + () ----------------------------------- = ubrr f osc 8 baud -------------------- 1 ? = baud f osc 2 ubrr 1 + () ----------------------------------- = ubrr f osc 2 baud -------------------- 1 ? = 178 8151h?avr?02/11 atmega128a setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. note however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. 20.3.3 external clock external clocking is used by the synchronous sl ave modes of operation. the description in this section refers to figure 20-2 for details. external clock input from the xck pin is sampled by a synchronization register to minimize the chance of meta-stability. the output from the synchronization register must then pass through an edge detector before it can be used by the transmitter and receiver. this process introduces a two cpu clock period delay and therefore the maximum external xck cl ock frequency is lim- ited by the following equation: note that f osc depends on the stability of the system clock source. it is therefore recommended to add some margin to avoid possible loss of data due to frequency variations. 20.3.4 synchronous clock operation when synchronous mode is used (umsel = 1), the xck pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sampling or data change is the same. the basic principle is that data input (on rxd) is sampled at the oppo- site xck clock edge of the edge the data output (txd) is changed. figure 20-3. synchronous mode xck timing. the ucpol bit ucrsc selects which xck clock edge is used for data sampling and which is used for data change. as figure 20-3 shows, when ucpol is zero the data will be changed at rising xck edge and sampled at falling xck edge. if ucpol is set, the data will be changed at falling xck edge and sampl ed at rising xck edge. f xck f osc 4 ----------- < rxd / txd xck rxd / txd xck ucpol = 0 ucpol = 1 sample sample 179 8151h?avr?02/11 atmega128a 20.4 frame formats a serial frame is defined to be one character of da ta bits with synchronizat ion bits (start and stop bits), and optionally a parity bi t for error checking. the usart accepts all 30 combinations of the following as valid frame formats: ? 1 start bit ? 5, 6, 7, 8, or 9 data bits ? no, even or odd parity bit ? 1 or 2 stop bits a frame starts with the start bit followed by the least significant data bit. then the next data bits, up to a total of nine, are succeeding, ending with t he most significant bit. if enabled, the parity bit is inserted after the data bits, before the stop bits. when a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. figure 20-4 illustrates the possible combinations of th e frame formats. bits inside brackets are optional. figure 20-4. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. sp stop bit, always high. idle no transfers on the communication line (rxd or txd). an idle line must be high. the frame format used by the usart is set by the ucsz2:0, upm1:0 and usbs bits in ucsrb and ucsrc. the receiver and transmitter use the same setting. note that changing the setting of any of these bits will corrupt all ongoing commun ication for both the rece iver and transmitter. the usart character size (ucsz2:0) bits select the number of data bits in the frame. the usart parity mode (upm1:0) bits enable and set the type of parity bit. the selection between one or two stop bits is done by the usart stop bit select (usbs) bit. the receiver ignores the second stop bit. an fe (frame error) will therefor e only be detected in the cases where the first stop bit is zero. 20.4.1 parity bit calculation the parity bit is calculated by do ing an exclusive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the re lation between the parity bit and data bits is as follows: p even parity bit using even parity p odd parity bit using odd parity 1 0 2 3 4 [5] [6] [7] [8] [p] st sp1 [sp2] (st / idle) (idle) frame p even d n 1 ? d 3 d 2 d 1 d 0 0 p odd d n 1 ? d 3 d 2 d 1 d 0 1 = = 180 8151h?avr?02/11 atmega128a d n data bit n of the character if used, the parity bit is located between the last data bit and first stop bit of a serial frame. 20.5 usart initialization the usart has to be initialized before any communication can take place. the initialization pro- cess normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the regist ers are changed. the txc flag can be used to check that the transmitter has completed all transfers, and the rxc flag can be used to check that there are no unread data in the receive buffer. note that the txc flag must be cleared before each transmission (before udr is written) if it is used for this purpose. the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the exampl es assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. 181 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8 . more advanced initialization routines can be ma de that include frame format as parameters, disable interrupts and so on. however, many applications use a fixed setting of the baud and control registers, and for these types of ap plications the initialization code can be placed directly in the main routine, or be combined with initialization code for other i/o modules. 20.6 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txen) bit in the ucsrb register. when the transmitter is enabled, the no rmal port operation of the txd pin is overrid- den by the usart and given the function as the transmitter?s serial output. the baud rate, mode of operation and frame format must be set up once before doing any trans missions. if synchro- nous operation is used, the clock on the xck pin will be ov erridden and used as transmission clock. assembly code example (1) usart_init: ; set baud rate out ubrrh, r17 out ubrrl, r16 ; enable receiver and transmitter ldi r16, (1< 185 8151h?avr?02/11 atmega128a note: 1. see ?about code examples? on page 8 . the function simply waits for data to be present in the receive buffer by checking the rxc flag, before reading the buffer and returning the value. 20.7.2 receiving frames with 9 data bits if 9-bit characters are used (ucsz=7) the ninth bit must be read from the rxb8 bit in ucsrb before reading the low bits from the udr. this rule applies to the fe, dor and upe status flags as well. read stat us from ucsra, then data from udr. reading the udr i/o location will change the state of the receive buffer fifo and consequently the txb8, fe, dor, and upe bits, which all are stored in the fifo, will change. the following code example shows a simple usart receive function that handles both nine bit characters and the status bits. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsra, rxc rjmp usart_receive ; get and return received data from buffer in r16, udr ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsra & (1< 187 8151h?avr?02/11 atmega128a 20.7.3 receive compete flag and interrupt the usart receiver has one flag that indicates the receiver state. the receive complete (rxc) flag indicates if there are unread data present in the receive buf- fer. this flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (that is, does not contain any unread data). if the receiver is disabled (rxen = 0), the receive bu ffer will be flushed and consequently the rxc bit will become zero. when the receive complete interrupt enable (rxcie) in ucsrb is set, the usart receive complete interrupt will be executed as long as the rxc flag is set (provided that global inter- rupts are enabled). when interrupt-driven data reception is used, the receive complete routine must read the received data fr om udr in order to clear the rx c flag, otherwise a new interrupt will occur once the interr upt routine terminates. 20.7.4 receiver error flags the usart receiver has three error flags: frame error (fe), data overrun (dor) and parity error (upe). all can be accessed by reading ucsra. common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. due to the buffering of the error flags, the ucsra must be read before the receive buffer (udr), since reading the udr i/o location changes the buffer read location. another equality for the error flags is that they can not be altered by software doing a write to the flag location. however, all flags must be set to zero when the ucsra is written for upward compatibility of future usart implementations. none of the error flags can generate interrupts. the frame error (fe) flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. the fe flag is zero when the stop bit was correctly read (as one), and the fe flag will be one when the stop bit wa s incorrect (zero). this flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. the fe flag is not affected by the setting of the usbs bit in ucsrc since the re ceiver ignores all, except for the first, stop bits. for co mpatibility with future device s, always set this bit to zero when writing to ucsra. the data overrun (dor) flag indicates data loss due to a receiver buffer full condition. a data overrun occurs when the receive buffer is full (two characters), it is a new character waiting in the receive shift register, and a new start bit is detected. if the dor flag is set there was one or more serial frame lost between the frame last read from udr, and the next frame read from udr. for compatibility with future devices, always write this bit to zero when writing to ucsra. the dor flag is cleared when the frame received was successfully moved from the shift regis- ter to the receive buffer. the parity error (upe) flag indicates that the next frame in the receive buffer had a parity error when received. if parity check is not enabled the upe bit will alwa ys be read zero. for compati- bility with future devices, always set this bi t to zero when wr iting to ucsra. fo r more details see ?parity bit calculation? on page 179 and ?parity checker? on page 187 . 20.7.5 parity checker the parity checker is active when the high usart parity mode (upm1) bit is set. type of parity check to be performed (odd or even) is select ed by the upm0 bit. when enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. the result of the check is stored in the receive buffer together with the received data and stop bits. the parity error (upe) flag can then be read by software to check if the frame had a parity error. 188 8151h?avr?02/11 atmega128a the upe bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabl ed at that point (upm1 = 1). this bit is valid until the receive buffer (udr) is read. 20.7.6 disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will therefore be lost. w hen disabled (that is, the rxen is set to zero) the receiver will no longer override the normal function of the rxd port pin. the receiver buffer fifo will be flushed when the receiver is disabled . remaining data in the buffer will be lost 20.7.7 flushing the receive buffer the receiver buffer fifo will be flushed when the receiver is disabled, that is, the buffer will be emptied of its contents. unread data will be lost. if the buffer has to be flushed during normal operation, due to for instance an error condition, read the udr i/o location until the rxc flag is cleared. the following code example shows how to flush the receive buffer. note: 1. see ?about code examples? on page 8 . the usart includes a clock recovery and a data recovery unit for handling asynchronous data reception. the clock recovery logic is us ed for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxd pin. the data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the receiver. the asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 20.7.8 asynchronous clock recovery the clock recovery logic synchronizes internal clock to the incoming serial frames. figure 20-5 illustrates the sampling process of th e start bit of an incoming frame. the sample rate is 16 times the baud rate for normal mode, and 8 times the baud rate for double speed mode. the horizon- tal arrows illustrate the synchronization variation due to the sampling process. note the larger time variation when using the double speed mode (u2x = 1) of operation. samples denoted zero are samples done when the rxd line is id le (that is, no communication activity). assembly code example (1) usart_flush: sbis ucsra, rxc ret in r16, udr rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsra & (1< 190 8151h?avr?02/11 atmega128a figure 20-7. stop bit sampling and ne xt start bit sampling the same majority voting is done to the stop bit as done for the other bits in the frame. if the stop bit is registered to have a logic 0 valu e, the frame error (f e) flag will be set. a new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. for normal speed mode, the first low level sample can be at point marked (a) in figure 20-7 . for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the ear ly start bit detection influences the operational range of the receiver. 20.7.10 asynchronous operational range the operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. if the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see table 20-2 ) base frequency, the receiver will not be abl e to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. table 20-2 and table 20-3 list the maximum receiver baud rate error that can be tolerated. note that normal speed mode has higher toleration of baud rate variations. 1234567 8 9 10 0/1 0/1 0/1 stop 1 123 4 5 6 0/1 rxd sample (u2x = 0) sample (u2x = 1) (a) (b) (c) d sum of character size and parity size (d = 5 to 10-bit). s samples per bit. s = 16 for normal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s n middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. r slow d 1 + () s s 1 ? ds ? s f ++ ------------------------------------------ - = r fast d 2 + () s d 1 + () ss m + ----------------------------------- = 191 8151h?avr?02/11 atmega128a the recommendations of the maximum receiver baud rate error was made under the assump- tion that the receiver and transmitter equally divides the maximum total error. there are two possible sources for the receivers baud rate error. the receiver?s system clock (xtal) will always have some minor instabilit y over the supply voltage range and the tempera- ture range. when using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get the b aud rate wanted. in this case an ubrr value that gives an acceptable low error can be used if possible. 20.8 multi-processor communication mode setting the multi-processor communication mode (mpcm) bit in ucsra enables a filtering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put in to the receive buffer. this effectively reduces the number of incoming frames that has to be handled by the cpu, in a system with multiple mcus that communicate via the same serial bus. the transmitter is unaffected by the mpcm setting, but has to be used diffe rently when it is a part of a system utilizing the multi-processor communication mode. if the receiver is set up to receive frames that c ontain 5 to 8 data bits, then the first stop bit indi- cates if the frame contains data or address information. if the receiver is set up for frames with 9 table 20-2. recommended maximum receiver baud rate error for normal speed mode (u2x = 0) d # (data+parity bit) r slow %r fast % max total error % recommended max receiver error % 5 93,20 106,67 +6.67/-6.8 3.0 6 94,12 105,79 +5.79/-5.88 2.5 7 94,81 105,11 +5.11/-5.19 2.0 8 95,36 104,58 +4.58/-4.54 2.0 9 95,81 104,14 +4.14/-4.19 1.5 10 96,17 103,78% +3.78/-3.83 1.5 table 20-3. recommended maximum receiver baud rate error for double speed mode (u2x = 1) d # (data+parity bit) r slow %r fast % max total error % recommended max receiver error % 5 94,12 105,66 +5.66/-5.88 2.5 6 94,92 104,92 +4.92/-5.08 2.0 7 95,52 104,35 +4.35/-4.48 1.5 8 96,00 103,90 +3.90/-4.00 1.5 9 96,39 103,53 +3.53/-3.61 1.5 10 96,70 103,23 +3.23/-3.30 1.0 192 8151h?avr?02/11 atmega128a data bits, then the ninth bit (r xb8) is used for identifying address and data frames. when the frame type bit (the first stop or the 9th bit) is one, the frame contains an address. when the frame type bit is zero the frame is a data frame. the multi-processor communication mode enables several slave mcus to receive data from a master mcu. this is done by first decoding an address frame to find out which mcu has been addressed. if a particular slave mcu has been addressed, it will rece ive the following data frames as normal, while the other slave mcus will ignore the received frames until another address frame is received. 20.8.1 using mpcm for an mcu to act as a master mcu, it can use a 9-bit character frame format (ucsz = 7). the ninth bit (txb8) must be set when an address frame (txb8 = 1) or cleared when a data frame (txb = 0) is being transmitted. the slave mcus must in this case be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communication mode: 1. all slave mcus are in multi-processor co mmunication mode (mpcm in ucsra is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxc flag in ucsra will be set as normal. 3. each slave mcu reads the udr register and determines if it has been selected. if so, it clears the mpcm bit in ucsra, otherwise it waits for the next address byte and keeps the mpcm setting. 4. the addressed mcu will receive all data fram es until a new address frame is received. the other slave mcus, which still have the mpcm bit set, will ignore the data frames. 5. when the last data frame is received by the addressed mcu, the addressed mcu sets the mpcm bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5-bit to 8-bit character frame formats is possible, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full-duplex operation difficult since the transmitter and receiver uses the same character size setting. if 5-bit to 8-bit character frames are used, the transmi tter must be set to use two stop bit (usbs = 1) since the first stop bit is used for indicating the frame type. do not use read-modify-write instructions (sbi and cbi) to set or clear the mpcm bit. the mpcm bit shares the same i/o location as the txc flag and this might accidentally be cleared when using sbi or cbi instructions. 20.9 register description 20.9.1 udrn - usartn i/o data register the usartn transmit data buffe r register and usartn receive data buffer registers share the same i/o address referred to as usartn data register or udrn. the transmit data buffer bit 76543210 rxbn[7:0] udrn (read) txbn[7:0] udrn (write) read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 193 8151h?avr?02/11 atmega128a register (txbn) will be the destination for data written to the udrn register location. reading the udrn register location will return the contents of the receive data bu ffer register (rxbn). for 5-bit, 6-bit, or 7-bit characters the upper unused bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written when the udren flag in the ucsran register is set. data written to udrn when the udren flag is not set, will be ignored by the usartn transmit- ter. when data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into the transmit shift regist er when the shift register is empty. then the data will be serially transmitted on the txdn pin. the receive buffer consists of a two level fifo . the fifo will change its state whenever the receive buffer is accessed. due to this behavior of the receive buffer, do not use read modify write instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will change the state of the fifo. 20.9.2 usart control and st atus register a ? ucsrna ? bit 7 ? rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (that is, does not contain any unread data). if the receiver is disabled, the receive buffer will be flus hed and consequently the rxcn bit will become zero. the rxcn flag can be used to generate a receive complete interr upt (see description of the rxcien bit). ? bit 6 ? txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see descrip- tion of the txcien bit). ? bit 5 ? udren: usart data register empty the udren flag indicates if the transmit buffer (udr n) is ready to receiv e new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrien bit). udren is set after a reset to indicate that the transmitter is ready. ? bit 4 ? fen: frame error this bit is set if the next character in the receive buffer had a frame error when received, that is, when the first stop bit of the next character in the receive buffer is zero. this bit is valid until the receive buffer (udrn) is read. the fen bit is zero when the stop bit of received data is one. always set this bit to ze ro when writing to ucsrna. bit 76543210 rxcn txcn udren fen dorn upen u2xn mpcmn ucsrna read/write r r/w r r r r r/w r/w initial value00100000 194 8151h?avr?02/11 atmega128a ? bit 3 ? dorn: data overrun this bit is set if a data overrun condition is detected. a data overrun occurs when the receive buffer is full (two characters), it is a new char acter waiting in the receive shift register, and a new start bit is detected. this bi t is valid until the receive buffer (udrn) is read . always set this bit to zero when writing to ucsrna. ? bit 2 ? upen: parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 1 ? u2xn: double the usart transmission speed this bit only has effect for the asynchronous operation. write this bit to zero when using syn- chronous operation. writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively dou- bling the transfer rate for asynchronous communication. ? bit 0 ? mpcmn: multi-processor communication mode this bit enables the multi-processor communica tion mode. when the mpcmn bit is written to one, all the incoming frames received by the usart receiver that do not contain address infor- mation will be ignored. th e transmitter is unaffected by the mpcmn setting. for more detailed information see ?multi-processor communication mode? on page 191 . 20.9.3 ucsrnb - usartn contro l and status register b ? bit 7 ? rxcien: rx co mplete interrupt enable writing this bit to one enables interrupt on the rxc flag. a usart receive complete interrupt will be generated only if th e rxcie bit is written to one, the gl obal interrupt flag in sreg is writ- ten to one and the rxc bit in ucsrna is set. ? bit 6 ? txcien: tx complete interrupt enable writing this bit to one enables interrupt on the txcn flag. a usartn transmit complete inter- rupt will be generated only if the tx cien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 ? udrien: usart data register empty interrupt enable writing this bit to one enables interrupt on the udren flag. a da ta register empty interrupt will be generated only if the udrien bit is written to one, the global interrupt flag in sreg is written to one and the udren bit in ucsrna is set. ? bit 4 ? rxenn: receiver enable writing this bit to one enables the usartn rece iver. the receiver will override normal port operation for the rxdn pin when enabled. disabl ing the receiver will fl ush the receive buffer invalidating the fen, dorn and upen flags. bit 76543 2 10 rxcien txcien udrien rxenn txenn ucszn2 rxb8n txb8n ucsrnb read/write r/w r/w r/w r/w r/w r/w r r/w initial value00000 0 00 195 8151h?avr?02/11 atmega128a ? bit 3 ? txenn: transmitter enable writing this bit to one enables the usartn transmitter. the transmi tter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txenn to zero) will not become effectiv e until ongoing and pen ding transmissions are completed, that is, when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2 ? ucszn2: character size the ucszn2 bits combined with the ucszn1:0 bit in ucsrnc sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 1 ? rxb8n: receive data bit 8 rxb8n is the ninth data bit of the received character when operating with serial frames with 9- data bits. must be read before reading the low bits from udrn. ? bit 0 ? txb8n: transmit data bit 8 txb8n is the 9th data bit in the character to be transmitted when operating with serial frames with 9 data bits. must be written bef ore writing the low bits to udrn. 20.9.4 ucsrnc - usart control and status register c note that this register is not available in at mega103 compat ibility mode. ? bit 7 ? reserved bit this bit is reserved for future use. for compatib ility with future devices, these bit must be written to zero when ucsrnc is written. ? bit 6 ? umseln: usart mode select this bit selects between asynchronous and synchronous mode of operation. ? bit 5:4 ? upmn1:0: parity mode these bits enable and set type of parity generation and check. if enabled, the transmitter will automatically generate and send the parity of th e transmitted data bits within each frame. the receiver will generate a parity value for the in coming data and compare it to the upmn0 setting. if a mismatch is detected, the upen flag in ucsrna will be set. bit 76 543210 ? umseln upmn1 upmn0 usbsn ucszn1 ucszn0 ucpoln ucsrnc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 1 1 0 table 20-4. umseln bit settings umseln mode 0 asynchronous operation 1 synchronous operation 196 8151h?avr?02/11 atmega128a ? bit 3 ? usbsn: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting. ? bit 2:1 ? ucszn1:0: character size the ucszn1:0 bits combined with the ucszn2 bit in ucsrnb sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 0 ? ucpoln: clock polarity this bit is used for synchronous mode only. write this bit to zero when asynchronous mode is used. the ucpoln bit sets the relationship between data output change and data input sample, and the synchronous clock (xckn). table 20-5. upmn bits settings upmn1 upmn0 parity mode 00disabled 0 1 (reserved) 1 0 enabled, even parity 1 1 enabled, odd parity table 20-6. usbsn bit settings usbsn stop bit(s) 01-bit 12-bits table 20-7. ucszn bits settings ucszn2 ucszn1 ucszn0 character size 0005-bit 0016-bit 0107-bit 0118-bit 1 0 0 reserved 1 0 1 reserved 1 1 0 reserved 1119-bit table 20-8. ucpoln bit settings ucpoln transmitted data ch anged (output of txdn pin) received data sampled (input on rxdn pin) 0 rising xckn edge falling xckn edge 1 falling xckn edge rising xckn edge 197 8151h?avr?02/11 atmega128a 20.9.5 ubrrnl and ubrrnh - usart baud rate registers ubrrnh is not available in mega103 comp atibility mode ? bit 15:12 ? reserved these bits are reserved for future use. for compatibility with future devices, these bit must be written to zero when ubrrnh is written. ? bit 11:0 ? ubrrn[11:0]: usartn baud rate register this is a 12-bit register which contains t he usartn baud rate. the ubrrnh contains the four most significant bits, and the ubrrnl contains the eight least significant bits of the usartn baud rate. ongoing transmissions by the transmit ter and receiver will be corrupted if the baud rate is changed. writing ubrr nl will trigger an immediate update of the baud ra te prescaler. bit 151413121110 9 8 ? ? ? ? ubrrn[11:8] ubrrnh ubrrn[7:0] ubrrnl 76543210 read/write r r r r r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 00000000 198 8151h?avr?02/11 atmega128a 20.10 examples of ba ud rate setting for standard crystal and resonator frequencies, the most commonly used baud rates for asyn- chronous operation can be generated by using the ubrr settings in table 20-9 . ubrr values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the table. higher error ratings are acceptable, but t he receiver will have less noise resistance when the error ratings are high, especially for large serial frames (see ?asynchronous operational range? on page 190 ). the error values are calculated using the following equation: error[%] baudrate closest match baudrate -------------------------------------------------------- 1 ? ?? ?? 100% ? = table 20-9. examples of ubrr settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 1.0000mhz f osc = 1.8432mhz f osc = 2.0000mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 250.2%510.2%470.0%950.0%510.2%1030.2% 4800 120.2%250.2%230.0%470.0%250.2%510.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k??????00.0%???? 250k??????????00.0% max (1) 62.5kbps 125kbps 115.2kbps 230.4kbps 125kbps 250kbps 1. ubrr = 0, error = 0.0% 199 8151h?avr?02/11 atmega128a table 20-10. examples of ubrr settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 3.6864mhz f osc = 4.0000mhz f osc = 7.3728mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 230.0%470.0%250.2%510.2%470.0%950.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0. 2% 25 0.2% 23 0.0% 47 0.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m ??????????0-7.8% max (1) 230.4kbps 460.8kbps 250kbps 0.5mbps 460.8kbps 921.6kbps 1. ubrr = 0, error = 0.0% table 20-11. examples of ubrr settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 8.0000mhz f osc = 11.0592 mhz f osc = 14.7456mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k 25 0.2% 51 0.2% 35 0. 0% 71 0.0% 47 0.0% 95 0.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k 12 0.2% 25 0.2% 17 0. 0% 35 0.0% 23 0.0% 47 0.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 200 8151h?avr?02/11 atmega128a 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m ? ? 0 0.0% ? ? ? ? 0 -7.8% 1 -7.8% max (1) 0.5mbps 1mbps 691.2kbps 1.3824mbps 921.6kbps 1.8432mbps 1. ubrr = 0, error = 0.0% table 20-11. examples of ubrr settings for commonly used oscillator freq uencies (continued) baud rate (bps) f osc = 8.0000mhz f osc = 11.0592 mhz f osc = 14.7456mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error table 20-12. examples of ubrr settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 16.0000mhz u2x = 0 u2x = 1 ubrr error ubrr error 2400 416 -0.1% 832 0.0% 4800 207 0.2% 416 -0.1% 9600 103 0.2% 207 0.2% 14.4k 68 0.6% 138 -0.1% 19.2k 51 0.2% 103 0.2% 28.8k 34 -0.8% 68 0.6% 38.4k 25 0.2% 51 0.2% 57.6k 16 2.1% 34 -0.8% 76.8k 12 0.2% 25 0.2% 115.2k 8 -3.5% 16 2.1% 230.4k 3 8.5% 8 -3.5% 250k 3 0.0% 7 0.0% 0.5m 1 0.0% 3 0.0% 1m 0 0.0% 1 0.0% max (1) 1mbps 2mbps 1. ubrr = 0, error = 0.0% 201 8151h?avr?02/11 atmega128a 21. two-wire serial interface 21.1 features ? simple yet powerful and flexible communication interface, only two bus lines needed ? both master and sla ve operation supported ? device can operate as transmitter or receiver ? 7-bit address space allows up to 128 different slave addresses ? multi-master arbitration support ? up to 400khz data transfer speed ? slew-rate limited output drivers ? noise suppression circuitry rejects spikes on bus lines ? fully programmable slave address with general call support ? address recognition causes wake-up when avr is in sleep mode 21.2 two-wire serial interface bus definition the two-wire serial interface (twi) is ideally suited for typical microcontroller applications. the twi protocol allows the systems designer to in terconnect up to 128 diffe rent devices using only two bi-directional bus lines, one for clock (scl) and one for data (sda). the only external hard- ware needed to implement the bus is a single pull- up resistor for each of the twi bus lines. all devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the twi protocol. figure 21-1. twi bus interconnection 21.2.1 twi terminology the following definitions are frequently encountered in this section. device 1 device 2 device 3 device n sda scl ........ r1 r2 v cc table 21-1. twi terminology term description master the device that initiates and terminates a transmission. the master also generates the scl clock slave the device addressed by a master transmitter the device placing data on the bus receiver the device reading data from the bus 202 8151h?avr?02/11 atmega128a 21.2.2 electrical interconnection as depicted in figure 21-1 , both bus lines are connected to the positive supply voltage through pull-up resistors. the bus drivers of all twi-compliant devices are open-drain or open-collector. this implements a wired-and functi on which is essential to the operation of the interface. a low level on a twi bus line is generated when one or more twi devices output a zero. a high level is output when all twi devices tri-state their outputs, allowing the pull-up resistors to pull the line high. note that all avr devices connected to the twi bus must be powered in order to allow any bus operation. the number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400pf and the 7-bit slave address space. a detailed specification of the electrical charac- teristics of the twi is given in ?two-wire serial interface characteristics? on page 325 . two different sets of specificati ons are presented there, one relev ant for bus speeds below 100khz, and one valid for bus speeds up to 400khz. 21.3 data transfer and frame format 21.3.1 transferring bits each data bit transferred on the twi bus is accompanied by a pulse on the clock line. the level of the data line must be stable when the clock line is high. the only exception to this rule is for generating start and stop conditions. figure 21-2. data validity 21.3.2 start and stop conditions the master initiates and terminates a data transmi ssion. the transmission is initiated when the master issues a start condition on the bus, and it is terminated when the master issues a stop condition. between a start and a stop condition, the bus is considered busy, and no other master should try to seize control of the bus. a special case occurs when a new start condition is issued between a start and stop condition. this is referred to as a repeated start condition, and is used when the master wis hes to initiate a new transfer without relin- quishing control of the bus. after a repeated start, the bus is considered busy until the next stop. this is identical to the start behavior, and therefore start is used to describe both start and repeated start for the remainder of this datasheet, unless otherwise noted. as depicted below, start and stop conditions are signalled by changing the level of the sda line when the scl line is high. sda scl data stable data stable data change 203 8151h?avr?02/11 atmega128a figure 21-3. start, repeated start and stop conditions 21.3.3 address packet format all address packets transmitted on the twi bus ar e 9 bits long, consisti ng of 7 address bits, one read/write control bit and an acknowledge bit. if the read/write bit is set, a read opera- tion is to be performed, otherwise a write operation should be performed. when a slave recognizes that it is being a ddressed, it should acknowledge by pulling sda low in the ninth scl (ack) cycle. if the addressed sl ave is busy, or for some other reason can not service the mas- ter?s request, the sda line should be left high in the ack clock cycle. the master can then transmit a stop condition, or a repeated start condition to initiate a new transmission. an address packet consisting of a slave address and a read or a write bit is called sla+r or sla+w, respectively. the msb of the address byte is transmitted first. slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. when a general call is issued, all slaves should respond by pulling the sda line low in the ack cycle. a general call is used when a master wi shes to transmit the same message to several slaves in the system. when the general call address followed by a write bit is transmitted on the bus, all slaves set up to ackn owledge the general call will pull th e sda line low in the ack cycle. the following data packets will then be received by all the slaves that acknowle dged the general call. note that transmitting the general call add ress followed by a read bit is meaningless, as this would cause contention if several slaves started transmitting different data. all addresses of the format 1111 xxx should be reserved for future purposes. figure 21-4. address packet format sda scl start stop repeated start stop start sda scl start 12 789 addr msb addr lsb r/w ack 204 8151h?avr?02/11 atmega128a 21.3.4 data packet format all data packets transmitted on the twi bus are 9 bits long, consisting of one data byte and an acknowledge bit. during a data transfer, the master generates the clock and the start and stop conditions, while the receiver is responsible for acknowledging the reception. an acknowledge (ack) is signalled by the receiver pulling the sda line low during the ninth scl cycle. if the receiver leaves the sda line hi gh, a nack is signalled. when the receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the transmitter by sending a nack after the final byte. the msb of the data byte is transmitted first. figure 21-5. data packet format 21.3.5 combining address and data packets into a transmission a transmission basically consists of a start co ndition, a sla+r/w, one or more data packets and a stop condition. an empty message, consisting of a start followed by a stop condi- tion, is illegal. note that the wired-an ding of the scl line can be used to implement handshaking between the master and the slave. the slave can extend the scl low period by pulling the scl line low. this is useful if the cloc k speed set up by the master is too fast for the slave, or the slave needs extra time for processing between the data transmissions. the slave extending the scl low period will not affect t he scl high period, which is determined by the master. as a consequence, the slave can reduce the twi data transfer speed by prolonging the scl duty cycle. figure 21-6 shows a typical data transmission. note that several data bytes can be transmitted between the sla+r/w and the stop condition, depending on the software protocol imple- mented by the application software. figure 21-6. typical data transmission 12 789 data msb data lsb ack aggregate sda sda from transmitter sda from receiver scl from master sla+r/w data byte stop, repeated start or next data byte 12 789 data byte data msb data lsb ack sda scl start 12 789 addr msb addr lsb r/w ack sla+r/w stop 205 8151h?avr?02/11 atmega128a 21.4 multi-master bus systems, arbitration and synchronization the twi protocol allows bus systems with seve ral masters. special concerns have been taken in order to ensure that transmis sions will proceed as normal, even if two or more masters initiate a transmission at the same time. two problems arise in multi-master systems: ? an algorithm must be implemented allowing only one of the masters to complete the transmission. all other masters should cease transmission when they discover that they have lost the selection process. this selection proc ess is called arbitration. when a contending master discovers that it has lost the arbitration process, it should immediately switch to slave mode to check whether it is being addressed by the winning master. the fact that multiple masters have started transmission at the same time should not be detectable to the slaves, that is, the data being transferred on the bus must not be corrupted. ? different masters may use different scl frequencies. a scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. this will fac ilitate the arbitration process. the wired-anding of the bus lines is used to solv e both these problems. the serial clocks from all masters will be wired-anded, yielding a co mbined clock with a high period equal to the one from the master with the shortest high period. the low period of the combined clock is equal to the low period of the master with the longest low period. note that all masters listen to the scl line, effectively starting to count their scl high and low time-out periods when the combined scl line goes high or low, respectively. figure 21-7. scl synchronization between multiple masters arbitration is carried out by all masters cont inuously monitoring the sda line after outputting data. if the value read from the sda line does not match the value the master had output, it has lost the arbitration. note that a master can only lose arbitration when it outputs a high sda value while another master outputs a low value. the losing master should immediately go to slave mode, checking if it is being addressed by the winning master. the sda line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. arbitration will cont inue until only one master re mains, and this may take many bits. if several masters are trying to address the same slave, ar bitration will cont inue into the data packet. ta low ta high scl from master a scl from master b scl bus line tb low tb high masters start counting low period masters start counting high period 206 8151h?avr?02/11 atmega128a figure 21-8. arbitration between two masters note that arbitration is not allowed between: ? a repeated start cond ition and a data bit ? a stop condition and a data bit ? a repeated start and a stop condition it is the user software?s responsibility to ensur e that these illegal arbitration conditions never occur. this implies that in multi-master systems, all data transfers must use the same composi- tion of sla+r/w and data packets. in other words: all transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined. 21.5 overview of the twi module the twi module is comprised of several submodules, as shown in figure 21-9 . all registers drawn in a thick line are accessible through the avr data bus. sda from master a sda from master b sda line synchronized scl line start master a loses arbitration, sda a sda 207 8151h?avr?02/11 atmega128a figure 21-9. overview of the twi module 21.5.1 scl and sda pins these pins interface the avr twi with the rest of the mcu system. the output drivers contain a slew-rate limiter in order to conform to the twi specification. the input stages contain a spike suppression unit removing spikes shorter than 50 ns. note that the internal pull-ups in the avr pads can be enabled by setting the port bits corresponding to the scl and sda pins, as explained in the i/o port section. the internal pull-ups can in some systems eliminate the need for external ones. 21.5.2 bit rate generator unit this unit controls the period of scl when oper ating in a master mode. the scl period is con- trolled by settings in the twi bit rate register (twbr) and the prescaler bits in the twi status register (twsr). slave operation does not depend on bit rate or prescaler settings, but the cpu clock frequency in the slave must be at least 16 times higher than the scl frequency. note that slaves may prolong the scl low period, thereby reducing the average twi bus clock period. the scl frequency is generated according to the following equation: ? twbr = value of the twi bit rate register ? twps = value of the prescaler bits in the twi status register note: pull-up resistor values should be selected according to the scl frequency and the capacitive bus line load. see table 27-4 on page 325 for value of pull-up resistor. 21.5.3 bus interface unit this unit contains the data and address shif t register (twdr), a start/stop controller and arbitration detection hardware. the twdr contains the address or data bytes to be transmitted, or the address or data bytes received. in addition to the 8-bit twdr, the bus interface unit also twi unit address register (twar) address match unit address comparator control unit control register (twcr) status register (twsr) state machine and status control scl slew-rate control spike filter sda slew-rate control spike filter bit rate generator bit rate register (twbr) prescaler bus interface unit start / stop control arbitration detection ack spike suppression address/data shift register (twdr) scl frequency cpu clock frequency 16 2(twbr) 4 twps ? + ----------------------------------------------------------- = 208 8151h?avr?02/11 atmega128a contains a register containing the (n)ack bit to be transmitted or receiv ed. this (n)ack regis- ter is not directly accessible by the application software. however, when re ceiving, it can be set or cleared by manipulating the twi control r egister (twcr). when in transmitter mode, the value of the received (n)ack bit can be determined by the value in the twsr. the start/stop controller is responsible for gene ration and detection of start, repeated start, and stop conditions. the start/stop controller is able to detect start and stop conditions even when the avr mcu is in one of the sleep modes, enabling the mcu to wake up if addressed by a master. if the twi has initiated a transmission as master, the arbitration detection hardware continu- ously monitors the transmission trying to determine if arbitration is in process. if the twi has lost an arbitration, the control unit is informed. correct action can then be taken and appropriate status codes generated. 21.5.4 address match unit the address match unit checks if received address bytes match the 7-bit address in the twi address register (twar). if the twi general call recognition enable (twgce) bit in the twar is written to one, all incoming address bits will also be compared against the general call address. upon an address match, the control unit is informed, allowing correct action to be taken. the twi may or may not acknowledge it s address, depending on settings in the twcr. the address match unit is able to compare addresses even when the avr mcu is in sleep mode, enabling the mcu to wake up if addressed by a master. if another interrupt (for example, int0) occurs during twi power-down address match and wakes up the cpu, the twi aborts operation and return to it?s idle state. if this cause any problems, ensure that twi address match is the only enabled interrupt when entering power-down. 21.5.5 control unit the control unit monitors the twi bus and generates responses corresponding to settings in the twi control register (twcr). when an event requiring the attention of the application occurs on the twi bus, the twi interrupt flag (twint) is asserted. in the next clock cycle, the twi sta- tus register (twsr) is updated with a stat us code identifying the event. the twsr only contains relevant status information when the tw i interrupt flag is asserted. at all other times, the twsr contains a special stat us code indicating that no relevant status information is avail- able. as long as the twint flag is set, the scl line is held low. this allows the application software to complete its tasks before allowing the twi transmission to continue. the twint flag is set in the following situations: ? after the twi has transmitted a start/repeated start condition ? after the twi has transmitted sla+r/w ? after the twi has transmitted an address byte ? after the twi has lost arbitration ? after the twi has been addressed by own slave address or general call ? after the twi has received a data byte ? after a stop or repeated start has been received while still ad dressed as a slave ? when a bus error has occurred due to an illegal start or stop condition 209 8151h?avr?02/11 atmega128a 21.6 using the twi the avr twi is byte-oriented and interrupt based. interrupts are issued after all bus events, like reception of a byte or transmission of a start condition. because the twi is interrupt-based, the application software is free to carry on other operations during a twi byte transfer. note that the twi interrupt enable (twie) bit in twcr to gether with the global interrupt enable bit in sreg allow the application to decide whether or not assertion of the twint flag should gener- ate an interrupt request. if the twie bit is cl eared, the application must poll the twint flag in order to detect actions on the twi bus. when the twint flag is asserted, the twi has finished an operation and awaits application response. in this case, the twi status register (twsr) contains a value indicating the current state of the twi bus. the application software can then decide how the twi should behave in the next twi bus cycle by manipulating the twcr and twdr registers. figure 21-10 is a simple example of how the application can interface to the twi hardware. in this example, a master wishes to transmit a single da ta byte to a slave. this description is quite abstract, a more detailed explanation follows later in this section. a simple code example imple- menting the desired behavior is also presented. figure 21-10. interfacing the application to the twi in a typical transmission 1. the first step in a twi transmission is to transmit a start condition. this is done by writing a specific value into twcr, instructing the twi hardware to transmit a start condition. which value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the tw int bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmission of the start condition. 2. when the start condition has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the start condition has success- fully been sent. 3. the application software should now examine the value of twsr, to make sure that the start condition was successfully transmitted. if twsr indicates otherwise, the appli- start sla+w a data a stop 1. application writes to twcr to initiate transmission of start 2. twint set. status code indicates start condition sent 4. twint set. status code indicates sla+w sendt, ack received 6. twint set. status code indicates data sent, ack received 3. check twsr to see if start was sent. application loads sla+w into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one, and twsta is written to zero. 5. check twsr to see if sla+w was sent and ack received. application loads data into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one. 7. check twsr to see if data was sent and ack received. application loads appropriate control signals to send stop into twcr, making sure that twint is written to one twi bus indicates twint set application action twi hardware action 210 8151h?avr?02/11 atmega128a cation software might take some special acti on, like calling an error routine. assuming that the status code is as expected, the application must load sla+w into twdr. remember that twdr is used both for address and data. after twdr has been loaded with the desired sla+w, a specific value must be written to twcr, instructing the twi hardware to transmit the sla+w present in twdr. which value to write is described later on. however, it is important t hat the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmis sion of the address packet. 4. when the address packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the address packet has success- fully been sent. the status code will also reflect whether a slave acknowledged the packet or not. 5. the application software should now examine the value of twsr, to make sure that the address packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some spe- cial action, like calling an error routine. assu ming that the status code is as expected, the application must load a data packet into twdr. subsequently, a specific value must be written to twcr, instructing the twi hardware to transmit the data packet present in twdr. which value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immedi- ately after the application has cleared twin t, the twi will initiate transmission of the data packet. 6. when the data packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the data packet has successfully been sent. the st atus code will also reflect whether a slave acknowledged the packet or not. 7. the application software should now examine the value of twsr, to make sure that the data packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some spe- cial action, like calling an error routine. assu ming that the status code is as expected, the application must write a specific valu e to twcr, instructing the twi hardware to transmit a stop condition. which value to wr ite is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the applicat ion has cleared twint, the twi will initiate transmission of the stop condition. note that twint is not set after a stop condition has been sent. even though this example is simple, it shows t he principles involved in all twi transmissions. these can be summarized as follows: ? when the twi has finished an operation and expects application response, the twint flag is set. the scl line is pulled low until twint is cleared. ? when the twint flag is set, the user must update all twi registers with the value relevant for the next twi bus cycle. as an example, twdr must be loaded with the value to be transmitted in the next bus cycle. after all twi register updates and other pendi ng application software tasks have been com- pleted, twcr is written. when writing twcr , the twint bit should be set. writing a one to twint clears the flag. the twi will then commen ce executing whatever operation was speci- fied by the twcr setting. 211 8151h?avr?02/11 atmega128a in the following an assembly and c implementation of the example is given. note that the code below assumes that several definitions have been made for example by using include-files. assembly code example c example comments 1 ldi r16, (1< 213 8151h?avr?02/11 atmega128a figure 21-11. data transfer in master transmitter mode a start condition is sent by wr iting the following value to twcr: twen must be set to enable the two-wire serial interface, twsta must be written to one to transmit a start condition and twint must be written to one to clear the twint flag. the twi will then test the two-wire serial bus and gene rate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hard- ware, and the status code in twsr will be $08 (see table 21-2 ). in order to enter mt mode, sla+w must be transmitted. this is done by writing sla+w to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to twcr: when sla+w have been transmitted and an acknowledgment bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are $18, $20, or $38. the appropriate action to be taken for each of these status codes is detailed in table 21-2 . when sla+w has been successfully transmitted, a data packet should be transmitted. this is done by writing the data byte to twdr. twdr must only be written when twint is high. if not, the access will be discarded, and the write collision bit (twwc) will be set in the twcr regis- ter. after updating twdr, the twint bit should be cleared (by writing it to one) to continue the transfer. this is acco mplished by writing the following value to twcr: this scheme is repeated until the last byte has been sent and the transfer is ended by generat- ing a stop condition or a repeated start condition. a stop condition is generated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master transmitter device 2 slave receiver device 3 device n sda scl ........ r1 r2 v cc 214 8151h?avr?02/11 atmega128a after a repeated start condition (state $10) the two-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control of the bus. table 21-2. status codes for master transmitter mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a $08 a start condition has been transmitted load sla+w 0 0 1 x sla+w will be transmitted; ack or not ack will be received $10 a repeated start condition has been transmitted load sla+w or load sla+r 0 0 0 0 1 1 x x sla+w will be transmitted; ack or not ack will be received sla+r will be transmitted; logic will switch to master receiver mode $18 sla+w has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset $20 sla+w has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset $28 data byte has been transmit- ted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset $30 data byte has been transmit- ted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset $38 arbitration lost in sla+w or data bytes no twdr action or no twdr action 0 1 0 0 1 1 x x two-wire serial bus will be released and not ad- dressed slave mode entered a start condition will be transmitted when the bus becomes free 215 8151h?avr?02/11 atmega128a figure 21-12. formats and states in the master transmitter mode 21.7.2 master receiver mode in the master receiver mode, a number of data bytes are received from a slave transmitter (see figure 21-13 ). in order to enter a master mode, a start condition must be transmitted. the for- mat of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitte d, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. s sla w a data a p $08 $18 $28 r sla w $10 ap $20 p $30 a or a $38 a other master continues a or a $38 other master continues r a $68 other master continues $78 $b0 to corresponding states in slave mode mt mr successfull transmission to a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address not acknowledge received after a data byte arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero s 216 8151h?avr?02/11 atmega128a figure 21-13. data transfer in ma ster receiver mode a start condition is sent by wr iting the following value to twcr: twen must be written to one to enable the two-wire serial interface, twsta must be written to one to transmit a start condit ion and twint must be set to clear the twint flag. the twi will then test the two-wire serial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hardware, and the status code in twsr will be $08 (see table 21-2 ). in order to enter mr mode, sla+r must be transmitted. this is done by writing sla+r to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the tr ansfer. this is accomplis hed by writing the follow- ing value to twcr: when sla+r have been transmitted and an acknow ledgment bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are $38, $40, or $48. the appropriate action to be taken for each of these status codes is detailed in table 21-12 . received data can be read from the twdr register when the twint flag is set high by hardware. this scheme is repe ated until the last byte has been received. after the last byte has been received, the mr should inform the st by sending a nack after the last received data byte. the transfer is ended by generating a stop condition or a repeated start condition. a stop condition is generated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state $10) the two-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control over the bus. twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master receiver device 2 slave transmitter device 3 device n sda scl ........ r1 r2 v cc 217 8151h?avr?02/11 atmega128a figure 21-14. formats and states in the master receiver mode s sla r a data a $08 $40 $50 sla r $10 ap $48 a or a $38 other master continues $38 other master continues w a $68 other master continues $78 $b0 to corresponding states in slave mode mr mt successfull reception from a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p data a $58 a r s table 21-3. status codes for master receiver mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a $08 a start condition has been transmitted load sla+r 0 0 1 x sla+r will be transmitted ack or not ack will be received $10 a repeated start condition has been transmitted load sla+r or load sla+w 0 0 0 0 1 1 x x sla+r will be transmitted ack or not ack will be received sla+w will be transmitted logic will switch to master transmitter mode $38 arbitration lost in sla+r or not ack bit no twdr action or no twdr action 0 1 0 0 1 1 x x two-wire serial bus will be released and not ad- dressed slave mode will be entered a start condition will be transmitted when the bus becomes free $40 sla+r has been transmitted; ack has been received no twdr action or no twdr action 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 218 8151h?avr?02/11 atmega128a 21.7.3 slave receiver mode in the slave receiver mode, a number of data bytes are received from a master transmitter (see figure 21-15 ). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 21-15. data transfer in slave receiver mode to initiate the slave receiver mode, twar and twcr must be initialized as follows: the upper seven bits are the address to which t he two-wire serial interface will respond when addressed by a master. if the l sb is set, the twi will respond to the general call address ($00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgment of the device?s own slave add ress or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?0? (write), the twi will operate in sr mode, otherwise st mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status c ode is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 21-4 . $48 sla+r has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset $50 data byte has been received; ack has been returned read data byte or read data byte 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $58 data byte has been received; not ack has been returned read data byte or read data byte or read data byte 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset table 21-3. status codes for master receiver mode twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x device 3 device n sda scl ........ r1 r2 v cc device 2 master transmitter device 1 slave receiver 219 8151h?avr?02/11 atmega128a the slave receiver mode may also be entered if arbitration is lost while the twi is in the master mode (see states $68 and $78). if the twea bit is reset during a transfer, the tw i will return a ?not acknowledge? (?1?) to sda after the next received data byte. this can be us ed to indicate that the slave is not able to receive any more bytes. while twea is zero, the twi does not acknowledge its own slave address. however, the two-wire serial bus is still monitored and address recognition may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the two-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the two-wire serial bus clock as a clock source. the part will then wake up from sleep and the twi will hold the scl clock low during the wake up and until the twint flag is cleared (by writing it to one). further data reception will be carri ed out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the two-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. table 21-4. status codes for slave receiver mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a $60 own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $68 arbitration lost in sla+r/w as master; own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $70 general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $78 arbitration lost in sla+r/w as master; general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $80 previously addressed with own sla+w; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $88 previously addressed with own sla+w; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 220 8151h?avr?02/11 atmega128a $90 previously addressed with general call; data has been re- ceived; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned $98 previously addressed with general call; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free $a0 a stop condition or repeated start condition has been received while still addressed as slave no action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free table 21-4. status codes for slave receiver mode (continued) 221 8151h?avr?02/11 atmega128a figure 21-16. formats and states in the slave receiver mode 21.7.4 slave transmitter mode in the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see figure ). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. data transfer in slave transmitter mode to initiate the slave transmitter mode, twar and twcr must be in itialized as follows: s sla w a data a $60 $80 $88 a $68 reception of the own slave address and one or more data bytes. all are acknowledged last data byte received is not acknowledged arbitration lost as master and addressed as slave reception of the general call address and one or more data bytes last data byte received is not acknowledged n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data a $80 $a0 p or s a a data a $70 $90 $98 a $78 p or s data a $90 $a0 p or s a general call arbitration lost as master and addressed as slave by general call data a device 3 device n sda scl ........ r1 r2 v cc device 2 master receiver device 1 slave transmitter 222 8151h?avr?02/11 atmega128a the upper seven bits are the address to which t he two-wire serial interface will respond when addressed by a master. if the l sb is set, the twi will respond to the general call address ($00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgment of the device?s own slave add ress or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?1? (read), the twi will operate in st mode, otherw ise sr mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status c ode is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 21-5 . the slave transmitter mode may also be entered if arbitration is lost while the twi is in the master mode (see state $b0). if the twea bit is written to zero during a transfer, the twi will transm it the last byte of the trans- fer. state $c0 or state $c8 will be entered, de pending on whether the master receiver transmits a nack or ack after the final byte. the twi is switched to the not addressed slave mode, and will ignore the master if it continues the transfer. thus the master receiver receives all ?1? as serial data. state $c8 is entered if the master demands additional data bytes (by transmitting ack), even though the slave has transmitted the last byte (twea zero and expecting nack from the master). while twea is zero, the twi does not respond to its own slave address. however, the two-wire serial bus is still monitored an d address recognition may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the two-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the two-wire serial bus clock as a clock source. the part will then wake up from sleep and the twi will hold the scl clock will low during the wake up and until the twint flag is cleared (by writing it to one). further data tr ansmission will be carried out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long ti me, blocking other data transmissions. note that the two-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x 223 8151h?avr?02/11 atmega128a table 21-5. status codes for slave transmitter mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a $a8 own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived $b0 arbitration lost in sla+r/w as master; own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived $b8 data byte in twdr has been transmitted; ack has been received load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived $c0 data byte in twdr has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free $c8 last data byte in twdr has been transmitted (twea = ?0?); ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 224 8151h?avr?02/11 atmega128a figure 21-17. formats and states in the slave transmitter mode 21.7.5 miscellaneous states there are two status codes that do not correspond to a defined twi state, see table 21-6 . status $f8 indicates that no relevant informatio n is available because the twint flag is not set. this occurs between other states, and when the twi is not involved in a serial transfer. status $00 indicates that a bus error has occurred during a two-wire serial bus transfer. a bus error occurs when a start or stop condition occurs at an illegal position in the format frame. examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. when a bus error occurs, twint is set. to recover from a bus error, the twsto flag must set and twint must be cleared by writing a logic one to it. this causes the twi to enter the not addressed slave mode and to clear the twsto flag (no other bits in twcr are affected). the sda and scl lines are released, and no stop condition is transmitted. 21.7.6 combining several twi modes in some cases, several twi modes must be combined in order to complete the desired action. consider for example reading data from a serial eeprom. typically, such a transfer involves the following steps: 1. the transfer must be initiated 2. the eeprom must be instructed what location should be read 3. the reading must be performed 4. the transfer must be finished s sla r a data a $a8 $b8 a $b0 reception of the own slave address and one or more data bytes last data byte transmitted. switched to not addressed slave (twea = '0') arbitration lost as master and addressed as slave n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data $c0 data a a $c8 p or s all 1's a table 21-6. miscellaneous states status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twin t twe a $f8 no relevant state information available; twint = ?0? no twdr action no twcr action wait or proceed current transfer $00 bus error due to an illegal start or stop condition no twdr action 0 1 1 x only the internal hardware is affected, no stop condi- tion is sent on the bus. in all cases, the bus is released and twsto is cleared. 225 8151h?avr?02/11 atmega128a note that data is transmitted both from master to slave and vice versa. the master must instruct the slave what location it wants to read, requi ring the use of the mt mode. subsequently, data must be read from the slave, implying the use of the mr mode. thus, the transfer direction must be changed. the master must keep control of the bus during all these steps, and the steps should be carried out as an atomical operation. if th is principle is violated in a multimaster sys- tem, another master can alter the data pointer in the eeprom between steps 2 and 3, and the master will read the wrong data lo cation. such a change in transfe r direction is accomplished by transmitting a repeated start between the trans mission of the address byte and reception of the data. after a repeated start, the master keeps ownership of the bus. the following figure shows the flow in this transfer. figure 21-18. combining several twi modes to access a serial eeprom 21.8 multi-master syst ems and arbitration if multiple masters are connected to the same bus, transmissions may be initiated simultane- ously by one or more of them. the twi standar d ensures that such situations are handled in such a way that one of the mast ers will be allowed to proceed wit h the transfer, and that no data will be lost in the process. an example of an ar bitration situation is depicted below, where two masters are trying to transmit data to a slave receiver. figure 21-19. an arbitration example several different scenarios may arise during arbitration, as described below: ? two or more masters are performing identical communication with the same slave. in this case, neither the slave nor any of the masters will know about the bus contention. ? two or more masters are accessing the same slave with different data or direction bit. in this case, arbitration will occur, either in the read /write bit or in the data bits. the masters trying to output a one on sda while another master outputs a zero will lose the arbitration. master transmitter master receiver s = start rs = repeated start p = stop transmitted from master to slave transmitted from slave to master s sla+w a address a rs sla+r a data a p device 1 master transmitter device 2 master transmitter device 3 slave receiver device n sda scl ........ r1 r2 v cc 226 8151h?avr?02/11 atmega128a losing masters will switch to no t addressed slave mode or wa it until the bus is free and transmit a new start condition, depending on application software action. ? two or more masters are access ing different slaves. in this ca se, arbitration will occur in the sla bits. masters trying to ou tput a one on sda while another mast er outputs a zero will lose the arbitration. masters losing arbitration in sla will switch to slave mode to check if they are being addressed by the winning master. if addressed, they will switch to sr or st mode, depending on the value of the read/write bit. if they are not being addressed, they will switch to not addressed slave mode or wait until the bus is free and transmit a new start condition, depending on application software action. this is summarized in figure 21-20 . possible status values are given in circles. figure 21-20. possible status codes caused by arbitration 21.9 register description 21.9.1 twbr - twi bit rate register ? bits 7:0 ? twi bit rate register twbr selects the division factor for the bit rate generator. the bit rate generator is a frequency divider which generates the scl clock frequency in the master modes. see ?bit rate generator unit? on page 207 for calculating bit rates. 21.9.2 twcr - twi control register the twcr is used to control the operation of the twi. it is used to enable the twi, to initiate a master access by applying a start condition to the bus, to generate a receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the own address / general call received arbitration lost in sla twi bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free no arbitration lost in data direction yes write data byte will be received and not ack will be returned data byte will be received and ack will be returned last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received read b0 68/78 38 sla start data stop bit 76543210 twbr7 twbr6 twbr5 twbr4 twbr3 twbr2 twbr1 twbr0 twbr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 twint twea twsta twsto twwc twen ? twie twcr read/write r/w r/w r/w r/w r r/w r r/w initial value 0 0 0 0 0 0 0 0 227 8151h?avr?02/11 atmega128a bus are written to the twdr. it also indicates a write collision if data is attempted written to twdr while the regist er is inaccessible. ? bit 7 ? twint: twi interrupt flag this bit is set by hardware when the twi has finished its current job and expects application software response. if the i-bit in sreg and twie in twcr are set, the mcu will jump to the twi interrupt vector. while the twint flag is set, the scl low period is stretched. the twint flag must be cleared by software by writing a logic one to it. note that this flag is not automatically cleared by hardware when executing the interrupt routine. also note that clearing this flag starts the operation of the twi, so all accesses to the twi address register (twar), twi status register (twsr), and twi data register (twdr) must be complete before clearing this flag. ? bit 6 ? twea: twi enable acknowledge bit the twea bit controls the generation of the acknowledge pulse. if the twea bit is written to one, the ack pulse is generated on the twi bus if the following conditions are met: 1. the device?s own slave address has been received. 2. a general call has been received, while the twgce bit in the twar is set. 3. a data byte has been received in master receiver or slave receiver mode. by writing the twea bit to zero, the device can be virtually disconnected from the two-wire serial bus temporarily. address recognition can then be resumed by writing the twea bit to one again. ? bit 5 ? twsta: twi start condition bit the application writes the twsta bit to one when it desires to become a master on the two- wire serial bus. the twi hardware checks if the bus is available, and generates a start con- dition on the bus if it is free. however, if the bus is not free, t he twi waits until a stop condition is detected, and then generates a new start condition to claim the bus master status. twsta must be cleared by software when the start condition has been transmitted. ? bit 4 ? twsto: twi stop condition bit writing the twsto bit to one in master mode will generate a stop condition on the two-wire serial bus. when the stop condition is exec uted on the bus, the twsto bit is cleared auto- matically. in slave mode, setting the twsto bit can be used to recover from an error condition. this will not generate a stop co ndition, but the twi returns to a well-defined unaddressed slave mode and releases the scl and sda lines to a high impedance state. ? bit 3 ? twwc: twi write collision flag the twwc bit is set when attempting to write to the twi data register ? twdr when twint is low. this flag is cleared by writing the twdr register when twint is high. ? bit 2 ? twen: twi enable bit the twen bit enables twi operation and activate s the twi interface. when twen is written to one, the twi takes control over the i/o pins connected to the scl and sda pins, enabling the slew-rate limiters and spike filters. if this bit is written to zero, the twi is switched off and all twi transmissions are terminated, regardless of any ongoing operation. 228 8151h?avr?02/11 atmega128a ? bit 1 ? res: reserved bit this bit is a reserved bit an d will always read as zero. ? bit 0 ? twie: twi interrupt enable when this bit is written to one, and the i-bit in sreg is set, th e twi interrupt request will be acti- vated for as long as the twint flag is high. 21.9.3 twsr - twi status register ? bits 7:3 ? tws: twi status these 5 bits reflect the status of the twi logic and the two-wire serial bus. the different status codes are described later in this section. note that the value read from twsr contains both the 5-bit status value and the 2-bit prescaler value. the application designer should mask the pres- caler bits to zero when checking the status bits. this makes status checking independent of prescaler setting. this approach is used in this datasheet, unless otherwise noted. ? bit 2 ? res: reserved bit this bit is reserved and will always read as zero. ? bits 1:0 ? twps: twi prescaler bits these bits can be read and written, and control the bit rate prescaler. to calculate bit rates, see ?bit rate generator unit? on page 207 . the value of twps1:0 is used in the equation. 21.9.4 twdr - twi data register in transmit mode, twdr contains the next byte to be transmitted. in receive mode, the twdr contains the last byte received. it is writable while the twi is not in the process of shifting a byte. this occurs when the twi interrupt flag (twint) is set by hardware. note that the data register cannot be initialized by the user before the first interrupt occurs. the data in twdr remains sta- ble as long as twint is set. while data is shifted out, data on the bus is simultaneously shifted bit 76543210 tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 twsr read/write r r r r r r r/w r/w initial value 1 1 1 1 1 0 0 0 table 21-7. twi bit rate prescaler twps1 twps0 prescaler value 001 014 1016 1164 bit 76543210 twd7 twd6 twd5 twd4 twd3 twd2 twd1 twd0 twdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111111 229 8151h?avr?02/11 atmega128a in. twdr always contains the last byte present on the bus, except after a wake up from a sleep mode by the twi interrupt. in this case, the conten ts of twdr is undefined. in the case of a lost bus arbitration, no data is lost in the transition from master to slave. handling of the ack bit is controlled automatically by the twi logic, the cpu cannot access the ack bit directly. ? bits 7:0 ? twd: twi data register these eight bits constitute the next data byte to be transmitted, or the latest data byte received on the two-wire serial bus. 21.9.5 twar - twi (slave) address register the twar should be loaded with the 7-bit slave address (in the seven most significant bits of twar) to which the twi will respond when progra mmed as a slave transm itter or receiver, and not needed in the master modes. in multimaster systems, twar must be set in masters which can be addressed as slaves by other masters. the lsb of twar is used to enable recognition of the general call address ($00). there is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. if a match is found, an interrupt request is generated. ? bits 7:1 ? twa: twi (slave) address register these seven bits constitute th e slave address of the twi unit. ? bit 0 ? twgce: twi general call recognition enable bit if set, this bit enables the recognition of a general call given over the two-wire serial bus. bit 76543210 twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce twar read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111110 230 8151h?avr?02/11 atmega128a 22. analog comparator 22.1 overview the analog comparator compares the input values on the positive pin ain0 and negative pin ain1. when the voltage on the positive pin ain0 is higher than the voltage on the negative pin ain1, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. th e user can select interrupt triggering on com- parator output rise, fall or toggle. a block diagram of the comparator and its surrounding logic is shown in figure 22-1 . figure 22-1. analog comparator block diagram notes: 1. see table 2 on page 231 . 2. refer to figure 1-1 on page 2 and table 12-14 on page 81 for analog comparator pin placement. 22.2 analog comparator multiplexed input it is possible to select any of the adc7:0 pins to replace the negative input to the analog com- parator. the adc multiplexer is used to select this input, and consequently, the adc must be switched off to utilize this feature. if the analog comparator multiplexer enable bit (acme in sfior) is set and the adc is switched off (aden in adcsra is zero), mux2:0 in admux select the input pin to replace the negative input to the analog comparator, as shown in table 2 . acbg bandgap reference adc multiplexer output acme aden 1) 231 8151h?avr?02/11 atmega128a if acme is cleared or aden is set, ain1 is applied to the negative input to the analog comparator. 22.3 register description 22.3.1 sfior - special function io register ? bit 3 ? acme: analog comparator multiplexer enable when this bit is written logic one and the adc is switched off (aden in adcsra is zero), the adc multiplexer selects the negative input to the analog comparator. when this bit is written logic zero, ain1 is applied to the negative input of the analog comparator. for a detailed description of this bit, see ?analog comparator multiplexed input? on page 230 . 22.3.2 acsr - analog comparator control and status register ? bit 7 ? acd: analog comparator disable when this bit is written logic one , the power to the analog comparator is switched off. this bit can be set at any time to tu rn off the analog com parator. this will reduce power consumption in active and idle mode. when changing the acd bit, the analog comparator interrupt must be disabled by clearing the acie bit in acsr. otherwise an interrupt can occur when the bit is changed. table 2. analog comparator multiplexed input acme aden mux2:0 analog comp arator negative input 0 x xxx ain1 1 1 xxx ain1 1 0 000 adc0 1 0 001 adc1 1 0 010 adc2 1 0 011 adc3 1 0 100 adc4 1 0 101 adc5 1 0 110 adc6 1 0 111 adc7 bit 7 6 5 4 3 2 1 0 tsm ? ? ? acme pud psr0 psr321 sfior read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 acd acbg aco aci acie acic acis1 acis0 acsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 n/a 0 0 0 0 0 232 8151h?avr?02/11 atmega128a ? bit 6 ? acbg: analog comparator bandgap select when this bit is set, a fixed bandgap reference vo ltage replaces the positive input to the analog comparator. when this bit is cleared, ain0 is ap plied to the positive input of the analog compar- ator. see ?internal voltage reference? on page 54. ? bit 5 ? aco: analog comparator output the output of the analog comparator is synchronized and then directly connected to aco. the synchronization introduces a delay of 1 ? 2 clock cycles. ? bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interr upt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when executing the corresponding inter- rupt handling vector. alternatively, aci is cleared by writing a logic one to the flag. ? bit 3 ? acie: analog comparator interrupt enable when the acie bit is written logic one and the i-bi t in the status register is set, the analog com- parator interrupt is activated. when written logic zero, the interrupt is disabled. ? bit 2 ? acic: analog comparator input capture enable when written logic one, this bit enables the input capture function in timer/counter1 to be trig- gered by the analog comparator. the comparator output is in this case directly connected to the input capture front-end logic, making the comp arator utilize the noise canceler and edge select features of the timer/counter1 input capture interrupt. when written logic zero, no connection between the analog comparator and the input capture function exists. to make the comparator trigger the timer/counter1 input capture interrupt, the ticie1 bit in the timer interrupt mask register (timsk) must be set. ? bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger the analog comparator interrupt. the different settings are shown in table 22-1 . when changing the acis1/acis0 bits, the analog comparator interrupt must be disabled by clearing its interrupt enable bit in the acsr register. otherwise an interrupt can occur when the bits are changed. table 22-1. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle 01reserved 1 0 comparator interrupt on falling output edge 1 1 comparator interrupt on rising output edge 233 8151h?avr?02/11 atmega128a 23. analog to digital converter 23.1 features ? 10-bit resolution ? 0.5 lsb integral non-linearity ? 2 lsb absolute accuracy ? 13 s - 260 s conversion time ? up to 76.9 ksps (up to 15 ksps at maximum resolution) ? 8 multiplexed single ended input channels ? 7 differential input channels ? 2 differential input ch annels with optional gain of 10x and 200x ? optional left adjustment for adc result readout ? 0 - vcc adc input voltage range ? selectable 2.56v adc reference voltage ? free running or single conversion mode ? interrupt on adc conversion complete ? sleep mode no ise canceler 23.2 overview the atmega128a features a 10-bit successive approximation adc. the adc is connected to an 8-channel analog multiplexer which allows 8 single-ended voltage inputs constructed from the pins of port f. the single-ended voltage inputs refer to 0v (gnd). the device also supports 16 differential voltage input combinations. two of the differential inputs (adc1, adc0 and adc3, adc2) are equipped wi th a programmable gain stage, providing amplification steps of 0 db (1x), 20 db (10x), or 46 db (200x) on the differential input voltage before the a/d conversion. seven differential analog input channels share a common negative terminal (adc1), while any other adc input can be selected as the positive input terminal. if 1x or 10x gain is used, 8-bit resolution can be expec ted. if 200x gain is used, 7-bit resolution can be expected. the adc contains a sample and hold circuit whic h ensures that the input voltage to the adc is held at a constant level during conversion . a block diagram of the adc is shown in figure 23-1 . the adc has a separate analog supply voltage pin, avcc. av cc must not differ more than 0.3v from v cc . see the paragraph ?adc noise canceler? on page 239 on how to connect this pin. internal reference voltages of nominally 2.56v or avcc are provided on-chip. the voltage refer- ence may be externally decoupled at the aref pi n by a capacitor for better noise performance. 234 8151h?avr?02/11 atmega128a figure 23-1. analog to digital converter block schematic 23.3 operation the adc converts an analog input voltage to a 10-bit digital value through successive approxi- mation. the minimum value represents gnd and the maximum value represents the voltage on the aref pin minus 1 lsb. optionally, avcc or an internal 2.56v reference voltage may be connected to the aref pin by writing to the refsn bits in the admux register. the internal voltage reference may thus be decoupled by an external capacitor at the aref pin to improve noise immunity. adc conversion complete irq 8-bit data bus 15 0 adc multiplexer select (admux) adc ctrl. & status register (adcsra) adc data register (adch/adcl) mux2 adie adfr adsc aden adif adif mux1 mux0 adps0 adps1 adps2 mux3 conversion logic 10-bit dac + - sample & hold comparator internal 2.56v reference mux decoder mux4 avcc adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 refs0 refs1 adlar + - channel selection gain selection adc[9:0] adc multiplexer output gain amplifier aref bandgap reference prescaler single ended / differential selection agnd pos. input mux neg. input mux 235 8151h?avr?02/11 atmega128a the analog input channel and diff erential gain are selected by writing to the mux bits in admux. any of the adc input pins, as well as gnd and a fixed bandgap voltage reference, can be selected as single ended inputs to the adc. a selection of adc input pins can be selected as positive and negative inputs to the differential gain amplifier. if differential channels are selected, the differential gain stage amplifies the voltage difference between the selected input channel pair by the se lected gain factor. this amplified value then becomes the analog input to the adc. if single ended channels are used, the gain amplifier is bypassed altogether. the adc is enabled by setting the adc enable bit, aden in adcsra. voltage reference and input channel selections will not go into effect until aden is set. the adc does not consume power when aden is cleared, so it is recommended to switch off the adc before entering power saving sleep modes. the adc generates a 10-bit result which is pr esented in the adc data registers, adch and adcl. by default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the adlar bit in admux. if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch, to ensure that the content of the data registers belongs to the same conversion. once adcl is read, adc access to data registers is blocked. this means that if adcl has been r ead, and a conversion completes before adch is read, neither register is updated and the result fr om the conversion is lost. when adch is read, adc access to the adch and ad cl registers is re-enabled. the adc has its own interrupt which can be triggered when a conversion completes. when adc access to the data registers is prohibited between r eading of adch and ad cl, the in terrupt will trigger even if the result is lost. 23.4 starting a conversion a single conversion is started by writing a l ogical one to the adc start conversion bit, adsc. this bit stays high as long as the conversi on is in progress and will be cleared by hardware when the conversion is completed. if a different data channel is selected while a conversion is in progress, the adc will finish the current conv ersion before performing the channel change. in free running mode, the adc is constantly sampling and updating the adc data register. free running mode is selected by writing the adfr bit in adcsra to one. the first conversion must be started by writing a logical one to the adsc bit in adcsra. in this mode the adc will perform successive conversions independently of whether the adc interrupt flag, adif is cleared or not. 236 8151h?avr?02/11 atmega128a 23.5 prescaling and conversion timing figure 23-2. adc prescaler by default, the successive approximation circ uitry requires an input clock frequency between 50khz and 200khz to get maximum resolution. if a lower resolution than 10 bits is needed, the input clock frequency to the adc can be higher than 200khz to get a higher sample rate. the adc module contains a prescaler, which generates an acceptable adc clock frequency from any cpu frequency above 100khz. the prescaling is set by the adps bits in adcsra. the prescaler starts counting from the moment the adc is switched on by setting the aden bit in adcsra. the prescaler keeps running for as lo ng as the aden bit is set, and is continuously reset when aden is low. when initiating a single ended conversion by se tting the adsc bit in adcsra, the conversion starts at the following rising edge of the adc clock cycle. see ?differential gain channels? on page 238 for details on differential conversion timing. a normal conversion takes 13 adc clock cycles. the first conversion after the adc is switched on (aden in adcsra is set) takes 25 adc clock cycles in order to initialize the analog circuitry. the actual sample-and-hold takes place 1.5 adc clock cycles after the start of a normal conver- sion and 13.5 adc clock cycles after the start of an first conv ersion. when a conversion is complete, the result is written to the adc data registers, and adif is set. in single conversion mode, adsc is cleared simultaneously. the software may then set adsc again, and a new conversion will be init iated on the first rising adc clock edge. in free running mode, a new conversion will be started immediately after the conversion com- pletes, while adsc remains high. for a summary of conversion times, see table 23-1 . 7-bit adc prescaler adc clock source ck adps0 adps1 adps2 ck/128 ck/2 ck/4 ck/8 ck/16 ck/32 ck/64 reset aden 237 8151h?avr?02/11 atmega128a figure 23-3. adc timing diagram, first conver sion (single conversion mode) figure 23-4. adc timing diagram, single conversion figure 23-5. adc timing diagram, free running conversion msb of result lsb of result adc clock adsc sample &hold adif adch adcl cycle number aden 1 212 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 first conversion next conversion 3 mux and refs update mux and refs update conversion complete 1 2 3 4 5 6 7 8 9 10 11 12 13 msb of result lsb of result adc clock adsc adif adch adcl cycle number 12 one conversion next conversion 3 sample & hold mux and refs update conversion complete mux and refs update 11 12 13 msb of result lsb of result adc clock adsc adif adch adcl cycle number 12 one conversion next conversion 34 conversion complete sample & hold mux and refs update 238 8151h?avr?02/11 atmega128a 23.5.1 differential gain channels when using differential gain channels, certain aspects of the conversion need to be taken into consideration. differential conversions are synchronized to the internal clock ck adc2 equal to half the adc clock. this synchronization is done automatically by the adc interface in such a way that the sample-and-hold occurs at a specific edge of ck adc2 . a conversion initiated by the user (that is, all single conversions, and the first free running conversion) when ck adc2 is low will take the same amount of time as a single ended conversion (13 adc clock cycles from the next pres- caled clock cycle). a conversion initiated by the user when ck adc2 is high will take 14 adc clock cycles due to the synchronization mechanism. in free running mode, a new conversion is initi- ated immediately after the previous conversion completes, and since ck adc2 is high at this time, all automatically started (that is , all but the first) free running conversions will take 14 adc clock cycles. the gain stage is optimized for a bandwidth of 4k hz at all gain settings . higher frequencies may be subjected to non-linear amplification. an exte rnal low-pass filter should be used if the input signal contains higher frequency components th an the gain stage bandwidth. note that the adc clock frequency is independent of the gain stage bandwidth limitation. for example the adc clock period may be 6 s, allowi ng a channel to be sa mpled at 12 ksps, r egardless of the band- width of this channel. 23.6 changing channel or reference selection the muxn and refs1:0 bits in the admux register are single buffered through a temporary register to which the cpu has random access. this ensures that the channels and reference selection only takes place at a safe point dur ing the conversion. the channel and reference selection is continuously updated until a conversion is started. once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the adc. con- tinuous updating resumes in the last adc clock cycle before the conversion completes (adif in adcsra is set). note that the conversion star ts on the following rising adc clock edge after adsc is written. the user is thus advised not to write new channel or reference selection values to admux until one adc clock cycle after adsc is written. special care should be taken when changing differential channels. once a differential channel has been selected, the gain stage may take as much as 125 s to stabilize to the new value. thus conversions should not be started within the first 125 s after selecting a new differential channel. alternatively, conversion results obtained within this period should be discarded. the same settling time should be observed for th e first differential conversion after changing adc reference (by changing the refs1:0 bits in admux). if the jtag interface is enabled, the functi on of adc channels on portf7:4 is overridden. refer to table 12-17, ?port f pins alternate functions,? on page 83 . table 23-1. adc conversion time condition sample & hold (cycles from start of conversion) conversion time (cycles) first conversion 13.5 25 normal conversions, single ended 1.5 13 normal conversions, differential 1.5/2.5 13/14 239 8151h?avr?02/11 atmega128a 23.6.1 adc input channels when changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: in single conversion mode, always select the channel before starting the conversion. the chan- nel selection may be changed one adc clock cycle after writing one to adsc. however, the simplest method is to wait for the conversion to complete before changing the channel selection. in free running mode, always select the channel before starting the first conversion. the chan- nel selection may be changed one adc clock cycle after writing one to adsc. however, the simplest method is to wait for the first conversion to complete, and then change the channel selection. since the next conver sion has already started automati cally, the next result will reflect the previous channel selection. subsequent conversions will refl ect the new channel selection. when switching to a differential gain channel, the first conversion result may have a poor accu- racy due to the required settling time for the automatic offset cancellation circuitry. the user should preferably disregard the first conversion result. 23.6.2 adc voltage reference the reference voltage for the adc (v ref ) indicates the conversion range for the adc. single ended channels that exceed v ref will result in code s close to 0x3ff. v ref can be selected as either av cc , internal 2.56v reference, or external aref pin. avcc is connected to the adc through a passive switch. the internal 2.56v reference is gener- ated from the internal bandgap reference (v bg ) through an internal amplifier. in either case, the external aref pin is directly connected to the adc, and the reference voltage can be made more immune to noise by connecting a capacitor between the aref pin and ground. v ref can also be measured at the aref pin with a high impedant voltmeter. note that v ref is a high impedant source, and only a capacitive load should be connected in a system. if the user has a fixed voltage source connected to the aref pin, the user may not use the other reference voltage options in the ap plication, as they will be shorte d to the external voltage. if no external voltage is applied to the aref pin, the user may switch between avcc and 2.56v as reference selection. the first adc conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result. if differential channels are used, the selected reference should not be closer to avcc than indicated in table 27-8 on page 331 . 23.7 adc noise canceler the adc features a noise canceler that enables conversion during sleep mode to reduce noise induced from the cpu core and other i/o peripherals. the noise canceler can be used with adc noise reduction and idle mode. to make use of this feature, the following procedure should be used: 1. make sure that the adc is enabled and is not busy converting. single conversion mode must be selected and the adc conversion complete interrupt must be enabled. 2. enter adc noise reduction mode (or idle mo de). the adc will start a conversion once the cpu has been halted. 3. if no other interrupts occur before the ad c conversion completes, the adc interrupt will wake up the cpu and execute the adc conversion complete interrupt routine. if another interrupt wakes up the cpu before the adc conversion is complete, that inter- rupt will be executed, and an adc conversion complete interrupt request will be 240 8151h?avr?02/11 atmega128a generated when the adc conversion comple tes. the cpu will remain in active mode until a new sleep command is executed. note that the adc will not be automatically turned off when entering other sleep modes than idle mode and adc noise reduction mode. the user is advised to write zero to aden before enter- ing such sleep modes to avoid excessive power consumption. if the adc is enabled in such sleep modes and the user wants to perform diff erential conversions, the user is advised to switch the adc off and on after waking up from sleep to prompt an extended conversion to get a valid result. 23.7.1 analog input circuitry the analog input circuitry for single ended channel s is illustrated in figure 23-6. an analog source applied to adcn is subjected to the pin capacitance and input leakage of that pin, regard- less of whether that channel is selected as input for the adc. when the channel is selected, the source must drive the s/h capacitor through the series resistance (combined resistance in the input path). the adc is optimized for analog signals wit h an output impedance of approximately 10 k or less. if such a source is used, the sampling time will be negligible. if a source with higher imped- ance is used, the sampling time will depend on how long time the source nee ds to charge the s/h capacitor, with can vary widely. the user is recommended to only use low impedant sources with slowly varying signals, since this minimizes the required charge transfer to the s/h capacitor. if differential gain channels are used, the input circuitry looks somewhat different, although source impedances of a few hundred k or less is recommended. signal components higher than the nyquist frequency (f adc / 2) should not be present for either kind of channels, to avoid distortion from unpredictable signal convolution. the user is advised to remove high frequency components with a low-pass filter before applying the signals as inputs to the adc. figure 23-6. analog input circuitry 23.7.2 analog noise canceling techniques digital circuitry inside and outside the device ge nerates emi which might affect the accuracy of analog measurements. if conversion accuracy is critical, the noise level can be reduced by applying the following techniques: adcn i ih 1..100 k c s/h = 14 pf v cc /2 i il 241 8151h?avr?02/11 atmega128a 1. keep analog signal paths as short as possible. make sure analog tracks run over the ground plane, and keep them well away from high-speed switching digital tracks. 2. the avcc pin on the device should be connected to the digital v cc supply voltage via an lc network as shown in figure 23-7 . 3. use the adc noise canceler function to reduce induced noise from the cpu. 4. if any adc port pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. figure 23-7. adc power connections 23.7.3 offset compe?nsation schemes the gain stage has a built-in offset cancellation circ uitry that nulls the offset of differential mea- surements as much as possible. the remaining offset in the analog path can be measured directly by selecting the same channel for both differential inputs. this offset residue can be then subtracted in software from the measurement resu lts. using this kind of software based offset correction, offset on any channel can be reduced below one lsb. 23.7.4 adc accuracy definitions an n-bit single-ended adc converts a voltage linearly between gnd and v ref in 2 n steps (lsbs). the lowest code is read as 0, and the highest code is read as 2 n -1. several parameters describe the deviation from the ideal behavior: v cc g n d 100nf (adc0) pf0 (adc7) pf7 (adc1) pf1 (adc2) pf2 (adc3) pf3 (adc4) pf4 (adc5) pf5 (adc6) pf6 aref g n d a v cc 52 53 54 55 56 57 5 8 59 60 61 61 62 62 63 63 64 64 1 51 pe n (ad0) pa0 10 h 242 8151h?avr?02/11 atmega128a ? offset: the deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 lsb). ideal value: 0 lsb. figure 23-8. offset error ? gain error: after adjusting for offset, the gain error is found as the deviation of the last transition (0x3fe to 0x3ff) compared to the ideal transition (at 1.5 lsb below maximum). ideal value: 0 lsb figure 23-9. gain error ? integral non-linearity (inl): after adjusting for offset and gain error, the inl is the maximum deviation of an actual transition compared to an ideal transition for any code. ideal value: 0 lsb. output code v ref input voltage ideal adc actual adc offset error output code v ref input voltage ideal adc actual adc gain error 243 8151h?avr?02/11 atmega128a figure 23-10. integral non-linearity (inl) ? differential non-linearity (dnl): the maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 lsb). ideal value: 0 lsb. figure 23-11. differential non-linearity (dnl) ? quantization error: due to the quantization of the input voltage into a finite number of codes, a range of input voltages (1 lsb wide) will code to the same value. always 0.5 lsb. ? absolute accuracy: the maximum deviation of an actual (unadjusted) transition compared to an ideal transition for any code. this is the compound effect of offset, gain error, differential error, non-linearity, and quantization error. ideal value: 0.5 lsb. 23.8 adc conversion result after the conversion is complete (adif is high ), the conversion result can be found in the adc result registers (adcl, adch). for single ended conversion, the result is output code v ref input voltage ideal adc actual adc inl output code 0x3ff 0x000 0 v ref input voltage dnl 1 lsb 244 8151h?avr?02/11 atmega128a where v in is the voltage on the selected input pin and v ref the selected voltage reference (see table 23-3 on page 245 and table 23-4 on page 246 ). 0x000 represents ground, and 0x3ff represents the selected reference voltage minus one lsb. if differential channels are used, the result is where v pos is the voltage on the positive input pin, v neg the voltage on the negative input pin, gain the selected gain factor, and v ref the selected voltage reference. the result is presented in two?s complement form, from 0x200 (-512d) through 0x1ff (+511d). note that if the user wants to perform a quick polarity check of the results, it is sufficient to read the msb of the result (adc9 in adch). if this bit is one, the result is neg ative, and if this bit is zero, the result is posi- tive. figure 23-12 shows the decoding of the differential input range. table 23-2 shows the resulting output codes if the differential input channel pair (adcn - adcm) is selected with a gain of gain and a reference voltage of v ref . figure 23-12. differential measurement range adc v in 1024 ? v ref -------------------------- = adc v pos v neg ? () gain 512 ?? v ref ------------------------------------------------------------------------ = 0 output code 0x1ff 0x000 v ref /gain differential input voltage (volts) 0x3ff 0x200 - v ref /gain 245 8151h?avr?02/11 atmega128a example: admux = 0xed (adc3 - adc2, 10x gain, 2.56v reference, left adjusted result) voltage on adc3 is 300 mv, voltage on adc2 is 500 mv. adcr = 512 10 (300 - 500) / 2560 = -400 = 0x270 adcl will thus read 0x00, and adch will read 0x9c. writing zero to adlar right adjusts the result: adcl = 0x70, adch = 0x02. 23.9 register description 23.9.1 admux - adc multiplexer selection register ? bit 7:6 ? refs1:0: reference selection bits these bits select the voltage reference for the adc, as shown in table 23-3 . if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). the internal voltage reference options may not be used if an external reference voltage is being applied to the aref pin. table 23-2. correlation between input voltage and output codes v adcn read code correspondi ng decimal value v adcm + v ref /gain 0x1ff 511 v adcm + 511/512 v ref /gain 0x1ff 511 v adcm + 511/512 v ref /gain 0x1fe 510 :. :. :. v adcm + 1/512 v ref /gain 0x001 1 v adcm 0x000 0 v adcm - 1/512 v ref /gain 0x3ff -1 :. :. :. v adcm - 511/512 v ref /gain 0x201 -511 v adcm - v ref /gain 0x200 -512 bit 76543210 refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 admux read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 23-3. voltage reference selections for adc refs1 refs0 voltage reference selection 0 0 aref, internal vref turned off 0 1 avcc with external capacitor at aref pin 10reserved 1 1 internal 2.56v voltage reference with external capacitor at aref pin 246 8151h?avr?02/11 atmega128a ? bit 5 ? adlar: adc left adjust result the adlar bit affects the presentation of the adc conversion result in the adc data register. write one to adlar to left adjust the result. otherwise, the result is right adjusted. changing the adlar bit will affect t he adc data register immediately, regardless of any ongoing conver- sions. for a complete description of this bit, see ?adcl and adch - the adc data register? on page 248 . ? bits 4:0 ? mux4:0: analog channel and gain selection bits the value of these bits selects which combination of analog inputs are connected to the adc. these bits also select the gain for the differential channels. see table 23-4 for details. if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). table 23-4. input channel and gain selections mux4:0 single ended input positive differential input negative differential input gain 00000 adc0 00001 adc1 00010 adc2 00011 adc3 n/a 00100 adc4 00101 adc5 00110 adc6 00111 adc7 01000 (1) adc0 adc0 10x 01001 adc1 adc0 10x 01010 (1) adc0 adc0 200x 01011 adc1 adc0 200x 01100 adc2 adc2 10x 01101 adc3 adc2 10x 01110 adc2 adc2 200x 01111 adc3 adc2 200x 10000 adc0 adc1 1x 10001 adc1 adc1 1x 10010 n/a adc2 adc1 1x 10011 adc3 adc1 1x 10100 adc4 adc1 1x 10101 adc5 adc1 1x 10110 adc6 adc1 1x 10111 adc7 adc1 1x 11000 adc0 adc2 1x 11001 adc1 adc2 1x 247 8151h?avr?02/11 atmega128a note: 1. can be used for offset calibration. 23.9.2 adcsra - adc control and status register a ? bit 7 ? aden: adc enable writing this bit to one enables the adc. by writi ng it to zero, the adc is turned off. turning the adc off while a conversion is in prog ress, will terminate this conversion. ? bit 6 ? adsc: adc start conversion in single conversion mode, write this bit to one to start each conversion. in free running mode, write this bit to one to start the first conversion. the first conversion after adsc has been written after the adc has been enabled, or if adsc is written at the same time as the adc is enabled, will take 25 adc clock cycles instead of the norma l 13. this first conversi on performs initializa- tion of the adc. adsc will read as one as long as a conversion is in progress. when the co nversion is complete, it returns to zero. writing zero to this bit has no effect. ? bit 5 ? adfr: adc free running select when this bit is written to one, the adc operat es in free running mode. in this mode, the adc samples and updates the data regi sters continuously. writing zero to this bit will terminate free running mode. ? bit 4 ? adif: adc interrupt flag this bit is set when an adc conversion completes and the data registers are updated. the adc conversion complete interrupt is executed if th e adie bit and the i-bit in sreg are set. adif is cleared by hardware when executing the corres ponding interrupt handling vector. alternatively, adif is cleared by writing a logical one to the flag. beware that if doing a read-modify-write on adcsra, a pending interrupt can be disabled. this also applies if the sbi and cbi instructions are used. ? bit 3 ? adie: adc interrupt enable when this bit is written to one and the i-bit in sreg is set, the adc conversion complete inter- rupt is activated. 11010 adc2 adc2 1x 11011 adc3 adc2 1x 11100 adc4 adc2 1x 11101 adc5 adc2 1x 11110 1.23v (v bg ) n/a 11111 0v (gnd) table 23-4. input channel and gain selections (continued) mux4:0 single ended input positive differential input negative differential input gain bit 76543210 aden adsc adfr adif adie adps2 adps1 adps0 adcsra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 248 8151h?avr?02/11 atmega128a ? bits 2:0 ? adps2:0: adc prescaler select bits these bits determine the division factor between the xtal frequency and the input clock to the adc. 23.9.3 adcl and adch - the adc data register 23.9.3.1 adlar = 0: 23.9.3.2 adlar = 1: when an adc conversion is complete, the result is found in these two registers. if differential channels are used, the result is presented in two?s complement form. when adcl is read, the adc data register is not updated unt il adch is read. consequently, if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch. the adlar bit in admux, and the muxn bits in admux affect the way the result is read from the registers. if adlar is set, the result is left adjusted. if adla r is cleared (default), the result is right adjusted. table 23-5. adc prescaler selections adps2 adps1 adps0 division factor 000 2 001 2 010 4 011 8 100 16 101 32 110 64 1 1 1 128 bit 151413121110 9 8 ?????? adc9 adc8 adch adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 adcl 76543210 read/write rrrrrrrr rrrrrrrr initial value00000000 00000000 bit 151413121110 9 8 adc9 adc8 adc7 adc6 adc5 adc4 adc3 adc2 adch adc1 adc0 ? ????? adcl 76543210 read/write rrrrrrrr rrrrrrrr initial value00000000 00000000 249 8151h?avr?02/11 atmega128a ? adc9:0: adc conversion result these bits represent the result from the conversion, as detailed in ?adc conversion result? on page 243 . 250 8151h?avr?02/11 atmega128a 24. jtag interface and on-chip debug system 24.1 features ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan ca pabilities according to the i eee std. 1149.1 (jtag) standard ? debugger access to: ? all internal peripheral units ? internal and external ram ? the internal register file ?program counter ? eeprom and flash memories ? extensive on-chip debug support for break conditions, including ?avr break instruction ? break on change of program memory flow ? single step break ? program memory breakpoints on single address or address range ? data memory breakpoints on single address or address range ? programming of flash, eeprom , fuses, and lock bits th rough the jtag interface ? on-chip debugging supported by avr studio 24.2 overview the avr ieee std. 1149.1 compliant jtag interface can be used for ? testing pcbs by using the jtag boundary-scan capability ? programming the non-volatile memories, fuses and lock bits ? on-chip debugging a brief description is given in the following se ctions. detailed descriptions for programming via the jtag interface, and using the boundary-scan chain can be found in the sections ?program- ming via the jtag interface? on page 308 and ?ieee 1149.1 (jtag) boundary-scan? on page 255 , respectively. the on-chip debug support is considered being private jtag instructions, and distributed within atmel and to selected third party vendors only. figure 24-1 shows a block diagram of the jtag interface and the on-chip debug system. the tap controller is a state machine controlled by the tck and tms signals. the tap controller selects either the jtag instruction register or one of several data registers as the scan chain (shift register) between the tdi ? input and tdo ? output. the instruction register holds jtag instructions controlling the be havior of a data register. the id-register, bypass register, and the boundary-scan chain are the data registers used for board-level testing. the jtag programming interf ace (actually consisting of several physical and virtual data registers) is used for serial programming via the jtag interface. the internal scan chain and break point scan chain are used for on-chip debugging only. 251 8151h?avr?02/11 atmega128a 24.3 tap ? test access port the jtag interface is accessed through four of the avr?s pins. in jtag terminology, these pins constitute the test access port ?? tap. these pins are: ? tms: test mode select. this pin is used for navigating through the tap-controller state machine. ? tck: test clock. jtag operation is synchronous to tck. ? tdi: test data in. serial input data to be shifted in to the instruction register or data register (scan chains). ? tdo: test data out. serial output data from instruction register or data register. ? the ieee std. 1149.1 also spec ifies an optional tap signal; trst ? test reset ? which is not provided. ? when the jtagen fuse is unprogrammed, these four tap pins are normal port pins and the tap controller is in reset. when programmed an d the jtd bit in mcucsr is cleared, the tap input signals are internally pulled high and the jtag is enabled for boundary-scan and programming. in this case, the tap output pin (tdo) is left floating in states where the jtag tap controller is not shifting data, and must therefore be connected to a pull-up resistor or other hardware having pull-ups (for instance the tdi-input of the next device in the scan chain). the device is shipped with this fuse programmed. ? for the on-chip debug system, in addition to the jtag interface pins, the reset pin is monitored by the debugger to be able to detect external reset sources. the debugger can also pull the reset pin low to reset the whole system, assuming only open collectors on the reset line are used in the application. figure 24-1. block diagram tap controller tdi tdo tck tms flash memory avr cpu digital peripheral units jtag / avr core communication interface breakpoint unit flow control unit ocd status and control internal scan chain m u x instruction register id register bypass register jtag programming interface pc instruction address data breakpoint scan chain address decoder analog peripherial units i/o port 0 i/o port n boundary scan chain analog inputs control & clock lines device boundary 252 8151h?avr?02/11 atmega128a figure 24-2. tap controller state diagram 24.4 tap controller the tap controller is a 16-state finite state machine that controls the operation of the boundary- scan circuitry, jtag programming circuitry, or on-chip debug system. the state transitions depicted in figure 24-2 depend on the signal present on tm s (shown adjacent to each state transition) at the time of the rising edge at tck. the initial state after a power-on reset is test- logic-reset. as a definition in this document, the lsb is shifted in and out first for all shift registers. assuming run-test/idle is the present state, a typical scenario for using the jtag interface is: ? at the tms input, apply the sequence 1, 1, 0, 0 at the rising edges of tck to enter the shift instruction register ? shift-ir state. while in this state, shift the 4 bits of the jtag instructions into the jtag instruction register from the tdi input at the rising edge of tck. the tms input must be held low during input of the 3 lsbs in order to remain in the shift-ir test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 253 8151h?avr?02/11 atmega128a state. the msb of the instruction is shifted in when this state is left by setting tms high. while the instruction is shifted in from the tdi pin, the captured ir-state 0x01 is shifted out on the tdo pin. the jtag instruction selects a particular data register as path between tdi and tdo and controls the circuitry surrounding the selected data register. ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. the instruction is latched onto the parallel output from the shift register path in the update-ir state. the exit-ir, pause-ir, and exit2-ir states are only used for navigating the state machine. ? at the tms input, apply the sequence 1, 0, 0 at the rising edges of tck to enter the shift data register ? shift-dr state. while in th is state, upload the selected data register (selected by the present jtag instruction in the jtag instruction register) from the tdi input at the rising edge of tck. in order to remain in the shift-dr state, the tms input must be held low during input of all bits except the msb. the msb of the data is shifted in when this state is left by setting tms high. while the data register is shifted in from the tdi pin, the parallel inputs to the data register captured in the capture-dr state is shifted out on the tdo pin. ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. if the selected data register has a latched parallel-output, the latching takes place in the update-dr state. the exit-dr, pause-dr, and exit2-dr states are only used for navigating the state machine. as shown in the state diagram, the run-test/idle state need not be entered between selecting jtag instruction and using data registers, and some jtag instructions may select certain functions to be performed in the run-test/idle, making it unsuitable as an idle state. note: independent of the initial state of the tap c ontroller, the test-logic-r eset state can always be entered by holding tms high for 5 tck clock periods. for detailed information on the jtag specification, refer to the literature listed in ?bibliography? on page 255 . 24.5 using the b oundary-scan chain a complete description of the boundary-sc an capabilities are gi ven in the section ?ieee 1149.1 (jtag) boundary-scan? on page 255 . 24.6 using the on-c hip debug system as shown in figure 24-1 , the hardware support for on-chi p debugging consists mainly of ? a scan chain on the interface between the internal avr cpu and the internal peripheral units ? break point unit ? communication interface between the cpu and jtag system all read or modify/write operations needed for implementing the debugger are done by applying avr instructions via the internal avr cpu scan chain. the cpu sends the result to an i/o memory mapped location which is part of the communication interface between the cpu and the jtag system. the break point unit implements break on change of program flow, single step break, two program memory breakpoints, and two combined br eak points. together, the four break points can be configured as either: ? 4 single program memory break points ? 3 single program memory break point + 1 single data memory break point ? 2 single program memory break points + 2 single data memory break points 254 8151h?avr?02/11 atmega128a ? 2 single program memory break points + 1 program memory break point with mask (?range break point?) ? 2 single program memory break points + 1 data memory break point with mask ?range break point?. a debugger, like the avr studio ? , may however use one or more of these resources for its inter- nal purpose, leaving less flexibility to the end-user. a list of the on-chip debug specific jtag instructions is given in ?on-chip debug specific jtag instructions? on page 254 . the jtagen fuse must be programmed to enable the jtag test access port. in addition, the ocden fuse must be programmed and no lock bits must be set for the on-chip debug system to work. as a security feature, the on-chip debug system is disabled when any lock bits are set. otherwise, the on-chip debug system would have provided a back-door into a secured device. the avr studio enables the user to fully contro l execution of programs on an avr device with on-chip debug capability, avr in- circuit emulator, or the built-i n avr instruction set simulator. avr studio supports source level execution of assembly programs assembled with atmel cor- poration?s avr assembler and c programs compiled with third party vendors? compilers. avr studio runs under microsoft ? windows ? 95/98/2000 and windows nt ? and windows xp ? . for a full description of the avr studio, please refer to the avr studio user guide found in the online help in avr studio. only highlights are presented in this document. all necessary execution commands are available in avr studio, both on source level and on disassembly level. the user can execute the program, single step through the code either by tracing into or stepping over functions, step out of functions, place the cursor on a statement and execute until the statement is reached, stop th e execution, and reset the execution target. in addition, the user can have an unlimited number of code break points (using the break instruc- tion) and up to two data memory break points, alternatively combined as a mask (range) break point. 24.7 on-chip debug specific jtag instructions the on-chip debug support is considered being private jtag instructions, and distributed within atmel and to selected third-party vendors only. instruction opcodes are listed for reference. private0; $8 private jtag instruction for accessing on-chip debug system. private1; $9 private jtag instruction for accessing on-chip debug system. private2; $a private jtag instruction for accessing on-chip debug system. private3; $b private jtag instruction for accessing on-chip debug system. 255 8151h?avr?02/11 atmega128a 24.8 using the jtag pr ogramming capabilities programming of avr parts via jtag is performed via the four-pin jtag port, tck, tms, tdi, and tdo. these are the only pins that need to be controlled/observed to perform jtag pro- gramming (in addition to power pins). it is not required to apply 12v externally. the jtagen fuse must be programmed and the jtd bit in the mcucsr register must be cleared to enable the jtag test access port. the jtag programmi ng capability supports: ? flash programming and verifying ? eeprom programming and verifying ? fuse programming and verifying ? lock bit programming and verifying the lock bit security is exactly as in parallel programming mode. if the lock bits lb1 or lb2 are programmed, the ocden fuse cannot be programmed unless first doing a chip erase. this is a security feature that ensures no back-door exists for reading out the content of a secured device. the details on programming through the jtag interface and programming specific jtag instructions are given in the section ?programming via the jtag interface? on page 308 . 24.9 bibliography for more information about general boundary-scan, the following literature can be consulted: ? ieee: ieee std 1149.1-1990. ieee standard test access port and boundary-scan architecture, ieee, 1993 ? colin maunder: the board designers guide to testable logic circuits, addison-wesley, 1992 24.10 ieee 1149.1 (jtag) boundary-scan 24.10.1 features ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan capabilities acco rding to the jtag standard ? full scan of all port functions as well as analog circuitry having off-chip connections ? supports the optional idcode instruction ? additional public avr_reset instruction to reset the avr 24.10.2 system overview the boundary-scan chain has the capability of driv ing and observing the lo gic levels on the dig- ital i/o pins, as well as the boundary between di gital and analog logic for analog circuitry having off-chip connections. at system level, all ics having jtag capabilities ar e connected serially by the tdi/tdo signals to form a long shift register. an external controller sets up the devices to drive values at their output pins, and observe the input values received from other devices. the controller compares the received data with the expected result. in this way, boundary-scan pro- vides a mechanism for testing interconnections and integrity of components on printed circuits boards by using the four tap signals only. the four ieee 1149.1 defined mandatory jtag in structions idcode, bypass, sample/pre- load, and extest, as well as the avr specif ic public jtag instruction avr_reset can be used for testing the prin ted circuit board. initial scanning of the data register path will show the 256 8151h?avr?02/11 atmega128a id-code of the device, since idcode is the default jtag instruction. it may be desirable to have the avr device in reset during test mode. if not reset, inputs to the device may be determined by the scan operations, and the internal software may be in an undetermined state when exiting the test mode. entering reset, the outputs of any port pin will instantly enter the high imped- ance state, making the high z instruction redundant. if nee ded, the bypass instruction can be issued to make the shortest possible scan c hain through the device. the device can be set in the reset state either by pulling the external reset pin low, or issuing the avr_reset instruction with appropriate setting of the reset data register. the extest instruction is used for sampling external pins and loading output pins with data. the data from the output latch will be driven out on the pins as soon as the extest instruction is loaded into the jtag ir-register. therefore, the sample/preload should also be used for setting initial values to the scan ring, to avoid damaging the board when issuing the extest instruction for the first time. sample/preload c an also be used for taking a snapshot of the external pins during normal operation of the part. the jtagen fuse must be prog rammed and the jtd bit in th e i/o register mcucsr must be cleared to enable the jtag test access port. when using the jtag interface for boundary-scan, using a jtag tck clock frequency higher than the internal chip frequency is possible. the chip clock is not required to run. 24.11 data registers the data registers relevant for boundary-scan operations are: ? bypass register ? device identification register ? reset register ? boundary-scan chain 24.11.1 bypass register the bypass register consists of a single shift register stage. when the bypass register is selected as path between tdi and tdo, the register is reset to 0 when leaving the capture-dr controller state. the bypass register can be used to shorten the scan chain on a system when the other devices are to be tested. 24.11.2 device identification register figure 24-3 shows the structure of the de vice identification register. figure 24-3. the format of the device identification register 24.11.2.1 version version is a 4-bit number identifying the revision of the component. the jtag version number follows the revision of the device, and wraps around at revision p (0xf). revision a and q is 0x0, revision b and r is 0x1 and so on. msb lsb bit 31 28 27 12 11 1 0 device id version part number manufacturer id 1 4 bits 16 bits 11 bits 1-bit 257 8151h?avr?02/11 atmega128a 24.11.2.2 part number the part number is a 16-bit code identifying the component. the jtag part number for atmega128a is listed in table 24-1 . 24.11.2.3 manufacturer id the manufacturer id is a 11-bit code identifying the manufacturer. the jtag manufacturer id for atmel is listed in table 24-2 . 24.11.3 reset register the reset register is a test data register used to reset the part. since the avr tri-states port pins when reset, the reset register can also replace the function of the unimplemented optional jtag instruction highz. a high value in the reset regist er corresponds to pulling the ex ternal reset low. the part is reset as long as there is a high value present in the reset register. depending on the fuse set- tings for the clock optio ns, the part will remain reset for a re set time-out period (refer to ?clock sources? on page 39 ) after releasing the reset register. the output from this data register is not latched, so the re set will take place immediately, as shown in figure 24-4 . figure 24-4. reset register 24.11.4 boundary-scan chain the boundary-scan chain has the capability of driv ing and observing the lo gic levels on the dig- ital i/o pins, as well as the boundary between di gital and analog logic for analog circuitry having off-chip connections. see ?boundary-scan chain? on page 259 for a complete description. table 24-1. avr jtag part number part number jtag part number (hex) atmega128a 0x9702 table 24-2. manufacturer id manufacturer jtag manufacturer id (hex) at m e l 0 x 0 1 f dq from tdi clockdr avr_reset to tdo from other internal and external reset sources internal reset 258 8151h?avr?02/11 atmega128a 24.12 boundary-scan specifi c jtag instructions the instruction register is 4-bit wide, suppor ting up to 16 instructions. listed below are the jtag instructions useful for boundary-scan operation. note that the optional highz instruction is not implemented, but all outputs with tri-stat e capability can be set in high-impedant state by using the avr_reset instruction, since the initial state for all port pins is tri-state. as a definition in this data sheet, the lsb is shifted in and out first for all shift registers. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. 24.12.1 extest; $0 mandatory jtag instruction for selecting the boundary-scan chain as data register for testing circuitry external to the avr package. for port- pins, pull-up disable, output control, output data, and input data are all accessible in the scan chain. for analog ci rcuits having off-chip connections, the interface between the analog and th e digital logic is in the scan chain. the con- tents of the latched outputs of the boundary-scan chain is driven out as soon as the jtag ir- register is loaded with the extest instruction. the active states are: ? capture-dr: data on the external pins are sampled into the boundary-scan chain. ? shift-dr: the internal scan chain is shifted by the tck input. ? update-dr: data from the scan chain is applied to output pins. 24.12.2 idcode; $1 optional jtag instruction selecting the 32-bit id register as data register. the id register consists of a version number, a device number and the manufacturer code chosen by jedec. this is the default inst ruction after power-up. the active states are: ? capture-dr: data in the idcode register is sampled into the boundary-scan chain. ? shift-dr: the idcode scan chain is shifted by the tck input. 24.12.3 sample_preload; $2 mandatory jtag instruction for pre-loading the output latches and taking a snap-shot of the input/output pins without affecting the system operation. however, the output latched are not connected to the pins. the boundary-scan chain is selected as data register. the active states are: ? capture-dr: data on the external pins are sampled into the boundary-scan chain. ? shift-dr: the boundary-scan chain is shifted by the tck input. ? update-dr: data from the boundary-scan chain is applied to the output latches. however, the output latches are not connected to the pins. 24.12.4 avr_reset; $c the avr specific public jtag instruction for forcing the avr device into the reset mode or releasing the jtag reset source. the tap controller is not reset by this instruction. the one bit reset register is selected as data register. note that the reset will be active as long as there is a logic 'one' in the reset chain. the output from this chain is not latched. 259 8151h?avr?02/11 atmega128a the active states are: ? shift-dr: the reset register is shifted by the tck input. 24.12.5 bypass; $f mandatory jtag instructio n selecting the bypass register for data register. the active states are: ? capture-dr: loads a logic ?0? into the bypass register. ? shift-dr: the bypass register cell between tdi and tdo is shifted. 24.13 boundary-scan chain the boundary-scan chain has the capability of drivin g and observing the logi c levels on the digi- tal i/o pins, as well as the boundary between digi tal and analog logic for analog circuitry having off-chip connection. 24.13.1 scanning the digital port pins figure 24-5 shows the boundary-scan cell for a bi-directional port pin with pull-up function. the cell consists of a standard boundary-scan cell for the pull-up enable ? puexn ? function, and a bi-directional pin cell that combines the three signals output control ? ocxn, output data ? odxn, and input data ? idxn, into only a two-stage shift register. the port and pin indexes are not used in the following description the boundary-scan logic is not included in the figures in the data sheet. figure 24-6 shows a simple digital port pin as described in the section ?i/o ports? on page 65 . the boundary-scan details from figure 24-5 replaces the dashed box in figure 24-6 . when no alternate port function is present, the input data ? id corresponds to the pinxn regis- ter value (but id has no synchronizer), output data corresponds to the port register, output control corresponds to the data direction ? dd register, and the pull-up enable ? puexn ? cor- responds to logic expression pud ddxn portxn. digital alternate port functions are connected outside the dotted box in figure 24-6 to make the scan chain read the actual pin value. for analog function, there is a direct connection from the external pin to the analog circuit, and a scan ch ain is inserted on the interface between the digi- tal logic and the analog circuitry. 260 8151h?avr?02/11 atmega128a figure 24-5. boundary-scan cell for bi-directional port pin with pull-up function. dq dq g 0 1 0 1 dq dq g 0 1 0 1 0 1 0 1 dq dq g 0 1 port pin (pxn) vcc extest to next cell shiftdr output control (oc) pullup enable (pue) output data (od) input data (id) from last cell updatedr clockdr ff2 ld2 ff1 ld1 ld0 ff0 261 8151h?avr?02/11 atmega128a figure 24-6. general port pin schematic diagram 24.13.2 boundary-scan and the two-wire interface the two two-wire interface pins scl and sda ha ve one additional cont rol signal in the scan- chain; two-wire interface enable ? twien. as shown in figure 24-7 , the twien signal enables a tri-state buffer with slew-rate control in parallel with the ordinary digital port pins. a general scan cell as shown in figure 24-12 is attached to the twien signal. notes: 1. a separate scan chain for the 50 ns spike filt er on the input is not provided. the ordinary scan support tnsfor digital port pins suffice for conne ctivity tests. the only reason for having twien in the scan path, is to be able to disconnec t the slew-rate control buffer when doing boundary- scan. 2. make sure the oc and twien signals are not asserted simultaneously, as this will lead to drive contention. clk rpx rrx wpx rdx wdx pud synchronizer wdx: write ddrx wpx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data b u s sleep sleep: sleep control pxn i/o i/o see boundary-scan description for details! puexn ocxn odxn idxn puexn: pullup enable for pin pxn ocxn: output control for pin pxn odxn: output data to pin pxn idxn: input data from pin pxn 262 8151h?avr?02/11 atmega128a figure 24-7. additional scan signal for the two-wire interface 24.13.3 scanning the reset pin the reset pin accepts 5v active low logic for standar d reset operation, and 12v active high logic for high voltage parallel programming. an observe-only cell as shown in figure 24-8 is inserted both for the 5v reset signal; rstt, and the 12v reset signal; rsthv. figure 24-8. observe-only cell 24.13.4 scanning the clock pins the avr devices have many clock options selectable by fuses. these are: internal rc oscilla- tor, external rc, external clock, (high frequency) crystal oscillator, low-frequency crystal oscillator, and ceramic resonator. figure 24-9 shows how each oscillator with external co nnection is supported in the scan chain. the enable signal is su pported with a gener al boundary-scan cell, while the oscillator/clock out- put is attached to an observe-only cell. in additi on to the main clock, the timer oscillator is scanned in the same way. the output from the internal rc oscillator is not scanned, as this oscillator does not have external connections. pxn puexn odxn idxn twien ocxn slew-rate limited src 0 1 dq from previous cell clockdr shiftdr to next cell from system pin to system logic ff1 263 8151h?avr?02/11 atmega128a figure 24-9. boundary-scan cells for os cillators and clock options figure 24-10. table 24-3 summaries the scan registers for t he external clock pin xtal1, oscil- lators with xtal1/xtal2 connections as well as 32khz timer oscillator. notes: 1. do not enable more than one clock source as main clock at a time. 2. scanning an oscillator output gives unpredictable results as there is a frequency drift between the internal oscillator and the jtag tck clock. if possible, scanning an external clock is preferred. 3. the clock configuration is programmed by fuses. as a fuse is not changed run-time, the clock configuration is considered fixed for a given app lication. the user is advised to scan the same clock option as to be used in the final system. the enable signals are supported in the scan chain because the system logic c an disable clock options in sl eep modes, thereby disconnect- ing the oscillator pins from the scan path if not provided. the intcap fuses are not supported in the scan-chain, so the boundary scan chain ca n not make a xtal oscillator requiring inter- nal capacitors to run unless the fuse is correctly programmed. 24.13.5 scanning the analog comparator the relevant comparator signals regarding boundary-scan are shown in figure 24-11 . the boundary-scan cell from figure 24-12 is attached to each of these signals. the signals are described in table 24-4 . the comparator need not be used for pure connectivity testing, since all analog inputs are shared with a digital port pin as well. table 24-3. scan signals for the oscillators (1)(2)(3) enable signal scanned clock line clock option scanned clock line when not used extclken extclk (xtal1) external clock 0 oscon oscck external crystal external ceramic resonator 0 rcoscen rcck external rc 1 osc32en osc32ck low freq. external crystal 0 toskon tosck 32khz timer oscillator 0 0 1 dq from previous cell clockdr shiftdr to next cell to system logic ff1 0 1 dq dq g 0 1 from previous cell clockdr updatedr shiftdr to next cell extest from digital logic xtal1/tosc1 xtal2/tosc2 oscillator enable output 264 8151h?avr?02/11 atmega128a figure 24-11. analog comparator figure 24-12. general boundary-scan cell used for signals for comparator and adc table 24-4. boundary-scan signals for the analog comparator signal name direction as seen from the comparator description recommended input when not in use output values when recommended inputs are used ac_idle input turns off analog comparator when true 1 depends upon c code being executed acbg bandgap reference adc multiplexer output acme ac_idle aco adcen 0 1 dq dq g 0 1 from previous cell clockdr updatedr shiftdr to next cell extest to analog circuitry/ to digital logic from digital logic/ from analog ciruitry 265 8151h?avr?02/11 atmega128a 24.13.6 scanning the adc figure 24-13 shows a block diagram of the adc with all relevant control and observe signals. the boundary-scan cell from figure 24-8 is attached to each of these signals. the adc need not be used for pure connectivity testing, since all analog inputs are shared with a digital port pin as well. figure 24-13. analog to digital converter the signals are described briefly in table 24-5 . aco output analog comparator output will become input to c code being executed 0 acme input uses output signal from adc mux when true 0 depends upon c code being executed acbg input bandgap reference enable 0 depends upon c code being executed table 24-4. boundary-scan signals for the analog comparator signal name direction as seen from the comparator description recommended input when not in use output values when recommended inputs are used 10-bit dac + - aref prech dacout comp muxen_7 adc_7 muxen_6 adc_6 muxen_5 adc_5 muxen_4 adc_4 muxen_3 adc_3 muxen_2 adc_2 muxen_1 adc_1 muxen_0 adc_0 negsel_2 adc_2 negsel_1 adc_1 negsel_0 adc_0 extch + - + - 10x 20x g10 g20 st aclk ampen 2.56v ref irefen aref vccren dac_9..0 adcen hold prech gnden passen acten comp sctest adcbgen to comparator 1.22v ref aref 266 8151h?avr?02/11 atmega128a table 24-5. boundary-scan signals for the adc signal name direction as seen from the adc description recommen- ded input when not in use output values when recommended inputs are used, and cpu is not using the adc comp output comparator output 0 0 aclk input clock signal to gain stages implemented as switch-cap filters 00 acten input enable path from gain stages to the comparator 00 adcbgen input enable band-gap reference as negative input to comparator 00 adcen input power-on signal to the adc 00 ampen input power-on signal to the gain stages 00 dac_9 input bit 9 of digital value to dac 11 dac_8 input bit 8 of digital value to dac 00 dac_7 input bit 7 of digital value to dac 00 dac_6 input bit 6 of digital value to dac 00 dac_5 input bit 5 of digital value to dac 00 dac_4 input bit 4 of digital value to dac 00 dac_3 input bit 3 of digital value to dac 00 dac_2 input bit 2 of digital value to dac 00 dac_1 input bit 1 of digital value to dac 00 dac_0 input bit 0 of digital value to dac 00 extch input connect adc channels 0 - 3 to by-pass path around gain stages 11 g10 input enable 10x gain 0 0 g20 input enable 20x gain 0 0 gnden input ground the negative input to comparator when true 00 267 8151h?avr?02/11 atmega128a hold input sample & hold signal. sample analog signal when low. hold signal when high. if gain stages are used, this signal must go active when aclk is high. 11 irefen input enables band-gap reference as aref signal to dac 00 muxen_7 input input mux bit 7 0 0 muxen_6 input input mux bit 6 0 0 muxen_5 input input mux bit 5 0 0 muxen_4 input input mux bit 4 0 0 muxen_3 input input mux bit 3 0 0 muxen_2 input input mux bit 2 0 0 muxen_1 input input mux bit 1 0 0 muxen_0 input input mux bit 0 1 1 negsel_2 input input mux for negative input for differential signal, bit 2 00 negsel_1 input input mux for negative input for differential signal, bit 1 00 negsel_0 input input mux for negative input for differential signal, bit 0 00 passen input enable pa ss-gate of gain stages. 11 prech input precharge output latch of comparator. (active low) 11 sctest input switch-cap test enable. output from x10 gain stage send out to port pin having adc_4 00 st input output of gain stages will settle faster if this signal is high first two aclk periods after ampen goes high. 00 vccren input selects vcc as the acc reference voltage. 00 table 24-5. boundary-scan signals for the adc (continued) signal name direction as seen from the adc description recommen- ded input when not in use output values when recommended inputs are used, and cpu is not using the adc 268 8151h?avr?02/11 atmega128a note: incorrect setting of the switches in figure 24-13 will make signal contention and may damage the part. there are several input choices to the s&h ci rcuitry on the negative i nput of the output com- parator in figure 24-13 . make sure only one path is selected from either one adc pin, bandgap reference source, or ground. if the adc is not to be used during scan, the recommended input values from table 24-5 should be used. the user is recommended not to use the differential gain stages during scan. switch- cap based gain stages require fast operation and accurate timing which is difficult to obtain when used in a scan chain. details concerning operations of the differential gain stage is there- fore not provided. the avr adc is based on the analog circuitry shown in figure 24-13 with a successive approx- imation algorithm implemented in the digital logic. when used in boundary-scan, the problem is usually to ensure that an applied analog voltag e is measured within some limits. this can easily be done without running a successive approximation algorithm: apply the lower limit on the digi- tal dac[9:0] lines, make sure the output from the comparator is low, then apply the upper limit on the digital dac[9:0] lines, and verify the output from the comparator to be high. the adc need not be used for pure connectivity te sting, since all analog inputs are shared with a digital port pin as well. when using the adc, remember the following ? the port pin for the adc channel in use must be configured to be an input with pull-up disabled to avoid signal contention. ? in normal mode, a dummy conversion (consisting of 10 comparisons) is performed when enabling the adc. the user is advised to wait at least 200ns after enabling the adc before controlling/observing any adc signa l, or perform a dummy conver sion before using the first result. ? the dac values must be stable at the midp oint value 0x200 when having the hold signal low (sample mode). as an example, consider the task of verifying a 1.5v 5% input signal at adc channel 3 when the power supply is 5.0v and aref is externally connected to v cc . the recommended values from table 24-5 are used unless other values are given in the algo- rithm in table 24-6 . only the dac and port pin values of the scan chain are shown. the column ?actions? describes what jtag instruct ion to be used before filling the boundary-scan register with the succeeding columns. the verification should be done on the data scanned out when scanning in the data on the same row in the table. table 24-6. algorithm for using the adc step actions adcen dac muxen hold prech pa3. data pa3. control pa 3 . pullup_ enable 1 sample_p reload 1 0x200 0x08 1 1 0 0 0 2 extest 1 0x200 0x08 0 1 0 0 0 3 1 0x200 0x08 1 1 0 0 0 4 1 0x123 0x08 1 1 0 0 0 5 1 0x123 0x08 1 0 0 0 0 the lower limit is: 1024 1.5 v 0,95 5 v ? ?? 291 0x123 == the upper limit is: 1024 1.5 v 1.05 5 v ? ?? 323 0x143 == 269 8151h?avr?02/11 atmega128a using this algorithm, the timing constraint on the hold signal constrains the tck clock fre- quency. as the algorithm keeps hold high for fi ve steps, the tck clock frequency has to be at least five times the number of scan bits divided by the maximum hold time, t hold,max 24.14 atmega128a boundary-scan order table 24-7 shows the scan order between tdi and tdo when the boundary-scan chain is selected as data path. bit 0 is the lsb; the first bit scanned in, and the first bit scanned out. the scan order follows the pin-out order as far as possible. therefore, the bits of port a is scanned in the opposite bit order of the other ports. exceptions from the rules are the scan chains for the analog circuits, which constitute the most significant bits of the scan chain regardless of which physical pin they are connected to. in figure 24-5 , pxn. data corresponds to ff0, pxn. control corresponds to ff1, and pxn. pullup_enable corresponds to ff2. bit 2, 3, 4, and 5 of port c is not in the scan chain, since these pins consti tute the tap pins when the jtag is enabled. 6 verify the comp bit scanned out to be 0 1 0x200 0x08 1 1 0 0 0 7 1 0x200 0x08 0 1 0 0 0 8 1 0x200 0x08 1 1 0 0 0 9 1 0x143 0x08 1 1 0 0 0 10 1 0x143 0x08 1 0 0 0 0 11 verify the comp bit scanned out to be 1 1 0x200 0x08 1 1 0 0 0 table 24-6. algorithm for using the adc step actions adcen dac muxen hold prech pa3. data pa3. control pa 3 . pullup_ enable table 24-7. atmega128a boundary-scan order bit number sign al name module 204 ac_idle comparator 203 aco 202 acme 201 ainbg 270 8151h?avr?02/11 atmega128a 200 comp adc 199 private_signal1 (1) 198 aclk 197 acten 196 private_signal1 (2) 195 adcbgen 194 adcen 193 ampen 192 dac_9 191 dac_8 190 dac_7 189 dac_6 188 dac_5 187 dac_4 186 dac_3 185 dac_2 184 dac_1 183 dac_0 182 extch 181 g10 180 g20 179 gnden 178 hold 177 irefen 176 muxen_7 table 24-7. atmega128a boundary-scan order (continued) bit number sign al name module 271 8151h?avr?02/11 atmega128a 175 muxen_6 adc 174 muxen_5 173 muxen_4 172 muxen_3 171 muxen_2 170 muxen_1 169 muxen_0 168 negsel_2 167 negsel_1 166 negsel_0 165 passen 164 prech 163 sctest 162 st 161 vccren 160 pen programming enable (observe only) 159 pe0.data port e 158 pe0.control 157 pe0.pullup_enable 156 pe1.data 155 pe1.control 154 pe1.pullup_enable 153 pe2.data 152 pe2.control 151 pe2.pullup_enable 150 pe3.data 149 pe3.control 148 pe3.pullup_enable 147 pe4.data 146 pe4.control 145 pe4.pullup_enable 144 pe5.data 143 pe5.control 142 pe5.pullup_enable 141 pe6.data 140 pe6.control table 24-7. atmega128a boundary-scan order (continued) bit number sign al name module 272 8151h?avr?02/11 atmega128a 139 pe6.pullup_enable port e 138 pe7.data 137 pe7.control 136 pe7.pullup_enable 135 pb0.data port b 134 pb0.control 133 pb0.pullup_enable 132 pb1.data 131 pb1.control 130 pb1.pullup_enable 129 pb2.data 128 pb2.control 127 pb2.pullup_enable 126 pb3.data 125 pb3.control 124 pb3.pullup_enable 123 pb4.data 122 pb4.control 121 pb4.pullup_enable 120 pb5.data 119 pb5.control 118 pb5.pullup_enable 117 pb6.data 116 pb6.control 115 pb6.pullup_enable 114 pb7.data 113 pb7.control 112 pb7.pullup_enable 111 pg3.data port g 110 pg3.control 109 pg3.pullup_enable 108 pg4.data 107 pg4.control 106 pg4.pullup_enable 105 tosc 32khz timer oscillator 104 toscon table 24-7. atmega128a boundary-scan order (continued) bit number sign al name module 273 8151h?avr?02/11 atmega128a 103 rstt reset logic (observe-only) 102 rsthv 101 extclken enable signals for main clock/oscillators 100 oscon 99 rcoscen 98 osc32en 97 extclk (xtal1) clock input and oscillators for the main clock (observe-only) 96 oscck 95 rcck 94 osc32ck 93 twien twi 92 pd0.data port d 91 pd0.control 90 pd0.pullup_enable 89 pd1.data 88 pd1.control 87 pd1.pullup_enable 86 pd2.data 85 pd2.control 84 pd2.pullup_enable 83 pd3.data 82 pd3.control 81 pd3.pullup_enable 80 pd4.data 79 pd4.control 78 pd4.pullup_enable 77 pd5.data 76 pd5.control 75 pd5.pullup_enable 74 pd6.data 73 pd6.control 72 pd6.pullup_enable 71 pd7.data 70 pd7.control 69 pd7.pullup_enable 68 pg0.data port g table 24-7. atmega128a boundary-scan order (continued) bit number sign al name module 274 8151h?avr?02/11 atmega128a 67 pg0.control port g 66 pg0.pullup_enable 65 pg1.data 64 pg1.control 63 pg1.pullup_enable 62 pc0.data port c 61 pc0.control 60 pc0.pullup_enable 59 pc1.data 58 pc1.control 57 pc1.pullup_enable 56 pc2.data 55 pc2.control 54 pc2.pullup_enable 53 pc3.data 52 pc3.control 51 pc3.pullup_enable 50 pc4.data 49 pc4.control 48 pc4.pullup_enable 47 pc5.data 46 pc5.control 45 pc5.pullup_enable 44 pc6.data 43 pc6.control 42 pc6.pullup_enable 41 pc7.data 40 pc7.control 39 pc7.pullup_enable 38 pg2.data port g 37 pg2.control 36 pg2.pullup_enable 35 pa7.data port a 34 pa7.control 33 pa7.pullup_enable 32 pa6.data table 24-7. atmega128a boundary-scan order (continued) bit number sign al name module 275 8151h?avr?02/11 atmega128a notes: 1. private_signal1 should always scanned in as zero. 2. private_signal2 should always scanned in as zero. 31 pa6.control port a 30 pa6.pullup_enable 29 pa5.data 28 pa5.control 27 pa5.pullup_enable 26 pa4.data 25 pa4.control 24 pa4.pullup_enable 23 pa3.data 22 pa3.control 21 pa3.pullup_enable 20 pa2.data 19 pa2.control 18 pa2.pullup_enable 17 pa1.data 16 pa1.control 15 pa1.pullup_enable 14 pa0.data 13 pa0.control 12 pa0.pullup_enable 11 pf3.data port f 10 pf3.control 9 pf3.pullup_enable 8pf2.data 7 pf2.control 6 pf2.pullup_enable 5pf1.data 4 pf1.control 3 pf1.pullup_enable 2pf0.data 1 pf0.control 0 pf0.pullup_enable table 24-7. atmega128a boundary-scan order (continued) bit number sign al name module 276 8151h?avr?02/11 atmega128a 24.15 boundary-scan description language files boundary-scan description language (bsdl) files describe boundary-scan capable devices in a standard format used by automated test-generation software. the order and function of bits in the boundary-scan data register are included in this description. 24.16 register description 24.16.1 ocdr - on-chip debug register the ocdr register provides a co mmunication channel from the running pr ogram in the micro- controller to the debugger. the cpu can transfer a byte to the debugger by writing to this location. at the same time, an in ternal flag; i/o debug register dirty ? idrd ? is set to indicate to the debugger that the register has been written. when the cpu reads the ocdr register the 7 lsb will be from the ocdr regi ster, while the msb is the idrd bit. the debugger clears the idrd bit when it has read the information. in some avr devices, this register is shared with a standard i/o location. in this case, the ocdr register can only be accessed if the ocden fuse is programmed, and the debugger enables access to the ocdr register. in all other cases, the standard i/o location is accessed. refer to the debugger documentation for further information on how to use this register. 24.16.2 mcucsr - mcu cont rol and status register the mcu control and status register contains control bits for general mcu functions, and pro- vides information on which reset source caused an mcu reset. ? bit 7 ? jtd: jtag interface disable when this bit is zero, the jtag interface is enab led if the jtagen fuse is programmed. if this bit is one, the jtag interface is disabled. in order to avoid unintentional disabling or enabling of the jtag interface, a timed sequence must be followed when changing this bit: the application soft- ware must write this bit to the desired value twice within four cycles to change its value. if the jtag interface is left unconnected to ot her jtag circuitry, the jtd bit should be set to one. the reason for this is to avoid static current at the tdo pin in the jtag interface. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. bit 7 6543210 msb/idrd lsb ocdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0000000 bit 76543210 jtd ? ?jtrf wdrf borf extrf porf mcucsr read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description 277 8151h?avr?02/11 atmega128a 25. boot loader support ? read -while-write self-programming 25.1 features ? read-while-write self-programming ? flexible boot memory size ? high security (separate boot lock bits for a flexible protection) ? separate fuse to select reset vector ? optimized page (1) size ? code efficient algorithm ? efficient read-modify-write support note: 1. a page is a section in the flash consisting of several bytes (see table 26-10 on page 296 ) used during programming. the page organization does not affect normal operation. 25.2 overview the boot loader support provides a real read- while-write self-programming mechanism for downloading and uploading program code by the m cu itself. this feature a llows flexible applica- tion software updates controlled by the mcu using a flash-resident boot loader program. the boot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory, or read the code from the program mem- ory. the program code within the boot loader section has the capability to write into the entire flash, including the boot loader memory. the b oot loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. the size of the boot loader memory is configurable with fuses and t he boot loader has two separate sets of boot lock bits which can be set indepen dently. this gives the user a uniq ue flexibility to select differ- ent levels of protection. 25.3 application and boot loader flash sections the flash memory is organized in two main sections, the application section and the boot loader section (see figure 25-2 ). the size of the different sections is configured by the bootsz fuses as shown in table on page 288 and figure 25-2 . these two sections can have different level of protection since they have different sets of lock bits. 25.3.1 application section the application section is the section of the flash that is used for storing the application code. the protection level for the application section ca n be selected by the application boot lock bits (boot lock bits 0), see table on page 280 . the application section can never store any boot loader code since the spm instruction is dis abled when executed from the application section. 25.3.2 boot loader section ? bls while the application section is used for storing the application code, the the boot loader soft- ware must be located in the bls since the spm instruction can initiate a programming when executing from the bls only. the spm instruct ion can access the entire flash, including the bls itself. the protection level for the boot loader section can be selected by the boot loader lock bits (boot lock bits 1), see table 25-3 on page 281 . 278 8151h?avr?02/11 atmega128a 25.4 read-while-write and no r ead-while-write flash sections whether the cpu supports read-while-write or if the cpu is halted during a boot loader soft- ware update is dependent on which address that is being programmed. in addition to the two sections that are configurable by the bootsz fuses as described above, the flash is also divided into two fixed sections, the read-whi le-write (rww) section and the no read-while- write (nrww) section. the limit between the rww- and nrww sections is given in table note: on page 288 and figure 25-2 on page 280 . the main difference between the two sections is: ? when erasing or writing a page located inside the rww section, the nrww section can be read during the operation. ? when erasing or writing a page located inside the nrww section, the cpu is halted during the entire operation. note that the user software can never read any code that is located inside the rww section dur- ing a boot loader software operation. the syntax ?read-while-write section? refers to which section that is being programmed (erased or written), not which section that actually is being read during a boot loader software update. 25.4.1 read-while-write section ? rww if a boot loader software update is programming a page inside the rww section, it is possible to read code from the flash, but only code that is located in the nrww section. during an on- going programming, the software must ensure that the rww section never is being read. if the user software is trying to read code that is located inside the rww section (that is, by a call/jmp/lpm or an interrupt) during programming, the software might end up in an unknown state. to avoid this, the interrupts should either be disabled or moved to the boot loader sec- tion. the boot loader section is always located in the nrww section. the rww section busy bit (rwwsb) in the store program memory cont rol and status register (spmcsr) will be read as logical one as long as the rww section is blocked for reading. after a programming is com- pleted, the rwwsb must be cleared by software before reading code located in the rww section. see ?spmcsr - store program memory control and status register? on page 289. for details on how to clear rwwsb. 25.4.2 no read-while-write section ? nrww the code located in the nrww section can be read when the boot loader software is updating a page in the rww section. when the boot loader code updates the nrww section, the cpu is halted during the entire page erase or page write operation. table 25-1. read-while-write features which section does the z- pointer address during the programming? which section can be read during programming? is the cpu halted? read-while- write supported? rww section nrww section no yes nrww section none yes no 279 8151h?avr?02/11 atmega128a figure 25-1. read-while-write vs. no read-while-write read-while-write (rww) section no read-while-write (nrww) section z-pointer addresses rww section z-pointer addresses nrww section cpu is halted during the operation code located in nrww section can be read during the operation 280 8151h?avr?02/11 atmega128a figure 25-2. memory sections (1) note: 1. the parameters in the figure above are given in table on page 288 . 25.5 boot loader lock bits if no boot loader capability is n eeded, the entire flash is available for application code. the boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique flexibility to sele ct different levels of protection. ? the user can select: ? to protect the entire flash from a software update by the mcu ? to protect only the boot loader flash section from a software update by the mcu ? to protect only the application flash section from a software update by the mcu ? allow software update in the entire flash see table 25-2 and table 25-3 for further details. the boot lock bits can be set in software and in serial or parallel programming mode, but they can be cleared by a chip erase command only. the general write lock (lock bit mode 2) does not control the programming of the flash mem- ory by spm instruction. similarly, the general read/write lock (lock bit mode 3) does not control reading nor writing by lpm/spm, if it is attempted. $0000 flashend program memory bootsz = '11' application flash section boot loader flash section flashend program memory bootsz = '10' $0000 program memory bootsz = '01' program memory bootsz = '00' application flash section boot loader flash section $0000 flashend application flash section flashend end rww start nrww application flash section boot loader flash section boot loader flash section end rww start nrww end rww start nrww $0000 end rww, end application start nrww, start boot loader application flash section application flash section application flash section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section end application start boot loader end application start boot loader end application start boot loader 281 8151h?avr?02/11 atmega128a note: 1. ?1? means unprogrammed, ?0? means programmed note: 1. ?1? means unprogrammed, ?0means programmed 25.6 entering the b oot loader program entering the boot loader takes place by a jump or call from the application program. this may be initiated by a trigger such as a command received via usart, or spi interface. alternatively, the boot reset fuse can be programmed so that the reset vector reset is pointing to the boot flash start address after a reset. in this case, the boot loader is started after a reset. after the application code is loaded, the program can start executing the application code. note that the fuses cannot be changed by the mcu itself. this means that once the boot reset fuse is pro- grammed, the reset vector will always point to the boot loader reset and the fuse can only be changed through the serial or parallel programming interface. table 25-2. boot lock bit0 protection modes (application section) (1) blb0 mode blb02 blb01 protection 111 no restrictions for spm or lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 lpm executing from the boot l oader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. table 25-3. boot lock bit1 protection modes (boot loader section) (1) blb1 mode blb12 blb11 protection 111 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interr upts are disabled while executing from the boot loader section. 401 lpm executing from the application section is not allowed to read from the boot loader se ction. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 25-4. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address $0000) 0 reset vector = boot loader reset (see table 25-6 on page 288 ) 282 8151h?avr?02/11 atmega128a note: 1. ?1? means unprogrammed, ?0means programmed 25.7 addressing the flash during self-programming the z-pointer together with rampz are used to address the spm commands. for details on how to use the rampz, see ?rampz - ram page z select register? on page 14. since the flash is organized in pages (see table 26-10 on page 296 ), the program counter can be treated as having two different sections. one sect ion, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 25-3 . note that the page erase and page write operations are addressed independently. therefore it is of major importance that the boot loader software addresses the same page in both the page erase and page write operation. once a programming operation is initiated, the address is latched and the z-pointer/rampz can be used for other operations. the only spm operation that does not use the z-pointer/rampz is setting the boot loader lock bits. the content of the z-pointer/rampz is i gnored and will have no ef fect on the operation. the (e)lpm instruction does also use the z-pointer/rampz to store the address. since this instruction addresses the flash byte by byte, also the lsb (bit z0) of the z-pointer is used. figure 25-3. addressing the flash during spm (1) notes: 1. the different variables used in figure 25-3 are listed in table 25-8 on page 288 . 2. pcpage and pcword are listed in table 26-11 on page 296 . bit 151413121110 9 8 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30) z7z6z5z4z3z2z1z0 76543210 program memory 0 1 15 z - register bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter rampz 283 8151h?avr?02/11 atmega128a 25.8 self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buf- fer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page write operation: alternative 1, fill the buff er before a page erase ? fill temporary page buffer ? perform a page erase ? perform a page write alternative 2, fill the bu ffer after page erase ? perform a page erase ? fill temporary page buffer ? perform a page write if only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. when using alternative 1, the boot loader provides an effective read-modify-write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alter- native 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. see ?simple assembly code example for a boot loader? on page 286 for an assembly code example. 25.8.1 performing page erase by spm to execute page erase, set up the address in the z-pointer and rampz, write ?x0000011? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer must be written zero during this operation. ? page erase to the rww section: the nrww section can be read during the page erase. ? page erase to the nrww section: the cpu is halted during the operation. note: if an interrupt occurs in the timed sequence t he four cycle access cannot be guaranteed. in order to ensure atomic operation disable interrupts before writing to spmcsr. 25.8.2 filling the temporary buffer (page loading) to write an instruction word, set up the address in the z-pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the content of pcword in the z-register is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page writ e operation or by writ ing the rwwsre bit in spmcsr. it is also erased after a system reset. note that it is not possible to write more than one time to each address without erasing the temporary buffer. note: if the eeprom is written in the middle of an spm page load operation, all data loaded will be lost. 284 8151h?avr?02/11 atmega128a 25.8.3 performing a page write to execute page write, set up the address in the z-pointer and rampz, write ?x0000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z-pointer must be written zero during this operation. ? page write to the rww section: the nrww section can be read during the page write. ? page write to the nrww section: the cpu is halted during the operation. 25.8.4 using the spm interrupt if the spm interrupt is en abled, the spm interrupt will genera te a constant in terrupt when the spmen bit in spmcsr is cleared. this means th at the interrupt can be used instead of polling the spmcsr register in software. when using the spm interrupt, the interrupt vectors should be moved to the bls section to avoid that an interrupt is accessing the rww section when it is blocked for reading. how to move the interrupts is described in ?interrupts? on page 59 . 25.8.5 consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit11 unprogrammed. an accidental write to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itself, it is recommended to program the boot lock bit11 to protect the boot loader software from any internal software changes. 25.8.6 prevent reading the rww section during self-programming during self-programming (either page erase or page write), the rww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self- programming operation. the rwws b in the spmcsr will be set as long as the rww section is busy. during self-programming the interrupt vector table should be moved to the bls as described in ?interrupts? on page 59 , or the interrupts must be disabled. before addressing the rww section after the programming is completed, the user software must clear the rwwsb by writing the rwwsre. see ?simple assembly code example for a boot loader? on page 286 for an example. 25.8.7 setting the boot loader lock bits by spm to set the boot loader lock bits, write the desired data to r0, write ?x0001001? to spmcsr and execute spm within four clock cycles afte r writing spmcsr. the only accessible lock bits are the boot lock bits that may prevent the a pplication and boot loader section from any soft- ware update by the mcu. see table 25-2 and table 25-3 for how the different settings of the boot loader bits affect the flash access. if bits 5:2 in r0 are cleared (zero), the corre sponding boot lock bit will be programmed if an spm instruction is executed within four cycles after blbset and spmen are set in spmcsr. the z-pointer is don?t ca re during this operation, but for fu ture compatibility it is recommended to load the z-pointer with $0001 (sam e as used for reading the lock bits). for future compatibility it is also recommended to set bits 7, 6, 1, and 0 in r0 to ?1? when writing the lock-bits. when pro- gramming the lock bits the entire flash can be read during the operation. bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 1 1 285 8151h?avr?02/11 atmega128a 25.8.8 eeprom write prevents writing to spmcsr note that an eeprom write oper ation will block all software progra mming to flash. reading the fuses and lock bits from software will also be prevented during the eeprom write operation. it is recommended that the user checks the status bit (eewe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. 25.8.9 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with $0001 and set th e blbset and spmen bits in spm csr. when an lpm instruc- tion is executed within three cpu cycles after the blbset and spmen bits are set in spmcsr, the value of the lock bits will be loaded in the destination register. the blbset and spmen bits will auto-clear upon completion of reading the lo ck bits or if no lpm instruction is executed within three cpu cycles or no spm instruction is executed within four cpu cycles. when blb- set and spmen are cleared, lpm will work as described in the instruction set manual. the algorithm for reading the fuse low bits is similar to the one described above for reading the lock bits. to read the fuse lo w bits, load the z-pointer with $0000 and set the blbset and spmen bits in spmcsr. when an lpm instruction is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse low bits (flb) will be loaded in the destination register as shown below. refer to table 26-5 on page 293 for a detailed description and mapping of the fuse low bits. similarly, when reading the fuse high bits, l oad $0003 in the z-pointer. when an lpm instruc- tion is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse high bits (fhb) will be lo aded in the destination r egister as shown below. refer to table 26-4 on page 292 for detailed description and mapping of the fuse high bits. when reading the extended fuse bits, load $0002 in the z-pointer. when an lpm instruction is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the extended fu se bits (efb) will be loaded in the destination register as shown below. refer to table 26-3 on page 292 for detailed description and mapping of the fuse high bits. fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. 25.8.10 preventing flash corruption during periods of low v cc, the flash program can be corrupted because the supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situ ations when the voltage is too low. first, a regular write sequence to the flash requires a minimum voltage to operate correctly. secondly, bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0 bit 76543210 rd ? ? ? ? ? ? efb1 efb0 286 8151h?avr?02/11 atmega128a the cpu itself can execute instruct ions incorrectly, if the supply voltage for executing instructions is too low. flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. if there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. keep the avr reset active (low) during peri ods of insufficient po wer supply voltage. this can be done by enabling the internal brown-out detector (bod) if the operating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 3. keep the avr core in power-down sleep mode during periods of low v cc . this will pre- vent the cpu from attempting to decode and execute instructions, effectively protecting the spmcsr register and thus the flash from unintentional writes. 25.8.11 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 25-5 shows the typical pro- gramming time for flash accesses from the cpu. 25.8.12 simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcsrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2 ;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcsrval, (1< 289 8151h?avr?02/11 atmega128a notes: 1. the z-register is only 16 bits wide. bit 16 is located in the rampz register in the i/o map. 2. z0: should be zero for all spm commands, byte select for the (e)lpm instruction. 3. see ?addressing the flash during self-programming? on page 282 for details about the use of z-pointer during self-programming. 25.9 register description 25.9.1 spmcsr - store program memory control and status register the store program memory control and status register contains the control bits needed to con- trol the boot loader operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bit in the status register is set (one), the spm ready interrupt will be enabled. the spm ready in terrupt will be ex ecuted as long as the spmen bit in the spmcsr register is cleared. ? bit 6 ? rwwsb: read-while-write section busy when a self-programming (page erase or page write) operation to the rww section is initiated, the rwwsb will be set (one) by hardware. when the rwwsb bit is set, the rww section can- not be accessed. the rwwsb bit will be cleared if the rwwsre bit is written to one after a self-programming operation is completed. alternatively the rwwsb bit will automatically be cleared if a page load operation is initiated. ? bit 5 ? res: reserved bit this bit is a reserved bit in the atmega128a and always read as zero. pag e m s b 6 most significant bit which is used to address the words within one page (128 words in a page requires 7 bits pc [6:0]). zpcmsb z16 (1) bit in z-register that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z7 bit in z-register that is mapped to pagemsb. because z0 is not used, the zpagemsb equals pag e m s b + 1 . pcpage pc[15:7] z16 (1) :z8 program counter page address: page select, for page erase and page write pcword pc[6:0] z7:z1 program counter word address: word select, for filling temporary buffer (must be zero during page write operation) table 25-8. explanation of different variables used in figure 25-3 and the mapping to the z- pointer (3) variable corresponding z-value description (2) bit 7 6 5 4 3 2 1 0 spmie rwwsb ? rwwsre blbset pgwrt pgers spmen spmcsr read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 290 8151h?avr?02/11 atmega128a ? bit 4 ? rwwsre: read-while-write section read enable when programming (page erase or page write) to the rww section, the rww section is blocked for reading (the rwwsb will be set by hardware). to re-enable the rww section, the user software must wait unt il the programming is complet ed (spmen will be cl eared). then, if the rwwsre bit is written to one at the same time as spmen, the next spm instruction within four clock cycles re-enables the rww secti on. the rww section cannot be re-enabled while the flash is busy with a page erase or a page writ e (spmen is set). if the rwwsre bit is writ- ten while the flash is being loaded, the flas h load operation will abort and the data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles sets boot lock bits, according to the data in r0. the data in r1 and the address in the z- pointer are ignored. the blbset bit will automatically be clear ed upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an lpm instruction within three cycles after blbset and spmen are set in the spmcsr reg- ister, will read either the lock bits or the fuse bits (depending on z0 in the z-pointer) into the destination register. see ?reading the fuse and lock bits from software? on page 285 for details. ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page write, with the data stored in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-clear upon completion of a page write, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 ar e ignored. the pgers bi t will auto-clear upon comp letion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 0 ? spmen: store program memory enable this bit enables the spm instruction for the next four clock cycles. if written to one together with either rwwsre, blbset, pgwrt? or pgers, t he following spm instruction will have a spe- cial meaning, see description abo ve. if only spmen is written, the following spm instruction will store the value in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the spmen bit will aut o-clear upon completion of an spm instruction, or if no spm instruction is executed within four clock cycles. during page erase and page write, the spmen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?00011? or ?00001? in the lower five bits will have no effect. 291 8151h?avr?02/11 atmega128a 26. memory programming 26.1 program and data memory lock bits the atmega128a provides six lock bits which can be left unprogrammed (?1?) or can be pro- grammed (?0?) to obtain the additional features listed in table 26-2 . the lock bits can only be erased to ?1? with the chip erase command. note: ?1? means unprogrammed, ?0means programmed table 26-1. lock bit byte lock bit byte bit no. description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) blb12 5 boot lock bit 1 (unprogrammed) blb11 4 boot lock bit 1 (unprogrammed) blb02 3 boot lock bit 1 (unprogrammed) blb01 2 boot lock bit 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) table 26-2. lock bit protection modes memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flas h and eeprom is disabled in parallel and spi/jtag serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parallel and spi/jtag serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) blb0 mode blb02 blb01 111 no restrictions for spm or (e)lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 292 8151h?avr?02/11 atmega128a notes: 1. program the fuse bits before programming the lock bits. 2. ?1? means unprogrammed, ?0means programmed 26.2 fuse bits the atmega128a has three fuse bytes. table 26-3 - table 26-5 describe briefly the functionality of all the fuses and how they are mapped into the fuse bytes. note that the fuses are read as logical zero, ?0?, if they are programmed. notes: 1. see ?atmega103 and atmega128a compatibility? on page 4 for details. 2. see ?wdtcr - watchdog timer control register? on page 57 for details. blb1 mode blb12 blb11 111 no restrictions for spm or (e)lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from the applic ation section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application sectio n, interrupts are disabled while executing from the boot loader section. 401 (e)lpm executing from the applic ation section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application sectio n, interrupts are disabled while executing from the boot loader section. table 26-2. lock bit protection modes (continued) memory lock bits protection type table 26-3. extended fuse byte extended fuse byte bit no . description default value ?7? 1 ?6? 1 ?5? 1 ?4? 1 ?3? 1 ?2? 1 m103c (1) 1 atmega103 compatibility mode 0 (programmed) wdton (2) 0 watchdog timer always on 1 (unprogrammed) table 26-4. fuse high byte fuse high byte bit no. description default value ocden (4) 7 enable ocd 1 (unprogrammed, ocd disabled) jtagen (5) 6 enable jtag 0 (programmed, jtag enabled) spien (1) 5 enable serial program and data downloading 0 (programmed, spi prog. enabled) ckopt (2) 4 oscillator options 1 (unprogrammed) 293 8151h?avr?02/11 atmega128a notes: 1. the spien fuse is not accessi ble in spi serial programming mode. 2. the ckopt fuse functionality depends on the setting of the cksel bits. see ?clock sources? on page 39 for details. 3. the default value of bootsz1:0 results in maximum boot size. see table 25-6 on page 288 4. never ship a product with the ocden fuse progra mmed regardless of the setting of lock bits and the jtagen fuse. a programmed ocden fuse enables some parts of the clock system to be running in all sleep modes. this may increase the power consumption. 5. if the jtag interface is left unconnected, the jt agen fuse should if possible be disabled. this to avoid static current at the tdo pin in the jtag interface. notes: 1. the default value of sut1:0 results in maximum start-up time. see table 8-9 on page 43 for details. 2. the default setting of cksel3:0 result s in internal rc oscillator @ 1mhz. see table 8-1 on page 39 for details. the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. 26.2.1 latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuses are also latched on power-up in normal mode. eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) bootsz1 2 select boot size (see table 25-6 for details) 0 (programmed) (3) bootsz0 1 select boot size (see table 25-6 for details) 0 (programmed) (3) bootrst 0 select reset vector 1 (unprogrammed) table 26-5. fuse low byte fuse low byte bit no. description default value bodlevel 7 brown out detector trigger level 1 (unprogrammed) boden 6 brown out detector enable 1 (unprogrammed, bod disabled) sut1 5 select start-up time 1 (unprogrammed) (1) sut0 4 select start-up time 0 (programmed) (1) cksel3 3 select clock source 0 (programmed) (2) cksel2 2 select clock source 0 (programmed) (2) cksel1 1 select clock source 0 (programmed) (2) cksel0 0 select clock source 1 (unprogrammed) (2) table 26-4. fuse high byte fuse high byte bit no. description default value 294 8151h?avr?02/11 atmega128a 26.3 signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the atmega128a the signature bytes are in table 26-6 . 26.4 calibration byte the atmega128a stores four different calibration values for the internal rc oscillator. these bytes resides in the signature row high byte of the addresses 0x000, 0x0001, 0x0002, and 0x0003 for 1mhz, 2mhz, 4mhz, and 8mhz respecti vely. during reset, th e 1mhz value is auto- matically loaded into the osccal register. if other frequencies are used, the calibration value has to be loaded manua lly, see ?osccal - oscillator cali bration register? on page 44 for details. 26.5 parallel programming paramete rs, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lock bits, and fuse bits in the atmega128a. pulses are assumed to be at least 250 ns unless otherwise noted. 26.5.1 signal names in this section, some pins of the atmega128a are referenced by signal names describing their functionality during parallel programming, see figure 26-1 and table 26-7 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a positive pulse. the bit coding is shown in table 26-9 . when pulsing wr or oe , the command loaded determines the action executed. the different commands are shown in table 26-10 . table 26-6. device and jtag id part signature bytes address jtag 0x000 0x001 0x002 part number manufacture id atmega128a 0x1e 0x97 0x02 9702 0x1f 295 8151h?avr?02/11 atmega128a figure 26-1. parallel programming table 26-7. pin name mapping signal name in programming mode pin name i/o function rdy/bsy pd1 o 0: device is busy programming, 1: device is ready for new command oe pd2 i output enable (active low) wr pd3 i write pulse (active low) bs1 pd4 i byte select 1 (?0? selects low byte, ?1? selects high byte) xa0 pd5 i xtal action bit 0 xa1 pd6 i xtal action bit 1 pagel pd7 i program memory and eeprom data page load bs2 pa 0 i byte select 2 (?0? selects lo w byte, ?1? selects 2?nd high byte) data pb7-0 i/o bi-directional data bus (output when oe is low) table 26-8. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 vcc +5v gnd xtal1 pd1 pd2 pd3 pd4 pd5 pd6 pb7 - pb0 data reset pd7 +12 v bs1 xa0 xa1 oe rdy/bsy pagel pa0 wr bs2 avcc +5v 296 8151h?avr?02/11 atmega128a 26.6 parallel programming 26.6.1 enter programming mode the following algorithm puts the devi ce in parallel programming mode: 1. apply 4.5v - 5.5v between v cc and gnd, and wait at least 100 s. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 26-8 on page 295 to ?0000? and wait at least 100 ns. 4. apply 11.5v - 12.5v to reset . any activity on prog_enable pins within 100 ns after +12v has been applied to reset , will cause the device to fail entering programming mode. table 26-9. xa1 and xa0 coding xa1 xa0 action when xtal1 is pulsed 0 0 load flash or eeprom address (high or low address byte determined by bs1) 0 1 load data (high or low data byte for flash determined by bs1) 1 0 load command 1 1 no action, idle table 26-10. command byte bit coding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom table 26-11. no. of words in a page and no. of pages in the flash flash size page size pcword no. of pages pcpage pcmsb 64k words (128 kbytes) 128 words pc[6:0] 512 pc[15:7] 15 table 26-12. no. of words in a page and no. of pages in the eeprom eeprom size page size pcword no. of pages pcpage eeamsb 4 kbytes 8 bytes eea[2:0] 512 eea[11:3] 8 297 8151h?avr?02/11 atmega128a note, if external crystal or external rc configurat ion is selected, it may not be possible to apply qualified xtal1 pulses. in such cases, the following algorithm should be followed: 1. set prog_enable pins listed in table on page 295 to ?0000?. 2. apply 4.5v - 5.5v between v cc and gnd simultaneously as 11.5v - 12.5v is applied to reset . 3. wait 100 s. 4. re-program the fuses to ensure that external clock is selected as clock source (cksel3:0 = 0b0000) if lock bits are prog rammed, a chip erase command must be executed before changing the fuses. 5. exit programming mode by power th e device down or by bringing reset pin to 0b0. 6. entering programming mode with the original algorithm, as described above. 26.6.2 considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered. ? the command needs only be loaded once when writing or reading multiple memory locations. ? skip writing the data value $ff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) a nd flash after a chip erase. ? address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256-byte eeprom. this consideration also applies to signature bytes reading. 26.6.3 chip erase the chip erase will eras e the flash and eeprom (note:) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are not changed. a chip erase must be performed before the flash and/or the eeprom are reprogrammed. note: the eeprpom memory is preserved during chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give wr a negative pulse. this starts the chip erase. rdy/bsy goes low. 6. wait until rdy/bsy goes high before loading a new command. 26.6.4 programming the flash the flash is organized in pages, see table 26-10 on page 296 . when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be pro- grammed simultaneously. the following procedure describes how to program the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 298 8151h?avr?02/11 atmega128a 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?0?. this selects low address. 3. set data = address low byte ($00 - $ff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte ($00 - $ff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte ($00 - $ff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 26-3 for signal waveforms) f. repeat b through e until the entire buffer is filled or until all data within the page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages within the flash . this is illustrated in figure 26-2 on page 299 . note that if less than 8 bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. g. load address high byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?1?. this selects high address. 3. set data = address high byte ($00 - $ff). 4. give xtal1 a positive pulse. this loads the address high byte. h. program page 1. set bs1 = ?0? 2. give wr a negative pulse. this starts programming of the entire page of data. rdy/bsy goes low. 3. wait until rdy/bsy goes high. (see figure 26-3 for signal waveforms) i. repeat b through h until the entire flash is programmed or until all data has been programmed. j. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write signals are reset. 299 8151h?avr?02/11 atmega128a figure 26-2. addressing the flash which is organized in pages note: 1. pcpage and pcword are listed in table 26-11 on page 296 . figure 26-3. programming the flash waveforms note: 1. ?xx? is don?t care. the letters refer to the programming description above. 26.6.5 programming the eeprom the eeprom is organized in pages, see table 26-11 on page 296 . when programming the eeprom, the program data is latche d into a page buffer. this al lows one page of data to be programmed simultaneously. th e programming algorithm for th e eeprom data memory is as follows (refer to ?programming the flash? on page 297 for details on command, address and data loading): program memory word address within a page page address within the flash instruction word page pcword[pagemsb:0]: 00 01 02 pageend page pcword pcpage pcmsb pagemsb program counter rdy/bsy wr oe reset +12v pagel bs2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 bs1 xtal1 xx xx xx ab cdeb cdegh f 300 8151h?avr?02/11 atmega128a 1. a: load command ?0001 0001?. 2. g: load address high byte ($00 - $ff). 3. b: load address low byte ($00 - $ff). 4. c: load data ($00 - $ff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page: 1. set bs1 to ?0?. 2. give wr a negative pulse. this starts prog ramming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page. (see figure 26-4 for signal waveforms.) figure 26-4. programming the eeprom waveforms 26.6.6 reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 297 for details on command and address loading): 1. a: load command ?0000 0010?. 2. g: load address high byte ($00 - $ff). 3. b: load address low byte ($00 - $ff). 4. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 5. set bs1 to ?1?. the flash word high byte can now be read at data. 6. set oe to ?1?. rdy/bsy wr oe reset +12v pagel bs2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 bs1 xtal1 xx agb ceb c el k 301 8151h?avr?02/11 atmega128a 26.6.7 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to ?programming the flash? on page 297 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte ($00 - $ff). 3. b: load address low byte ($00 - $ff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. 26.6.8 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 297 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?0? and bs2 to ?0?. 4. give wr a negative pulse and wait for rdy/bsy to go high. 26.6.9 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 297 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?1? and bs2 to ?0?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs1 to ?0?. this selects low data byte. 26.6.10 programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to ?programming the flash? on page 297 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs2 to ?1? and bs1 to ?0?. this selects extended data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs2 to ?0?. this selects low data byte. 302 8151h?avr?02/11 atmega128a figure 26-5. programming the fuses 26.6.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 297 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. 26.6.12 reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 297 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, bs2 to ?0?, and bs1 to ?0?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, bs2 to ?1?, and bs1 to ?1?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, bs2 to ?1?, and bs1 to ?0?. the status of the extended fuse bits can now be read at data (?0? means programmed). 5. set oe to ?0?, bs2 to ?0?, and bs1 to ?1?. the status of the lock bits can now be read at data (?0? means programmed). 6. set oe to ?1?. rdy/bsy wr oe reset +12v pagel $40 data data xx xa1 xa0 bs1 xtal1 ac $ 4 0 data xx ac write fuse low byte write fuse high byte $ 4 0 data xx ac write extended fuse byte bs2 303 8151h?avr?02/11 atmega128a figure 26-6. mapping between bs1, bs2 and the fuse- and lock bits during read 26.6.13 reading the signature bytes the algorithm for reading the signature bytes is as follows (refer to programming the flash for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte ($00 - $02). 3. set oe to ?0?, and bs1 to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 26.6.14 reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to programming the flash for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. 26.6.15 parallel programming characteristics see ?parallel programming characteristics? on page 326 . 26.7 serial downloading both the flash and eeprom memo ry arrays can be programmed using the serial spi bus while reset is pulled to gnd. the serial interface consists of pins sck, mosi (input) and miso (out- put). after reset is set low, the programming enable instruction needs to be executed first before program/erase operations can be executed. note, in table 26-13 on page 304 , the pin mapping for spi programming is listed. not all pa rts use the spi pins dedicated for the internal spi interface. note that throughout the description about serial downloading, mosi and miso are used to describe the serial data in and serial data out respectively. for atmega128a these pins are mapped to pdi and pdo. lock bits 0 1 bs2 fuse high byte 0 1 bs1 data fuse low byte 0 1 bs2 extended fuse byte 304 8151h?avr?02/11 atmega128a 26.8 spi serial programming pin mapping even though the spi programming interface re-uses the spi i/o module, there is one important difference: the mosi/miso pins that are mapped to pb2 and pb3 in the spi i/o module are not used in the programming interface. instead, pe0 and pe1 are used for data in spi program- ming mode as shown in table 26-13 . figure 26-7. spi serial programming and verify (1) notes: 1. if the device is clocked by the internal oscillator, it is no need to connect a clock source to the xtal1 pin. 2. v cc - 0.3v < avcc < v cc + 0.3v, however, avcc should always be within 2.7v - 5.5v. when programming the eeprom, an auto-erase cycle is built into the self-timed programming operation (in the serial mode only) and there is no need to first execute the chip erase instruc- tion. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into $ff. depending on cksel fuses, a valid clock must be present. the minimum low and high periods for the serial clock (sck) input are defined as follows: low: > 2 cpu clock cycles for f ck < 12mhz, 3 cpu clock cycles for f ck 12mhz high: > 2 cpu clock cycles for f ck < 12mhz, 3 cpu clock cycles for f ck 12mhz 26.8.1 spi serial programming algorithm when writing serial data to the atmega128a, data is clocked on the rising edge of sck. table 26-13. pin mapping spi serial programming symbol pins i/o description mosi (pdi) pe0 i serial data in miso (pdo) pe1 o serial data out sck pb1 i serial clock vcc gnd xtal1 sck pdo pdi reset pe0 pe1 pb1 +2.7 - 5.5v avcc +2.7 - 5.5v (2) 305 8151h?avr?02/11 atmega128a when reading data from the at mega128a, data is clocked on the falling edge of sck. see fig- ure 26-8 for timing details. to program and verify the atmega128a in the spi serial programming mode, the following sequence is recommended (see four byte instruction formats in table 26-8 ): 1. power-up sequence: apply power between v cc and gnd while reset and sck are set to ?0?. in some sys- tems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. as an alternative to using the reset signal, pen can be held low during power-on reset while sck is set to ?0?. in this case, only the pen value at power-on reset is important. if the programmer cannot guarantee that sck is held low during power-up, the pen method cannot be used. the device must be powered down in order to com- mence normal operation when using this method. 2. wait for at least 20ms and enable spi serial programming by sending the program- ming enable serial instruction to pin mosi. 3. the spi serial programming instructions will not work if the comm unication is out of synchronization. when in sync. the second byte ($53), will echo back when issuing the third byte of the programming enable instruction. whether the echo is correct or not, all four bytes of the instruction must be transmitted. if the $53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the page size is found in table 26-11 on page 296 . the memory page is loaded one byte at a time by supplying the 7 lsb of the address and data together with the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for given address. the program memory page is stored by loading the write program memory page instruction with the 9m sb of the address. if polling is not used, the user must wait at least t wd_flash before issuing the next page. (see table 26-14 ). note: if other commands than polling (read) are applied before any write operation (flash, eeprom, lock bits, fuses) is completed, may result in incorrect programming. 5. the eeprom array is programmed one byte at a time by supplying the address and data together with the appropriate write instruction. an eeprom memory location is first automatically erased before new data is written. if pollin g is not used, the user must wait at least t wd_eeprom before issuing the next byte. (see table 26-14 ). in a chip erased device, no $ffs in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the content at the selected address at serial output miso. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. tu r n v cc power off. 26.8.2 data polling flash when a page is being programmed into the flash, reading an address location within the page being programmed will give the va lue $ff. at the time the devic e is ready for a new page, the programmed value will read correctly. this is used to determine w hen the next page can be writ- ten. note that the entire page is written simultaneously and any address within the page can be used for polling. data polling of the flash will not work for the va lue $ff, so when programming 306 8151h?avr?02/11 atmega128a this value, the user will have to wait for at least t wd_flash before programming the next page. as a chip-erased device contains $ff in all locations, programming of addresses that are meant to contain $ff, can be skipped. see table 26-14 for t wd_flash value 26.8.3 data polling eeprom when a new byte has been written and is being programmed into eeprom, reading the address location being programmed will give the va lue $ff. at the time the device is ready for a new byte, the programmed value will read correctly. this is us ed to determine when the next byte can be written. this will not work for the value $ff, but the user should have the following in mind: as a chip-erased device contains $ff in all locations, programming of addresses that are meant to contain $ff, can be skipped. this does not apply if the eeprom is re-programmed without chip-erasing the device. in this case, data polling cannot be used for the value $ff, and the user will have to wait at least t wd_eeprom before programming the next byte. see table 26-14 for t wd_eeprom value. figure 26-8. .spi serial programming waveforms table 26-14. minimum wait delay before writing the next flash or eeprom location, v cc = 5v 10% symbol minimum wait delay t wd_fuse 4.5ms t wd_flash 5ms t wd_eeprom 10ms t wd_erase 10ms msb msb lsb lsb serial clock input (sck) serial data input (mosi) (miso) sample serial data output 307 8151h?avr?02/11 atmega128a note: a = address high bits b = address low bits h = 0 - low byte, 1 - high byte o = data out i = data in x = don?t care table 26-15. spi serial programming instruction set instruction instruction format operation byte 1 byte 2 byte 3 byte4 programming enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx enable spi serial programming after reset goes low. chip erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx chip erase eeprom and flash. read program memory 0010 h 000 aaaa aaaa bbbb bbbb oooo oooo read h (high or low) data o from program memory at word address a : b . load program memory page 0100 h 000 xxxx xxxx x bbb bbbb iiii iiii write h (high or low) data i to program memory page at word address b . data low byte must be loaded before data high byte is applied within the same address. write program memory page 0100 1100 aaaa aaaa bx xx xxxx xxxx xxxx write program memory page at address a : b . read eeprom memory 1010 0000 xxxx aaaa bbbb bbbb oooo oooo read data o from eeprom memory at address a : b . write eeprom memory 1100 0000 xxxx aaaa bbbb bbbb iiii iiii write data i to eeprom memory at address a : b . read lock bits 0101 1000 0000 0000 xxxx xxxx xx oo oooo read lock bits. ?0? = programmed, ?1? = unprogrammed. see table 26-1 on page 291 for details. write lock bits 1010 1100 111x xxxx xxxx xxxx 11 ii iiii write lock bits. set bits = ?0? to program lock bits. see table 26-1 on page 291 for details. read signature byte 0011 0000 xxxx xxxx xxxx xx bb oooo oooo read signature byte o at address b . write fuse bits 1010 1100 1010 0000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. see table 26-5 on page 293 for details. write fuse high bits 1010 1100 1010 1000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. see table 26-4 on page 292 for details. write extended fuse bits 1010 1100 1010 0100 xxxx xxxx xxxx xxii set bits = ?0? to program, ?1? to unprogram. see table 26-5 on page 293 for details. read fuse bits 0101 0000 0000 0000 xxxx xxxx oooo oooo read fuse bits. ?0? = programmed, ?1? = unprogrammed. see table 26-5 on page 293 for details. read extendend fuse bits 0101 0000 0000 1000 xxxx xxxx oooo oooo read extended fuse bits. ?0? = pro-grammed, ?1? = unprogrammed. see table 26-5 on page 293 for details. read fuse high bits 0101 1000 0000 1000 xxxx xxxx oooo oooo read fuse high bits. ?0? = pro-grammed, ?1? = unprogrammed. see table 26-4 on page 292 for details. read calibration byte 0011 1000 xxxx xxxx 0000 00 bb oooo oooo read calibration byte o at address b . 308 8151h?avr?02/11 atmega128a 26.8.4 spi serial programming characteristics for characteristics of the spi module, see ?spi timing characteristics? on page 328 . 26.9 programming via the jtag interface programming through the jtag interface requires control of the four jtag specific pins: tck, tms, tdi, and tdo. control of the reset and clock pins is not required. to be able to use the jtag interface, the jtagen fuse must be programmed. the device is default shipped with the fuse programmed. in addition, the jtd bit in mcucsr must be cleared. alternatively, if the jtd bit is set, the external reset can be forced low. then, the jtd bit will be cleared after two chip clocks, and the jtag pins are available fo r programming . this pro- vides a means of using the jtag pi ns as normal port pi ns in running mode while still allowing in- system programming via the jtag interface. note that this technique can not be used when using the jtag pins for boundary-scan or on-chi p debug. in these cases the jtag pins must be dedicated for this purpose. as a definition in this data sheet, the lsb is shifted in and out first of all shift registers. 26.9.1 programming specific jtag instructions the instruction register is 4-bit wide, supporti ng up to 16 instructions. the jtag instructions useful for programming are listed below. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. the run-test/idle state of the tap controller is used to generate internal clocks. it can also be used as an idle state between jtag sequences. the state machine sequence for changing the instruction word is shown in figure 26-9 . 309 8151h?avr?02/11 atmega128a figure 26-9. state machine sequence for changing the instruction word 26.9.2 avr_reset ($c) the avr specific public jtag in struction for setting the avr device in the reset mode or taking the device out from the reset mode. the tap controller is not reset by this instruction. the one bit reset register is selected as data register. no te that the reset will be active as long as there is a logic 'one' in the reset chain. the output from this chain is not latched. the active states are: ? shift-dr: the reset register is shifted by the tck input. 26.9.3 prog_enable ($4) the avr specific public jtag instruction for enabling programming via the jtag port. the 16- bit programming enable register is selected as data register. the active states are the following: ? shift-dr: the programming enable signature is shifted into the data register. test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 310 8151h?avr?02/11 atmega128a ? update-dr: the programming enable signature is compared to the correct value, and programming mode is entered if the signature is valid. 26.9.4 prog_commands ($5) the avr specific public jtag instruction for entering programming commands via the jtag port. the 15-bit programming command register is selected as data register. the active states are the following: ? capture-dr: the result of the previous command is loaded into the data register. ? shift-dr: the data register is shifted by the tck input, shifting out the result of the previous command and shifting in the new command. ? update-dr: the programming command is applied to the flash inputs. ? run-test/idle: one clock cycle is generated, executing the applied command. 26.9.5 prog_pageload ($6) the avr specific public jtag instruction to directly load the flash data page via the jtag port. the 2048-bit virtual flash page load register is selected as data register. this is a virtual scan chain with length equal to the number of bits in one flash page. internally the shift register is 8- bit. unlike most jtag instructions, the update-dr state is not used to transfer data from the shift register. the data are automatically transferre d to the flash page buffer byte by byte in the shift-dr state by an internal state machine. this is the only active state: ? shift-dr: flash page data are shifted in from tdi by the tck input, and automatically loaded into the flash page one byte at a time. note: the jtag instruction prog_pageload can only be used if the avr device is the first device in jtag scan chain. if the avr cannot be the first de vice in the scan chain, the byte-wise program- ming algorithm must be used. 26.9.6 prog_pageread ($7) the avr specific public jtag instruction to read one full flash data page via the jtag port. the 2056-bit virtual flash page read register is selected as data register. this is a virtual scan chain with length equal to the number of bits in one flash page plus 8. internally the shift regis- ter is 8-bit. unlike most jtag instructions, the capture-dr state is not used to transfer data to the shift register. the data are automatically transferred from the flash page buffer byte by byte in the shift-dr state by an internal state machine. this is the only active state: ? shift-dr: flash data are automatically read one byte at a time and shifted out on tdo by the tck input. the tdi input is ignored. note: the jtag instruction prog_pageread can only be used if the avr device is the first device in jtag scan chain. if the avr cannot be the first de vice in the scan chain, the byte-wise program- ming algorithm must be used. 26.9.7 data registers the data registers are selected by the jtag instruction registers described in section ?program- ming specific jtag instructions? on page 308 . the data registers relevant for programming operations are: ? reset register ? programming enable register ? programming command register ? virtual flash page load register 311 8151h?avr?02/11 atmega128a ? virtual flash page read register 26.9.8 reset register the reset register is a test data register used to reset the part during programming. it is required to reset the part before entering programming mode. a high value in the reset register corresponds to pulling the external reset low. the part is reset as long as there is a high value present in the reset register. depending on the fuse set- tings for the clock optio ns, the part will remain reset for a re set time-out period (refer to ?clock sources? on page 39 ) after releasing the reset register. the output from this data register is not latched, so the reset will take place immediately, as shown in figure 24-4 on page 257 . 26.9.9 programming enable register the programming enable register is a 16-bit regist er. the contents of this register is compared to the programming enable signature, binary code 1010_0011_0111_0000. when the contents of the register is equal to the programming enable signature, programming via the jtag port is enabled. the register is reset to 0 on power-on reset, and should always be reset when leav- ing programming mode. figure 26-10. programming enable register 26.9.10 programming command register the programming command register is a 15-bit regist er. this register is us ed to serially shift in programming commands, and to serially shift out the result of the previous command, if any. the jtag programming instruction set is shown in table 26-16 . the state sequence when shifting in the programming comma nds is illustrated in figure 26-12 . tdi tdo d a t a = dq clockdr & prog_enable programming enable $a370 312 8151h?avr?02/11 atmega128a figure 26-11. programming command register tdi tdo s t r o b e s a d d r e s s / d a t a flash eeprom fuses lock bits table 26-16. jtag programming instruction set a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes 1a. chip erase 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx 1b. poll for chip erase complete 0110011_10000000 xxxxx o x_xxxxxxxx (2) 2a. enter flash write 0100011_00010000 xxxxxxx_xxxxxxxx 2b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 2c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 2d. load data low byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 2e. load data high byte 0010111_ iiiiiiii xxxxxxx_xxxxxxxx 2f. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2g. write flash page 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 313 8151h?avr?02/11 atmega128a 2h. poll for page write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 3a. enter flash read 0100011_00000010 xxxxxxx_xxxxxxxx 3b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 3c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 3d. read data low and high byte 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo low byte high byte 4a. enter eeprom write 0100011_00010001 xxxxxxx_xxxxxxxx 4b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 4c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 4d. load data byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 4e. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 4f. write eeprom page 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 4g. poll for page write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 5a. enter eeprom read 0100011_00000011 xxxxxxx_xxxxxxxx 5b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 5c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 5d. read data byte 0110011_ bbbbbbbb 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 6a. enter fuse write 0100011_01000000 xxxxxxx_xxxxxxxx 6b. load data low byte (6) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6c. write fuse extended byte 0111011_00000000 0111001_00000000 0111011_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6d. poll for fuse write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6e. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6f. write fuse high byte 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6g. poll for fuse write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6h. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) table 26-16. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x instruction tdi sequence tdo sequence notes 314 8151h?avr?02/11 atmega128a notes: 1. this command sequence is not required if the seven msb are correctly set by the previous command sequence (which is normally the case). 2. repeat until o = ?1?. 3. set bits to ?0? to program the corresponding fuse, ?1? to unprogram the fuse. 6i. write fuse low byte 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6j. poll for fuse write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 7a. enter lock bit write 0100011_00100000 xxxxxxx_xxxxxxxx 7b. load data byte (9) 0010011_11 iiiiii xxxxxxx_xxxxxxxx (4) 7c. write lock bits 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 7d. poll for lock bit write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 8a. enter fuse/lock bit read 0100011_00000100 xxxxxxx_xxxxxxxx 8b. read extended fuse byte (6) 0111010_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8c. read fuse high byte (7) 0111110_00000000 0111111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8d. read fuse low byte (8) 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8e. read lock bits (9) 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xx oooooo (5) 8f. read fuses and lock bits 0111010_00000000 0111110_00000000 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo (5) fuse ext. byte fuse high byte fuse low byte lock bits 9a. enter signature byte read 0100011_00001000 xxxxxxx_xxxxxxxx 9b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 9c. read signature byte 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 10a. enter calibration byte read 0100011_00001000 xxxxxxx_xxxxxxxx 10b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 10c. read calibration byte 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 11a. load no operation command 0100011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx table 26-16. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x instruction tdi sequence tdo sequence notes 315 8151h?avr?02/11 atmega128a 4. set bits to ?0? to program the corresponding lock bit, ?1? to leave the lock bit unchanged. 5. ?0? = programmed, ?1? = unprogrammed. 6. the bit mapping for fuses extended byte is listed in table 26-3 on page 292 7. the bit mapping for fuses high byte is listed in table 26-4 on page 292 8. the bit mapping for fuses low byte is listed in table 26-5 on page 293 9. the bit mapping for lock bits byte is listed in table 26-1 on page 291 10. address bits exceeding pcmsb and eeamsb ( table 26-10 and table 26-11 ) are don?t care figure 26-12. state machine sequence for changing/reading the data word 26.9.11 virtual flash page load register the virtual flash page load register is a virtual scan chain with length equal to the number of bits in one flash page. internally the shift regist er is 8-bit, and the data are automatically trans- ferred to the flash page buffer byte by byte. shift in all instruction words in the page, starting with the lsb of the first instruction in the page and ending with the msb of the last instruction in the page. this provides an efficient way to load the entire flash page buffer before executing page write. test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 316 8151h?avr?02/11 atmega128a figure 26-13. virtual flash page load register 26.9.12 virtual flash page read register the virtual flash page read register is a virtual scan chain with length equal to the number of bits in one flash page plus 8. internally the sh ift register is 8-bit, and the data are automatically transferred from the flash data page byte by byte . the first eight cycles are used to transfer the first byte to the internal shift register, and the bits that are shifted out during these 8 cycles should be ignored. following this initialization, data are shifted out starting with the lsb of the first instruction in the page and ending with the msb of the last instruction in the page. this pro- vides an efficient way to read one full flash page to verify programming. figure 26-14. virtual flash page read register 26.9.13 programming algorithm all references below of type ?1a?, ?1b?, and so on, refer to table 26-16 . tdi tdo d a t a flash eeprom fuses lock bits strobes address state machine tdi tdo d a t a flash eeprom fuses lock bits strobes address state machine 317 8151h?avr?02/11 atmega128a 26.9.14 entering programming mode 1. enter jtag instruction avr_reset and shift 1 in the reset register. 2. enter instruction prog_enable and shift 1010_0011_0111_0000 in the program- ming enable register. 26.9.15 leaving programming mode 1. enter jtag instruction prog_commands. 2. disable all programming instructions by using no operation instruction 11a. 3. enter instruction prog_enable and shift 0000_0000_0000_0000 in the program- ming enable register. 4. enter jtag instruction avr_reset and shift 0 in the reset register. 26.9.16 performing chip erase 1. enter jtag instruction prog_commands. 2. start chip erase using programming instruction 1a. 3. poll for chip erase complete using programming instruction 1b, or wait for t wlrh_ce (refer to table note: on page 327 ). 26.9.17 programming the flash before programming the flash a chip erase must be performed. see ?performing chip erase? on page 318 . 1. enter jtag instruction prog_commands. 2. enable flash write using programming instruction 2a. 3. load address high byte using programming instruction 2b. 4. load address low byte using programming instruction 2c. 5. load data using programming instructions 2d, 2e and 2f. 6. repeat steps 4 and 5 for all instruction words in the page. 7. write the page using programming instruction 2g. 8. poll for flash write complete using programming instruction 2h, or wait for t wlrh (refer to table note: on page 327 ). 9. repeat steps 3 to 7 until all data have been programmed. a more efficient data transfer can be achieved using the prog_pageload instruction: 1. enter jtag instruction prog_commands. 2. enable flash write using programming instruction 2a. 3. load the page address using programming instructions 2b and 2c. pcword (refer to table 26-10 on page 296 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageload. 5. load the entire page by shifting in all instruction words in the page, starting with the lsb of the first instruction in the page and ending with the msb of the last instruction in the page. 6. enter jtag instruction prog_commands. 7. write the page using programming instruction 2g. 8. poll for flash write complete using programming instruction 2h, or wait for t wlrh (refer to table note: on page 327 ). 9. repeat steps 3 to 8 until all data have been programmed. 318 8151h?avr?02/11 atmega128a 26.9.18 reading the flash 1. enter jtag instruction prog_commands. 2. enable flash read using programming instruction 3a. 3. load address using programming instructions 3b and 3c. 4. read data using programming instruction 3d. 5. repeat steps 3 and 4 until all data have been read. a more efficient data transfer can be ac hieved using the prog_pageread instruction: 1. enter jtag instruction prog_commands. 2. enable flash read using programming instruction 3a. 3. load the page address using programming instructions 3b and 3c. pcword (refer to table 26-10 on page 296 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageread. 5. read the entire page by shifting out all instruction words in the page, starting with the lsb of the first instruction in the page and ending with the msb of the last instruction in the page. remember that the first 8 bits shifted out should be ignored. 6. enter jtag instruction prog_commands. 7. repeat steps 3 to 6 until all data have been read. 26.9.19 programming the eeprom before programming the eeprom a chip erase must be performed. see ?performing chip erase? on page 318 . 1. enter jtag instruction prog_commands. 2. enable eeprom write using programming instruction 4a. 3. load address high byte using programming instruction 4b. 4. load address low byte using programming instruction 4c. 5. load data using programming instructions 4d and 4e. 6. repeat steps 4 and 5 for all data bytes in the page. 7. write the data using programming instruction 4f. 8. poll for eeprom write complete using programming instruction 4g, or wait for t wlrh (refer to table note: on page 327 ). 9. repeat steps 3 to 8 until all data have been programmed. note that the prog_pageload instruction can not be used when programming the eeprom 26.9.20 reading the eeprom 1. enter jtag instruction prog_commands. 2. enable eeprom read using programming instruction 5a. 3. load address using programming instructions 5b and 5c. 4. read data using programming instruction 5d. 5. repeat steps 3 and 4 until all data have been read. note that the prog_pageread instructio n can not be used when reading the eeprom 26.9.21 programming the fuses 1. enter jtag instruction prog_commands. 2. enable fuse write using programming instruction 6a. 319 8151h?avr?02/11 atmega128a 3. load data byte using prog ramming instructions 6b. a bit value of ?0? will program the corresponding fuse, a ?1? will unprogram the fuse. 4. write extended fuse byte using programming instruction 6c. 5. poll for fuse write complete using prog ramming instruction 6d, or wait for t wlrh (refer to table note: on page 327 ). 6. load data byte using programming instructions 6e. a bit value of ?0? will program the corresponding fuse, a ?1? will unprogram the fuse. 7. write fuse high byte using programming instruction 6f. 8. poll for fuse write complete using prog ramming instruction 6g, or wait for t wlrh (refer to table note: on page 327 ). 9. load data byte using progra mming instructions 6h. a ?0? will program the fuse, a ?1? will unprogram the fuse. 10. write fuse low byte using programming instruction 6i. 11. poll for fuse write complete using pr ogramming instruction 6j, or wait for t wlrh (refer to table note: on page 327 ). 26.9.22 programming the lock bits 1. enter jtag instruction prog_commands. 2. enable lock bit write usin g programming instruction 7a. 3. load data using programming instructions 7b. a bit value of ?0? will program the corre- sponding lock bit, a ?1? will leave the lock bit unchanged. 4. write lock bits using programming instruction 7c. 5. poll for lock bit write complete using programming instruction 7d, or wait for t wlrh (refer to table note: on page 327 ). 26.9.23 reading the fuses and lock bits 1. enter jtag instruction prog_commands. 2. enable fuse/lock bit read using programming instruction 8a. 3. to read all fuses and lock bits, use programming instruction 8f. to only read extended fuse byte, use programming instruction 8b. to only read fuse high byte, use programming instruction 8c. to only read fuse low byte, use programming instruction 8d. to only read lock bits, use programming instruction 8e. 26.9.24 reading the signature bytes 1. enter jtag instruction prog_commands. 2. enable signature byte read using programming instruction 9a. 3. load address $00 using programming instruction 9b. 4. read first signature byte us ing programming instruction 9c. 5. repeat steps 3 and 4 with address $01 and address $02 to read the second and third signature bytes, respectively. 26.9.25 reading the calibration byte 1. enter jtag instruction prog_commands. 2. enable calibration byte read using programming instruction 10a. 3. load address $00 using programming instruction 10b. 4. read the calibration byte using programming instruction 10c. 320 8151h?avr?02/11 atmega128a 27. electrical characteristics 27.1 absolute maximum ratings* 27.2 dc characteristics operating temperature.................................. -55c to +125c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature ..................................... -65c to +150c voltage on any pin except reset with respect to ground ................................-0.5v to v cc +0.5v voltage on reset with respect to ground......-0.5v to +13.0v maximum operating voltage ............................................ 6.0v dc current per i/o pin ............................................... 40.0 ma dc current v cc and gnd pins.................... 200.0 - 400.0 ma t a = -40c to 85c, v cc = 2.7v to 5.5v (unless otherwise noted) symbol parameter condition min typ max units v il input low voltage except xtal1 and reset pins v cc = 2.7 - 5.5v -0.5 0.2 v cc (1) v v ih input high voltage except xtal1 and reset pins v cc = 2.7 - 5.5v 0.6 v cc (2) v cc + 0.5 v il1 input low voltage xtal1 pin v cc = 2.7 - 5.5v -0.5 0.1 v cc (1) v ih1 input high voltage xtal1 pin v cc = 2.7 - 5.5v 0.7 v cc (2) v cc + 0.5 v il2 input low voltage reset pin v cc = 2.7 - 5.5v -0.5 0.2 v cc (1) v ih2 input high voltage reset pin v cc = 2.7 - 5.5v 0.85 v cc (2) v cc + 0.5 v ol output low voltage (3) (ports a,b,c,d, e, f, g) i ol = 20 ma, v cc = 5v i ol = 10 ma, v cc = 3v 0.9 0.6 v oh output high voltage (4) (ports a,b,c,d, e, f, g) i oh = -20 ma, v cc = 5v i oh = -10 ma, v cc = 3v 4.2 2.2 i il input leakage current i/o pin vcc = 5.5 v, p i n l o w (absolute value) 1.0 a i ih input leakage current i/o pin vcc = 5.5 v, pin high (absolute value) 1.0 r rst reset pull-up resistor 30 60 85 k r pen pen pull-up resistor 30 60 r pu i/o pin pull-up resistor 20 50 321 8151h?avr?02/11 atmega128a notes: 1. ?max? means the highest value where the pin is guaranteed to be read as low 2. ?min? means the lowest value where t he pin is guaranteed to be read as high 3. although each i/o port can sink more than the test conditions (20 ma at v cc = 5v, 10 ma at v cc = 3v) under steady state conditions (non-transient), th e following must be observed: tqfp and qfn/mlf package: 1] the sum of all iol, for all ports, should not exceed 400 ma. 2] the sum of all iol, for ports a0 - a7, g2, c3 - c7 should not exceed 100 ma. 3] the sum of all iol, for ports c0 - c2, g0 - g1, d0 - d7, xtal2 should not exceed 100 ma. 4] the sum of all iol, for ports b0 - b7, g3 - g4, e0 - e7 should not exceed 100 ma. 5] the sum of all iol, for ports f0 - f7, should not exceed 100 ma. if iol exceeds the test condition, vol may exceed the related sp ecification. pins are not guar anteed to sink current greater than the listed test condition. 4. although each i/o port can source more than the test conditio ns (20 ma at vcc = 5v, 10 ma at vcc = 3v) under steady state conditions (non-transient), th e following must be observed: tqfp and qfn/mlf package: 1] the sum of all ioh, for a ll ports, should not exceed 400 ma. 2] the sum of all ioh, for ports a0 - a7 , g2, c3 - c7 should not exceed 100 ma. 3] the sum of all ioh, for ports c0 - c2, g0 - g1, d0 - d7, xtal2 should not exceed 100 ma. 4] the sum of all ioh, for ports b0 - b7, g3 - g4, e0 - e7 should not exceed 100 ma. 5] the sum of all ioh, for ports f0 - f7, should not exceed 100 ma. if ioh exceeds the test condition, voh ma y exceed the related specification. pins are not guaranteed to source current greater than the listed test condition. i cc power supply current active 4mhz, v cc = 3v 3 5.5 ma active 8mhz, v cc = 5v 9.8 19 idle 4mhz, v cc = 3v 1 2.5 idle 8mhz, v cc = 5v 3.5 11 power-down mode wdt enabled, v cc = 3v < 10 25 a wdt disabled, v cc = 3v < 1 10 v acio analog comparator input offset voltage v cc = 5v v in = v cc /2 40 mv i aclk analog comparator input leakage current v cc = 5v v in = v cc /2 -50 50 na t acpd analog comparator propagation delay v cc = 2.7v v cc = 5.0v 750 500 ns t a = -40c to 85c, v cc = 2.7v to 5.5v (unless otherwise noted) (continued) symbol parameter condition min typ max units 322 8151h?avr?02/11 atmega128a 27.3 speed grades figure 27-1. maximum frequency vs. v cc . 27.4 clock characteristics figure 27-2. external clock drive waveforms 2.7v 4.5v 5.5v sa fe oper a ting are a 16 mhz 8 mhz table 27-1. external clock drive symbol parameter v cc = 2.7v to 5.5 vv cc = 4.5v to 5.5 v units minmaxminmax 1/t clcl oscillator frequency 0 8 0 16 mhz t clcl clock period 125 62.5 ns t chcx high time 50 25 t clcx low time 50 25 t clch rise time 1.6 0.5 s t chcl fall time 1.6 0.5 t clcl change in period from one clock cycle to the next 22% v il1 v ih1 323 8151h?avr?02/11 atmega128a notes: 1. r should be in the range 3 k - 100 k , and c should be at least 20pf. the c values given in the table includes pin capacitance. this will vary with package type. 2. the frequency will vary with package type and board layout. 27.5 system and reset characteristics notes: 1. the power-on reset will not work un less the supply voltage has been below v pot (falling) 2. v bot may be below nominal minimum operating voltage for some devices. for devices where this is the case, the device is tested down to v cc = v bot during the production test. this guar- antees that a brown-out reset will occur before v cc drops to a voltage where correct operation of the microcontroller is no long er guaranteed. the test is performed using bodlevel=0 and bodlevel=1. table 27-2. external rc oscillato r, typical frequencies r [k ] (1) c [pf] f (2) 33 22 650khz 10 22 2.0mhz table 27-3. reset characteristics symbol parameter condition min typ max units v pot power-on reset threshold voltage (rising) 1.4 2.3 v power-on reset threshold voltage (falling) (1) 1.3 2.3 v v rst reset pin threshold voltage 0.2 v cc 0.85 v cc v t rst pulse width on reset pin 1.5 s v bot brown-out reset threshold voltage (2) bodlevel = 0 3.7 4.0 4.5 v t bod minimum low voltage period for brown-out detection bodlevel = 0 2 s v hyst brown-out detector hysteresis 100 mv 324 8151h?avr?02/11 atmega128a 27.6 two-wire serial in terface characteristics table 27-4 describes the requirements for devices connected to the two-wire serial bus. the atmega128a two-wire serial interface meets or exceeds these requirements under the noted conditions. timing symbols refer to figure 27-3 . notes: 1. in atmega128a, this parameter is characterized and not 100% tested. table 27-4. two-wire serial bus requirements symbol parameter condition min max units vil input low-voltage -0.5 0.3 v cc v vih input high-voltage 0.7 v cc v cc + 0.5 v vhys (1) hysteresis of schmitt trigger inputs 0.05 v cc (2) ?v vol (1) output low-voltage 3 ma sink current 0 0.4 v tr (1) rise time for both sda and scl 20 + 0.1c b (3)(2) 300 ns tof (1) output fall time from v ihmin to v ilmax 10pf < c b < 400pf (3) 20 + 0.1c b (3)(2) 250 ns tsp (1) spikes suppressed by input filter 0 50 (2) ns i i input current each i/o pin 0.1 v cc < v i < 0.9 v cc -10 10 a c i (1) capacitance for each i/o pin ? 10 pf f scl scl clock frequency f ck (4) > max(16f scl , 250khz) (5) 0 400 khz rp value of pull-up resistor f scl 100khz f scl > 100khz t hd;sta hold time (repeated) start condition f scl 100khz 4.0 ? s f scl > 100khz 0.6 ? s t low low period of the scl clock f scl 100khz 4.7 ? s f scl > 100khz 1.3 ? s t high high period of the scl clock f scl 100khz 4.0 ? s f scl > 100khz 0.6 ? s t su;sta set-up time for a repeated start condition f scl 100khz 4.7 ? s f scl > 100khz 0.6 ? s t hd;dat data hold time f scl 100khz 0 3.45 s f scl > 100khz 0 0.9 s t su;dat data setup time f scl 100khz 250 ? ns f scl > 100khz 100 ? ns t su;sto setup time for stop condition f scl 100khz 4.0 ? s f scl > 100khz 0.6 ? s t buf bus free time between a stop and start condition f scl 100khz 4.7 ? s v cc 0.4v ? 3ma ---------------------------- - 1000ns c b ------------------- v cc 0.4v ? 3ma ---------------------------- 300ns c b --------------- - 325 8151h?avr?02/11 atmega128a 2. required only for f scl > 100khz. 3. c b = capacitance of one bus line in pf. 4. f ck = cpu clock frequency 5. this requirement applies to all atmega128a two-wire serial interface operation. other devices connected to the two-wire serial bus need only obey the general f scl requirement. figure 27-3. two-wire serial bus timing 27.7 parallel programmi ng characteristics figure 27-4. parallel programming timing, including some general timing requirements figure 27-5. parallel programming timing, loading sequence with timing requirements note: the timing requirements shown in figure 27-4 (that is t dvxh , t xhxl , and t xldx ) also apply to load- ing operation. t su;sta t low t high t low t of t hd;sta t hd;dat t su;dat t su;sto t buf scl sda t r data & contol (data, xa0/1, bs1, bs2) xtal1 t xhxl t wl wh t dvxh t xldx t plwl t wlrh wr rdy/bsy pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) load data (low byte) load data (high byte) load data load address (low byte) 326 8151h?avr?02/11 atmega128a figure 27-6. parallel programming timing, reading sequence (within the same page) with timing requirements note: the timing requirements shown in figure 27-4 (that is t dvxh , t xhxl , and t xldx ) also apply to read- ing operation. table 27-5. parallel programming characteristics, v cc = 5v 10% symbol parameter min typ max units v pp programming enable voltage 11.5 12.5 v i pp programming enable current 250 a t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 ns t xhxl xtal1 pulse width high 150 ns t xldx data and control hold after xtal1 low 67 ns t xlwl xtal1 low to wr low 0 ns t xlph xtal1 low to pagel high 0 ns t plxh pagel low to xtal1 high 150 ns t bvph bs1 valid before pagel high 67 ns t phpl pagel pulse width high 150 ns t plbx bs1 hold after pagel low 67 ns t wlbx bs2/1 hold after wr low 67 ns t plwl pagel low to wr low 67 ns t bvwl bs1 valid to wr low 67 ns t wlwh wr pulse width low 150 ns t wlrl wr low to rdy/bsy low 0 1 s t wlrh wr low to rdy/bsy high (1) 3.7 5 ms t wlrh_ce wr low to rdy/bsy high for chip erase (2) 7.5 10 ms t xlol xtal1 low to oe low 0 ns xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bhdv t oldv t xlol t ohdz 327 8151h?avr?02/11 atmega128a notes: 1. t wlrh is valid for the write flash, write eepro m, write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command. 27.8 spi timing characteristics see figure 27-7 and figure 27-8 for details. note: 1. in spi programming mode the minimum sck high/low period is: - 2 t clcl for f ck < 12mhz - 3 t clcl for f ck >12mhz t bvdv bs1 valid to data valid 0 250 ns t oldv oe low to data valid 250 ns t ohdz oe high to data tri-stated 250 ns table 27-5. parallel programming characteristics, v cc = 5v 10% (continued) symbol parameter min typ max units table 27-6. spi timing parameters description mode min typ max 1 sck period master see table 19-4 ns 2 sck high/low master 50% duty cycle 3 rise/fall time master 3.6 4 setup master 10 5 hold master 10 6 out to sck master 0.5 ? t sck 7 sck to out master 10 8 sck to out high master 10 9 ss low to out slave 15 10 sck period slave 4 ? t ck 11 sck high/low (1) slave 2 ? t ck 12 rise/fall time slave 1.6 s 13 setup slave 10 ns 14 hold slave 10 15 sck to out slave 15 16 sck to ss high slave 20 17 ss high to tri-state slave 10 18 ss low to sck slave 2 ? t ck 328 8151h?avr?02/11 atmega128a figure 27-7. spi interface timing requirements (master mode) figure 27-8. spi interface timing requirements (slave mode) mosi (data output) sck (cpol = 1) miso (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 61 22 3 45 8 7 mi so (data output) sck (cpol = 1) mo si (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 10 11 11 12 13 14 17 15 9 x 16 18 329 8151h?avr?02/11 atmega128a 27.9 adc characteristics notes: 1. values are guidelines only. 2. minimum for avcc is 2.7v. 3. maximum for avcc is 5.5v table 27-7. adc characteristics, single ended channels symbol parameter condition min (1) typ (1) max (1) units resolution single ended conversion 10 bits absolute accuracy (including inl, dnl, quantization error, gain and offset error) single ended conversion v ref = 4v, v cc = 4v adc clock = 200khz 1.5 lsb single ended conversion v ref = 4v, v cc = 4v adc clock = 1mhz 3.25 lsb single ended conversion v ref = 4v, v cc = 4v adc clock = 200khz noise reduction mode 1.5 lsb single ended conversion v ref = 4v, v cc = 4v adc clock = 1mhz noise reduction mode 3.75 lsb integral non-linearity (inl) single ended conversion v ref = 4v, v cc = 4v adc clock = 200khz 0.75 lsb differential non-linearity (dnl) single ended conversion v ref = 4v, v cc = 4v adc clock = 200khz 0.5 lsb gain error single ended conversion v ref = 4v, v cc = 4v adc clock = 200khz 1lsb offset error single ended conversion v ref = 4v, v cc = 4v adc clock = 200khz 1lsb clock frequency 50 1000 khz conversion time 13 260 s avcc analog supply voltage v cc - 0.3 (2) v cc + 0.3 (3) v v ref reference voltage 2.0 avcc v v in input voltage gnd v ref v input bandwidth 38.5 khz v int internal voltage reference 2.3 2.56 2.7 v r ref reference input resistance 32 k r ain analog input resistance 55 100 m 330 8151h?avr?02/11 atmega128a table 27-8. adc characteristics, differential channels symbol parameter condition min (1) typ (1) max (1) units resolution gain = 1x 10 bits gain = 10x 10 bits gain = 200x 10 bits absolute accuracy gain = 1x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 17 lsb gain = 10x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 17 lsb gain = 200x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 7lsb integral non-linearity (inl) (accuracy after calibration for offset and gain error) gain = 1x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 1.5 lsb gain = 10x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 2lsb gain = 200x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 5lsb gain error gain = 1x 1.5 % gain = 10x 1.5 % gain = 200x 0.5 % offset error gain = 1x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 2lsb gain = 10x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 3lsb gain = 200x v ref = 4v, v cc = 5v adc clock = 50 - 200khz 4lsb clock frequency 50 200 khz conversion time 65 260 s av cc analog supply voltage v cc - 0.3 (2) v cc + 0.3 (3) v v ref reference voltage 2.0 av cc - 0.5 v v in input voltage gnd v cc v v diff input differential voltage -v ref /gain v ref /gain v adc conversion output -511 511 lsb input bandwidth 4khz 331 8151h?avr?02/11 atmega128a notes: 1. values are guidelines only. 2. minimum for avcc is 2.7v. 3. maximum for avcc is 5.5v. 27.10 external data memory timing notes: 1. this assumes 50% clock duty cycl e. the half peri od is actually the high time of the external clock, xtal1. 2. this assumes 50% clock duty cycle. the half period is actually the low time of the external clock, xtal1. v int internal voltage reference 2.3 2.56 2.7 v r ref reference input resistance 32 k r ain analog input resistance 55 100 m table 27-9. external data memory characterist ics, 4.5v - 5.5v, no wait-state symbol parameter 8mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 1t lhll ale pulse width 115 1.0t clcl -10 ns 2t avll address valid a to ale low 57.5 0.5t clcl -5 (1) ns 3a t llax_st address hold after ale low, write access 55 ns 3b t llax_ld address hold after ale low, read access 55 ns 4t avllc address valid c to ale low 57.5 0.5t clcl -5 (1) ns 5t avrl address valid to rd low 115 1.0t clcl -10 ns 6t avwl address valid to wr low 115 1.0t clcl -10 ns 7t llwl ale low to wr low 47.5 67.5 0.5t clcl -15 (2) 0.5t clcl +5 (2) ns 8t llrl ale low to rd low 47.5 67.5 0.5t clcl -15 (2) 0.5t clcl +5 (2) ns 9t dvrh data setup to rd high 40 40 ns 10 t rldv read low to data valid 75 1.0t clcl -50 ns 11 t rhdx data hold after rd high 0 0 ns 12 t rlrh rd pulse width 115 1.0t clcl -10 ns 13 t dvwl data setup to wr low 42.5 0.5t clcl -20 (1) ns 14 t whdx data hold after wr high 115 1.0t clcl -10 ns 15 t dvwh data valid to wr high 125 1.0t clcl ns 16 t wlwh wr pulse width 115 1.0t clcl -10 ns table 27-8. adc characteristics, differe ntial channels (continued) symbol parameter condition min (1) typ (1) max (1) units 332 8151h?avr?02/11 atmega128a table 27-10. external data memory characteristic s, 4.5v - 5.5v, 1 cycle wait-state symbol parameter 8mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 10 t rldv read low to data valid 200 2.0t clcl -50 ns 12 t rlrh rd pulse width 240 2.0t clcl -10 ns 15 t dvwh data valid to wr high 240 2.0t clcl ns 16 t wlwh wr pulse width 240 2.0t clcl -10 ns table 27-11. external data memory characteristics, 4.5v - 5.5v, srwn1 = 1, srwn0 = 0 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 10 t rldv read low to data valid 325 3.0t clcl -50 ns 12 t rlrh rd pulse width 365 3.0t clcl -10 ns 15 t dvwh data valid to wr high 375 3.0t clcl ns 16 t wlwh wr pulse width 365 3.0t clcl -10 ns table 27-12. external data memory characteristics, 4.5v - 5.5v, srwn1 = 1, srwn0 = 1 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 10 t rldv read low to data valid 325 3.0t clcl -50 ns 12 t rlrh rd pulse width 365 3.0t clcl -10 ns 14 t whdx data hold after wr high 240 2.0t clcl -10 ns 15 t dvwh data valid to wr high 375 3.0t clcl ns 16 t wlwh wr pulse width 365 3.0t clcl -10 ns table 27-13. external data memory characterist ics, 2.7v - 5.5v, no wait-state symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 1t lhll ale pulse width 235 t clcl -15 ns 2t avll address valid a to ale low 115 0.5t clcl -10 (1) ns 3a t llax_st address hold after ale low, write access 55 ns 333 8151h?avr?02/11 atmega128a notes: 1. this assumes 50% clock duty cycl e. the half peri od is actually the high time of the external clock, xtal1. 2. this assumes 50% clock duty cycle. the half period is actually the low time of the external clock, xtal1. 3b t llax_ld address hold after ale low, read access 55 ns 4t avllc address valid c to ale low 115 0.5t clcl -10 (1) ns 5t avrl address valid to rd low 235 1.0t clcl -15 ns 6t avwl address valid to wr low 235 1.0t clcl -15 ns 7t llwl ale low to wr low 115 130 0.5t clcl -10 (2) 0.5t clcl +5 (2) ns 8t llrl ale low to rd low 115 130 0.5t clcl -10 (2) 0.5t clcl +5 (2) ns 9t dvrh data setup to rd high 45 45 ns 10 t rldv read low to data valid 190 1.0t clcl -60 ns 11 t rhdx data hold after rd high 0 0 ns 12 t rlrh rd pulse width 235 1.0t clcl -15 ns 13 t dvwl data setup to wr low 105 0.5t clcl -20 (1) ns 14 t whdx data hold after wr high 235 1.0t clcl -15 ns 15 t dvwh data valid to wr high 250 1.0t clcl ns 16 t wlwh wr pulse width 235 1.0t clcl -15 ns table 27-13. external data memory characteristics, 2.7v - 5.5v, no wait-state (continued) symbol parameter 4mhz oscillator variable oscillator unit min max min max table 27-14. external data memory characteristics, 2.7v - 5.5v, srwn1 = 0, srwn0 = 1 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 10 t rldv read low to data valid 440 2.0t clcl -60 ns 12 t rlrh rd pulse width 485 2.0t clcl -15 ns 15 t dvwh data valid to wr high 500 2.0t clcl ns 16 t wlwh wr pulse width 485 2.0t clcl -15 ns table 27-15. external data memory characteristics, 2.7v - 5.5v, srwn1 = 1, srwn0 = 0 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 10 t rldv read low to data valid 690 3.0t clcl -60 ns 12 t rlrh rd pulse width 735 3.0t clcl -15 ns 15 t dvwh data valid to wr high 750 3.0t clcl ns 16 t wlwh wr pulse width 735 3.0t clcl -15 ns 334 8151h?avr?02/11 atmega128a figure 27-9. external memory timing (srwn1 = 0, srwn0 = 0 table 27-16. external data memory characteristics, 2.7v - 5.5 v, srwn1 = 1, srwn0 = 1 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 10 t rldv read low to data valid 690 3.0t clcl -60 ns 12 t rlrh rd pulse width 735 3.0t clcl -15 ns 14 t whdx data hold after wr high 485 2.0t clcl -15 ns 15 t dvwh data valid to wr high 750 3.0t clcl ns 16 t wlwh wr pulse width 735 3.0t clcl -15 ns ale t1 t2 t3 write read wr t4 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address system clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 335 8151h?avr?02/11 atmega128a figure 27-10. external memory timing (srwn1 = 0, srwn0 = 1) figure 27-11. external memory timing (srwn1 = 1, srwn0 = 0) ale t1 t2 t3 write read wr t5 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address system clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 t4 ale t1 t2 t3 write read wr t6 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address system clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 t4 t5 336 8151h?avr?02/11 atmega128a figure 27-12. external memory timing (srwn1 = 1, srwn0 = 1) () the ale pulse in the last period (t 4-t7) is only present if the next instruction accesses the ram (internal or external). ale t1 t2 t3 write read wr t7 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address system clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 t4 t5 t6 337 8151h?avr?02/11 atmega128a 28. typical characteristics the following charts show typical behavior. t hese figures are not tested during manufacturing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a sine wave generator with rail-to-rail output is used as clock source. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating frequency, loading of i/o pins, switching rate of i/o pins, code executed and ambient tempera- ture. the dominating factors are operating voltage and frequency. the current drawn from capacitive loaded pins may be estimated (for one pin) as c l * v cc *f where c l = load capacitance, v cc = operating voltage and f = average switching frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with watchdog timer enabled and power-down mode with watchdog timer disabled represents the differential cur- rent drawn by the watchdog timer. 28.1 active supply current figure 28-1. active supply current vs. low frequency (0.1mhz - 1.0mhz) 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 0 0.5 1 1.5 2 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma) 338 8151h?avr?02/11 atmega128a figure 28-2. active supply current vs . frequency (1mhz - 16mhz) figure 28-3. active supply current vs. v cc (internal rc o scillator, 1mhz) 0 5 10 15 20 25 0246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 2.7v 3.3v 4.0v 4.5v 5.0v 5.5v 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 339 8151h?avr?02/11 atmega128a figure 28-4. active supply current vs. v cc (internal rc o scillator, 2mhz) figure 28-5. active supply current vs. v cc (internal rc o scillator, 4mhz) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 8 5 c 25 c -40 c 0 1 2 3 4 5 6 7 8 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 340 8151h?avr?02/11 atmega128a figure 28-6. active supply current vs. v cc (internal rc o scillator, 8mhz) figure 28-7. active supply current vs. v cc (32khz external oscillator) 8 5 c 25 c -40 c 0 2 4 6 8 10 12 14 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 25 c 0 20 40 60 8 0 100 120 140 2,5 3 3,5 4 4,5 5 5,5 v cc ( v ) i cc ( u a) 341 8151h?avr?02/11 atmega128a 28.2 idle supply current figure 28-8. idle supply current vs. low frequency (0.1mhz - 1.0mhz) figure 28-9. idle supply current vs. frequency (1mhz - 16mhz) 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 0 0.2 0.4 0.6 0. 8 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma) 0 1 2 3 4 5 6 7 8 9 10 0246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 2.7v 3.3v 4.0v 4.5v 5.0v 5.5v 342 8151h?avr?02/11 atmega128a figure 28-10. idle supply current vs. v cc (internal rc o scillator, 1mhz) figure 28-11. idle supply current vs. v cc (internal rc o scillator, 2mhz) 8 5 c 25 c -40 c 0 0.2 0.4 0.6 0. 8 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 8 5 c 25 c -40 c 0 0.2 0.4 0.6 0. 8 1 1.2 1.4 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 343 8151h?avr?02/11 atmega128a figure 28-12. idle supply current vs. v cc (internal rc o scillator, 4mhz) figure 28-13. idle supply current vs. v cc (internal rc o scillator, 8mhz) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 8 5 c 25 c -40 c 0 1 2 3 4 5 6 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 344 8151h?avr?02/11 atmega128a figure 28-14. idle supply current vs. v cc (32khz external oscillator) 28.3 power-down supply current figure 28-15. power-down supply current vs. v cc (watchdog timer disabled) 25 c 0 5 10 15 20 25 30 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc ( u a) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc ( u a) 345 8151h?avr?02/11 atmega128a figure 28-16. power-down supply current vs. v cc (watchdog timer enabled) 28.4 power-save supply current figure 28-17. power-save supply current vs. v cc (watchdog timer disabled) 8 5 c 25 c -40 c 0 5 10 15 20 25 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc ( u a) 25 c 0 2 4 6 8 10 12 14 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc ( u a) 346 8151h?avr?02/11 atmega128a 28.5 standby supply current figure 28-18. standby supply current vs. v cc , figure 28-19. standby supply current vs. v cc (ckopt programmed) 6mhz_xt a l 6mhz_re s 4mhz_xt a l 4mhz_re s 450khz_re s 2mhz_xt a l 2mhz_re s 1mhz_re s 0 0.02 0.04 0.06 0.0 8 0.1 0.2 0.14 0.16 2.5 33 .5 4 4.5 5 5.5 v cc (v) i cc (ma) 6mhz_xtal_fs w 4mhz_xtal_fs w 2mhz_xtal_fs w 16mhz_xtal_fs w 12mhz_xtal_fs w 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc (ma) 347 8151h?avr?02/11 atmega128a 28.6 pin pull-up figure 28-20. i/o pin pull-up resistor current vs. input voltage (v cc = 5v) figure 28-21. i/o pin pull-up resistor current vs. input voltage (v cc = 2.7v) 0 20 40 60 8 0 100 120 140 160 0123456 v op ( v ) i op ( u a) 0 20 40 60 8 0 0 0.5 1 1.5 2 2.5 3 v op ( v ) i op ( u a) 348 8151h?avr?02/11 atmega128a 28.7 pin driver strength figure 28-22. i/o pin source current vs. output voltage (v cc = 5v) figure 28-23. i/o pin source current vs. output voltage (v cc = 2.7v) 8 5 c 25 c -40 c 0 10 20 30 40 50 60 70 8 0 90 2.5 3 3.5 4 4.5 5 5.5 v oh ( v ) i oh (ma) 8 5 c 25 c -40 c 0 5 10 15 20 25 30 0.511.522.53 v oh ( v ) i oh (ma) 349 8151h?avr?02/11 atmega128a figure 28-24. i/o pin sink current vs. output voltage (v cc = 5v) figure 28-25. i/o pin sink current vs. output voltage, v cc = 2.7v 8 5 c 25 c -40 c 0 10 20 30 40 50 60 70 8 0 90 0 0.5 1 1.5 2 2.5 v ol ( v ) i ol (ma) 8 5 c 25 c -40 c 0 5 10 15 20 25 30 35 0 0.5 1 1.5 2 2.5 v ol ( v ) i ol (ma) 350 8151h?avr?02/11 atmega128a 28.8 pin thresholds and hysteresis figure 28-26. i/o pin input threshold voltage vs. v cc (vih, i/o pin read as ?1?) figure 28-27. i/o pin input threshold voltage vs. v cc (vil, i/o pin read as ?0?) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) threshold ( v ) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) threshold ( v ) 351 8151h?avr?02/11 atmega128a figure 28-28. i/o pin input hysteresis vs. v cc 28.9 bod thresholds and anal og comparator offset figure 28-29. bod threshold vs. temperature (bodlevel is 4.0v) 8 5 c 25 c -40 c 0 0.1 0.2 0. 3 0.4 0.5 0.6 0.7 0. 8 2.5 33 .5 4 4.5 5 5.5 v cc (v) inp u t hy s tere s i s (mv) rising v falling v 3.9 3.95 4 4.05 4.1 4.15 4.2 4.25 4.3 -60 -40 -20 0 20 40 60 8 0 100 temperat u re (c) threshold ( v ) cc cc 352 8151h?avr?02/11 atmega128a figure 28-30. bod threshold vs. temperature (bodlevel is 2.7v) figure 28-31. bandgap voltage vs. operating voltage rising v falling v 2.5 2.55 2.6 2.65 2.7 2.75 2. 8 -60 -40 -20 0 20 40 60 8 0100 temperat u re (c) threshold ( v ) cc cc 8 5 c 25 c -40 c 1.1 8 5 1.19 1.195 1.2 1.205 1.21 1.215 2.5 33 .5 4 4.5 5 5.5 vcc (v) b a ndg a p volt a ge (v) 353 8151h?avr?02/11 atmega128a 28.10 internal oscillator speed figure 28-32. watchdog oscillato r frequency vs. v cc figure 28-33. calibrated 1mhz rc oscillator frequency vs. temperature 8 5 c 25 c -40 c 1040 1060 10 8 0 1100 1120 1140 1160 11 8 0 1200 1220 2.5 33 .5 4 4.5 5 5.5 v cc (v) f rc (khz) 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 0.9 0.95 1 1.05 -60 -40 -20 0 20 40 60 8 0100 temperat u re (c) f rc (mhz) 354 8151h?avr?02/11 atmega128a figure 28-34. calibrated 1mhz rc oscillator frequency vs. v cc figure 28-35. 1mhz rc oscillator fre quency vs. osccal value 8 5 c 25 c -40 c 0.9 0.95 1 1.05 2.5 33 .5 4 4.5 5 5.5 v cc (v) f rc (mhz) 8 5 c 25 c -40 c 0 0.2 0.4 0.6 0. 8 1 1.2 1.4 1.6 1. 8 016 3 24 8 64 8 0 96 112 12 8 144 160 176 192 20 8 224 240 256 o s ccal (x1) f rc (mhz) 355 8151h?avr?02/11 atmega128a figure 28-36. calibrated 2mhz rc oscillator frequency vs. temperature figure 28-37. calibrated 2mhz rc oscillator frequency vs. v cc 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1. 8 1. 8 5 1.9 1.95 2 2.05 2.1 -60 -40 -20 0 20 40 60 8 0 100 temperat u re f rc (mhz) (c) 8 5 c 25 c -40 c 1. 8 1. 8 5 1.9 1.95 2 2.05 2.1 2.5 33 .5 4 4.5 5 5.5 v cc (v) f rc (mhz) 356 8151h?avr?02/11 atmega128a figure 28-38. 2mhz rc oscillator fre quency vs. osccal value figure 28-39. calibrated 4mhz rc oscillator frequency vs. temperature 8 5 c 25 c -40 c 0 0,5 1 1,5 2 2,5 3 3 ,5 4 016 3 24 8 64 8 09611212 8 144 160 176 192 20 8 224 240 256 o s ccal (x1) f rc (mhz) 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 3.5 3.6 3.7 3. 8 3.9 4 4.1 4.2 -60 -40 -20 0 20 40 60 8 0100 temperat u re (c) f rc (mhz) 357 8151h?avr?02/11 atmega128a figure 28-40. calibrated 4mhz rc oscillator frequency vs. v cc figure 28-41. 4mhz rc oscillator fre quency vs. osccal value 8 5 c 25 c -40 c 3 .5 3 .6 3 .7 3 . 8 3 .9 4 4.1 4.2 2.5 33 .5 4 4.5 5 5.5 v cc (v) f rc (mhz) 8 5 c 25 c -40 c 0 1 2 3 4 5 6 7 8 016 3 24 8 64 8 09611212 8 144 160 176 192 20 8 224 240 256 o s ccal (x1) f rc (mhz) 358 8151h?avr?02/11 atmega128a figure 28-42. calibrated 8mhz rc oscillator frequency vs. temperature figure 28-43. calibrated 8mhz rc oscillator frequency vs. v cc 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 6.6 7 7.4 7. 8 8 .2 8 .6 -60 -40 -20 0 20 40 60 8 0100 temperat u re (c) f rc (mhz) 8 5 c 25 c -40 c 0 1 2 3 4 5 6 7 8 9 2.5 33 .5 4 4.5 5 5.5 v cc (v) f rc (mhz) 359 8151h?avr?02/11 atmega128a figure 28-44. 8mhz rc oscillator fre quency vs. osccal value 28.11 current consumption of peripheral units figure 28-45. brownout detector current vs. v cc 8 5 c 25 c -40 c 0 2 4 6 8 10 12 14 16 016 3 24 8 64 8 09611212 8 144 160 176 192 20 8 224 240 256 o s ccal (x1) f rc (mhz) 8 5 c 25 c -40 c 0 5 10 15 20 2.5 33 .5 4 4.5 5 5.5 v cc (v) i cc ( u a) 360 8151h?avr?02/11 atmega128a figure 28-46. adc current vs. av cc (adc at 50khz) figure 28-47. adc current vs. av cc (adc at 1mhz) 8 5 c 25 c -40 c 0 100 200 300 400 500 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc ( u a) 8 5 c 25 c -40 c 0 50 100 150 200 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) i cc ( u a) 361 8151h?avr?02/11 atmega128a figure 28-48. analog comparator current vs. v cc figure 28-49. programming current vs. v cc 8 5 c 25 c -40 c 0 10 20 3 0 40 50 60 70 8 0 2.5 33 .5 4 4.5 5 5.5 v (v) i cc ( u a) cc 8 5 c 25 c -40 c 0 1 2 3 4 5 6 7 8 9 2.5 33 .5 4 4.5 5 5.5 v cc (v) i cc (ma) 362 8151h?avr?02/11 atmega128a 28.12 current consumption in r eset and reset pulse width figure 28-50. reset supply current vs. v cc (0.1mhz - 1.0mhz, excluding current through the reset pull-up) figure 28-51. reset supply current vs. v cc (1mhz - 20mhz, excluding current through the reset pull-up) 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 0 0.5 1 1.5 2 2.5 3 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fre qu ency (mhz) i cc (ma) 0 2 4 6 8 10 12 14 16 1 8 0246 8 10 12 14 16 fre qu ency (mhz) i cc (ma) 2.7v 3.3v 4.0v 4.5v 5.0v 5.5v 363 8151h?avr?02/11 atmega128a figure 28-52. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 5.0v) figure 28-53. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 2.7v) 25 c 0 20 40 60 8 0 100 0123456 v reset ( v ) i reset ( u a) - 40 c 8 5 c 8 5 c 25 c -40 c 0 10 20 30 40 50 60 0 0.5 1 1.5 2 2.5 3 v reset ( v ) i reset ( u a) 364 8151h?avr?02/11 atmega128a figure 28-54. reset input threshold voltage vs. v cc (vih, reset pin read as ?1?) figure 28-55. reset input threshold voltage vs. v cc (vil, reset pin read as ?0?) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) threshold ( v ) 8 5 c 25 c -40 c 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) threshold ( v ) 365 8151h?avr?02/11 atmega128a figure 28-56. reset input pin hysteresis vs. v cc figure 28-57. reset pulse width vs. v cc (external clock, 1mhz) 8 5 c 25 c -40 c 0 0.1 0.2 0. 3 0.4 0.5 2.5 33 .5 4 4.5 5 5.5 v cc (v) inp u t hy s tere s i s (mv) 25 c 0 100 200 300 400 500 600 700 8 00 900 2.5 3 3.5 4 4.5 5 5.5 v cc ( v ) p u lse w idth (ns) 366 8151h?avr?02/11 atmega128a 29. register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page ($ff) reserved ? ? ? ? ? ? ? ? : reserved ? ? ? ? ? ? ? ? ($9e) reserved ? ? ? ? ? ? ? ? ($9d) ucsr1c ? umsel1 upm11 upm10 usbs1 ucsz11 ucsz10 ucpol1 195 ($9c) udr1 usart1 i/o data register 192 ($9b) ucsr1a rxc1 txc1 udre1 f e1 dor1 upe1 u2x1 mpcm1 193 ($9a) ucsr1b rxcie1 txcie1 udrie1 rxen1 txen1 ucsz12 rxb81 txb81 194 ($99) ubrr1l usart1 baud rate register low 197 ($98) ubrr1h ? ? ? ? usart1 baud rate register high 197 ($97) reserved ? ? ? ? ? ? ? ? ($96) reserved ? ? ? ? ? ? ? ? ($95) ucsr0c ? umsel0 upm01 upm00 usbs0 ucsz01 ucsz00 ucpol0 195 ($94) reserved ? ? ? ? ? ? ? ? ($93) reserved ? ? ? ? ? ? ? ? ($92) reserved ? ? ? ? ? ? ? ? ($91) reserved ? ? ? ? ? ? ? ? ($90) ubrr0h ? ? ? ? usart0 baud rate register high 197 ($8f) reserved ? ? ? ? ? ? ? ? ($8e) reserved ? ? ? ? ? ? ? ? ($8d) reserved ? ? ? ? ? ? ? ? ($8c) tccr3c foc3a foc3b foc3c ? ? ? ? ? 138 ($8b) tccr3a com3a1 com3a0 com3b1 com3b0 com3c1 com3c0 wgm31 wgm30 134 ($8a) tccr3b icnc3 ices3 ? wgm33 wgm32 cs32 cs31 cs30 137 ($89) tcnt3h timer/counter3 ? counter register high byte 139 ($88) tcnt3l timer/counter3 ? counter register low byte 139 ($87) ocr3ah timer/counter3 ? output compare register a high byte 140 ($86) ocr3al timer/counter3 ? output compare register a low byte 140 ($85) ocr3bh timer/counter3 ? output compare register b high byte 140 ($84) ocr3bl timer/counter3 ? output compare register b low byte 140 ($83) ocr3ch timer/counter3 ? output compare register c high byte 140 ($82) ocr3cl timer/counter3 ? output compare register c low byte 140 ($81) icr3h timer/counter3 ? input capture register high byte 141 ($80) icr3l timer/counter3 ? input capture register low byte 141 ($7f) reserved ? ? ? ? ? ? ? ? ($7e) reserved ? ? ? ? ? ? ? ? ($7d) etimsk ? ? ticie3 ocie3a ocie3b toie3 ocie3c ocie1c 142 ($7c) etifr ? ? icf3 ocf3a ocf3b tov3 ocf3c ocf1c 143 ($7b) reserved ? ? ? ? ? ? ? ? ($7a) tccr1c foc1a foc1b foc1c ? ? ? ? ? 138 ($79) ocr1ch timer/counter1 ? output compare register c high byte 140 ($78) ocr1cl timer/counter1 ? output compare register c low byte 140 ($77) reserved ? ? ? ? ? ? ? ? ($76) reserved ? ? ? ? ? ? ? ? ($75) reserved ? ? ? ? ? ? ? ? ($74) twcr twint twea twsta twsto twwc twen ? twie 226 ($73) twdr two-wire serial interface data register 228 ($72) twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce 229 ($71) twsr tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 228 ($70) twbr two-wire serial interface bit rate register 226 ($6f) osccal oscillator calibration register 44 ($6e) reserved ? ? ? ? ? ? ? ? ($6d) xmcra ? srl2 srl1 srl0 srw01 srw00 srw11 34 ($6c) xmcrb xmbk ? ? ? ? xmm2 xmm1 xmm0 35 ($6b) reserved ? ? ? ? ? ? ? ? ($6a) eicra isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 90 ($69) reserved ? ? ? ? ? ? ? ? ($68) spmcsr spmie rwwsb ? rwwsre blbset pgwrt pgers spmen 289 ($67) reserved ? ? ? ? ? ? ? ? ($66) reserved ? ? ? ? ? ? ? ? ($65) portg ? ? ? portg4 portg3 portg2 portg1 portg0 89 ($64) ddrg ? ? ? ddg4 ddg3 ddg2 ddg1 ddg0 89 ($63) ping ? ? ? ping4 ping3 ping2 ping1 ping0 89 367 8151h?avr?02/11 atmega128a ($62) portf portf7 portf6 portf5 po rtf4 portf3 portf2 portf1 portf0 89 ($61) ddrf ddf7 ddf6 ddf5 ddf4 ddf3 ddf2 ddf1 ddf0 89 ($60) reserved ? ? ? ? ? ? ? ? $3f ($5f) sreg i t h s v n z c 10 $3e ($5e) sph sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 13 $3d ($5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 13 $3c ($5c) xdiv xdiven xdiv6 xdiv5 xdiv4 xdiv3 xdiv2 xdiv1 xdiv0 38 $3b ($5b) rampz ? ? ? ? ? ? ? rampz0 14 $3a ($5a) eicrb isc71 isc70 isc61 isc60 isc51 isc50 isc41 isc40 91 $39 ($59) eimsk int7 int6 int5 int4 int3 int2 int1 int0 92 $38 ($58) eifr intf7 intf6 intf5 intf4 intf3 intf intf1 intf0 92 $37 ($57) timsk ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 110, 141, 162 $36 ($56) tifr ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 110, 143, 162 $35 ($55) mcucr sre srw10 se sm1 sm0 sm2 ivsel ivce 33, 50, 63 $34 ($54) mcucsr jtd ? ? jtrf wdrf borf extrf porf 56, 257 $33 ($53) tccr0 foc0 wgm00 com01 com00 wgm01 cs02 cs01 cs00 106 $32 ($52) tcnt0 timer/counter0 (8 bit) 109 $31 ($51) ocr0 timer/counter0 output compare register 109 $30 ($50) assr ? ? ? ? as0 tcn0ub ocr0ub tcr0ub 109 $2f ($4f) tccr1a com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 wgm11 wgm10 134 $2e ($4e) tccr1b icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 137 $2d ($4d) tcnt1h timer/counter1 ? counter register high byte 139 $2c ($4c) tcnt1l timer/counter1 ? counter register low byte 139 $2b ($4b) ocr1ah timer/counter1 ? output compare register a high byte 139 $2a ($4a) ocr1al timer/counter1 ? output compare register a low byte 139 $29 ($49) ocr1bh timer/counter1 ? output compare register b high byte 139 $28 ($48) ocr1bl timer/counter1 ? output compare register b low byte 139 $27 ($47) icr1h timer/counter1 ? input capture register high byte 140 $26 ($46) icr1l timer/counter1 ? input capture register low byte 140 $25 ($45) tccr2 foc2 wgm20 com21 com20 wgm21 cs22 cs21 cs20 159 $24 ($44) tcnt2 timer/counter2 (8 bit) 161 $23 ($43) ocr2 timer/counter2 output compare register 162 $22 ($42) ocdr idrd/ocdr7 ocdr6 ocdr5 ocdr4 ocdr3 ocdr2 ocdr1 ocdr0 276 $21 ($41) wdtcr ? ? ? wdce wde wdp2 wdp1 wdp0 57 $20 ($40) sfior tsm ? ? ? acme pud psr0 psr321 86, 111, 146, 231 $1f ($3f) eearh ? ? ? ? eeprom address register high 30 $1e ($3e) eearl eeprom address register low byte 30 $1d ($3d) eedr eeprom data register 30 $1c ($3c) eecr ? ? ? ? eerie eemwe eewe eere 30 $1b ($3b) porta porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 87 $1a ($3a) ddra dda7 dda6 dda 5 dda4 dda3 dda2 dda1 dda0 87 $19 ($39) pina pina7 pina6 pina5 pina4 pina3 pina2 pina1 pina0 87 $18 ($38) portb portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 87 $17 ($37) ddrb ddb7 ddb6 ddb 5 ddb4 ddb3 ddb2 ddb1 ddb0 87 $16 ($36) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 87 $15 ($35) portc portc7 portc6 portc5 portc4 portc3 portc2 portc1 portc0 87 $14 ($34) ddrc ddc7 ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 87 $13 ($33) pinc pinc7 pinc6 pinc5 pinc4 pinc3 pinc2 pinc1 pinc0 88 $12 ($32) portd portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 88 $11 ($31) ddrd ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 88 $10 ($30) pind pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 88 $0f ($2f) spdr spi data register 173 $0e ($2e) spsr spif wcol ? ? ? ? ? spi2x 173 $0d ($2d) spcr spie spe dord mstr cpol cpha spr1 spr0 171 $0c ($2c) udr0 usart0 i/o data register 192 $0b ($2b) ucsr0a rxc0 txc0 udre0 fe0 dor0 upe0 u2x0 mpcm0 193 $0a ($2a) ucsr0b rxcie0 txcie0 udri e0 rxen0 txen0 ucsz02 rxb80 txb80 194 $09 ($29) ubrr0l usart0 baud rate register low 197 $08 ($28) acsr acd acbg aco aci acie acic acis1 acis0 231 $07 ($27) admux refs1 refs0 ad lar mux4 mux3 mux2 mux1 mux0 245 $06 ($26) adcsra aden adsc adfr adif adie adps2 adps1 adps0 247 $05 ($25) adch adc data register high byte 248 $04 ($24) adcl adc data register low byte 248 $03 ($23) porte porte7 porte6 porte5 porte4 porte3 porte2 porte1 porte0 88 29. register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page 368 8151h?avr?02/11 atmega128a notes: 1. for compatibility with future devices, reserved bits s hould be written to zero if accessed. reserved i/o memory address es should never be written. 2. some of the status flags are cleared by writing a logical o ne to them. note that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag r ead as set, thus clearing the fl ag. the cbi and sbi instruction s work with registers $00 to $1f only. $02 ($22) ddre dde7 dde6 dde 5 dde4 dde3 dde2 dde1 dde0 88 $01 ($21) pine pine7 pine6 pine5 pine4 pine3 pine2 pine1 pine0 88 $00 ($20) pinf pinf7 pinf6 pinf5 pinf4 pinf3 pinf2 pinf1 pinf0 89 29. register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page 369 8151h?avr?02/11 atmega128a 30. instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd rd ? rr z,n,v 1 andi rd, k logical and register and constant rd rd ? k z,n,v 1 or rd, rr logical or registers rd rd v rr z,n,v 1 ori rd, k logical or register and constant rd rd v k z,n,v 1 eor rd, rr exclusive or registers rd rd rr z,n,v 1 com rd one?s complement rd $ff ? rd z,c,n,v 1 neg rd two?s complement rd $00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd rd ? ($ff - k) z,n,v 1 inc rd increment rd rd + 1 z,n,v 1 dec rd decrement rd rd ? 1 z,n,v 1 tst rd test for zero or minus rd rd ? rd z,n,v 1 clr rd clear register rd rd rd z,n,v 1 ser rd set register rd $ff none 1 mul rd, rr multiply unsigned r1:r0 rd x rr z,c 2 muls rd, rr multiply signed r1:r0 rd x rr z,c 2 mulsu rd, rr multiply signed with unsigned r1:r0 rd x rr z,c 2 fmul rd, rr fractional multiply unsigned r1:r0 (rd x rr) << 1 z,c 2 fmuls rd, rr fractional multiply signed r1:r0 (rd x rr) << 1 z,c 2 fmulsu rd, rr fractional multiply signed with unsigned r1:r0 (rd x rr) << 1 z,c 2 branch instructions rjmp k relative jump pc pc + k + 1 none 2 ijmp indirect jump to (z) pc z none 2 jmp k direct jump pc knone3 rcall k relative subroutine call pc pc + k + 1 none 3 icall indirect call to (z) pc znone3 call k direct subroutine call pc knone4 ret subroutine return pc stack none 4 reti interrupt return pc stack i 4 cpse rd,rr compare, skip if equal if (rd = rr) pc pc + 2 or 3 none 1 / 2 / 3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc pc + 2 or 3 none 1 / 2 / 3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc pc + 2 or 3 none 1 / 2 / 3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 none 1 / 2 / 3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 none 1 / 2 / 3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 none 1 / 2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 none 1 / 2 breq k branch if equal if (z = 1) then pc pc + k + 1 none 1 / 2 brne k branch if not equal if (z = 0) then pc pc + k + 1 none 1 / 2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 none 1 / 2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 none 1 / 2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 none 1 / 2 brlo k branch if lower if (c = 1) then pc pc + k + 1 none 1 / 2 brmi k branch if minus if (n = 1) then pc pc + k + 1 none 1 / 2 brpl k branch if plus if (n = 0) then pc pc + k + 1 none 1 / 2 brge k branch if greater or equal, signed if (n v= 0) then pc pc + k + 1 none 1 / 2 brlt k branch if less than zero, signed if (n v= 1) then pc pc + k + 1 none 1 / 2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 none 1 / 2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 none 1 / 2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 none 1 / 2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 none 1 / 2 370 8151h?avr?02/11 atmega128a brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 none 1 / 2 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 none 1 / 2 mnemonics operands description operation flags #clocks brie k branch if interrupt enabled if ( i = 1) then pc pc + k + 1 none 1 / 2 brid k branch if interrupt disabled if ( i = 0) then pc pc + k + 1 none 1 / 2 data transfer instructions mov rd, rr move between registers rd rr none 1 movw rd, rr copy register word rd+1:rd rr+1:rr none 1 ldi rd, k load immediate rd knone1 ld rd, x load indirect rd (x) none 2 ld rd, x+ load indirect and post-inc. rd (x), x x + 1 none 2 ld rd, - x load indirect and pre-dec. x x - 1, rd (x) none 2 ld rd, y load indirect rd (y) none 2 ld rd, y+ load indirect and post-inc. rd (y), y y + 1 none 2 ld rd, - y load indirect and pre-dec. y y - 1, rd (y) none 2 ldd rd,y+q load indirect with displacement rd (y + q) none 2 ld rd, z load indirect rd (z) none 2 ld rd, z+ load indirect and post-inc. rd (z), z z+1 none 2 ld rd, -z load indirect and pre-dec. z z - 1, rd (z) none 2 ldd rd, z+q load indirect with displacement rd (z + q) none 2 lds rd, k load direct from sram rd (k) none 2 st x, rr store indirect (x) rr none 2 st x+, rr store indirect and post-inc. (x) rr, x x + 1 none 2 st - x, rr store indirect and pre-dec. x x - 1, (x) rr none 2 st y, rr store indirect (y) rr none 2 st y+, rr store indirect and post-inc. (y) rr, y y + 1 none 2 st - y, rr store indirect and pre-dec. y y - 1, (y) rr none 2 std y+q,rr store indirect with displacement (y + q) rr none 2 st z, rr store indirect (z) rr none 2 st z+, rr store indirect and post-inc. (z) rr, z z + 1 none 2 st -z, rr store indirect and pre-dec. z z - 1, (z) rr none 2 std z+q,rr store indirect with displacement (z + q) rr none 2 sts k, rr store direct to sram (k) rr none 2 lpm load program memory r0 (z) none 3 lpm rd, z load program memory rd (z) none 3 lpm rd, z+ load program memory and post-inc rd (z), z z+1 none 3 elpm extended load program memory r0 (rampz:z) none 3 elpm rd, z extended load program memory rd (rampz:z) none 3 elpm rd, z+ extended load program memory and post-inc rd (rampz:z), rampz:z rampz:z+1 none 3 spm store program memory (z) r1:r0 none - in rd, p in port rd pnone1 out p, rr out port p rr none 1 push rr push register on stack stack rr none 2 pop rd pop register from stack rd stack none 2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) 1none2 cbi p,b clear bit in i/o register i/o(p,b) 0none2 lsl rd logical shift left rd(n+1) rd(n), rd(0) 0 z,c,n,v 1 lsr rd logical shift right rd(n) rd(n+1), rd(7) 0 z,c,n,v 1 rol rd rotate left through carry rd(0) c,rd(n+1) rd(n),c rd(7) z,c,n,v 1 ror rd rotate right through carry rd(7) c,rd(n) rd(n+1),c rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) rd(n+1), n=0:6 z,c,n,v 1 swap rd swap nibbles rd(3:0) rd(7:4),rd(7:4) rd(3:0) none 1 bset s flag set sreg(s) 1 sreg(s) 1 bclr s flag clear sreg(s) 0 sreg(s) 1 bst rr, b bit store from register to t t rr(b) t 1 bld rd, b bit load from t to register rd(b) tnone1 sec set carry c 1c1 clc clear carry c 0 c 1 sen set negative flag n 1n1 cln clear negative flag n 0 n 1 sez set zero flag z 1z1 clz clear ze ro flag z 0 z 1 sei global interrupt enable i 1i1 cli global interrupt disable i 0 i 1 30. instruction set summary (continued) 371 8151h?avr?02/11 atmega128a ses set signed test flag s 1s1 cls clear signed test flag s 0 s 1 mnemonics operands description operation flags #clocks sev set twos complement overflow. v 1v1 clv clear twos complement overflow v 0 v 1 set set t in sreg t 1t1 clt clear t in sreg t 0 t 1 seh set half carry flag in sreg h 1h1 clh clear half carry flag in sreg h 0 h 1 mcu control instructions nop no operation none 1 sleep sleep (see specific descr. for sleep function) none 1 wdr watchdog reset (see specific descr. for wdr/timer) none 1 break break for on-chip debug only none n/a 30. instruction set summary (continued) 372 8151h?avr?02/11 atmega128a 31. ordering information 31.1 atmega128a notes: 1. the device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. pb-free packaging complies to the european directive for re striction of hazardous substances (rohs directive). also halide free and fully green. 3. tape & reel speed (mhz) power supply ordering code (2) package (1) operation range 16 2.7v - 5.5v atmega128a-au atmega128a-aur (3) atmega128a-mu atmega128a-mur (3) 64a 64a 64m1 64m1 industrial (-40 o c to 85 o c) package type 64a 64-lead, 14 14 1.0 mm, thin prof ile plastic quad flat package (tqfp) 64m1 64-pad, 9 9 1.0 mm, quad flat no -lead/micro lead frame package (qfn/mlf) 373 8151h?avr?02/11 atmega128a 32. packaging information 32.1 64a 2 3 25 orch a rd p a rkw a y sa n jo s e, ca 951 3 1 title drawing no. r rev. 64a, 64-le a d, 14 x 14 mm body s ize, 1.0 mm body thickne ss , 0. 8 mm le a d pitch, thin profile pl as tic q ua d fl a t p a ck a ge (tqfp) c 64a 2010-10-20 pin 1 identifier 0~7 pin 1 l c a1 a2 a d1 d e e1 e b common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note note s : 1.thi s p a ck a ge conform s to jedec reference m s -026, v a ri a tion aeb. 2. dimen s ion s d1 a nd e1 do not incl u de mold protr us ion. allow ab le protr us ion i s 0.25 mm per s ide. dimen s ion s d1 a nd e1 a re m a xim u m pl as tic b ody s ize dimen s ion s incl u ding mold mi s m a tch. 3 . le a d copl a n a rity i s 0.10 mm m a xim u m. a ? ? 1.20 a1 0.05 ? 0.15 a2 0.95 1.00 1.05 d 15.75 16.00 16.25 d1 1 3 .90 14.00 14.10 note 2 e 15.75 16.00 16.25 e1 1 3 .90 14.00 14.10 note 2 b 0. 3 0 ? 0.45 c 0.09 ? 0.20 l 0.45 ? 0.75 e 0. 8 0 typ 374 8151h?avr?02/11 atmega128a 32.2 64m1 2 3 25 orch a rd p a rkw a y sa n jo s e, ca 951 3 1 title drawing no. r rev. 64m1 , 64-p a d, 9 x 9 x 1.0 mm body, le a d pitch 0.50 mm, h 64m1 2010-10-19 common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note a 0. 8 0 0.90 1.00 a1 ? 0.02 0.05 b 0.1 8 0.25 0. 3 0 d d2 5.20 5.40 5.60 8 .90 9.00 9.10 8 .90 9.00 9.10 e e2 5.20 5.40 5.60 e 0.50 b s c l0. 3 5 0.40 0.45 note s : 1. jedec s t a nd a rd mo-220, ( s aw s ing u l a tion) fig. 1, vmmd. 2. dimen s ion a nd toler a nce conform to a s mey14.5m-1994. top view s ide view bottom view d e m a rked pin# 1 id s eating plane a1 c a c 0.0 8 1 2 3 k 1.25 1.40 1.55 e2 d2 b e pin #1 corner l pin #1 tr i a ngle pin #1 ch a mfer (c 0. 3 0) option a option b pin #1 notch (0.20 r) option c k k 5.40 mm expo s ed p a d, micro le a d fr a me p a ck a ge (mlf) 375 8151h?avr?02/11 atmega128a 33. errata the revision letter in this section refers to the revision of the atmega128a device. 33.1 atmega128a rev. u ? first analog comparator conversion may be delayed ? interrupts may be lost when writing the timer registers in the asynchronous timer ? stabilizing time needed wh en changing xdiv register ? stabilizing time n eeded when changing osccal register ? idcode masks data from tdi input ? reading eeprom by using st or sts to set eer e bit triggers unexp ected interr upt request 1. first analog comparator conversion may be delayed if the device is powered by a slow rising v cc , the first analog comparator conversion will take longer than expected on some devices. problem fix/workaround when the device has been powered or reset, disable then enable the analog comparator before the first conversion. 2. interrupts may be lost when writing the timer registers in the asynchronous timer the interrupt will be lo st if a timer register that is synchr onous timer clock is written when the asynchronous timer/counter register (tcntx) is 0x00. problem fix/workaround always check that the asynchronous timer/counter register neither have the value 0xff nor 0x00 before writing to the asynchronous timer control register (tccrx), asynchronous timer counter register (tcntx), or asynchronous output compare register (ocrx). 3. stabilizing time needed when changing xdiv register after increasing the source clock frequency more than 2% with settings in the xdiv register, the device may execute some of the subsequent instructions incorrectly. problem fix / workaround the nop instruction will always be executed correctly also right after a frequency change. thus, the next 8 instructions after the change s hould be nop instructions. to ensure this, follow this procedure: 1.clear the i bit in the sreg register. 2.set the new pre-scaling factor in xdiv register. 3.execute 8 nop instructions 4.set the i bit in sreg this will ensure that all subsequent instructions will execute correctly. assembly code example: cli ; clear global interrupt enable out xdiv, temp ; set new prescale value nop ; no operation nop ; no operation nop ; no operation nop ; no operation 376 8151h?avr?02/11 atmega128a nop ; no operation nop ; no operation nop ; no operation nop ; no operation sei ; set global interrupt enable 4. stabilizing time needed when changing osccal register after increasing the source clock frequency more than 2% with settings in the osccal reg- ister, the device may execute some of the subsequent instructions incorrectly. problem fix / workaround the behavior follows errata number 3., and the same fix / workaround is applicable on this errata. 5. idcode masks data from tdi input the jtag instruction idcode is not working correctly. data to succeeding devices are replaced by all-ones during update-dr. problem fix / workaround ? if atmega128a is the only device in the scan chain, the problem is not visible. ? select the device id register of the atmega128a by issuing the idcode instruction or by entering the test-logic-reset state of the tap controller to read out the contents of its device id register an d possibly data from succeeding devices of the scan chain. issue the bypass instruct ion to the atmega128 a while reading the device id registers of preceding devices of the boundary scan chain. ? if the device ids of all devices in the boundary scan chain must be captured simultaneously, the atmega128a must be the fist device in the chain. 6. reading eeprom by using st or sts to set eere bit triggers unexpected interrupt request. reading eeprom by using the st or sts command to set th e eere bit in the eecr reg- ister triggers an unexpecte d eeprom interrupt request. problem fix / workaround always use out or sbi to set eere in eecr. 377 8151h?avr?02/11 atmega128a 34. datasheet revision history please note that the referring page numbers in th is section are referred to this document. the referring revision in this section are referring to the document revision. 34.1 rev. 8151h ? 02/11 34.2 rev. 8151g ? 07/10 34.3 rev. 8151f ? 06/10 34.4 rev. 8151e ? 02/10 34.5 rev. 8151d ? 07/09 1. editing update according to the atmel new styl e guide. no more space betweeen the numbers and their units. 2. updated the last page. 1. updated the table note of table 27-3 on page 324 . the test is performed using bodlevel=0 and bodlevel=1 1. inserted cross reference in ?minimizing power consumption? on page 48 2. updated technical terminology according to atmel standard 3. note 6 and note 7 below ?two-wire serial bus requirements? on page 325 have been removed 4. the text in ?bit 6 ? txcien: tx complete interrupt enable? on page 194 has been corrected by adding an ?n? 1. updated ?receiving frames with 9 data bits? on page 185 . the c code updated. 2. updated ?packaging information? on page 374 . 3. updated ?performing page erase by spm? on page 283 . 1. updated ?errata? on page 376 . 2. updated the last page with atmel?s new addresses. 378 8151h?avr?02/11 atmega128a 34.6 rev. 8151c ? 05/09 34.7 rev. 8151b ? 03/09 34.8 rev. 8151a ? 08/08 1. updated ?errata? on page 376 . atmega128a rev. u. 1. updated view of ?typical characteristics? on page 338 . 2. editorial updates. 1. initial revision. (based on the at mega128/l datasheet 2467r-avr-06/08) changes done compared to the atmega128/l datasheet 2467r-avr-06/08: - updated ?stack pointer? on page 13 description. - ?power management and sleep modes? on page 46 is reorganized. - all electrical characteristics is moved to ?electrical characteristics? on page 321 . - output low voltage (v ol ) and reset pull-up resistor (r rst ) limits updated in ?dc characteristics? on page 321 . - register descriptions are moved to sub sections at the end of each chapter. - new graphics in ?typical characteristics? on page 338 . - new ?ordering information? on page 373 . i 8151h?avr?02/11 atmega128a table of contents 1 pin configurations ..... ................ ................. ................ ................. ............ 2 2 overview ............ ................ ................ ............... .............. .............. ............ 2 2.1 block diagram ...................................................................................................3 2.2 atmega103 and at mega128a compatibility ...................................................4 2.3 pin descriptions .................................................................................................5 3 resources .............. .............. .............. ............... .............. .............. ............ 8 4 data retention .......... ................ ................ ................. ................ ............... 8 5 about code examples ........ .............. ............... .............. .............. ............ 8 6 avr cpu core .......... ................ ................ ................. ................ ............... 9 6.1 introduction ........................................................................................................9 6.2 architectural overview .......................................................................................9 6.3 alu ? arithmetic logic unit .............................................................................10 6.4 status register ................................................................................................10 6.5 general purpose register file ........................................................................11 6.6 stack pointer ...................................................................................................13 6.7 instruction execution timing ...........................................................................14 6.8 reset and interrupt handling ...........................................................................15 7 memories ............... .............. .............. ............... .............. .............. .......... 18 7.1 in-system reprogrammable flash program memory .....................................18 7.2 sram data memory ........................................................................................19 7.3 eeprom data memory . ................. ................ ............. ............ ............. ..........21 7.4 i/o memory ......................................................................................................22 7.5 external memory interface ..............................................................................22 7.6 register description ........................................................................................30 8 system clock and clock options ................ ................. .............. .......... 37 8.1 clock systems and their distribution ...............................................................37 8.2 clock sources .................................................................................................39 8.3 default clock source .......................................................................................39 8.4 crystal oscillator .............................................................................................39 8.5 low-frequency crystal oscillator .....................................................................41 8.6 external rc oscillator .....................................................................................41 8.7 calibrated internal rc oscillator .....................................................................42 ii 8151h?avr?02/11 atmega128a 8.8 external clock .................................................................................................43 8.9 timer/counter oscillator ..................................................................................44 8.10 register description ........................................................................................44 9 power management and sleep mo des ............... .............. ............ ........ 46 9.1 overview ..........................................................................................................46 9.2 sleep modes ....................................................................................................46 9.3 idle mode .........................................................................................................47 9.4 adc noise reduction mode ............................................................................47 9.5 power-down mode ...........................................................................................47 9.6 power-save mode ............................................................................................47 9.7 standby mode .................................................................................................48 9.8 extended standby mode .................................................................................48 9.9 minimizing power consumption ......................................................................48 9.10 register description ........................................................................................50 10 system control and reset .... .............. .............. .............. .............. ........ 51 10.1 resetting the avr ...........................................................................................51 10.2 reset sources .................................................................................................51 10.3 internal voltage reference ..............................................................................54 10.4 watchdog timer ..............................................................................................55 10.5 timed sequences for changing the configuration of the watchdog timer ....55 10.6 register description ........................................................................................56 11 interrupts ............... .............. .............. ............... .............. .............. .......... 59 11.1 interrupt vectors in atmega128a ...................................................................59 11.2 register description ........................................................................................63 12 i/o ports ............... ................ .............. ............... .............. .............. .......... 65 12.1 introduction ......................................................................................................65 12.2 ports as general digital i/o .............................................................................66 12.3 alternate port functions ..................................................................................71 12.4 register description ........................................................................................86 13 external interrupts .......... ................ ................. .............. .............. .......... 90 13.1 register description ........................................................................................90 14 8-bit timer/counter0 with pwm and asynchronous operation ........ 93 14.1 features ..........................................................................................................93 14.2 overview ..........................................................................................................93 iii 8151h?avr?02/11 atmega128a 14.3 timer/counter clock sources .........................................................................94 14.4 counter unit ....................................................................................................94 14.5 output compare unit .......................................................................................95 14.6 compare match output unit ............................................................................97 14.7 modes of operation .........................................................................................98 14.8 timer/counter timing diagrams ...................................................................102 14.9 asynchronous operation of timer/counter0 .................................................104 14.10 timer/counter prescaler ...............................................................................106 14.11 register description ......................................................................................106 15 16-bit timer/counter (timer/counte r1 and timer/counter3) ........... 112 15.1 features ........................................................................................................112 15.2 overview ........................................................................................................112 15.3 accessing 16-bit registers ............................................................................115 15.4 timer/counter clock sources .......................................................................118 15.5 counter unit ..................................................................................................118 15.6 input capture unit .........................................................................................120 15.7 output compare units ...................................................................................122 15.8 compare match output unit ..........................................................................124 15.9 modes of operation .......................................................................................125 15.10 timer/counter timing diagrams ...................................................................132 15.11 register description ......................................................................................134 16 timer/counter3, timer/counter2, and timer/counter1 prescalers . 145 16.1 internal clock source ....................................................................................145 16.2 prescaler reset .............................................................................................145 16.3 external clock source ...................................................................................145 16.4 register description ......................................................................................146 17 8-bit timer/counter2 with pwm ................... .............. .............. ........... 148 17.1 features ........................................................................................................148 17.2 overview ........................................................................................................148 17.3 timer/counter clock sources .......................................................................149 17.4 counter unit ..................................................................................................149 17.5 output compare unit .....................................................................................150 17.6 compare match output unit ..........................................................................152 17.7 modes of operation .......................................................................................153 17.8 timer/counter timing diagrams ...................................................................157 iv 8151h?avr?02/11 atmega128a 17.9 register description ......................................................................................159 18 output compare modulator (ocm1c2) .......... .............. .............. ........ 163 18.1 overview ........................................................................................................163 18.2 description .....................................................................................................163 19 serial peripheral interface ? spi ................ ................ .............. ........... 165 19.1 features ........................................................................................................165 19.2 overview ........................................................................................................165 19.3 ss pin functionality ......................................................................................170 19.4 data modes ...................................................................................................170 19.5 register description ......................................................................................171 20 usart ............. ................. ................ .............. .............. .............. ........... 174 20.1 features ........................................................................................................174 20.2 overview ........................................................................................................174 20.3 clock generation ...........................................................................................176 20.4 frame formats ..............................................................................................179 20.5 usart initialization .......................................................................................180 20.6 data transmission ? the usart transmitter ..............................................181 20.7 data reception ? the usart receiver .......................................................184 20.8 multi-processor communication mode ..........................................................191 20.9 register description ......................................................................................192 20.10 examples of baud rate setting .....................................................................198 21 two-wire serial interface .. .............. .............. .............. .............. ........... 201 21.1 features ........................................................................................................201 21.2 two-wire serial interface bus definition ........................................................201 21.3 data transfer and frame format ..................................................................202 21.4 multi-master bus systems, arbitration and synchronization .........................205 21.5 overview of the twi module .........................................................................206 21.6 using the twi ................................................................................................209 21.7 transmission modes .....................................................................................212 21.8 multi-master systems and arbitration ............................................................225 21.9 register description ......................................................................................226 22 analog comparator .......... .............. .............. .............. .............. ........... 230 22.1 overview ........................................................................................................230 22.2 analog comparator multiplexed input ...........................................................230 v 8151h?avr?02/11 atmega128a 22.3 register description ......................................................................................231 23 analog to digital converter ............. ............... .............. .............. ........ 233 23.1 features ........................................................................................................233 23.2 overview ........................................................................................................233 23.3 operation .......................................................................................................234 23.4 starting a conversion ....................................................................................235 23.5 prescaling and conversion timing ................................................................236 23.6 changing channel or reference selection ...................................................238 23.7 adc noise canceler .....................................................................................239 23.8 adc conversion result .................................................................................243 23.9 register description ......................................................................................245 24 jtag interface and on-chi p debug system ............ .............. ........... 250 24.1 features ........................................................................................................250 24.2 overview ........................................................................................................250 24.3 tap ? test access port ................................................................................251 24.4 tap controller ...............................................................................................252 24.5 using the boundary-scan chain ....................................................................253 24.6 using the on-chip debug system .................................................................253 24.7 on-chip debug specific jtag instructions ...................................................254 24.8 using the jtag programming capabilitie s ...................................................255 24.9 bibliography ...................................................................................................255 24.10 ieee 1149.1 (jtag) boundary-scan .............................................................255 24.11 data registers ...............................................................................................256 24.12 boundary-scan specific jtag instructions ...................................................258 24.13 boundary-scan chain ....................................................................................259 24.14 atmega128a boundary-scan order .............................................................269 24.15 boundary-scan description language files ..................................................276 24.16 register description ......................................................................................276 25 boot loader support ? read-while-wri te self-programming ......... 277 25.1 features ........................................................................................................277 25.2 overview ........................................................................................................277 25.3 application and boot loader flash sections .................................................277 25.4 read-while-write and no read-while-write flash sections ........................278 25.5 boot loader lock bits ...................................................................................280 25.6 entering the boot loader program ................................................................281 vi 8151h?avr?02/11 atmega128a 25.7 addressing the flash during self-programming ...........................................282 25.8 self-programming the flash ..........................................................................283 25.9 register description ......................................................................................289 26 memory programming ........ .............. ............... .............. .............. ........ 291 26.1 program and data memory lock bits ............................................................291 26.2 fuse bits ........................................................................................................292 26.3 signature bytes .............................................................................................294 26.4 calibration byte .............................................................................................294 26.5 parallel programming parameters, pin mapping, and commands ...............294 26.6 parallel programming ....................................................................................296 26.7 serial downloading ........................................................................................303 26.8 spi serial programming pin mapping ...........................................................304 26.9 programming via the jtag interface ............................................................308 27 electrical characteristics ... .............. ............... .............. .............. ........ 320 27.1 absolute maximum ratings* .........................................................................320 27.2 dc characteristics .........................................................................................320 27.3 speed grades ...............................................................................................322 27.4 clock characteristics .....................................................................................322 27.5 system and reset characteristics ................................................................323 27.6 two-wire serial interface characteristics ......................................................324 27.7 parallel programming characteristics ...........................................................325 27.8 spi timing characteristics ............................................................................327 27.9 adc characteristics ......................................................................................329 27.10 external data memory timing .......................................................................331 28 typical characteristics ....... .............. ............... .............. .............. ........ 337 28.1 active supply current ....................................................................................337 28.2 idle supply current ........................................................................................341 28.3 power-down supply current ..........................................................................344 28.4 power-save supply current ...........................................................................345 28.5 standby supply current ................................................................................346 28.6 pin pull-up .....................................................................................................347 28.7 pin driver strength ........................................................................................348 28.8 pin thresholds and hysteresis ......................................................................350 28.9 bod thresholds and analog comparator offset ..........................................351 28.10 internal oscillator speed ...............................................................................353 vii 8151h?avr?02/11 atmega128a 28.11 current consumption of peripheral units ......................................................359 28.12 current consumption in reset and reset pulse width .................................362 29 register summary ............ .............. .............. .............. .............. ........... 366 30 instruction set summary ... .............. ............... .............. .............. ........ 369 31 ordering information .......... .............. ............... .............. .............. ........ 372 31.1 atmega128a .................................................................................................372 32 packaging information .......... ................ ................. ................ ............. 373 32.1 64a ................................................................................................................373 32.2 64m1 ..............................................................................................................374 33 errata ........... ................ ................ ................. ................ .............. ........... 375 33.1 atmega128a rev. u .....................................................................................375 34 datasheet revision history .. ................ ................. ................ ............. 377 34.1 rev. 8151h ? 02/11 .......................................................................................377 34.2 rev. 8151g ? 07/10 ......................................................................................377 34.3 rev. 8151f ? 06/10 .......................................................................................377 34.4 rev. 8151e ? 02/10 .......................................................................................377 34.5 rev. 8151d ? 07/09 .......................................................................................377 34.6 rev. 8151c ? 05/09 .......................................................................................378 34.7 rev. 8151b ? 03/09 .......................................................................................378 34.8 rev. 8151a ? 08/08 .......................................................................................378 table of contents.......... ................. ................ ................. ................ ........... i 8151h?avr?02/11 atmel corporation 2325 orchard parkway san jose, ca 95131 usa tel : (+1)(408) 441-0311 fax : (+1)(408) 487-2600 www.atmel.com atmel asia limited unit 1-5 & 16, 19/f bea tower, millennium city 5 418 kwun tong road kwun tong, kowloon hong kong tel : (+852) 2245-6100 fax : (+852) 2722-1369 atmel munich gmbh business campus parkring 4 d-85748 garching b. munich germany tel : (+49) 89-31970-0 fax : (+49) 89-3194621 atmel japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel : (+81)(3) 3523-3551 fax : (+81)(3) 3523-7581 ? 2011 atmel corporation. all rights reserved. / rev. corp0xxxx atmel ? , atmel logo and combinations thereof, avr ? , avr studio ? , and others are registered trademarks or trademarks of atmel cor- poration or its subsidiaries. windows ? and others are registered trademarks of microsoft corporation in u.s. and or other countries. other terms and product names may be trademarks of others. disclaimer: the information in this document is provided in connection wi th atmel products. no license, ex press or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in the atmel terms and conditions of sales located on the atmel website, atmel assumes no liability whatsoever and disclaims any express, implied or statutory warranty relating to its pro ducts including, but not limited to, the implied warranty of merchantability, fitness for a particular purp ose, or non-infringement. in no even t shall atmel be liable for any direct, indirect, consequential, punitive, special or incidental damages (including, without limitati on, damages for loss and prof- its, business interruption, or loss of information) arising out of the use or inability to use this document, even if atmel has been advised of the possibility of such damages. atmel makes no representations or warranties with respect to the accuracy or com- pleteness of the contents of th is document and reserves the right to make changes to specifications and product descriptions at any time without notice. atmel does not make any commitment to update the information cont ained herein. unless specifically provided otherwise, atmel pr oducts are not suit- able for, and shall not be used in, automotive applications. atme l products are not intended, authorized, or warranted for use as components in applica- tions intended to support or sustain life. |
Price & Availability of ATMELCORP-AT572D940HF-CL
![]() |
|
|
All Rights Reserved © IC-ON-LINE 2003 - 2022 |
[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy] |
Mirror Sites : [www.datasheet.hk]
[www.maxim4u.com] [www.ic-on-line.cn]
[www.ic-on-line.com] [www.ic-on-line.net]
[www.alldatasheet.com.cn]
[www.gdcy.com]
[www.gdcy.net] |