Part Number Hot Search : 
NTE30109 BU2508DW P1014 A5800751 2SD60 LRD5R1FP MLL4616 MP3384EQ
Product Description
Full Text Search
 

To Download ATTINY167-A15XZ Datasheet File

  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 ? 123 powerful instructions ? most single clock cycle execution ? 32 x 8 general purpose working registers ? fully static operation ? non-volatile program and data memories ? 8k/16k byte of in-system progra mmable (isp) program memory flash endurance: 10,000 write/erase cycles ? 512 bytes in-system programmable eeprom endurance: 100,000 write/erase cycles ? 512 bytes internal sram ? programming lock for self-program ming flash program and eeprom data security ? low size lin/uart software in-system programmable ? peripheral features ? lin 2.1 and 1.3 controller or 8-bit uart (lin 2.1 certified) ? 8-bit asynchronous timer/counter0: . 10-bit clock prescaler . 1 output compare or 8-bit pwm channel ? 16-bit synchronous timer/counter1: . 10-bit clock prescaler . external event counter . 2 output compares units or 16-bit pwm channels each driving up to 4 ouput pins ? master/slave spi serial interface, ? universal serial interface (usi) with st art condition detector (master/slave spi, twi, ...) ? 10-bit adc: . 11 single ended channels . 8 differential adc channel pairs wi th programmable gain (8x or 20x) ? on-chip analog comparator with selectable voltage reference ? 100a 10% current source (lin node identification) ? on-chip temperature sensor ? programmable watchdog timer with separate on-chip oscillator ? special microcontroller features ? dynamic clock switching (external/internal rc/watchdog clock) for power control, emc reduction ? debugwire on-chip debug (ocd) system ? hardware in-system programmable (isp) via spi port ? external and internal interrupt sources ? interrupt and wake-up on pin change ? low power idle, adc noise reduction, and power-down modes ? enhanced power-on reset circuit ? programmable brown-out detection circuit ? internal calibrated rc oscillator 8mhz ? 4-16 mhz and 32 khz crystal/ceramic resonator oscillators ? i/o and packages ? 16 programmable i/o lines ? 20-pin soic, 32-pad qfn and 20-pin tssop ? operating voltage: ? 2.7 - 5.5v for attiny87/167 ? speed grade: ? 0 - 8 mhz @ 2.7 - 5.5v (automotive temp. range: -40c to +125c) ? 0 - 16 mhz @ 4.5 - 5.5v (automotive temp. range: -40c to +125c) 8-bit microcontroller with 8k/16k bytes in-system programmable flash and lin controller attiny87 attiny167 automotive 7728g?avr?06/10
2 7728g?avr?06/10 attiny87/attiny167 1. description 1.1 comparison between attiny87 and attiny167 attiny87 and attiny167 are hardware and software compatible. they differ only in memory sizes as shown in table 1-1 . 1.2 part description the attiny87/167 is a low-power cmos 8-bi t microcontroller based on the avr enhanced risc architecture. by executing powerful instruct ions in a single clock cycle, the attiny87/167 achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consumption versus processing speed. the 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 instruction executed in one clock cycle. the resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional cisc microcontrollers. the attiny87/167 provides the following featur es: 8k/16k byte of in-system programmable flash, 512 bytes eeprom , 512 bytes sram, 16 general pu rpose i/o lines, 32 general pur- pose working registers, one 8-bit timer/counter with compare modes, one 8-bit high speed timer/counter, universal serial interface, a lin controller, internal and external interrupts, a 11-channel, 10-bit adc, a programmable watchdog timer with internal oscillator, and three software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counter, adc, anal og comparator, and interrupt system to continue function- ing. the power-down mode saves the register co ntents, disabling all chip functions until the next interrupt or hardware re set. the adc noise reduction mode stops the cpu and all i/o modules except adc, to minimize switching noise during adc conversions. the device is manufactured using atmel?s high density non-volatile memory technology. the on-chip isp flash allows the program memory to be re-programmed in-system through an spi serial interface, by a conventional non-volatile memory programmer or by an on-chip boot code running on the avr core. the boot program can use any interface to download the appli- cation program in the flash memory. by co mbining an 8-bit risc cpu with in-system self-programmable flash on a monolithic chip, the atmel attiny87/167 is a powerful micro- controller that provides a highly flexible and co st effective solution to many embedded control applications. the attiny87/167 avr is supported with a full suite of program and system development tools including: c compilers, macro assemblers, program debugger/simulators, in-circuit emula- tors, and evaluation kits. table 1-1. memory size summary device flash eeprom sram interrupt vector size attiny167 16k bytes 512 bytes 512 bytes 2-instruction-words / vector attiny87 8k bytes 512 bytes 512 bytes 2-instruction-words / vector
3 7728g?avr?06/10 attiny87/attiny167 1.3 automotive quality grade the attiny87/167 have been developed and manufa ctured according to the most stringent requirements of the international standard iso-ts-16949. this data sheet contains limit val- ues extracted from the results of extensive characterization (temperature and voltage). the quality and reliability of the attiny87/167 have been verified during regular product qualifica- tion as per aec-q100 grade 1. as indicated in the ordering information paragraph, this document refers only to grade 1 prod- ucts, for grade 0 products refer to appendix a. 1.4 disclaimer typical values contained in this data sheet are based on simulations and characterization of other avr microcontrollers manufactured on the same process technology. min. and max val- ues will be available after the device is characterized. table 1-2. temperature grade identification for automotive products temperature temperature identifier comments -40c / +125c z grade 1 -40c / +150c d grade 0
4 7728g?avr?06/10 attiny87/attiny167 1.5 block diagram figure 1-1. block diagram port a ( 8 ) lin / uart port b ( 8 ) s pi & u s i timer/co u nter-0 timer/co u nter-1 a/d conv. intern a l volt a ge reference s an a log comp. s ram fl as h eeprom w a tchdog o s cill a tor w a tchdog timer o s cill a tor circ u it s / clock gener a tion power su pervi s ion por / bod & re s et vcc gnd program logic de bu gwire agnd avcc data b u s pa[0..7] pb[0..7] 11 re s et xtal[1;2] cpu 2
5 7728g?avr?06/10 attiny87/attiny167 1.6 pin configuration figure 1-2. pinout attiny87/167 - soic20 & tssop20 figure 1-3. pinout attiny87/167 - qfn32 pb0 (pcint 8 / oc1au / di / s da) pb1 (pcint9 / oc1bu / do) pb2 (pcint10 / oc1av / u s ck / s cl) pb 3 (pcint11 / oc1bv) gnd vcc pb4 (pcint12 / oc1aw / xtal1 / clki) pb5 (pcint1 3 / adc 8 / oc1bw / xtal2 / clko) pb6 (pcint14 / adc9 / oc1ax / int0) pb7 (pcint15 / adc10 / oc1bx / re s et / dw) (rxlin / rxd / adc0 / pcint0) pa0 (txlin / txd / adc1 / pcint1) pa1 (mi s o / do / oc0a / adc2 / pcint2) pa2 (int1 / i s rc / adc 3 / pcint 3 ) pa 3 avcc agnd (mo s i / s da / di / icp1 / adc4 / pcint4) pa4 ( s ck / s cl / u s ck / t1 / adc5 / pcint5) pa5 ( ss / ain0 / adc6 / pcint6) pa6 (aref / xref / ain1 / adc7 / pcint7) pa7 1 2 3 4 5 6 7 8 9 10 20 19 1 8 17 16 15 14 1 3 12 11 20-pin top view (int0 / oc1ax / adc9 / pcint14 ) pb6 pb5 (pcint1 3 / adc 8 / oc1bw / xtal2 / clko) pb4 (pcint12 / oc1aw / xtal1 / clki) vcc gnd 1 2 3 4 5 21 20 19 1 8 17 3 2 3 0 29 2 8 3 1 9 11 12 1 3 10 3 2-le a d top view pb2 (pcint10 / oc1av / u s ck / s cl) pb1 (pcint9 / oc1bu / do) (dw / re s et / oc1bx / adc10 / pcint15) pb7 (aref / xref / ain1 / adc7 / pcint7) pa7 ( ss / ain0 / adc6 / pcint6) pa6 ( s ck / s cl / u s ck / t1 / adc5 / pcint5) pa5 agnd avcc (int1 / i s rc / adc 3 / pcint 3 ) pa 3 pa1 (pcint1 / adc1 / txd / txlin) pa2 (pcint2 / adc2 / oc0a / do / mi s o) nc nc nc nc nc nc nc nc nc nc nc nc pa0 (pcint0 / adc0 / rxd / rxlin) index corner bottom p a d s ho u ld b e s oldered to gro u nd 6 7 8 14 15 16 pb 3 (pcint11 / oc1bv) 24 2 3 22 27 25 26 pb0 (pcint 8 / oc1au / di / s da) (mo s i / s da / di / icp1 / adc4 / pcint4) pa4
6 7728g?avr?06/10 attiny87/attiny167 1.7 pin description 1.7.1 vcc supply voltage. 1.7.2 gnd ground. 1.7.3 avcc analog supply voltage. 1.7.4 agnd analog ground. 1.7.5 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 dr ive characteristics with both high sink and source capability. as input s, port a pins 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. port a also serves the functions of various special features of the attiny87/167 as listed on section 9.3.3 ?alternate functions of port a? on page 76 . 1.7.6 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 dr ive characteristics with both high sink and source capability. as input s, port b pins 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 attiny87/167 as listed on section 9.3.4 ?alternate functions of port b? on page 81 . 1.8 resources a comprehensive set of development tools, application notes and datasheets are available for download on http:// www.atmel.com/avr. 1.9 about code examples this documentation contains simple code examples that briefly show how to use various parts of the device. these code examples assume th at the part specific header file is included before compilation. be aware that not all c compiler vendors include bit definitions in the header files and interrupt handling in c is compiler dependent. please confirm with the c com- piler documentation for more details.
7 7728g?avr?06/10 attiny87/attiny167 2. avr cpu core 2.1 overview this section discusses the avr core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access mem- ories, perform calculations, control peripherals, and handle interrupts. figure 2-1. block diagram of the avr architecture in order to maximize performance and parallelis m, 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. whil e one instruction is being executed, the next instruction is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program me mory is in-system reprogrammable flash memory. the fast-access register file contai ns 32 x 8-bit general purpose working registers with a single clock cycle access time. this allo ws single-cycle arithmetic logic unit (alu) operation. in a typical alu operation, two oper ands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control eeprom data bus 8-bit i/o lines data sram direct addressing indirect addressing i/o module 2 analog comparator i/o module1 watchdog timer i/o module n interrupt unit a.d.c.
8 7728g?avr?06/10 attiny87/attiny167 six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing ? enabling efficient address ca lculations. one of the these address pointers can also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16-bit x-, y-, and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic operation, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and un conditional jump and call instructions, able to directly address the whole address space. most avr instructions have a single 16-bit word format. every program memory address contains a 16- or 32-bit instruction. during interrupts and subroutine calls, the return address 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 t he total sram size and the usage of the sram. all user pro- grams must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read/writ e accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control registers in the i/o space with an additional global interrupt enable bit in the status register. all interrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector position. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresses for cpu peripheral functions as control regis- ters, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5f. 2.2 alu ? arithm etic logic unit the high-performance avr alu operates in direct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immedi ate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-functions. some implementa- tions of the architecture also provide a pow erful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruction set? section for a detailed description. 2.3 status register the status register contains information about the result of the most recently executed arith- metic instruction. this information can be used for altering program flow in order to perform conditional operations. note that the status register is updated after all alu operations, as specified in the instruction set reference. this will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software.
9 7728g?avr?06/10 attiny87/attiny167 2.3.1 sreg ? avr status register the avr status register ? sreg ? is defined as: ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for the interrupts to be enabled. the individual interrupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of the in terrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i-bit can also be set and cleared by the application with the sei and cli in structions, as described in the instruction set reference. ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (bit store) use the t-bit as source or des- tination 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 use- ful in bcd arithmetic. see the ?instruction set description? for detailed information. ? bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or between the negative flag n and the two?s complement overflow flag v. see the ?instruction set description? for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v supports two?s complement arithmetics. see the ?instruction set description? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmetic or logic operation. see the ?instruction set description? for de tailed information. bit 76543210 ithsvnzcsreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
10 7728g?avr?06/10 attiny87/attiny167 2.4 general purpose register file the register file is optimized for the avr enhanc ed risc instruction set. in order to achieve the required performance and flexibility, the fo llowing input/output schemes are supported by the register file: ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 2-2 shows the structure of the 32 general purpose working registers in the cpu. figure 2-2. 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 2-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 me mory organization pr ovides 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. 2.4.1 the x-register, y-register, and z-register the registers r26..r31 have some added func tions to their general purpose usage. these registers are 16-bit address pointers for indirect addressing of the data space. the three indi- rect address registers x, y, and z are defined as described in figure 2-3 on page 11 . 70addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte
11 7728g?avr?06/10 attiny87/attiny167 figure 2-3. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displace- ment, automatic increment, and automatic decrement (see the instruction set reference for details). 2.5 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. the stack pointer register always points to the top of the stack. note that the stack is implemented as growing from higher memory locations to lower memory locations . this implies that a stack push command decreases the stack pointer. the stack pointer points to the data sram stack area where the subroutine and interrupt stacks are located. this stack space in the data sram must be defined by the program before any subroutine calls are executed or in terrupts are enabled. the stack pointer must be set to point above 0x60. the stack pointer is decremented by one when data is pushed onto the stack with the push instruction, and it is decremented by two when the return address is pushed onto the stack with subroutine call or interrupt. the stack pointer is incremented by one when data is popped from the stack with the pop instruction, and it is incremented by two when data is popped from the stack with return from subroutine ret or return from interrupt reti. the avr stack pointer is implemented as two 8-bit registers in the i/o space. the number of bits actually used is implementation dependent. note that the data space in some implementa- tions of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present 2.5.1 sph and spl ? stack pointer register 15 xh xl 0 x-register 7 0 7 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 7 0 7 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 7 0 7 0 r31 (0x1f) r30 (0x1e) 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/w r/w r/w r/w r/w r/w r/w r/w initial value isram end (see table 3-1 on page 15 )
12 7728g?avr?06/10 attiny87/attiny167 2.6 instruction execution timing this section describes the general access timing 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 cl ock division is used. figure 2-4 shows the parallel instruction fetches and instruction executions enabled by the harvard architecture and the fast access register file concept. this is the basic pipelining concept to obtain up to 1 mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 2-4. the parallel instruction fetches and instruction executions figure 2-5 shows the internal timing concept for t he register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destination register. figure 2-5. single cycle alu operation 2.7 reset and inte rrupt handling the avr provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global inter- rupt enable bit in the status register in order to enable the interrupt. 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 section 7. ?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 hi ghest priority, and next is int0 ? the external interrupt request 0. 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
13 7728g?avr?06/10 attiny87/attiny167 2.7.1 interrupt behavior 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 first type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vector in order to execute the interrupt handling routine, and hardware clears the correspond- ing interrupt flag. interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the in terrupt flag will be set and reme mbered until the interrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is cleared, the correspond ing interrupt flag(s) will be set and remembered until the global inte rrupt enable bit is set, and will then be executed by order of priority. the second type of interrupts will trigger as long as t he interrupt c ondition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. when the avr exits from an in terrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. note that the status register is not automat ically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable interrupts, the interrupts will be immediately dis- abled. no interrupt will be executed after the cl i instruction, even if it occurs simultaneously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eempe ; start eeprom write sbi eecr, eepe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ _cli(); eecr |= (1< 14 7728g?avr?06/10 attiny87/attiny167 when using the sei instruction to enable interrupts, the instruction following sei will be exe- cuted before any pending interrupts, as shown in this example. 2.7.2 interrupt response time the interrupt execution response for all the ena bled avr interrupts is four clock cycles mini- mum. after four clock cycles the program vector address for the actual interrupt handling routine is executed. during th is four clock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interrupt occu rs during execution of a multi-cycl e instruction, this instruction is completed before the interrupt is served. if an interrupt occurs when the mcu is in sleep mode, the interrupt execution response time is increased by four clock cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine takes four clock cycles. during these four clock cycles, the program counter (two bytes) is popped back from the stack, the stack pointer is incremented by two, and the i-bit in sreg is set. assembly code example sei ; set global interrupt enable sleep ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s) c code example _sei(); /* set global interrupt enable */ _sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
15 7728g?avr?06/10 attiny87/attiny167 3. avr memories this section describes the diff erent memories in the attiny87/167. the avr architecture has two main memory spaces, the data memory and the program memory space. in addition, the attiny87/167 features an eeprom memory for data storage. all three memory spaces are linear and regular. notes: 1. byte address. 2. word (16-bit) address. 3.1 in-system re-programmable flash program memory the attiny87/167 contains on -chip in-system reprogrammable flash memory for program storage (see ?flash size? in table 3-1 on page 15 ). since all avr instructions are 16 or 32 bits wide, the flash is organized as 16 bits wide. attiny87/167 does not have separate boot loader and application program sections, and the spm instruction can be executed from the entire flash. see selfprgen description in section 20.2.1 ?store program memory control and status register ? spmcsr? on page 219 for more details. the flash memory has an endurance of at least 10,000 write/erase cycles in automotive range. the attiny87/167 program counter (pc) address the program memory locations. sec- tion 21. ?memory programming? on page 225 contains a detailed description on flash data serial downloading using the spi pins. constant tables can be allocated within the entire program memory address space (see the lpm ? load program memory instruction description). table 3-1. memory mapping. memory mnemonic attiny87 attiny167 flash size flash size 8 k bytes 16 k bytes start address - 0x0000 end address flash end 0x1fff (1) 0x0fff (2) 0x3fff (1) 0x1fff (2) 32 registers size - 32 bytes start address - 0x0000 end address - 0x001f i/o registers size - 64 bytes start address - 0x0020 end address - 0x005f ext i/o registers size - 160 bytes start address - 0x0060 end address - 0x00ff internal sram size isram size 512 bytes start address isram start 0x0100 end address isram end 0x02ff eeprom size e2 size 512 bytes start address - 0x0000 end address e2 end 0x01ff
16 7728g?avr?06/10 attiny87/attiny167 timing diagrams for instruction fetch and execution are presented in section 2.6 ?instruction execution timing? on page 12 . figure 3-1. program memory map 3.2 sram data memory figure 3-2 shows how the attiny87/167 sram memory is organized. the attiny87/167 is a complex microcontroller with more peripheral units than can be sup- ported within the 64 locations reserved in the opcode for the in and out instructions. for the extended i/o space in sram, only the st/sts/std and ld/lds/ldd instructions can be used. the 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 locations address the internal data sram (see ?isram size? in table 3-1 on page 15 ). 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, 160 extended i/o registers and the internal data sram in the attiny87/167 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 10 . 0x0000 flash end program memory
17 7728g?avr?06/10 attiny87/attiny167 figure 3-2. data memory map 3.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 3-3 . figure 3-3. on-chip data sram access cycles 3.3 eeprom data memory the attiny87/167 contains eeprom memory (see ?e2 size? in table 3-1 on page 15 ). 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 in au tomotive range. the access between the eeprom and the cpu is de scribed in the following, specifying the eeprom address registers, the eeprom data register and the eeprom control register. section 21. ?memory programming? on page 225 contains a detailed description on eeprom programming in spi or parallel programming mode. 32 registers 64 i/o registers internal sram (isram size) 0x0000 - 0x001f 0x0020 - 0x005f isram end 0x0060 - 0x00ff data memory 160 ext i/o reg. isram start clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction
18 7728g?avr?06/10 attiny87/attiny167 3.3.1 eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access times for the eeprom are given in table 3-2 . a self-timing function, how- ever, lets the user software detect when the next byte can be written. if the user code contains instructions that write the eeprom, some precautions must be taken. in heavily filtered power supplies, vcc is likely to rise or fall slowly on power-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see ?preventing eeprom co rruption? on page 20 for details on how to avoid problems in these situations. in order to prevent unintenti onal eeprom writes, a specific wr ite procedure must be followed. refer to ?atomic byte programming? on page 18 and ?split byte programming? on page 18 for details on this. when the eeprom is read, the cpu is halted for four clock cycl es before the ne xt instruction is executed. when the eeprom is written, the cpu is halted for two clock cycles before the next instruction is executed. 3.3.2 atomic byte programming using atomic byte programming is the simplest mode. when writing a byte to the eeprom, the user must write the addres s into the eearl register and da ta into eedr register. if the eepmn bits are zero, writing eepe (within four cycles after eempe is written) will trigger the erase/write operation. both the erase and write cycle are done in one operation and the total programming time is given in table 1. the eepe bit remains set until the erase and write operations are completed. while the device is busy with programming, it is not possible to do any other eeprom operations. 3.3.3 split byte programming it is possible to split the erase and write cycle in two different operations. this may be useful if the system requires short access time for some limited period of time (typically if the power supply voltage falls). in order to take advantage of this method, it is required that the locations to be written have been erased before the write operation. but since the erase and write oper- ations are split, it is possible to do the er ase operations when th e system allows doing time-critical operations (t ypically after power-up). 3.3.4 erase to erase a byte, the address mu st be written to eear. if the eepmn bits are 0b01, writing the eepe (within four cycles afte r eempe is written) will trigger the erase operation only (pro- gramming time is given in t able 1). the eepe bit remains set until the erase operation completes. while the devi ce is busy programming, it is not possible to do any other eeprom operations. 3.3.5 write to write a location, the user must write the address into eear and the data into eedr. if the eepmn bits are 0b10, writing the eepe (within four cycles after eempe is written) will trigger the write operation only (programming time is given in table 1). the eepe bit remains set until the write operation completes. if the location to be written has not been erased before write, the data that is stored must be considered as lost. while the device is busy with programming, it is not possible to do any other eeprom operations.
19 7728g?avr?06/10 attiny87/attiny167 the calibrated oscillator is used to time the eeprom accesse s. make sure the oscillator fre- quency is within the requirements described in ?osccal ? oscillator ca libration register? on page 37 . the following code examples show one assemb ly and one c function for erase, write, or atomic write of the eeprom. the examples assu me that interrupts ar e controlled (e.g., by disabling interrupts globally ) so that no interrupts will oc cur during execution of these functions. assembly code example eeprom_write: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_write ; set programming mode ldi r16, (0< 20 7728g?avr?06/10 attiny87/attiny167 the next code examples show assembly a nd c functions for r eading the eeprom. the examples assume that interrupts are controlled so that no interrupts will occur during execu- tion of these functions. 3.3.6 preventing eeprom corruption during periods of low vcc, the eeprom data can be corrupted because the supply voltage is too low for the cpu and the eeprom to operate properly. these issues are the same as for board level systems using eepr om, and the same design so lutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate cor- rectly. secondly, the cpu itself ca n execute instructions incorrectly, if the supply voltage is too low. eeprom data corruption can ea sily be avoided by followin g this design recommendation: assembly code example eeprom_read: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example unsigned char eeprom_read( unsigned char ucaddress) { /* wait for completion of previous write */ while(eecr & (1< 21 7728g?avr?06/10 attiny87/attiny167 keep the avr reset active (low) during periods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low vcc reset protection circuit can be used. if a reset occurs while a writ e operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 3.4 i/o memory the i/o space definition of the attiny87/167 is shown in section 25. ?register summary? on page 268 . all attiny87/167 i/os and peripherals are placed in the i/o space. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using t he 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 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the attiny87/167 is a complex microcontroller with more peripheral units than can be supported within the 64 loca- tion reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. for compatibility with future devi ces, reserved bits should be wr itten to zero if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avrs, the cbi and sbi inst ructions will only operate on th e specified bit, and can there- fore be used on registers containing such st atus flags. the cbi and sbi instructions work with registers 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections. 3.4.1 general purpose i/o registers the attiny87/167 contains three general purpose i/o registers. these registers can be used for storing any information, and they are particularly useful for storing global variables and sta- tus flags. the general purpose i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi, cbi, sbis, and sbic instructions. 3.5 register description 3.5.1 eearh and eearl ? eeprom address register bit 76543210 -------eear8eearh eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl bit 76543210 read/write rrrrrrrr/w read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value0000000x initial valuexxxxxxxx
22 7728g?avr?06/10 attiny87/attiny167 ? bit 7:1 ? reserved bits these bits are reserved for future use and will always r ead as 0 in attiny87/167. ? bits 8:0 ? eear8:0: eeprom address the eeprom address registers ? eearh and eearl ? specifies the high eeprom address in the eeprom space (see ?e2 size? in table 3-1 on page 15 ). the eeprom data bytes are addressed linearly between 0 and ?e2 size?. the initial value of eear is undefined. a proper value mu st be written before the eeprom may be accessed. note: for information only - attiny47: eear8 exists as register bit but it is not used for addressing. 3.5.2 eedr ? eeprom data register ? bits 7:0 ? eedr7:0: eeprom data for the eeprom write operation the eedr register contains the data to be written to the eeprom in the address given by the eear register. for the eeprom read op eration, the eedr contains the data read out from the eeprom at the add ress given by eear. 3.5.3 eecr ? eeprom control register ? bit 7,6 ? res: reserved bits these bits are reserved for future use and will always read as 0 in atti ny87/167. after reading, mask out these bits. for compatibility with future avr devices, always write these bits to zero. ? bits 5, 4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bits setting defines which programming action that will be triggered when writing eepe. it is possible to program data in one atomic operation (erase the old value and program the new value) or to split the erase and write operations in two differ- ent operations. the programming times for the different modes are shown in table 3-2 . while eepe is set, any write to eepmn will be ignored. during reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming. bit 76543210 eedr7 eedr6 eedr5 eedr4 eedr3 eedr2 eedr1 eedr0 eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 x x 0 0 x 0 table 3-2. eeprom mode bits eepm1 eepm0 typical programming time operation 0 0 3.4 ms erase and write in one operation (atomic operation) 0 1 1.8 ms erase only 1 0 1.8 ms write only 1 1 ? reserved for future use
23 7728g?avr?06/10 attiny87/attiny167 ? bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the eeprom ready interrupt if the i- bit in sreg is set. writing eerie to zero disables the interrupt. the eeprom ready interrupt generates a constant interrupt when non-volatile me mory is ready for programming. ? bit 2 ? eempe: eeprom master program enable the eempe bit determines whether writing eepe to o ne will have effect or not. when eempe is set, setting eepe within four clock cycles will program the eeprom at the selected address. if eempe is zero, setting eepe will have no effect. when eempe has been written to one by software, hardware clears the bit to zero after four clock cycles. ? bit 1 ? eepe: eeprom program enable the eeprom program enable signal eepe is the programming enable signal to the eeprom. when eepe is written, the eeprom will be programmed a ccording to the eepmn bits setting. the eempe bit must be written to one before a logical one is written to eepe, oth- erwise no eeprom write takes place. when the write access time has elapsed, the eepe bit is cleared by hardware. when eepe has been set, the cpu is halt ed for two cycles before the next instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal ? eere ? is the read strobe to the eeprom. when the correct address is set up in the eear register, the eere bit must be written to one to trigger the eeprom read. the eeprom read access take s one instruction, a nd the requested data is available immediately. when the eeprom is read, the cpu is halted for four cycles before the next instruction is executed. the user sh ould poll the eepe bit be fore starting the read operation. if a write operation is in progress, it is neither possible to read the eeprom, nor to change the eear register. 3.5.4 general purpose i/o register 2 ? gpior2 3.5.5 general purpose i/o register 1 ? gpior1 3.5.6 general purpose i/o register 0 ? gpior0 bit 76543210 gpior27 gpior26 gpior25 gpior24 gpior23 gpior22 gpior21 gpior20 gpior2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 bit 76543210 gpior17 gpior16 gpior15 gpior14 gpior13 gpior12 gpior11 gpior10 gpior1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 bit 76543210 gpior07 gpior06 gpior05 gpior04 gpior03 gpior02 gpior01 gpior00 gpior0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000
24 7728g?avr?06/10 attiny87/attiny167 4. system clock and clock options the attiny87/167 provides a large number of clock sources. they can be divided into two cat- egories: internal and external. some exter nal clock sources can be shared with the asynchronous timer. after reset, the clock sour ce is determined by the cksel fuses. once the device is running, software clock switch ing is possible to any other clock sources. hardware controls are provided for clock sw itching management but some specific proce- dures must be observed. clock switching shoul d be performed with caution as some settings could result in the device having an incorrect configuration. 4.1 clock systems and their distribution figure 4-1 presents the principal clock systems in the avr and their distribution. all of the clocks may not need to be active at any given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using different sle ep modes or by using features of the dynamic clock switch circuit (see ?power management and sleep modes? on page 42 and ?dynamic clock switch? on page 31 ). the clock systems are detailed below. figure 4-1. clock distribution modules clk i/o clk asy avr clock control unit clk cpu clk flash source clock watchdog timer watchdog oscillator reset logic prescaler multiplexer watchdog clock low-frequency crystal oscillator crystal oscillator external clock clk adc asynchronous timer/counter0 general i/o adc cpu core ram flash and eeprom calibrated rc oscillator pb5 / xtal2 / clko pb4 / xtal1 / clki ckout fuse clock switch
25 7728g?avr?06/10 attiny87/attiny167 4.1.1 cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with the avr core operation. exam- ples of such modules are the general purpose register file, the status register and the data memory holding the stack pointer. halting t he cpu clock inhibits the core from performing general operations and calculations. 4.1.2 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like synchronous timer/counter. the i/o clock is also used by the external interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. 4.1.3 flash clock ? clk flash the flash clock controls operation of the flash interface. the flash clock is usually active simultaneously with the cpu clock. 4.1.4 asynchronous timer clock ? clk asy the asynchronous timer clock allows the asynchronous timer/counter to be clocked directly from an external clock or an external lo w frequency crystal. the dedicated clock domain allows using this timer/ counter as a real-time counter even when the device is in sleep mode. 4.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 digi tal circuitry. this gives more accurate adc conversion results. 4.2 clock sources the device has the following clock source options, selectable by flash fuse bits (default) or by the clkselr register (dynamic clock switch circuit) as sh own below. the clock from the selected source is input to the avr clock generator, and routed to the appropriate modules. notes: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. 2. flash fuse bits. 3. clkselr register bits. table 4-1. device clocking options select (1) vs. pb4 and pb5 functionality device clocking option cksel3..0 (2) csel3..0 (3) pb4 pb5 external clock 0000 b clki clko - i/o calibrated internal rc oscillator 8.0 mhz 0010 b i/o clko - i/o watchdog oscillator 128 khz 0011 b i/o clko - i/o external low-frequency oscillator 01xx b xtal1 xtal2 external crystal/ceramic resonator (0.4 - 0.9 mhz) 100x b xtal1 xtal2 external crystal/ceramic resonator (0.9 - 3.0 mhz) 101x b xtal1 xtal2 external crystal/ceramic resonator (3.0 - 8.0 mhz) 110x b xtal1 xtal2 external crystal/ceramic resonator (8.0 - 16.0 mhz) 111x b xtal1 xtal2
26 7728g?avr?06/10 attiny87/attiny167 the various choices for each clocking option are given in the following sections. when the cpu wakes up from power-down or power-save, or when a new clock source is enabled by the dynamic clock switch circuit, t he selected clock source is used to time the start-up, ensuring stable o scillator operation before inst ruction execution starts. when the cpu starts from reset, there is an ad ditional delay allowing the power to reach a sta- ble level before commencing norma l operation. the watc hdog oscillator is used for timing this real-time part of the start-up sequence. the nu mber of wdt oscillator cycles used for each time-out is shown in table 4-2 . 4.2.1 default clock source at reset, the cksel and sut fuse settings are copied into the clkselr register. the device will then use the cloc k source and the start-up timi ngs defined by t he clkselr bits (csel3..0 and csut1:0). the device is shipped with cksel fuses = 0010 b , sut fuses = 10 b , and ckdiv8 fuse pro- grammed. the default clock source setting is therefor e the internal rc oscillator running at 8 mhz with the longest start-up time and an initial system clock divided by 8. this default setting ensures that all users can make their desired clock source setting using an in-system or high-voltage programmer. this set-up must be taken into account when using isp tools. 4.2.2 calibrated internal rc oscillator by default, the internal rc o scillator provides an approximat e 8.0 mhz clock. though voltage and temperature dependent, this clock can be accurately calibrated by the user. see table 22-1 on page 245 and section 24.7 ?int ernal oscillator speed? on page 265 for more details. if selected, it can operate without external components. at reset, hardware loads the pre-pro- grammed calibration value into the osccal r egister and thereby automatically configuring the rc oscillator. the accuracy of this calib ration is shown as factory calibration in table 22-1 on page 245 . by adjusting the osccal register in software, see ?osccal ? oscillator calibration regis- ter? on page 37 , it is possible to get a higher calibration accuracy than by using the factory calibration. the accuracy of this calibra tion is shown as user calibration in table 22-1 on page 245 . the watchdog oscillator will still be used for the watchdog time r and for the reset time-out even when this oscillator is used as the device clock. for more information on the pre-pro- grammed calibration value, see the section ?calibration byte? on page 228 . table 4-2. number of watchdog oscillator cycles typ. time-out (vcc = 5.0v) typ. time-out (vcc = 5.0v) number of cycles 4.1 ms 4.3 ms 512 65 ms 69 ms 8k (8,192)
27 7728g?avr?06/10 attiny87/attiny167 notes: 1. if 8 mhz frequency exceeds the specification of the device (depends on vcc), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. 2. the frequency ranges are guideline values. 3. the device is shipped with this cksel = ?0010?. 4. flash fuse bits. 5. clkselr register bits. when this oscillator is selected , start-up times are determined by the sut fuses or by csut field as shown in table 4-4 . notes: 1. flash fuse bits 2. clkselr register bits 3. this setting is only available if rstdisbl fuse is not set 4. the device is shipped with this option selected. 4.2.3 128 khz internal oscillator the 128 khz internal oscillator is a low power oscillator providing a clock of 128 khz. the frequency is nominal at 3v and 25c. this clock may be selected as the system clock by pro- gramming cksel fuses or csel field as shown in table 4-1 on page 25 . when this clock source is selected, start-up times are determined by the sut fuses or by csut field as shown in table 4-5 . notes: 1. flash fuse bits 2. clkselr register bits 3. this setting is only available if rstdisbl fuse is not set table 4-3. internal calibrated rc o scillator operating modes (1) frequency range (2) (mhz) cksel3..0 (3)(4) csel3..0 (5) 7.6 - 8.4 0010 table 4-4. start-up times for the internal calib rated rc oscillato r clock selection sut1..0 (1) csut1..0 (2) start-up time from power-down/save additional delay from reset (vcc = 5.0v) recommended usage 00 (3) 6 ck 14ck bod enabled 01 6 ck 14ck + 4.1 ms fast rising power 10 (4) 6 ck 14ck + 65 ms slowly rising power 11 reserved table 4-5. start-up times for the 128 khz internal oscillator sut1..0 (1) csut1..0 (2) start-up time from power-down/save additional delay from reset (vcc = 5.0v) recommended usage 00 (3) 6 ck 14ck bod enabled 01 6 ck 14ck + 4.1 ms fast rising power 10 6 ck 14ck + 65 ms slowly rising power 11 reserved
28 7728g?avr?06/10 attiny87/attiny167 4.2.4 crystal oscillator xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-c hip oscillator, as shown in figure 4-2 . either a quartz crystal or a ceramic resonator may be used. c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 4-6 . for ceramic resonators, the capacitor values given by the manufacturer should be used. figure 4-2. crystal oscillator connections the oscillator can operate in three different modes, each optimized for a specific frequency range. the oper ating mode is selected by cksel3..1 fuses or by c sel3..1 field as shown in table 4-6 . notes: 1. flash fuse bits. 2. clkselr register bits. 3. this option should not be used with crystals, only with ceramic resonators. table 4-6. crystal oscillator operating modes cksel3..1 (1) csel3..1 (2) frequency range (mhz) recommended range for capacitors c1 and c2 for use with crystals (pf) 100 (3) 0.4 - 0.9 ? 101 0.9 - 3.0 12 - 22 110 3.0 - 8.0 12 - 22 111 8.0 - 16.0 12 - 22 xtal2 xtal1 gnd c2 c1
29 7728g?avr?06/10 attiny87/attiny167 the cksel0 fuse together with the sut1..0 fu ses or csel0 together with csut1..0 field select the start-up times as shown in table 4-7 . notes: 1. flash fuse bits. 2. clkselr register bits. 3. 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. 4. these options are intended for use with ce ramic resonators and will ensure frequency stabil- ity at start-up. they can also be used with crystals when not operating close to the maximum frequency of the device, and if frequency stab ility at start-up is not important for the application. 5. this setting is only available if rstdisbl fuse is not set. 4.2.5 low-frequency crystal oscillator to use a 32.768 khz watch crystal as the clock source for the device, the low-frequency crys- tal oscillator must be select ed by setting cksel fuses or csel field as shown in table 4-1 on page 25 . the crystal should be connected as shown in figure 4-3 . refer to the 32.768 khz crystal oscillator applicat ion note for deta ils on oscillator operation and how to c hoose appro- priate values for c1 and c2. the 32.768 khz watch crystal oscillator c an be used by the asynchronous timer if the (high-frequency) crystal oscilla tor is not running or if the external clock is not enabed ( see ?enable/disable clock source? on page 32. ). the asynchronous timer is then able to start itself this low-frequ ency crystal oscillator. table 4-7. start-up times for the crysta l oscillator clock selection cksel0 (1) csel0 (2) sut1..0 (1) csut1..0 (2) start-up time from power-down/save additional delay from reset (vcc = 5.0v) recommended usage 0 00 258 ck (3) 14ck + 4.1 ms ceramic resonator, fast rising power 0 01 258 ck (3) 14ck + 65 ms ceramic resonator, slowly rising power 010 (5) 1k (1024) ck (4) 14ck ceramic resonator, bod enabled 0 11 1k (1024)ck (4) 14ck + 4.1 ms ceramic resonator, fast rising power 1 00 1k (1024)ck (4) 14ck + 65 ms ceramic resonator, slowly rising power 101 (5) 16k (16384) ck 14ck crystal oscillator, bod enabled 1 10 16k (16384) ck 14ck + 4.1 ms crystal oscillator, fast rising power 1 11 16k (16384) ck 14ck + 65 ms crystal oscillator, slowly rising power
30 7728g?avr?06/10 attiny87/attiny167 figure 4-3. low-frequency crystal oscillator connections when this oscillator is selected, start-up times are determined by the sut fuses or by csut field as shown in table 4-8 . notes: 1. flash fuse bits. 2. clkselr register bits. 3. these options should only be used if frequency stability at start-up is not important for the application. 4.2.6 external clock to drive the device from this external clock source, clki should be driven as shown in figure 4-4 . to run the device on an ex ternal clock, the cksel fuses or csel field must be pro- grammed as shown in table 4-1 on page 25 . figure 4-4. external clock drive configuration when this clock source is selected, start-up times are determined by the sut fuses or csut field as shown in table 4-9 . this external clock can be used by the asynchronous timer if the high or low frequency crystal oscillator is not running ( see ?enable/disable clock source? on page 32. ). the asynchronous timer is then able to enable this input. table 4-8. start-up times for the lo w frequency crystal oscillator clock selection sut1..0 (1) csut1..0 (2) start-up time from power-down/save additional delay from reset (vcc = 5.0v) recommended usage 00 1k (1024) ck (3) 4.1 ms fast rising power or bod enabled 01 1k (1024) ck (3) 65 ms slowly rising power 10 32k (32768) ck 65 ms stable frequency at start-up 11 reserved xtal2 xtal1 gnd c1=12-22 pf 32.768 khz 12-22 pf capacitors may be necessary if parasitic impedance (pads, wires & pcb) is very low. c2=12-22 pf (xtal2) (clko) clki (xtal1) gnd ~ external clock signal
31 7728g?avr?06/10 attiny87/attiny167 notes: 1. flash fuse bits. 2. clkselr register bits. 3. additional delay (+ 4ms) available if rstdisbl fuse is set. note that the system clock prescaler can be used to implement run-time changes of the inter- nal clock frequency while still ensu ring stable operation. refer to ?system clock prescaler? on page 37 for details. 4.2.7 clock output buffer if not using a crystal oscillator, the device c an output the system clock on the clko pin. to enable the output, the ckout fuse or cout bit of clksel r register has to be programmed. this option is useful when the device clock is needed to drive other circuits on the system. note that the clock will not be ou tput during reset and the norm al operation of i/o pin will be overridden when the fuses are programmed. if the system clock prescaler is used, it is the divided system clock that is output. 4.3 dynamic clock switch 4.3.1 features the attiny87/167 provides a powerful dynamic clock switch circuit that allows users to turn on and off clocks of the device on the fly. the built -in de-glitching circuitr y allows clocks to be enabled or disabled asynchronously. this enabl es efficient power management schemes to be implemented easily and quickly. in a safety application, the dynamic clock switch circuit allows continuous monitoring of the external clock permitting a fallback scheme in case of clock failure. the control of the dynamic clock switch circuit must be supervised by software. this operation is facilitated by th e following features: ? safe commands , to avoid unintentional commands, a special write procedure must be followed to change the clkcsr register bits ( see ?clkpr ? clock prescaler register? on page 38. ): ? exclusive action , the actions are controlled by a decoding table (commands) written to the clkcsr register. this ensures that only one command operation can be launched at any time. the main actions of the decoding table are: ?? disable clock source ?, ?? enable clock source ?, ?? request clock availability ?, ?? clock source switching ?, table 4-9. start-up times for the external clock selection sut1..0 (1) csut1..0 (2) start-up time from power-down/save additional delay from reset (vcc = 5.0v) recommended usage 00 6 ck 14ck (+ 4.1 ms (3) ) bod enabled 01 6 ck 14ck + 4.1 ms fast rising power 10 6 ck 14ck + 65 ms slowly rising power 11 reserved
32 7728g?avr?06/10 attiny87/attiny167 ?? recover system clock source ?, ?? enable watchdog in automatic reload mode ?. ? command status return. the ? request clock availability ? command returns status via the clkrdy bit in the clkcsr register. the ? recover system clock source ? command returns a code of the current clock source in the clkselr re gister. this information is used in the supervisory software routines as shown in section 4.3.7 on page 33 . 4.3.2 clkselr register 4.3.2.1 fuses substitution at reset, bits of the low fuse byte are copied into the clkselr register. th e content of this register can subsequently be user modified to overwrite the default values from the low fuse byte. cksel3..0, sut1..0 and ckout fuses correspond respectively to csel3..0, csut1:0 and ~(cout) bits of the cl kselr register as shown in figure 4-5 on page 32 . 4.3.2.2 source selection the available codes of clock source are given in table 4-1 on page 25 . figure 4-5. fuses substitution and clock source selection the clkselr register contains the csel, csut and cout values which will be used by the ?enable/disable clock source?, ?request for clo ck availability? or ?clock source switching? commands. 4.3.2.3 source recovering the ? recover system clock source ? command updates the cksel field of clkselr register ( see ?system clock source recovering? on page 33. ). 4.3.3 enable/disable clock source the ? enable clock source ? command selects and enables a clock source configured by the settings in the clkselr regist er. csel3..0 will select the clock source and csut1:0 will select the start-up time (just as cksel and sut fuse bits do). to be sure that a clock source is operating, the ? request for clock availability ? command must be executed after the ? enable clksel[3..0] sut[1..0] ckout register: clkselr fuse: fuse low byte csel[3..0] csut[1..0] cout default r/w reg. sel decoder sel-1 sel-0 sel-2 sel-n cksel[3..0] sut[1..0] sel encoder en-1 en-0 en-2 en -n ckout reset sclkrq ( * ) sclkrq ( * ) : command of clock control & status register internal data bus selected configuration clock switch current configuration
33 7728g?avr?06/10 attiny87/attiny167 clock source ? command. this will indicate via the clkrdy bit in the clkcsr register that a valid clock source is available and operational. the ? disable clock source ? command disables the clock source indicated by the settings of clkselr register (only csel3..0). if the clock so urce indicated is curr ently the one that is used to drive the system clock, the command is not executed. because the selected configuration is latched at clock source level, it is possible to enable many clock sources at a given time (ex: the in ternal rc oscillator for syst em clock + an oscilla- tor with external crystal). the user (code) is responsible of this management. 4.3.4 cout command the ? ckout ? command allows to drive the clko pin. refer to section 4.2.7 ?clock output buffer? on page 31 for using. 4.3.5 clock availability ?request for clock availability? command enables a hardware oscillation cycle counter driven by the selected source clock, csel3..0. the count limit value is determined by the settings of csut1..0. the clock is declared ready (clkrdy = 1) when the count limit value is reached. the clkrdy flag is reset when the count starts. once set, this flag remains unchanged until a new count is commanded. to perform this chec king, the cksel and csut fields should not be changed while the operation is running. note that once the new clock source is selected (? enable clock source ? command), the count procedure is automatically started. the user (code) should wait for the setting of the clkrdy flag in clkscr register before using a newly selected clock. at any time, the user (code) ca n ask for the availabilit y of a clock source. the user (code) can request it by writing the ?request for clock availability ? command in the clkscr register. a full polling of the status of clock sources can thus be done. 4.3.6 system clock source recovering the ? recover system clock source ? command returns the current clock source used to drive the system clock as per table 4-1 on page 25 . the cksel field of cl kselr register is then updated with this returned value. there is no information on the sut used or status on ckout. 4.3.7 clock switching to drive the system clock, the user can switch from the current clock source to any other of the following ones (one of them being the current clock source): 1. calibrated internal rc oscillator 8.0 mhz, 2. internal watchdog oscillator 128 khz, 3. external clock, 4. external low-frequency oscillator, 5. external crystal/ceramic resonator. the clock switching is performed by a sequence of commands. first, the user (code) must make sure that the new clock source is operating. then the ? clock source switching ? com- mand can be issued. once this command has been successfully completed using the ? recover system clock source ? command, the user (code) may stop the previous clock source.
34 7728g?avr?06/10 attiny87/attiny167 it is strongly recommended to run this sequenc e only once the interrupts have been disabled. the user (code) is responsible for the correct implementation of the clock switching sequence. here is a ?light? c-code that describes such a sequence of commands. warning : in the attiny87/167, only one among the three external clock sources can be enabled at a given time. moreover, the enables of the exte rnal clock and of the external low-frequency oscillator are shared with the asynchronous timer. 4.3.8 clock monitoring a safe system needs to monitor its clock s ources. two domains n eed to be monitored: - clock sources for peripherals, - clocks sources for syst em clock generation. c code example void clockswiching (unsigned char clk _ number, unsigned char sut) { #define clock _ recover 0x05 #define clock _ enable 0x02 #define clock _ switch 0x04 #define clock _ disable 0x01 unsigned char previous _ clk, temp; // disable interrupts temp = sreg; asm ("cli"); // save the current system clock source clkcsr = 1 << clkcce; clkcsr = clock _ recover; previous _ clk = clkselr & 0x0f; // enable the new clock source clkselr = ((sut << 4 ) & 0x30) | (clk _ number & 0x0f); clkcsr = 1 << clkcce; clkcsr = clock _ enable; // wait for clock validity while ((clkcsr & (1 << clkrdy)) == 0); // switch clock source clkcsr = 1 << clkcce; clkcsr = clock _ switch; // wait for effective switching while (1){ clkcsr = 1 << clkcce; clkcsr = clock _ recover; if ((clkselr & 0x0f) == (clk _ number & 0x0f)) break; } // shut down unneeded clock source if (previous_clk != (clk_number & 0x0f)) { clkselr = previous _ clk; clkcsr = 1 << clkcce; clkcsr = clock _ disable; } // re-enable interrupts sreg = temp; }
35 7728g?avr?06/10 attiny87/attiny167 in the first domain, the user (code) can eas ily check the validity of the clock(s) ( see ?cout command? on page 33. ). in the second domain, the lack of a clock results in the code not running. thus, the presence of the system clock needs to be monitored by hardware. using the on-chip watchdog allows this monitoring. normally, the watchdog reloading is per- formed only if the code reaches some specific software labels, reaching these labels proves that the system clock is running. otherwise the watchdog reset is enabl ed. this behavior can be considered as a clock monitoring. if the standard watchdog functionality is not desired, the attiny87/167 watchdog permits the system clock to be monitored with out having to resort to the complexity of a full software watchdog handler. the solution proposed in the attiny87/167 is to automate the watchdog reloading with only one command, at the beginning of the session. so, to monitor the system clock, the user will have two options: 1. using the standard watchdog features (software reload), 2. or using the automatic reloading (hardware reload). the two options are exclusive. note: warning : these two options make sense on ly if the clock source at reset is an in ternal source. the fuse settings determine this operation. figure 4-6. watchdog timer with automatic reloading. the ? enable watchdog in automatic reload mode ? command has priority over the standard watchdog enabling. in this mode, only the reset function of the watchdog is enabled (no more watchdog interrupt). the wdp3..0 bits of the wdtcsr register always determine the watch- dog timer prescaling. as the watchdog will not be ac tive before executing the ? enable watchdog in automatic reload mode ? command, it is recommended to activate this command before switching to an external clock source (see note on page 35 ). notes: 1. only the reset (watchdog reset included) disables this function. the watchdog system reset flag (wdrf bit of mcusr register) can be used to monitor the reset cause. 2. only clock frequencies greater than or equal to (4 * watchdog clock frequency) can be monitored. internal bus register: wdtcsr wde wdp [3..0] wdif wdie checker reload enable system clk automatic reloading mode watchdog clock wd interrupt wd reset watchdog 01
36 7728g?avr?06/10 attiny87/attiny167 here is a ?light? c-code of a clock switching function using automatic clock monitoring. c code example void clockswiching (unsigned char clk _ number, unsigned char sut) { #define clock _ recover 0x05 #define clock _ enable 0x02 #define clock _ switch 0x04 #define clock _ disable 0x01 #define wd _ arl _ enable 0x06 #define wd _ 2048cycles 0x07 unsigned char previous _ clk, temp; // disable interrupts temp = sreg; asm ("cli"); // save the current system clock source clkcsr = 1 << clkcce; clkcsr = clock _ recover; previous _ clk = clkselr & 0x0f; // enable the new clock source clkselr = ((sut << 4 ) & 0x30) | (clk _ number & 0x0f); clkcsr = 1 << clkcce; clkcsr = clock _ enable; // wait for clock validity while ((clkcsr & (1 << clkrdy)) == 0); // switch clock source clkcsr = 1 << clkcce; clkcsr = clock _ switch; // wait for effective switching while (1){ clkcsr = 1 << clkcce; clkcsr = clock _ recover; if ((clkselr & 0x0f) == (clk _ number & 0x0f)) break; } // shut down unneeded clock source if (previous_clk != (clk_number & 0x0f)) { clkselr = previous _ clk; clkcsr = 1 << clkcce; clkcsr = clock _ disable; } // re-enable interrupts sreg = temp; } // enable the watchdog in automatic reload mode wdtcsr = (1 << wdce) | (1 << wde); wdtcsr = (1 << wde ) | wd _ 2048cycles; clkcsr = 1 << clkcce; clkcsr = wd _ arl _ enable;
37 7728g?avr?06/10 attiny87/attiny167 4.4 system clock prescaler 4.4.1 features the attiny87/167 system clock can be divided by setting the clock prescaler register ? clkpr. this feature can be used to decrease power consumption when the requirement for processing power is low. this can be used with all clock source options, and it will affect the clock frequency of the cpu and all synchronous peripherals. clk i/o , clk adc , clk cpu , and clk flash are divided by a factor as shown in table 4-10 on page 39 . 4.4.2 switching time when switching between prescaler settings, the system clock presca ler ensures that no glitches occur in the clock system and that no intermediate frequency is higher than neither the clock frequency corresponding to the previous setting, nor the clock frequency corre- sponding to the new setting. the ripple counter that implements the prescaler runs at the frequency of the undivided clock, which may be faster than the cpu?s clock frequency. hence, it is not possible to determine the state of the prescaler ? even if it were readable, and the exact time it takes to switch from one clock division to another cannot be exactly predicted. from the time the clkps values are written, it takes between t1 + t2 and t1 + 2*t2 before the new clock frequency is active. in this interval, 2 active clock edges are produced. here, t1 is the previous clock period, and t2 is the pe riod corresponding to the new prescaler setting. 4.5 register description 4.5.1 osccal ? oscillato r calibration register ? bits 7:0 ? cal7:0: oscillator calibration value the oscillator calibration register is used to trim the calibrated internal rc oscillator to remove process variations from the oscillator frequency. the factory-calibrated value is auto- matically written to this regist er during chip reset, giving an oscillator frequency of 8.0 mhz at 25c. the application software can write this register to change the oscillator frequency. the oscillator can be calibrated to any frequency in the range 7. 3 - 8.1 mhz within 2% accuracy. calibration outside that range is not guaranteed. note that this oscillator is used to time eeprom and flash write accesses, and these write times will be affected accordingly. if the eepr om or flash are writt en, do not calibrate to more than 8.8 mhz. otherwise, th e eeprom or flash write may fail. the cal7 bit determines the range of operation for the oscillato r. setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. the two fre- quency ranges are overlapping, in other words a setting of osccal = 0x7f gives a higher frequency than osccal = 0x80. the cal6..0 bits are used to tune the frequency within the selected range. a setting of 0x00 gives the lowest frequency in that range, and a setting of 0x7f gives the highest frequency in 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 specific calibration value
38 7728g?avr?06/10 attiny87/attiny167 the range. incrementing cal6..0 by 1 will give a frequency incremen t of less than 2% in the frequency range 7.3 - 8.1 mhz. 4.5.2 clkpr ? clock prescaler register ? bit 7 ? clkpce: clock prescaler change enable the clkpce bit must be written to logic one to enable change of the clkps bits. the clk- pce bit is only updated when the other bits in clkpr are simultaneously written to zero. clkpce is cleared by hard ware four cycles after it is written or w hen the clkps bits are writ- ten. rewriting the clkpce bit within this time-out period does neither extend the time-out period, nor clear the clkpce bit. ? bits 6:4 ? res: reserved bits these bits are reserved bits in the at tiny87/167 and will always read as zero. ? bits 3:0 ? clkps3:0: clock prescaler select bits 3 - 0 these bits define the division factor between the selected clock source and the internal sys- tem clock. these bits can be written run-time to vary the clock frequency to suit the application requirements. as the divider divides the master clock input to the mcu, the speed of all syn- chronous peripherals is reduced when a division factor is used. the division factors are given in table 4-10 . to avoid unintentional changes of clock frequency, a special write procedure must be followed to change the clkps bits: 1. write the clock prescaler change enable (clkpce) bit to one and all other bits in clkpr to zero. 2. within four cycles, write the desired valu e to clkps while writing a zero to clkpce. interrupts must be disabled when changing prescaler setting in order not to disturb the procedure. the ckdiv8 fuse determines the initial value of the clkps bits . if ckdiv8 is unprogrammed, the clkps bits will be reset to ?0000?. if ckdiv8 is program med, clkps bits are reset to ?0011?, giving a division factor of eight at star t up. this feature should be used if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. note that any value can be written to th e clkps bits rega rdless of the ckdiv8 fuse setting. the application software must ensure that a sufficient division factor is chosen if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. the device is shipped with the ckdiv8 fuse programmed. bit 76543210 clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 clkpr read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 see bit description
39 7728g?avr?06/10 attiny87/attiny167 4.5.3 clkcsr ? clock control & status register ? bit 7 ? clkcce: clock control change enable the clkcce bit must be written to logic one to enable change of the clkcsr bits. the clkcce bit is only updated when the other bits in clkcsr are simultaneously written to zero. clkcce is cleared by hardware four cycl es after it is written or when the clkcsr bits are written. rewriting the clkcce bit within this time-out period does neither extend the time-out period, nor clear the clkcce bit. ? bits 6:5 ? res: reserved bits these bits are reserved bits in the at tiny87/167 and will always read as zero. ? bits 4 ? clkrdy: clock ready flag this flag is the output of the ? clock availability ? logic. this flag is cleared by the ? request for clock availability ? command or ? enable clock source ? command being entered. it is set when ? clock availability ? logic confirms that the (selected) clock is running and is sta- ble. the delay from the request and the flag setting is not fixed, it depends on the clock table 4-10. clock prescaler select clkps3 clkps2 clkps1 clkps0 clock division factor 0000 1 0001 2 0010 4 0011 8 0100 16 0101 32 0110 64 0111 128 1000 256 1 0 0 1 reserved 1 0 1 0 reserved 1 0 1 1 reserved 1 1 0 0 reserved 1 1 0 1 reserved 1 1 1 0 reserved 1 1 1 1 reserved bit 7 65 4 3210 clkcce ? ? clkrdy clkc3 clkc2 clkc1 clkc0 clkcsr read/write r/w r r r r/w r/w r/w r/w initial value0 00 0 0000
40 7728g?avr?06/10 attiny87/attiny167 start-up time, the clock frequency and, of course, if the clock is alive. the user?s code has to differentiate between ? no_clock_signal ? and ? clock_signal_not_yet_available ? condition. ? bits 3:0 ? clkc3:0: clock control bits 3 - 0 these bits define the command to provide to the ? clock switch? module. the special write pro- cedure must be followed to change the clkc3..0 bits ( see ?bit 7 ? clkcce: clock control change enable? on page 39. ). 1. write the clock control change enable (clkcce) bit to one and all other bits in clkcsr to zero. 2. within 4 cycles, write the desired value to clkcsr register while clearing clkcce bit. interrupts should be disabled when setting clkcsr register in order not to disturb the procedure. 4.5.4 clkselr - clock selection register ? bit 7? res: reserved bit this bit is reserved bit in the atti ny87/167 and will always read as zero. ? bit 6 ? cout: clock out the cout bit is initialized with ~(ckout) fuse bit. the cout bit is only used in case of ? ckout ? command. refer to section 4.2.7 ?clock output buffer? on page 31 for using. in case of ? recover system clock source ? command, cout it is not affected (no recovering of this setting). table 4-11. clock command list. clock command clkc3..0 no command 0000 b disable clock source 0001 b enable clock source 0010 b request for clock availability 0011 b clock source switch 0100 b recover system clock source code 0101 b enable watchdog in automatic reload mode 0110 b ckout command 0111 b no command 1 xxx b bit 7 6 543210 - cout csut1 csut0 csel3 csel2 csel1 csel0 clkselr read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 ~ (ckout) fuse sut1..0 fuses cksel3..0 fuses
41 7728g?avr?06/10 attiny87/attiny167 ? bits 5:4 ? csut1:0: clock start-up time csut bits are initialized with the values of sut fuse bits. in case of ? enable/disable clock source ? command, csut field provides the code of the clock start-up time. refer to subdivisions of section 4.2 ?clock sources? on page 25 for code of clock start-up times. in case of ? recover system clock source ? command, csut field is not affected (no recover- ing of sut code). ? bits 3:0 ? csel3:0: clock source select csel bits are initialized with the values of cksel fuse bits. in case of ? enable/disable clock source ?, ? request for clock availability ? or ? clock source switch ? command, csel field provides the code of the clock source. refer to table 4-1 on page 25 and subdivisions of section 4.2 ?clock sources? on page 25 for clock source codes. in case of ? recover system clock source ? command, csel field contains the code of the clock source used to drive the clock control unit as described in figure 4-1 on page 24 .
42 7728g?avr?06/10 attiny87/attiny167 5. power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes allowing the user to tailor the power consump- tion to the application?s requirements. when enabled, the brown-out detector (bod) actively monitors the power supply voltage dur- ing the sleep periods. to further save power, it is possible to disable the bod in some sleep modes. see ?bod disable? on page 43 for more details. 5.1 sleep modes figure 4-1 on page 24 presents the different clock systems in the attiny87/167, and their dis- tribution. the figure is helpful in selecting an appropriate sleep mode. table 5-1 shows the different sleep modes, their wake up sources and bod disable ability. note: 1. for int1 and int0, only level interrupt. to enter any of the four sleep modes, the se bit in smcr must be written to logic one and a sleep instruction must be exec uted. the sm1, and sm0 bits in the smcr register select which sleep mode (idle, adc no ise reduction, powe r-down, or power-save) will be activated by the sleep instruction. see table 5-2 on page 47 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mo de, the mcu wakes up. the mcu is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction follow ing 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 5-1. active clock domains and wake-up sources in the different sleep modes active clock domains oscillators wake-up sources software bod disable sleep mode clk cpu clk flash clk io clk adc clk asy main clock source enabled timer0 osc. enable int1, int0 and pin change spm/eeprom ready adc wdt usi start condition timer0 other i/o idle x x x x x x x xxxxx adc noise reduction xx x x x (1) x xxxx power-down x (1) xx x power-save x x x (1) xxx x
43 7728g?avr?06/10 attiny87/attiny167 5.2 bod disable when the brown-out detector (bod) is enabled by bodlevel fuses, table 21-3 on page 226 , the bod is actively monitoring the power supply voltage during a sleep period. to save power, it is possible to disable the bod by software for some of the sleep modes, see table 5-1 . the sleep mode power consumpt ion will then be at the same level as when bod is glob- ally disabled by fuses. if bod is disabled in software, the bod function is turned off immediately after entering the sleep mode. upon wake-up from sleep, bod is automatically enabled again. this ensures safe operation in case the vcc level has dropped during the sleep period. when the bod has been disabl ed, the wake-up time from sl eep mode will be approximately 60 s to ensure that the bod is working correctly before the mcu continues executing code. bod disable is controlled by bods bit (bod sleep) in the control register mcucr, see ?mcucr ? mcu control register? on page 47 . setting it to one turns off the bod in relevant sleep modes, while a zero in this bit keeps bo d active. default setting keeps bod active, i.e. bods is cleared to zero. writing to the bods bit is controll ed by a timed sequence and an enable bit, see ?mcucr ? mcu control register? on page 47 . 5.3 idle mode when the sm1..0 bits are written to 00, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing the spi, an alog comparator, adc, usi start condition, asynchronous timer/counter, watchdog, and the interrupt system to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the other clocks to run. idle mode enables the mcu to wake up from external triggered interrupts as well as internal ones like the spi 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 compara- tor control and status register ? acsr. this will reduce power consumption in idle mode. if the adc is enabled, a conversion starts au tomatically when this mode is entered. 5.4 adc noise reduction mode when the sm1..0 bits are written to 01, the sleep instruction makes the mcu enter adc noise reduction mode, stopping the cpu but allo wing the adc, the external interrupts, the usi start condition, the asynchronous timer/counter and the watchdog to continue operating (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 adc, enabling higher resolution measurements. if the adc is enabled, a conversion starts automa tically when this mode is entered. apart from the adc conversion complete inte rrupt, only an external reset, a watchdog system reset, a watchdog interrupt, a brown-out reset, a usi start condition interrupt, an asynchronous timer/counter inte rrupt, an spm/eeprom read y interrupt, an external level inte rrupt on int0 or int1 or a pin change interrupt can wake up the mcu from adc noise reduction mode.
44 7728g?avr?06/10 attiny87/attiny167 5.5 power-down mode when the sm1..0 bits are written to 10 , the sleep instruction makes the mcu enter power-down mode. in this mode, the external os cillator is stopped, while the external inter- rupts, the usi start condition, and the watchdog continue operating (if enabled). only an external reset, a watchdog system reset, a watchdog interrupt, a brown-out reset, the usi start condition interrupt, an external level interrupt on int0 or int1, or a pin change interrupt can wake up the mcu. this sl eep mode basically halts all g enerated clocks, allowing opera- tion 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 section 8. ?external interrupts? on page 62 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 section 4.2 ?clock sources? on page 25 . 5.6 power-save mode when the sm1..0 bits are written to 11 , the sleep instruction makes the mcu enter power-save mode. this mode is identica l to power-down, wi th one exception: if timer/counter0 is clocked a synchronously, i.e., t he as0 bit in assr is set, time r/counter0 will run during sleep. th e device can wake up from either timer overflow or output compare event from timer/counter0 if the corresponding timer/counter0 interrupt enable bits are set in timsk0, and the global interrupt enable bit in sreg is set. if the asynchronous timer is not clocked asynchronously, po wer-down mode is recom- mended 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 asynchro- nous modules, including timer/coun ter0 if clocked asynchronously. 5.7 power reduction register the power reduction register (prr), see ?prr ? power reduction register? on page 47 , provides a method to stop the clock to individual peripherals to reduce power consumption. the current state of the peripheral is frozen and the i/o registers can not be read or written. resources used by the periphe ral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock. waking up a module, which is done by clearing the bit in prr, puts the module in the same state as before shutdown. module shutdown can be used in idle mode and active mode to significantly reduce the overall power consumption. in all other sleep modes, the clock is already stopped.
45 7728g?avr?06/10 attiny87/attiny167 5.8 minimizing power consumption there are several possibilities to consider w hen 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 fe w as possible of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption. 5.8.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 ext ended conversion. refer to section 17. ?adc ? analog to digital con- verter? on page 191 for details on adc operation. 5.8.2 analog comparator when entering idle mode, the analog comparator should be disabled if not used. when enter- ing adc noise reduction mode, the analog comparator should be disabled. in other sleep modes, the analog comparator is automatically disabled. however, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be dis- abled in all sleep modes. otherwise, the internal voltage re ference will be enabled, independent of sleep mode. refer to section 18. ?anacomp - analog comparator? on page 211 for details on how to configure the analog comparator. 5.8.3 brown-out detector if the brown-out detector is not needed by the application, this module should be turned off. if the brown-out detector is enabled by the bo dlevel fuses, it will be enabled in all sleep modes, and hence, always cons ume power. in the de eper sleep modes, th is will contribute significantly to the total current consumption. refer to section 6.1.5 ?brown-out detection? on page 51 for details on how to configure the brown-out detector. 5.8.4 internal voltage reference the internal voltage re ference will be enabled wh en needed by the brow n-out detection, the analog comparator or the adc. if these modules are disabled as described in the sections above, the internal voltage reference will be disabled and it will not be consuming power. when turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to section 6.2 ?internal voltage reference? on page 53 for details on the start-up time. output the internal voltage reference is not needed in the deeper sleep modes. this module should be turned off to reduce significantly to the total current consumption. refer to ?amiscr ? analog miscellaneous control register? on page 190 for details on how to disable the inter- nal voltage reference output. 5.8.5 internal current source the internal current source is not needed in the deeper sleep modes. this module should be turned off to reduce significantly to the total current consumption. refer to ?amiscr ? analog miscellaneous control register? on page 190 for details on how to disable the internal current source.
46 7728g?avr?06/10 attiny87/attiny167 5.8.6 watchdog timer if the watchdog timer is not needed in the application, the module should be turned off. if the watchdog timer is enabled, it will be enabled in all sleep modes and hence always consume power. in the deeper sleep modes, this will contribute significantly to the total current con- sumption. refer to section 6.3 ?watchdog timer? on page 53 for details on how to configure the watchdog timer. 5.8.7 port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where 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 section 9.2.6 ?digital input enable and sleep modes? on page 72 for details on which pins are enabled. if the input buffer is enabled and the input signal is left floating or have an analog si gnal level close to vcc/2, the input buffer will use excessive power. for analog input pins, the digital input buffer should be disabled at all times. an analog signal level close to vcc/2 on an input pin can cause si gnificant current even in active mode. digital input buffers can be disabled by writing to the digital input disable registers (didr1 and didr0). refer to section 17.11.6 ?didr1 ? digital input disable register 1? on page 210 and section 17.11.5 ?didr0 ? digital input disable register 0? on page 209 for details. 5.8.8 on-chip debug system if the on-chip debug system is enabled by the dwen fuse and the chip enters sleep mode, the main clock source is enabled and hence always consumes power. in the deeper sleep modes, this will contribute significantly to the total cu rrent consumption. 5.9 register description 5.9.1 smcr ? sleep mode control register the sleep mode control register contains control bits for power management. ? bits 7..3 res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. ? bits 2..1 ? sm1..0: sleep mode select bits 1, and 0 these bits select between the four available sleep modes as shown in table 5-2 . bit 76543210 ?????sm1sm0sesmcr read/write rrrrrr/wr/wr/w initial value00000000
47 7728g?avr?06/10 attiny87/attiny167 ? bit 0 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the slee p mode unless it is the pro- grammer?s purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep inst ruction and to clear it im mediately after waking up. 5.9.2 mcucr ? mcu control register ? bit 6 ? bods: bod sleep the bods bit must be written to logic one in order to turn off bod during sleep, see table 5-1 on page 42 . writing to the bods bit is controll ed by a timed sequence and an enable bit, bodse in mcucr. to disable bod in rele vant sleep modes, both bods and bodse must first be set to one. then, to set the bods bit, bods must be set to one and bodse must be set to zero within four clock cycles. the bods bit is active three clock cycles after it is set. a sleep instruction must be executed while bods is active in order to turn off t he bod for the actual sleep mode. the bods bit is automatically cleared after three clock cycles. ? bit 5 ? bodse: bod sleep enable bodse enables setting of bods control bit, as explained in bods bit description. bod dis- able is controlled by a timed sequence. 5.9.3 prr ? power reduction register ? bit 7 - res: reserved bit this bit is reserved in attiny87 /167 and will always read as zero. ? bit 6 - res: reserved bit this bit is reserved in attiny87 /167 and will always read as zero. table 5-2. sleep mode select sm1 sm0 sleep mode 00idle 0 1 adc noise reduction 10power-down 11power-save bit 7 6 5 4 3 2 1 0 ? bods bodse pud ? ? ? ? mcucr read/write r r/w r/w r/w r r r r initial value 0 0 0 0 0 0 0 0 bit 76543210 ? ? prlin prspi prtim1 prtim0 prusi pradc prr read/write r r r/wr/wr/wr/wr/wr/w initial value 0 0 0 0 0 0 0 0
48 7728g?avr?06/10 attiny87/attiny167 ? bit5 - prlin: power reduction lin / uart controller writing a logic one to this bit shuts down the lin by stopping the clock to the module. when waking up the lin again, the lin should be re initialized to ensure proper operation. ? bit 4 - prspi: power reduction serial peripheral interface if using debugwire on-chip debug system, this bit should not be written to one. writing a logic one to this bit sh uts down the serial peripheral interface by stopping the clock to the module. when waking up the spi again, the spi should be re initialized to ensure proper operation. ? bit 3 - prtim1: power reduction timer/counter1 writing a logic one to this bit shuts down the timer/counter1 module. when the timer/counter1 is enabl ed, operation will continue like before the shutdown. ? bit 2 - prtim0: power reduction timer/counter0 writing a logic one to this bit shuts down the timer/counter0 module in synchronous mode (as0 is 0). when the timer/counter0 is enabled, operation will continue like before the shutdown. ? bit 1 - prusi: power reduction usi writing a logic one to this bit shuts down the usi by stopping the clock to the module. when waking up the usi again, the usi should be re-initialized to ensure proper operation. ? bit 0 - pradc: power reduction adc writing a logic one to this bit shuts down t he adc. the adc must be disabled before shut down. the analog comparator cannot use the adc input mux when the adc is shut down.
49 7728g?avr?06/10 attiny87/attiny167 6. system control and reset 6.1 reset 6.1.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 an rjmp ? relative jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. the circuit diagram in figure 6-1 shows the reset circuit. tables in section 22.5 ?reset characterist ics? on page 246 defines the electrical parame ters of the reset circuitry. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay counter is defined by the us er through the sut and cksel fuses. the different selections for the delay period are presented in section 4.2 ?clock sources? on page 25 . 6.1.2 reset sources the attiny87/167 has four 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 wh en a low level is present on the reset pin for longer than the minimum pulse length. ? watchdog system reset. the mcu is reset when the watchdog timer period expires and the watchdog system reset mode is enabled. ? brown-out reset. the mcu is reset when the supply voltage vcc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled.
50 7728g?avr?06/10 attiny87/attiny167 figure 6-1. reset circuit 6.1.3 power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detection level is defined in table 22-4 on page 246 . the por is activated whenever vcc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reaching the power-on reset threshold voltage invokes the delay counter, which determines how long the device is kept in reset after vcc rise. t he reset signal is activated again, without any delay, when vcc decreases below the detection level. figure 6-2. mcu start-up, reset tied to vcc mcu status register (mcusr) brown-out reset circuit bodlevel [2..0] delay counters cksel[3:0] ck timeout wdrf borf extrf porf data bus clock generator spike filter pull-up resistor watchdog oscillator sut[1:0] power-on reset circuit rstdisbl v time-out internal reset t tout v pot v pormax v pormin cc v ccrr
51 7728g?avr?06/10 attiny87/attiny167 figure 6-3. mcu start-up, reset extended externally 6.1.4 external reset an external reset is generate d by a low level on the reset pin. reset pulses longer than the minimum pulse width (see table 22-3 on page 246 ) 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. the external reset can be disabled by the rstdisbl fuse, see table 21-4 on page 226 . figure 6-4. external reset during operation 6.1.5 brown-out detection attiny87/167 has an on-chip brown-out detection (bod) circuit for monitoring the vcc level during operation by comparing it to a fixed trigger level. the trigger level for the bod can be selected by the bodlevel fuses ( see ?bodlevel fuse coding? on page 247. ). the trigger level has a hysteresis to ensure spike free brow n-out detection. the hysteresis on the detec- tion level should be interpreted as v bot + =v bot +v hyst /2andv bot ? =v bot -v hyst /2. when the bod is enabled, and vcc decreases to a value below the trigger level (v bot ? in fig- ure 6-5 ), the brown-out reset is immediately activated. when vcc increases above the trigger level (v bot + in figure 6-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 vcc if the voltage stays below th e trigger level for lon- ger than t bod given in table 22-6 on page 247 . v reset time-out internal reset t tout v rst v por cc v ccrr cc
52 7728g?avr?06/10 attiny87/attiny167 figure 6-5. brown-out reset during operation 6.1.6 watchdog system reset when the watchdog times out, it will generate a short reset pulse of one ck cycle duration. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . refer to page 53 for details on operation of the watchdog timer. figure 6-6. watchdog system reset during operation 6.1.7 mcu status register ? mcusr the mcu status register provides information on which reset source caused an mcu reset. ? bit 7..4 ? res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. ? bit 3 ? wdrf: watchdog system reset flag this bit is set if a watchdog system reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. v cc reset time-out internal reset v bot- v bot+ t tout ck cc bit 76543210 ? ? ? ? wdrf borf extrf porf mcusr read/write rrrrr/wr/wr/wr/w initial value 0 0 0 0 see bit description
53 7728g?avr?06/10 attiny87/attiny167 ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcusr as early as possible in the prog ram. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 6.2 internal voltage reference attiny87/167 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. 6.2.1 voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in table 22-7 on page 247 . 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 prog ramming the bodlevel [2:0] fuses). 2. when the bandgap reference is connected to the analog comparator (by setting the acirs bit in acsr). 3. when the adc is enabled. thus, when the bod is not enabled, after setting the acirs bit or enabling the adc, the user must always allow the reference to start up before the output from the analog comparator or adc is used. to reduce power consumption in power-down mode or in power-save, the user can avoid the three conditions above to ensure t hat the reference is turned off before entering in these power reduction modes. 6.3 watchdog timer attiny87/167 has an enhanced watchdog timer (wdt). the main features are: ? clocked from separat e on-chip oscillator ? 4 operating modes ?interrupt ? system reset ? interrupt and system reset ? clock monitoring ? selectable time-out period from 16ms to 8s ? possible hardware fuse watchdog al ways on (wdton) for fail-safe mode 6.3.1 watchdog timer behavior the watchdog timer (wdt) is a timer counting cycles of a separate on-chip 128 khz oscillator.
54 7728g?avr?06/10 attiny87/attiny167 figure 6-7. watchdog timer the wdt gives an interrupt or a system reset when the counter reaches a given time-out value. in normal oper ation mode, it is required that the system uses the wdr - watchdog timer reset - instruction to restart the counter before the time-out value is reached. if the sys- tem doesn't restart the counter, an inte rrupt or system rese t will be issued. in interrupt mode, the wdt gives an interrupt when the timer expires. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one example is to limit the maximum time allowed for certain operations, giving an interrupt when the opera- tion has run longer than expected. in system reset mode, the wdt gives a reset when the timer expires. this is typically used to prevent system hang-up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an interrupt and then switch to system reset mode. this mode will for instance allow a safe shutdown by saving critical parameters before a system reset. the watchdog always on (wdton) fuse, if pr ogrammed, will force the watchdog timer to system reset mode. with the fuse programmed the system reset mode bit (wde) and inter- rupt mode bit (wdie) are locked to 1 and 0 respectively. to further ensure program security, alterations to the watchdog set-up must follo w timed sequences. the sequence for clearing wde and changing time-out configuration is as follows: 1. in the same operation, write a logic one to the watchdog change enable bit (wdce) and wde. a logic one must be written to wde regardless of the previous value of the wde bit. 2. within the next four clock cycles, write the wde and watchdog prescaler bits (wdp) as desired, but with the wdce bit cleared. this must be done in one operation. mcu reset watchdog reset clock monitoring interrupt wde wdif wdie wdp0 wdp1 wdp2 wdp3 osc / 1024k osc / 512k osc / 4k osc / 2k osc / 256k osc / 128k osc / 64k osc / 32k osc / 16k osc / 8k watchdog prescaler ~128 khz oscillator
55 7728g?avr?06/10 attiny87/attiny167 the following code example shows one assemb ly and one c function for turning off the watchdog timer. the example assumes that interrupts are controlled (e.g. by disabling inter- rupts globally) so that no interrupts will o ccur during the executio n of these functions. note: 1. see ?about code examples? on page 6. note that if the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset an d the watchdog timer will stay enabled. if the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. to avoid this situation, the application software should always clear the watchdog sys- tem reset flag (wdrf) and the wde control bit in the initialization routine, even if the watchdog is not in use. assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< 56 7728g?avr?06/10 attiny87/attiny167 the following code example shows one assembly and one c function for changing the time-out value of the watchdog timer. notes: 1. see ?about code examples? on page 6. 2. the watchdog timer should be reset before any change of the wdp bits, since a change in the wdp bits can result in a time-out when switching to a shorter time-out period. 6.3.2 clock monitoring the watchdog timer can be used to detect a loss of system clock. this configuration is driven by the dynamic clock switch circuit. please refer to section 4.3.8 ?clock monitoring? on page 34 for more information. assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence lds r16, wdtcr ori r16, (1< 57 7728g?avr?06/10 attiny87/attiny167 6.3.3 watchdog timer control register - wdtcr ? bit 7 - wdif: watchdog interrupt flag this bit is set when a time-out occurs in the watchdog timer and the watchdog timer is con- figured for interrupt. wdif is cleared by hard ware when executing the corresponding interrupt handling vector. alternatively, wdif is cleared by writing a logic one to the flag. when the i-bit in sreg and wdie are set, the watchd og time-out interrupt is executed. ? bit 6 - wdie: watchdog interrupt enable when this bit is written to one and the i-bit in the status register is set, the watchdog interrupt is enabled. if wde is cleared in combination with this setting, the watchdog timer is in inter- rupt mode, and the corresponding interrupt is executed if time-out in the watchdog timer occurs. if wde is set, the watchdog timer is in interrupt and system reset mode. the first time-out in the watchdog timer will set wdif. executing the corresponding interr upt vector will clear wdie and wdif automatically by hardware (the watchdog goes to system reset mode). this is useful for keeping the watchdog timer security while using the interrup t. to stay in interrupt and system reset mode, wdie must be set after each interrupt. this should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the watchdog system reset mode. if the interrupt is not executed before the next time-out, a system reset will be applied. if the watchdog timer is used as clock monitor (c.f. section ? ?bits 3:0 ? clkc3:0: clock con- trol bits 3 - 0? on page 40 ), the system reset mode is enabled and the interrupt mode is automatically disabled. note: 1. at least one of these three enables (wdton, wde & wdie) equal to 1. ? bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changing wde and prescaler bits. to clear the wde bit, and/or change the prescaler bits, wdce must be set. once written to one, ha rdware will clear wdce after four clock cycles. bit 76543210 wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 wdtcr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 x 0 0 0 table 6-1. watchdog timer configuration clock monitor wdton wde wdie mode action on time-out x 0 0 0 stopped none on y (1) y (1) y (1) system reset mode reset off 0 0 1 interrupt mode interrupt 0 1 0 system reset mode reset 011 interrupt and system reset mode interrupt, then go to system reset mode 1 x x system reset mode reset
58 7728g?avr?06/10 attiny87/attiny167 ? bit 3 - wde: watchdog system reset enable wde is overridden by wdrf in mcusr. this means that wde is always set when wdrf is set. to clear wde, wdrf must be cleared first. this feature ensures multiple resets during conditions causing failure, and a safe start-up after the failure. ? bit 5, 2..0 - wdp3..0: watchdog timer prescaler 3, 2, 1 and 0 the wdp3..0 bits determine the watchdog timer prescaling when the watchdog timer is run- ning. the different prescaling values and t heir corresponding time-out periods are shown in table 6-2 on page 58 . table 6-2. watchdog timer prescale select wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at vcc = 5.0v 0 0 0 0 2k (2048) cycles 16 ms 0 0 0 1 4k (4096) cycles 32 ms 0 0 1 0 8k (8192) cycles 64 ms 0 0 1 1 16k (16384) cycles 0.125 s 0 1 0 0 32k (32768) cycles 0.25 s 0 1 0 1 64k (65536) cycles 0.5 s 0 1 1 0 128k (131072) cycles 1.0 s 0 1 1 1 256k (262144) cycles 2.0 s 1 0 0 0 512k (524288) cycles 4.0 s 1 0 0 1 1024k (1048576) cycles 8.0 s 1010 reserved 1011 1100 1101 1110 1111
59 7728g?avr?06/10 attiny87/attiny167 7. interrupts this section describes the specifics of the interrupt handling as performed in attiny87/167. for a general explanation of the avr interrupt handling, refer to ?reset and interrupt han- dling? on page 12 . 7.1 interrupt vectors in attiny87/167 table 7-1. reset and interrupt vectors in attiny87/167 vector nb. program address source interrupt definition attiny87 attiny167 1 0x0000 0x0000 reset external pin, power-on reset, brown-out reset and watchdog system reset 2 0x0001 0x0002 int0 external interrupt request 0 3 0x0002 0x0004 int1 external interrupt request 1 4 0x0003 0x0006 pcint0 pin change interrupt request 0 5 0x0004 0x0008 pcint1 pin change interrupt request 1 6 0x0005 0x000a wdt watchdog time-out interrupt 7 0x0006 0x000c timer1 capt timer/counter1 capture event 8 0x0007 0x000e timer1 compa tim er/counter1 compare match a 9 0x0008 0x0010 timer1 compb timer/coutner1 compare match b 10 0x0009 0x0012 timer1 ovf timer/counter1 overflow 11 0x000a 0x0014 timer0 compa timer/counter0 compare match a 12 0x000b 0x0016 timer0 ovf timer/counter0 overflow 13 0x000c 0x0018 lin tc lin/uart transfer complete 14 0x000d 0x001a lin err lin/uart error 15 0x000e 0x001c spi, stc spi serial transfer complete 16 0x000f 0x001e adc adc conversion complete 17 0x0010 0x0020 ee ready eeprom ready 18 0x0011 0x0022 analog comp analog comparator 19 0x0012 0x0024 usi start usi start condition detection 20 0x0013 0x0026 usi ovf usi counter overflow
60 7728g?avr?06/10 attiny87/attiny167 7.2 program setup in attiny87 the most typical and general program setup for the reset and interrupt vector addresses in attiny87 is (2-byte step - using ?rjmp? instruction): address (note:) label code comments 0x0000 rjmp reset ; reset handler 0x0001 rjmp int0addr ; irq0 handler 0x0002 rjmp int1addr ; irq1 handler 0x0003 rjmp pcint0addr ; pcint0 handler 0x0004 rjmp pcint1addr ; pcint1 handler 0x0005 rjmp wdtaddr ; watchdog timer handler 0x0006 rjmp icp1addr ; timer1 capture handler 0x0007 rjmp oc1aaddr ; timer1 compare a handler 0x0008 rjmp oc1baddr ; timer1 compare b handler 0x0009 rjmp ovf1addr ; timer1 overflow handler 0x000a rjmp oc0aaddr ; timer0 compare a handler 0x000b rjmp ovf0addr ; timer0 overflow handler 0x000c rjmp lintcaddr ; lin transfer complete handler 0x000d rjmp linerraddr ; lin error handler 0x000e rjmp spiaddr ; spi transfer complete handler 0x000f rjmp adccaddr ; adc conversion complete handler 0x0010 rjmp erdyaddr ; eeprom ready handler 0x0011 rjmp aciaddr ; analog comparator handler 0x0012 rjmp usistartaddr ; usi start condition handler 0x0013 rjmp usiovfaddr ; usi overflow handler 0x0014 reset: ldi r16, high(ramend); main program start 0x0015 out sph,r16 ; set stack pointer to top of ram 0x0016 ldi r16, low(ramend) 0x0017 out spl,r16 0x0018 sei ; enable interrupts 0x0019 xxx ... ... ... ... note: 16-bit address
61 7728g?avr?06/10 attiny87/attiny167 7.3 program setup in attiny167 the most typical and general program setup for the reset and interrupt vector addresses in attiny167 is (4-byte step - using ?jmp? instruction): address (note:) label code comments 0x0000 jmp reset ; reset handler 0x0002 jmp int0addr ; irq0 handler 0x0004 jmp int1addr ; irq1 handler 0x0006 jmp pcint0addr ; pcint0 handler 0x0008 jmp pcint1addr ; pcint1 handler 0x000a jmp wdtaddr ; watchdog timer handler 0x000c jmp icp1addr ; timer1 capture handler 0x000e jmp oc1aaddr ; timer1 compare a handler 0x0010 jmp oc1baddr ; timer1 compare b handler 0x0012 jmp ovf1addr ; timer1 overflow handler 0x0014 jmp oc0aaddr ; timer0 compare a handler 0x0016 jmp ovf0addr ; timer0 overflow handler 0x0018 jmp lintcaddr ; lin transfer complete handler 0x001a jmp linerraddr ; lin error handler 0x001c jmp spiaddr ; spi transfer complete handler 0x001e jmp adccaddr ; adc conversion complete handler 0x0020 jmp erdyaddr ; eeprom ready handler 0x0022 jmp aciaddr ; analog comparator handler 0x0024 jmp usistartaddr ; usi start condition handler 0x0026 jmp usiovfaddr ; usi overflow handler 0x0028 reset: ldi r16, high(ramend); main program start 0x0029 out sph,r16 ; set stack pointer to top of ram 0x002a ldi r16, low(ramend) 0x002b out spl,r16 0x002c sei ; enable interrupts 0x002d xxx ... ... ... ... note: 16-bit address
62 7728g?avr?06/10 attiny87/attiny167 8. external interrupts 8.1 overview the external interrupts are triggered by the int1..0 pins or any of the pcint15..0 pins. observe that, if enabled, the interrupts will trigger even if the int1..0 or pcint15..0 pins are configured as outputs. this feature provides a way of generating a software interrupt. the pin change interrupt pcint1 will trigger if any enabled pcin t15..8 pin togg les. the pin change interrupt pcint0 will tri gger if any enabled pcint7..0 pin toggles. the pcmsk1 and pcmsk0 registers control which pins contri bute to the pin change interrupts. pin change interrupts on pcint15..0 are detected asynchronous ly. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the int1..0 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 register a ? eicra. when the int1..0 interrupts are enabled and are configured as level tr iggered, the inte rrupts will trig- ger as long as the pin is held low. the recognition of falling or rising edge interrupts on int1..0 requires the presence of an i/o clock, described in ?clock systems and their distribution? on page 24 . low level interrupts and the edge interrupt on int1..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 or power-save, the required level must be held long enough for the mcu to complete the wake-up to trigger the level interrupt. if the level disappears before the end of the start- up time, the mcu will still wake up, but no interrupt will be generated. the start-up time is defined by the sut and cksel fuses as described in ?clock systems and their distribution? on page 24 . 8.2 pin change interrupt timing an example of timing of a pin change interrupt is shown in figure 8-1 . figure 8-1. timing of pin change interrupts le dq dq clk pin_lat pin_sync pcint_in[i] pcint[i] pin pcint[i] bit (of pcmsk n ) dq dq dq clk pcint_sync pcint_set/flag 0 7 pcif n  (interrupt flag) pcint[i] pin pin_lat pin_sync clk pcint_in[i] pcint_syn pcint_set/flag pcif n
63 7728g?avr?06/10 attiny87/attiny167 8.3 external interrupts register description 8.3.1 external interrupt control register a ? eicra the external interrupt control register a contains control bits for interrupt sense control. ? bit 7..4 ? res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. ? bit 3, 2 ? isc11, isc10: interrupt sense control 1 bit 1 and bit 0 the external interrupt 1 is activated by the external pin int1 if the sreg i-flag and the corre- sponding interrupt mask are set. the level and edges on the external int1 pin that activate the interrupt are defined in table 8-1 . the value on the int1 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longe r than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, th e low level must be held until the co mpletion of the currently executing instruction to generate an interrupt. ? bit 1, 0 ? isc01, isc00: interrupt sense control 0 bit 1 and bit 0 the external interrupt 0 is activated by the external pin int0 if the sreg i-flag and the corre- sponding interrupt mask are set. the level and edges on the external int0 pin that activate the interrupt are defined in table 8-1 . the value on the int0 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longe r than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, th e low level must be held until the co mpletion of the currently executing instruction to generate an interrupt. 8.3.2 external interrupt mask register ? eimsk ? bit 7, 2 ? res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. bit 76543210 ? ? ? ? isc11 isc10 isc01 isc00 eicra read/write r r r r r/w r/w r/w r/w initial value00000000 table 8-1. interrupt sense control 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 of intn generates an interrupt request. 1 1 the rising edge of intn generates an interrupt request. bit 76543210 ??????int1int0eimsk read/writerrrrrrr/wr/w initial value00000000
64 7728g?avr?06/10 attiny87/attiny167 ? bit 1 ? int1: external interrupt request 1 enable when the int1 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the interrupt sense control1 bits 1/0 (isc11 and isc10) in the external interrupt control register a (eicra) define whether the external interrupt is acti- vated on rising and/or falling edge of the int1 pin or level sensed. activity on the pin will cause an interrupt request even if int1 is configured as an output. the corresponding interrupt of external interrupt request 1 is execut ed from the int1 interrupt vector. ? bit 0 ? int0: external interrupt request 0 enable when the int0 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the interrupt sense control0 bits 1/0 (isc01 and isc00) in the external interrupt control register a (eicra) define whether the external interrupt is acti- vated on rising and/or falling edge of the int0 pin or level sensed. activity on the pin will cause an interrupt request even if int0 is configured as an output. the corresponding interrupt of external interrupt request 0 is execut ed from the int0 interrupt vector. 8.3.3 external interrupt flag register ? eifr ? bit 7, 2 ? res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. ? bit 1 ? intf1: external interrupt flag 1 when an edge or logic change on the int1 pin triggers an interrupt request, intf1 becomes set (one). if th e i-bit in sreg and the int1 bit in eimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. this flag is always cleared when int1 is configured as a level interrupt. ? bit 0 ? intf0: external interrupt flag 0 when an edge or logic change on the int0 pin triggers an interrupt request, intf0 becomes set (one). if th e i-bit in sreg and the int0 bit in eimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. this flag is always cleared when int0 is configured as a level interrupt. 8.3.4 pin change interrupt control register ? pcicr ? bit 7, 2 ? res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. bit 76543210 ??????intf1intf0eifr read/writerrrrrrr/wr/w initial value00000000 bit 76543210 ??????pcie1pcie0pcicr read/writerrrrrrr/wr/w initial value00000000
65 7728g?avr?06/10 attiny87/attiny167 ? bit 1 - pcie1: pin change interrupt enable 1 when the pcie1 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 1 is enabled. any change on any enabled pcint15..8 pin will cause an inter- rupt. the corresponding interrupt of pin change interrupt request is executed from the pci1 interrupt vector. pcint15..8 pins are enabled individually by the pcmsk1 register. ? bit 0 - pcie0: pin change interrupt enable 0 when the pcie0 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 0 is enabled. any change on any enabled pcint7..0 pin will cause an inter- rupt. the corresponding interrupt of pin change interrupt request is executed from the pci0 interrupt vector. pcint7..0 pins are enabled individually by the pcmsk0 register. 8.3.5 pin change interrupt flag register ? pcifr ? bit 7, 2 ? res: reserved bits these bits are unused bits in the atti ny87/167, and will alwa ys read as zero. ? bit 1 - pcif1: pin change interrupt flag 1 when a logic change on any pcint15..8 pin tri ggers an interrupt request, pcif1 becomes set (one). if the i-bit in sreg and the pcie1 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cl eared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. ? bit 0 - pcif0: pin change interrupt flag 0 when a logic change on any pcint7..0 pin triggers an interrupt request, pcif0 becomes set (one). if the i-bit in sreg and the pcie0 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cl eared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. 8.3.6 pin change mask register 1 ? pcmsk1 ? bit 7..0 ? pcint15..8: pin change enable mask 15..8 each pcint15..8-bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint15..8 is set and the pcie1 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint15..8 is cleared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 ??????pcif1pcif0pcifr read/write r r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 pcint15 pcint14 pcint13 pcint12 pcint11 pcint10 pcint9 pcint8 pcmsk1 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
66 7728g?avr?06/10 attiny87/attiny167 8.3.7 pin change mask register 0 ? pcmsk0 ? bit 7..0 ? pcint7..0: pin change enable mask 7..0 each pcint7..0 bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint7..0 is set and the pcie0 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint7..0 is cl eared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
67 7728g?avr?06/10 attiny87/attiny167 9. i/o-ports 9.1 introduction all avr ports have true read-modify-write functionality when used as general digital i/o ports. this means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). each output buffer has symmetrical drive characteristics with both high sink and source capability. the pin driver is strong enough to drive led displays directly. all port pins have individually selectable pull-up resistors with a supply-voltage invariant resis- tance. all i/o pins have protection diodes to both vcc and ground as indicated in figure 9-1 . refer to ?electrical characteristics? on page 243 for a complete list of parameters. figure 9-1. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? rep- resents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a program, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o registers and bit locations are listed in ?register description for i/o ports? on page 86 . three i/o memory address locations are allocated for each port, one each for the data regis- ter ? portx, data direction register ? ddrx, and the port input pins ? pinx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. however, writing a logic one to a bit in the pinx register, will result in a toggle in the corresponding bit in the data register. in addition, the pull-up disable ? pud bit in mcucr or pudx in portcr disables the pull-up function for all pins in all ports when set. using the i/o port as genera l digital i/o is described in ?ports as general digital i/o? on page 68 . most port pins are multiplexed with alternat e functions for the peripheral features on the device. how each alternate function interferes with the port pin is described in ?alternate port functions? on page 72 . refer to the individual module sections for a full description of the alternate 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. c pin logic r pu see figure "general digital i/o" for details pxn
68 7728g?avr?06/10 attiny87/attiny167 9.2 ports as gener al digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 9-2 shows a func- tional description of one i/o-port pin, here generically called pxn. figure 9-2. general digital i/o (note:) note: wrx, wpx, wdx, rrx, rpx, and rdx are comm on to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 9.2.1 configuring the pin each port pin consists of three register bi ts: ddxn, portxn, and pinxn. as shown in ?regis- ter description for i/o ports? 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 direction of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is wr itten logic zero, pxn is configured as an input pin. if portxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when reset condition becomes active, even if no clocks are running. if portxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). clk rpx rrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx 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 wpx 0 1 wrx wpx: write pinx register
69 7728g?avr?06/10 attiny87/attiny167 9.2.2 toggling the pin writing a logic one to pinxn toggles the value of portxn, independent on the value of ddrxn. note that the sbi assembler instruction can be used to toggle one single bit in a port. 9.2.3 break-before-make switching in the break-before-make mode when switching the ddrxn bit from input to outp ut an imme- diate tri-state period lasting one system cl ock cycle is introduced as indicated in figure 9-3 . for example, if the system clo ck is 4 mhz and the ddrxn is written to make an output, the immediate tri-state period of 250 ns is introduced, before the value of portxn is seen on the port pin. to avoid glitches it is recomme nded that the maximum ddrxn toggle frequency is two system clock cycles. the break-before-make is a port-wise mode and it is activated by the port-wise bbmx enable bits. for furthe r information about the bbmx bits, see ?port control register ? portcr? on page 75 . when switching the ddrxn bit from output to input there is no immediate tri-state period introduced. figure 9-3. break before make, switching between input and output 9.2.4 switching between input and output when switching between tri-state ({ddxn, portxn} = 0, 0) and output high ({ddxn, portxn} = 1, 1), an intermediate state with either pull-up enabled {ddxn, portxn} = 0, 1) or output low ({ddxn, portxn} = 1, 0) must occur. normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. if this is not the case, the pud bit in the mcucr register or the pudx bit in portcr register can be set to disable all pull-ups in the port. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0, 0) or the output high state ({ddxn, portxn} = 1, 1) as an intermediate step. tri-state tri-state tri-state 0x02 0x02 0x01 0x01 0x01 0x55 nop immediate tri-state cycle out ddrx, r16 ystem clock r 16 r 17 nstructions portx ddrx px0 px1 out ddrx, r17 immediate tri-state cycle
70 7728g?avr?06/10 attiny87/attiny167 table 9-1 summarizes the control signals for the pin value. note: 1. or port-wise pudx bit in portcr register. 9.2.5 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 9-2 , the pinxn register bit and the preceding latch constitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 9-4 shows a timing diagram of the synchronization when re ading an externally applied pin value. the max- imum and minimum propagation delays are denoted t pd,max and t pd,min respectively. figure 9-4. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of the system clock. the latch is closed when the clock is low, and goes transparent when the cl ock is high, as indi- cated 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 pi nxn register at the succeeding positive clock edge. as indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in figure 9-5 . the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is 1 system clock period. table 9-1. port pin configurations ddxn portxn pud (in mcucr) (1) 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) xxx in r17, pinx 0x00 0xff instructions sync latch pinxn r17 xxx system clk t pd, max t pd, min
71 7728g?avr?06/10 attiny87/attiny167 figure 9-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 result- ing pin values are read back again, but as pr eviously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. 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. assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 72 7728g?avr?06/10 attiny87/attiny167 9.2.6 digital input enable and sleep modes as shown in figure 9-2 , the digital input signal can be clamped to ground at the input of the schmitt trigger. the signal denoted sleep in the figure, is set by the mcu sleep controller in power-down or power-save mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to vcc/2. sleep is overridden for port pins enabled as ex ternal interrupt pins. if the external interrupt request is not enabled, sleep is active also fo r these pins. sleep is al so overridden by vari- ous other alternate functions as described in ?alternate port functions? on page 72 . 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 inter- rupt is not enabled, the corresponding external interrupt flag will be set when resuming from the above mentioned sleep mode, as the clamping in these sleep mode produces the requested logic change. 9.2.7 unconnected pins if some pins are unused, it is recommended to ensure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduc e current consumption in all other modes where the digital inputs are enabled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. in this case, the pull- up will be disabled during reset. if low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. connecting unused pins directly to vcc or gnd is not recommended, since this may cause excessive cur- rents if the pin is accidentally configured as an output. 9.3 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 9-6 shows how the port pin control signals from the simplified figure 9-2 can be overridden by alternate functions. the overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the avr microcontroller family.
73 7728g?avr?06/10 attiny87/attiny167 figure 9-6. alternate port functions (1) note: 1. wrx, 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. all other signals are unique for each pin. clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data bus 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o 0 1 ptoexn wpx ptoexn: pxn, port toggle override enable wpx: write pinx
74 7728g?avr?06/10 attiny87/attiny167 table 9-2 summarizes the function of the overriding signals. the pin and port indexes from figure 9-6 are not shown in the succeeding tables. the overriding signals are generated inter- nally in the modules having the alternate function. the following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. refer to the alternate function description for fur- ther details. table 9-2. 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 or pdux)} = 0, 1, 0. 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, pud and pudx 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. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. 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 cleared, the digital input enable is determined by mcu state (normal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital in put is enabled/disabled when dieov is set/cleared, regardl ess of the mcu state (normal mode, sleep mode). di digital input this is the digital input to altern ate functions. in the figure, the signal is connected to the out put 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.
75 7728g?avr?06/10 attiny87/attiny167 9.3.1 mcu control register ? mcucr ? bit 4 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0, 1). see ?con- figuring the pin? on page 68 for more details about this feature. 9.3.2 port control register ? portcr ? bits 5, 4 ? bbmx: break-before-make mode enable when these bits are written to one, the port-wise break-before-make mode is activated. the intermediate tri-state cy cle is then inserted when writing dd rxn to make an output. for further information, see ?break-before-make switching? on page 69 . ? bits 1, 0 ? pudx: port-wise pull-up disable when these bits are written to one, the port-w ise pull-ups in the defined i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0, 1). the port-wise pull-up dis able bits are ored with the global pull-up disable bit (pud) from the mcucr register. see ?configuring the pin? on page 68 for more details about this feature. bit 7 6 5 4 3 2 1 0 ? bods bodse pud ? ? ? ? mcucr read/write r r/w r/w r/w r r r r initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 - - bbmb bbma - - pudb puda portcr 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
76 7728g?avr?06/10 attiny87/attiny167 9.3.3 alternate functions of port a the port a pins with alternate functions are shown in table 9-3 . table 9-3. port a pins alternate functions port pin alternate function pa 7 pcint7 (pin change interrupt 7) adc7 (adc input channel 7) ain1 (analog comparator positive input) xref (internal volta ge reference output) aref (external voltage reference input) pa 6 pcint6 (pin change interrupt 6) adc6 (adc input channel 6) ain0 (analog comparator negative input) ss (spi slave select input) pa 5 pcint5 (pin change interrupt 5) adc5 (adc input channel 5) t1 (timer/counter1 clock input) usck (three-wire mode usi alternate clock input) scl (two-wire mode usi alternate clock input) sck (spi master clock) pa 4 pcint4 (pin change interrupt 4) adc4 (adc input channel 4) icp1 (timer/counter1 input capture trigger) di (three-wire mode usi alternate data input) sda (two-wire mode usi alternate data input / output) mosi (spi master output / slave input) pa 3 pcint3 (pin change interrupt 3) adc3 (adc input channel 3) isrc (current source pin) int1 (external interrupt1 input) pa 2 pcint2 (pin change interrupt 2) adc2 (adc input channel 2) oc0a (output compare and pwm output a for timer/counter0) do (three-wire mode usi alternate data output) miso (spi master i nput / slave output) pa 1 pcint1 (pin change interrupt 1) adc1 (adc input channel 1) txd (uart transmit pin) txlin (lin transmit pin) pa 0 pcint0 (pin change interrupt 0) adc0 (adc input channel 0) rxd (uart receive pin) rxlin (lin receive pin)
77 7728g?avr?06/10 attiny87/attiny167 the alternate pin configuration is as follows: ? pcint7/adc7/ain1/xref/aref ? port a, bit7 pcint7: pin change interrupt, source 7. adc7: analog to digital converter, channel 7. ain1: analog comparator positive input. this pin is directly connected to the positive input of the analog comparator. xref: internal voltage reference output. the internal voltage reference 2.56v or 1.1v is output when xrefen is set and if either 2.56v or 1.1v is used as reference for adc conversion. when xref output is enabled, the pin port pull-up and digital output driver are turned off. aref: external voltage reference input for adc. the pin port pull-up and digital output driver are disabled when the pin is used as an external voltage reference input for adc or as when the pin is only used to connect a bypass capacitor for the voltage ref- erence of the adc. ? pcint6/adc6/ain0/ss ? port a, bit6 pcint6: pin change interrupt, source 6. adc6: analog to digital converter, channel 6. ain0: analog comparator negative input. this pin is directly connected to the negative input of the analog comparator. ss : spi slave select input. when the spi is enab led as a slave, this pin is configured as an input regardless of the setting of dda6. as a slave, the spi is activated when this pin is driven low. when the spi is enabled as a master, the data direction of this pin is controlled by dda6. when the pin is forced to be an input, the pull-up can still be con- trolled by the porta6 bit. ? pcint5/adc5/t1/usck/scl/sck ? port a, bit5 pcint5: pin change interrupt, source 5. adc5: analog to digital converter, channel 5. t1: timer/counter1 clock input. usck: three-wire mode usi clock input. scl: two-wire mode usi clock input. sck: spi master clock output, slave clock input pin. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of dda5. when the spi is enabled as a master, the data direction of this pin is controlled by dda5. when the pin is forced to be an input, the pull-up c an still be controlled by the porta5 bit. ? pcint4/adc4/icp1/di/sda/m osi ? port a, bit 4 pcint4: pin change interrupt, source 4. adc4: analog to digital converter, channel 4. icp1: timer/counter1 input capture trigger. the pa3 pin can act as an input capture pin for timer/counter1. di: three-wire mode usi data input. usi three-wire mode does not override normal port functions, so pin must be configure as an input for di function. sda: two-wire mode serial interface (usi) data input / output. mosi: spi master output / slave input. when the spi is enabled as a slave, this pin is con- figured as an input regardless of the setting of dda3. when the spi is enabled as a
78 7728g?avr?06/10 attiny87/attiny167 master, the data direction of this pin is controlled by dda3. when the pin is forced by the spi to be an input, the pull-up ca n still be controlled by the porta3 bit. ? pcint3/adc3/isrc/int1 ? port a, bit 3 pcint3: pin change interrupt, source 3. adc3: analog to digital converter, channel 3. iscr: current source output pin. while current is sourced by the current source module, the user can use the analog to digital converter channel 4 (adc4) to measure the pin voltage. int1: external interrupt, source 1. the pa4 pin can serve as an external interrupt source. ? pcint2/adc2/oc0a/do/miso ? port a, bit 2 pcint2: pin change interrupt, source 2. adc2: analog to digital converter, channel 2. oc0a: output compare match a or output pwm a for timer/counter0. the pin has to be configured as an output (dda2 set ( one ) ) to serve these functions. do: three-wire mode usi data output. three-wire mode data output overrides porta2 and it is driven to the port when the data direction bit dda2 is set. porta2 still enables the pull-up, if the direction is input and porta2 is set ( one ). 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 regardless of the setting of dda2. when the spi is enabled as a salve, the data direction of this pin is controlled by dda2. when the pin is forced to be an input, th e pull-up can still be controlled by porta2. ? pcint1/adc1/txd/txlin ? port a, bit 1 pcint1: pin change interrupt, source 1. adc1: analog to digital converter, channel 1. txd: uart transmit pin. when the uart transmitter is enabled, this pin is configured as an output regardless the value of dda1. porta1 still enab les the pull-up, if the direction is input and porta2 is set ( one ). txlin: lin transmit pin. when the lin is enabled, this pin is configured as an output regardless the value of dda1. porta1 still enables the pu ll-up, if the direction is input and porta2 is set ( one ). ? pcint0/adc0/rxd/rxlin ? port a, bit 0 pcint0: pin change interrupt, source 0. adc0: analog to digital converter, channel 0. rxd: uart receive pin. when the uart receiver is enabled, this pin is configured as an input regardless of the value of dda0. when the pin is forced to be an input, a logical one in porta0 will turn on the internal pull-up. rxlin: lin receive pin. when the lin is enabled, this pin is configured as an input regard- less of the value of dda0. when the pin is forced to be an input, a logical one in porta0 will turn on the internal pull-up. table 9-4 and table 9-5 relate the alternate functions of port a to the overriding signals shown in figure 9-6 on page 73 .
79 7728g?avr?06/10 attiny87/attiny167 table 9-4. overriding signals for alternate functions in pa7..pa4 signal name pa7/ p cin t7/ adc7/ain1 /xref/aref pa6/ p cin t6/ adc6/ain0/ss pa5/pcint5/adc5/ t1/usck/scl/sck pa4/pcint4/adc4/ icp1/di/sda/mosi puoe 0 spe & mstr spe & mstr spe & mstr puov 0 porta6 & pud porta5 & pud porta4 & pud ddoe 0 spe & mstr (spe & mstr ) | (usi_2_wire & usipos) (spe & mstr ) | (usi_2_wire & usipos) ddov 0 0 (usi_scl_hold | porta5 ) & ddra6 { (spe & mstr ) ? (0) : (usi_shiftout | porta4 ) & ddra4) } pvoe 0 0 (spe & mstr) | (usi_2_wire & usipos & ddra5) (spe & mstr) | (usi_2_wire & usipos & ddra4) pvov 0 0 { (spe & mstr) ? (sck_output) : ~ (usi_2_wire & usipos & ddra5) } { (spe & mstr) ? (mosi_output) : ~ (usi_2_wire & usipos & ddra4) } ptoe 0 0 usi_ptoe & usipos 0 dieoe adc7d | (pcie0 & pcmsk07) adc6d | (pcie0 & pcmsk06) adc5d | (usisie & usipos) | (pcie0 & pcmsk05) adc4d | (usisie & usipos) | (pcie0 & pcmsk04) dieov pcie0 & pcmsk07 pcie0 & pcmsk06 (usisie & usipos) | (pcie0 & pcmsk05) (usisie & usipos) | (pcie0 & pcmsk04) di pcint7 pcint6 -/- ss pcint5 -/- t1 -/- usck -/- scl -/- sck pcint4 -/- icp1 -/- di -/- sda -/- mosi aio adc7 -/- ain1 -/- xref -/- aref adc6 -/- ain0 adc5 adc4
80 7728g?avr?06/10 attiny87/attiny167 table 9-5. overriding signals for alternate functions in pa3..pa0 signal name pa3/pcint3/adc3/ isrc/int1 pa2/pcint2/adc2/ oc0a/do/miso pa1/pcint1/adc1/ txd/txlin pa0/pcint0/adc0/ rxd/rxlin puoe 0 spe & mstr lin_tx_enable lin_rx_enable puov porta3 & pud porta2 & pud { (lin_tx_enable) ? (0) : (porta1 & pud ) } porta0 & pud ddoe 0 spe & mstr lin_tx_enable lin_rx_enable ddov 0 0 lin_tx_enable 0 pvoe 0 (spe & mstr) | (usi_2_wire & usi_3_wire & usipos) | oc0a lin_tx_enable 0 pvov 0 { (spe & mstr) ? (miso_output) : ( ( usi_2_wire & usi_3_wire & usipos ) ? (usi_shiftout) : (oc0a) ) } { (lin_tx_enable) ? (lin_tx) : (0) } 0 ptoe 0 0 0 0 dieoe adc3d | int1_enable | (pcie0 & pcmsk03) adc2d | (pcie0 & pcmsk02) adc1d | (pcie0 & pcmsk01) adc0d | (pcie0 & pcmsk00) dieov int1_enable | (pcie0 & pcmsk03) pcie0 & pcmsk02 pcie0 & pcmsk01 pcie0 & pcmsk00 di pcint3 -/- int1 pcint2 -/- miso pcint1 pcint0 aio adc3 -/- isrc adc2 adc1 adc0
81 7728g?avr?06/10 attiny87/attiny167 9.3.4 alternate functions of port b the port b pins with alternate functions are shown in table 9-6 . the alternate pin configuration is as follows: ? pcint15/adc10/oc1bx/reset /dw ? port b, bit 7 pcint15: pin change interrupt, source 15. adc10: analog to digital converter, channel 10. oc1bx: output compare and pwm output b-x for timer/counter1. the pb7 pin has to be configured as an output (ddb7 set (one)) to serve this function. the oc1bx pin is also the output pin for the pwm mode timer function (c.f. oc1bx bit of tccr1d regis- ter). table 9-6. port b pins alternate functions port pin alternate functions pb7 pcint15 (pin change interrupt 15) adc10 (adc input channel 10) oc1bx (output compare and pwm output b-x for timer/counter1) reset (reset input pin) dw ( debugwire i/o) pb6 pcint14 (pin change interrupt 14) adc9 (adc input channel 9) oc1ax (output compare and pwm output a-x for timer/counter1) int0 (external interrupt0 input) pb5 pcint13 (pin change interrupt 13) adc8 (adc input channel 8) oc1bw (output compare and pwm output b-w for timer/counter1) xtal2 (chip clock oscillator pin 2) clko (system clock output) pb4 pcint12 (pin change interrupt 12) oc1aw (output compare and pwm output a-w for timer/counter1) xtal1 (chip clock oscillator pin 1) clki (external clock input) pb3 pcint11 (pin change interrupt 11) oc1bv (output compare and pwm output b-v for timer/counter1) pb2 pcint10 (pin change interrupt 10) oc1av (output compare and pwm output a-v for timer/counter1) usck (three-wire mode usi default clock input) scl (two-wire mode usi default clock input) pb1 pcint9 (pin change interrupt 9) oc1bu (output compare and pwm ou tput b-u for timer/counter1) do (three-wire mode usi default data output) pb0 pcint8 (pin change interrupt 8) oc1au (output compare and pwm ou tput a-u for timer/counter1) di (three-wire mode usi default data input) sda (two-wire mode usi default data input / output)
82 7728g?avr?06/10 attiny87/attiny167 reset : reset input pin. when the rstdisbl fuse is programmed, this pin functions as a normal i/o pin, and the part will have to re ly on power-on reset and brown-out reset as its reset sources. when the rstdisbl fuse is unprogrammed, the reset circuitry is connected to the pin, and the pin can not be used as an i/o pin. if pb7 is used as a reset pin, ddb 7, portb7 and pinb7 will all read 0. dw: when the debugwire enable (dwen) fuse is programmed and lock bits are unpro- grammed, the reset port pin is configured as a wire-and (open-drain) bi-directional i/o pin with pull-up enabled and becomes the communication gateway between target and emulator. ? pcint14/adc9/oc1ax/int 0 ? port b, bit 6 pcint14: pin change interrupt, source 14. adc9: analog to digital converter, channel 9. oc1ax: output compare and pwm output a-x for timer/counter1. the pb6 pin has to be configured as an output (ddb6 set (one)) to serve this function. the oc1ax pin is also the output pin for the pwm mode timer function (c.f. oc1ax bit of tccr1d regis- ter). int0: external interrupt0 input. the pb6 pin can serve as an external interrupt source. ? pcint13/adc8/oc1 bw/xtal2/clko ? port b, bit 5 pcint13: pin change interrupt, source 13. adc8: analog to digital converter, channel 8. oc1bw: output compare and pwm output b-w for timer/counter1. the pb5 pin has to be configured as an output (ddb5 set (one)) to serve this function. the oc1bw pin is also the output pin for the pwm mode timer function (c.f. oc1bw bit of tccr1d reg- ister). xtal2: chip clock oscillator pin 2. used as cl ock pin for crystal oscillator or low-frequency crystal oscillator. when used as a clock pi n, the pin can not be used as an i/o pin. clko: divided system clock output. the divided system clock can be output on the pb5 pin. the divided system clock will be output if the ckout fuse is programmed, regardless of the portb5 and ddb5 settings. it will also be output during reset. ? pcint12/oc1aw/xtal1/clki ? port b, bit 4 pcint12: pin change interrupt, source 12. oc1aw: output compare and pwm output a-w for timer/counter1. the pb4 pin has to be configured as an output (ddb4 set (one)) to serve this function. the oc1aw pin is also the output pin for the pwm mode timer function (c.f. oc1aw bit of tccr1d reg- ister). xtal1: chip clock oscillator pin 1. used for a ll chip clock sources exce pt internal calibrated rc oscillator. when used as a clock pin, the pin can not be used as an i/o pin. clki: external clock input. when used as a cl ock pin, the pin can not be used as an i/o pin. note: if pb4 is used as a clock pin (xtal1 or clki), ddb4, portb4 and pinb4 will all read 0. ? pcint11/oc1bv ? port b, bit 3 pcint11: pin change interrupt, source 11. oc1bv: output compare and pwm output b-v for timer/counter1. the pb3 pin has to be configured as an output (ddb3 set (one)) to serve this function. the oc1bv pin is also the output pin for the pwm mode timer function (c.f. oc1bv bit of tccr1d regis- ter).
83 7728g?avr?06/10 attiny87/attiny167 ? pcint10/oc1av/usck/scl ? port b, bit 2 pcint10: pin change interrupt, source 10. oc1av: output compare and pwm output a-v for timer/counter1. the pb2 pin has to be configured as an output (ddb2 set (one)) to serve this function. the oc1av pin is also the output pin for the pwm mode timer function (c.f. oc1av bit of tccr1d regis- ter). usck: three-wire mode usi clock input. scl: two-wire mode usi clock input. ? pcint9/oc1bu/do ? port b, bit 1 pcint9: pin change interrupt, source 9. oc1bu: output compare and pwm output b-u for timer/counter1. the pb1 pin has to be configured as an output (ddb1 set (one)) to serve this function. the oc1bu pin is also the output pin for the pwm mode timer function (c.f. oc1bu bit of tccr1d reg- ister). do: three-wire mode usi data output. three-wire mode data output overrides portb1 and it is driven to the port when the da ta direction bit ddb1 is set. portb1 still enables the pull-up, if the direction is input and portb1 is set ( one ). ? pcint8/oc1au/di/sda ? port b, bit 0 ipcint8: pin change interrupt, source 8. oc1au: output compare and pwm output a-u for timer/counter1. the pb0 pin has to be configured as an output (ddb0 set (one)) to serve this function. the oc1au pin is also the output pin for the pwm mode timer function (c.f. oc1au bit of tccr1d regis- ter). di: three-wire mode usi data input. usi three-wire mode does not override normal port functions, so pin must be configure as an input for di function. sda: two-wire mode serial interface (usi) data input / output.
84 7728g?avr?06/10 attiny87/attiny167 table 9-7 and table 9-8 relate the alternate functions of port b to the overriding signals shown in figure 9-6 on page 73 . table 9-7. overriding signals for alternate functions in pb7..pb4 signal name pb7/pcint15/adc10 / oc1bx/reset /dw pb6/pcint14/adc9/ oc1ax/int0 pb5/pcint13/adc8/ oc1bw/xtal2/clk o pb4/pcint12/ oc1aw/xtal1/clki puoe0000 puov0000 ddoe0000 ddov0000 pvoe oc1b_enable & oc1bx oc1a_enable & oc1ax oc1b_enable & oc1bw oc1a_enable & oc1aw pvov oc1b oc1a oc1b oc1a ptoe0000 dieoe adc10d | (pcie1 & pcmsk15) adc9d | int0_enable | (pcie1 & pcmsk14) adc8d | (pcie1 & pcmsk13) (pcie1 & pcmsk13) dieov pcie1 & pcmsk15 int0_enable | (pcie1 & pcmsk14) pcie1 & pcmsk13 1 di pcint15 pcint14 -/- int1 pcint13 pcint12 aio reset -/- adc10 -/- adc9 -/- isrc adc8 -/- xtal2 xtal1 -/- clki
85 7728g?avr?06/10 attiny87/attiny167 table 9-8. overriding signals for alternate functions in pb3..pb0 signal name pb3/pcint11/ oc1bv pb2/pcint10/ oc1av/usck/scl pb1/pcint9/ oc1bu/do pb0/ipcint8/ oc1au/di/sda puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 (usi_2_wire & usipos ) 0 (usi_2_wire & usipos ) ddov 0 (usi_scl_hold | portb2 ) & ddrb2 0 (usi_shiftout | portb0 ) & ddrb0) pvoe oc1b_enable & oc1bv (usi_2_wire & usipos & ddrb2) | (oc1a_enable & oc1av) (usi_2_wire & usi_3_wire & usipos ) | (oc1b_enable & oc1bu) (usi_2_wire & usipos & ddrb0) | (oc1a_enable & oc1au) pvov oc1b { (usi_2_wire & usipos & ddrb2) ? (0) : (oc1a) } { (usi_2_wire & usi_3_wire & usipos ) ? (usi_shiftout) : (oc1b) } { (usi_2_wire & usipos & ddrb0) ? (0) : (oc1a) } ptoe 0 usi_ptoe & usipos 00 dieoe pcie1 & pcmsk11 (usisie & usipos ) | (pcie1 & pcmsk10) pcie1 & pcmsk9 (usisie & usipos ) | (pcie1 & pcmsk8) dieov 1 (usisie & usipos ) | (pcie1 & pcmsk10) 1 (usisie & usipos ) | (pcie1 & pcmsk8) di pcint11 pcint10 -/- usck -/- scl pcint9 pcint8 -/- di -/- sda aio 0 0 0 0
86 7728g?avr?06/10 attiny87/attiny167 9.4 register descrip tion for i/o ports 9.4.1 port a data register ? porta 9.4.2 port a data direction register ? ddra 9.4.3 port a input pins register ? pina 9.4.4 port b data register ? portb 9.4.5 port b data direction register ? ddrb 9.4.6 port b input pins register ? pinb 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 value 0 0 0 0 0 0 0 0 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 value 0 0 0 0 0 0 0 0 bit 76543210 pina7 pina6 pina5 pina4 pi na3 pina2 pina1 pina0 pina read/write r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) initial value n/a n/a n/a n/a n/a n/a n/a n/a 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 value 0 0 0 0 0 0 0 0 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 pi nb3 pinb2 pinb1 pinb0 pinb read/write r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) initial value n/a n/a n/a n/a n/a n/a n/a n/a
87 7728g?avr?06/10 attiny87/attiny167 10. 8-bit timer/counter0 an d asynchronous operation timer/counter0 is a general purpose, single channel, 8-bit timer/counter module. the main features are: 10.1 features ? single channel counter ? clear timer on compare match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? frequency generator ? 10-bit clock prescaler ? overflow and compare match inte rrupt sources (tov0 and ocf0a) ? allows clocking from external crystal (i.e. 32 khz watch crystal) indepe ndent of the i/o clock 10.2 overview many register and bit references in this section 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, i.e., tcnt0 for accessing timer/counter0 counter value and so on. ? a lower case ?x? replaces the output compare unit channel, in this case a. however, when using the register or bit defines in a program, the precise form must be used, i.e., ocr0a for accessing timer/counter0 output compare channel a value and so on. a simplified block diagram of the 8-bit timer/counter is shown in figure 10-1 . for the actual placement of i/o pins, refer to ?pin configuration? on page 5 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?8-bit timer/counter register description? on page 100 .
88 7728g?avr?06/10 attiny87/attiny167 figure 10-1. 8-bit timer/counter0 block diagram the timer/counter (tcnt0) and output compare register (ocr0a) are 8-bit registers. inter- rupt request (shorten as int.req.) signals are all visible in the timer interrupt flag register (tifr0). all interrupts are individually ma sked with the timer interrupt mask register (timsk0). tifr0 and timsk0 are not shown in the figure. the timer/counter can be clocked internally, vi a the prescaler, or asynchronously clocked from the xtal1/2 pins, as detailed later in this section. the asynchronous operation is con- trolled by the asynchronous status register (assr). the clock select logic block controls which clock source the timer/ counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t 0). the double buffered output compare register (ocr0a) is compared with the timer/counter value at all times. the result of the compare can be used by the waveform generator to gen- erate a pwm or variable frequency output on the output compare pin (oc0a). see ?output compare unit? on page 90. for details. the compare match event will also set the compare flag (ocf0a) which can be used to generate an output compare interrupt request. timer/counter data bus = tcntn waveform generation ocnx = 0 control logic = 0xff top bottom count clear direction tovn (int.req.) ocnx (int.req.) synchronization unit ocrnx tccrnx assrn status flags clk i/o clk asy synchronized status flags asynchronous mode select (asn) xtal2 oscillator xtal1 prescaler clk tn clk i/o
89 7728g?avr?06/10 attiny87/attiny167 10.2.1 definitions the following definitions are used extensively throughout the section: 10.3 timer/counter clock sources the timer/counter can be clocked by an inte rnal synchronous or an external asynchronous clock source. the clock source is selected by the clock select logic which is controlled by the clock select (cs02:0) bits located in the ti mer/counter control register (tccr0).the clock source clk t 0 is by default equal to the mcu clock, clk i/o . when the as0 bit in the assr regis- ter is written to logic one, the clock source is taken from the timer/coun ter oscillator connected to xtal1 and xtal2 or directly from xtal1. for details on asynchronous opera- tion, see ?asynchronous status register ? assr? on page 103 . for details on clock sources and prescaler, see ?timer/counter0 prescaler? on page 100 . 10.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. fig- ure 10-2 shows a block diagram of the counter and its surrounding environment. figure 10-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/counter0 clock. top signalizes that tcnt0 has reached maximum value. bottom signalizes that tcnt0 has reached minimum value (zero). 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 ocr0a register. the assignment is dependent on the mode of operation. data bus tcntn control logic count tovn (int.req.) top bottom direction clear xtal2 oscillator xtal1 prescaler clk i/o clk tn clk tns
90 7728g?avr?06/10 attiny87/attiny167 depending on the mode of operation used, the counter is cleared, incremented, or decre- mented at each timer clock (clk t 0). clk t 0 can be generated from an external or internal clock source, selected by the clock select bits (cs0 2: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 t 0 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 (t ccr0a). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare out- put oc0a. for more details about advanced c ounting sequences and waveform generation, see ?modes of operation? on page 92 . the timer/counter overflow flag (tov0) is set according to the mode of operation selected by the wgm01:0 bits. tov0 can be used for generating a cpu interrupt. 10.5 output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare register (ocr0a). whenever tcnt0 equal s ocr0a, the comparator signa ls a match. a match will set the output compare flag (ocf0a) at the next timer clock cycle. if enabled (ocie0a = 1), the output compare flag generates an output compare interrupt. the ocf0a flag is automati- cally cleared when the interrupt is executed. alternatively, the ocf0a 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 wgm01:0 bits and compare output mode (com0a1:0) bits. the max and bottom signals are used by the wave- form generator for handling the special cases of the extreme values in some modes of operation ( ?modes of operation? on page 92 ). figure 10-3 shows a block diagram of the output compare unit. figure 10-3. output compare unit, block diagram ocfnx (int.req.) = (8-bit comparator ) ocrnx ocnx data bus tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
91 7728g?avr?06/10 attiny87/attiny167 the ocr0a register is double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double bu ffering synchronizes the update of the ocr0a compare register to either top or bottom of the counting sequence. the synchronization pre- vents the occurrence of odd-length, non-symme trical pwm pulses, thereby making the output glitch-free. the ocr0a register access may seem complex, but this is not case. when the double buff- ering is enabled, the cpu has access to the ocr0a buffer register, and if double buffering is disabled the cpu will access the ocr0a directly. 10.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 (foc0a) bit. forcing compare match will not set the ocf0a flag or reload/cle ar the timer, but the oc0a pin will be updated as if a real com- pare match had occurred (the com0a1:0 bits se ttings define whether the oc0a pin is set, cleared or toggled). 10.5.2 compare match bloc king by tcnt0 write all cpu write operations to the tcnt0 register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr0a to be initialized to the same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. 10.5.3 using the output compare unit since writing tcnt0 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt0 when using the output compare channel, independently of whether the timer/counter is running or not. if the value written to tcnt0 equals the ocr0a value, the compare match will be missed, resulting in incorrect waveform generation. similarly, do not write the tcnt0 value equal to bottom when the counter is downcounting. the setup of the oc0a should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0a value is to use the force output com- pare (foc0a) strobe bit in normal mode. t he oc0a register keeps its value even when changing between waveform generation modes. be aware that the com0a1:0 bits are not double buffered together with the compare value. changing the com0a1:0 bits will take effect immediately. 10.6 compare match output unit the compare output mode (com0a1:0) bits have two functions. the waveform generator uses the com0a1:0 bits for defining the output compare (oc0a) state at the next compare match. also, the com0a1:0 bits control the oc0a pin output source. figure 10-4 shows a simplified schematic of the logic affected by the com0a1: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 com0a1:0 bits are shown. when referring to the oc0a state, the reference is for the internal oc0a register, not the oc0a pin.
92 7728g?avr?06/10 attiny87/attiny167 figure 10-4. compare match output logic 10.6.1 compare output function the general i/o port function is overridden by the output compare (oc0a) from the wave- form generator if either of the com0a1:0 bits are set. however, the oc0a pin direction (input or output) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc0a pin (ddr_oc0a) must be set as output before the oc0a value is visible on the pin. the port override function is independent of the waveform genera- tion mode. the design of the output compare pin logic allows initialization of the oc0a state before the output is enabled. note that some com0a1:0 bit settings are reserved for certain modes of operation. see ?8-bit timer/counter register description? on page 100. 10.6.2 compare output mode and waveform generation the waveform generator uses the com0a1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com0a1:0 = 0 tells the waveform generator that no action on the oc0a register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 10-1 on page 101 . for fast pwm mode, refer to table 10-2 on page 101 , and for phase correct pwm refer to table 10-3 on page 101 . a change of the com0a1:0 bits state will have ef fect at the first comp are match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the foc0a strobe bits. 10.7 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm01:0) and compare output mode (com0a1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com0a1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com0a1:0 bits control whether the output should be set, cleared, or tog- gled at a compare match ( see ?compare match output unit? on page 91. ). port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data bus focnx clk i/o
93 7728g?avr?06/10 attiny87/attiny167 for detailed timing information refer to ?timer/counter timing diagrams? on page 97 . 10.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 soft- ware. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 10.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm01:0 = 2), the ocr0a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the coun- ter value (tcnt0) matches the ocr0a. the ocr0a defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output fre- quency. it also simplifies the operati on of counting external events. the timing diagram for the ctc mode is shown in figure 10-5 . the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0a, and then counter (tcnt0) is cleared. figure 10-5. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updat- ing the top value. however, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0a is lower than the current value of tcnt0, the counter will miss the compare match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. tcntn ocnx (toggle) ocnx interrupt flag set 1 4 period 2 3 (comnx1:0 = 1)
94 7728g?avr?06/10 attiny87/attiny167 for generating a waveform output in ctc mode, the oc0a output can be set to toggle its log- ical level on each compare match by setting the compare output mode bits to toggle mode (com0a1:0 = 1). the oc0a value will not be visi ble on the port pin unless the data direction for the pin is set to output. the waveform generated will have a maximum frequency of f oc 0 a = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the follow- ing 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 sa me timer clock cycle that the counter counts from max to 0x00. 10.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 differs 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 (oc0a) is cleared on the com- pare match between tcnt0 and ocr0a, and set at bottom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that uses dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physically small sized external compon ents (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 ti mer clock cycle. the timing diagram for the fast pwm mode is shown in figure 10-6 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent com- pare matches between ocr0a and tcnt0. figure 10-6. fast pwm mode, timing diagram f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------------- = tcntn ocrnx update and tovn interrupt flag set 1 period 2 3 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag set 4 5 6 7
95 7728g?avr?06/10 attiny87/attiny167 the timer/counter overflow flag (tov0) is se t 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 oc0a pin. setting the com0a1:0 bits to two will produce a non-inverted pwm and an inverted pwm out- put can be generated by setting the com0a1:0 to three (see table 10-2 on page 101 ). the actual oc0a 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 se tting (or clearing) the oc0a register at the compare match between ocr0a and tcnt0, and cl earing (or setting) the oc0a register at the timer clock cycle the counter 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 ocr0a register represent special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0a is set equal to bott om, the output will be a narrow spike for each max+1 timer clock cycle. setti ng the ocr0a equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com0a1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc0a to toggle its logical level on each compare match (com0a1:0 = 1). the wave- form generated will have a maximum frequency of f oc 0 a = f clk_i/o /2 when ocr0a is set to zero. this feature is similar to the oc0a toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. 10.7.4 phase correct pwm mode the phase correct pwm mode (wgm01:0 = 1) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope opera- tion. the counter counts repeatedly from bottom to max and then from max to bottom. in non-inverting compare output mode, the output compare (oc0a) is cleared on the com- pare match between tcnt0 and ocr0a while upcounting, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operat ion frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are pre- ferred for motor control applications. the pwm resolution for the phase correct pwm mode is fixed to eight bits. in phase correct pwm mode the counter is incremented until the counter value matches max. when the coun- ter reaches max, it changes the count directi on. the tcnt0 value will be equal to max for one timer clock cycle. the timing diagram fo r the phase correct pwm mode is shown on fig- ure 10-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 ocr0a and tcnt0. f ocnxpwm f clk_i/o n 256 ? -------------------- - =
96 7728g?avr?06/10 attiny87/attiny167 figure 10-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 bot- tom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0a pin. setting the com0a1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com0a1:0 to three (see table 10-3 on page 101 ). the actual oc0a 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 oc0a regis- ter at the compare match between ocr0a and tcnt0 when the counter increments, and setting (or clearing) the oc0a register at compare match between ocr0a and tcnt0 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 prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr0a register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr0a is set equal to bottom, the output will be continuously low an d if set equal to max the out put will be continuously high for non-inverted pwm mode. for in verted pwm the output will have the opposite logic values. tovn interrupt flag set ocnx interrupt flag set 1 2 3 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update f ocnxpcpwm f clk_i/o n 510 ? -------------------- - =
97 7728g?avr?06/10 attiny87/attiny167 10.8 timer/counter timing diagrams the following figures show the timer/counter in synchronous mode, and the timer clock (clk t 0) is therefore shown as a clock enable signal. in asynchronous mode, clk i/o should be replaced by the timer/co unter oscillator clock. the figures include info rmation on when inter- rupt flags are set. figure 10-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 10-8. timer/counter timing diagram, no prescaling figure 10-9 shows the same timing data, but with the prescaler enabled. figure 10-9. timer/counter timing dia gram, with prescaler (f clk_i/o /8) figure 10-10 shows the setting of ocf0a in all modes except ctc mode. figure 10-10. timer/counter timing diagram, setting of ocf0a, with prescaler (f clk_i/o /8) clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1 tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8)
98 7728g?avr?06/10 attiny87/attiny167 figure 10-11 shows the setting of ocf0a and the clearing of tcnt0 in ctc mode. figure 10-11. timer/counter timing diagram, clear timer on compare match mode, with prescaler (f clk_i/o /8) 10.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, ocr0a, and tccr0a might be corrupted. a safe procedure for switching clock source is: a. disable the timer/counter0 interrupts by clearing ocie0a and toie0. b. select clock source by setting as0 and exclk as appropriate. c. write new values to t cnt0, ocr0a, and tccr0a. d. to switch to asynchronous operation: wait for tcn0ub, ocr0ub, and tcr0ub. e. clear the timer/counter0 interrupt flags. f. enable interrupts, if needed. ? if an 32.768 khz watch crystal is used, the cpu main clock frequency must be more than four times the oscillator or external clock frequency. ? when writing to one of the registers tcnt0, ocr0a, or tccr0a, 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 e.g. writing to tcnt0 does not disturb an ocr0a 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 mode after having written to tcnt0, ocr0a, or tccr0a, the user must wait until the written register has been updated if timer/counter0 is used to wake up the device. otherwise, the mcu will enter sleep m ode 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 ocr0a 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. ? if timer/counter0 is used to wake the device up from power-save mode, precautions must be taken if the user wants to re-enter one of these modes: the interrupt logic needs one ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
99 7728g?avr?06/10 attiny87/attiny167 tosc1 cycle to be reset. if the time between wake-up and re-entering sleep mode is less than one tosc1 cycle, the interr upt 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 mode is sufficient, the following algorithm can be used to ensu re that one tosc1 cycle has elapsed: a. write a value to tccr0a, tcnt0, or ocr0a. b. wait until the corresponding update busy flag in assr returns to zero. c. enter power-save or adc noise reduction mode. ? when the asynchronous operatio n is selected, the oscillator fo r timer/counter0 is always running, except in power-down mode. after a power-up reset or wake-up from power-down 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 mode. the contents of all timer/counter0 registers must be considered lost after a wake-up from power-down mode due to unstable clock signal upon start-up, no matter whet her the oscillator is in use or a clock signal is applied to the xtal1 pin. ? description of wake up from power-save 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 clock, reading tcnt0 must be done through a register synchronized to the internal i/o clock domain (cpu main clock). synchronization takes place for every ri sing xtal1 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 xtal1 edge. the phase of the xtal1 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: a. write any value to either of the registers ocr0a or tccr0a. b. wait for the corresponding update busy flag to be cleared. c. read tcnt0. ? during asynchronous operation, the synchronization of the interrupt flags for the asynchronous timer takes 3 processor cycles plus one timer cycle. the timer is therefore advanced by at least one before the processo r 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.
100 7728g?avr?06/10 attiny87/attiny167 10.10 timer/counter0 prescaler figure 10-12. prescaler for timer/counter0 the clock source for timer/counter0 is named clk t 0 s . clk t 0 s is by default connected to the main system i/o clock clk io . by setting the as0 bit in assr , timer/counter0 is asynchro- nously clocked from the xtal o scillator or xtal1 pin. this ena bles use of timer/counter0 as a real time counter (rtc). a crystal can then be connected between the xtal1 and xtal2 pins to serve as an indepen- dent clock source for timer/counter0. a external clock can also be used using xtal1 as input. setting as0 and exclk enables this configuration. for timer/counter0, the possible prescaled selections are: clk t 0 s /8, clk t 0 s /32, clk t 0 s /64, clk t 0 s /128, clk t 0 s /256, and clk t 0 s /1024. additionally, clk t 0 s as well as 0 (stop) may be selected. setting the psr0 bit in gtccr resets the prescaler. this allows the user to operate with a predictable prescaler. 10.11 8-bit timer/counter register description ? timer/counter0 control register a ? tccr0a ? bit 7:6 ? com0a1:0: compare match output mode a these bits control the output compare pin (oc0a) behavior. if one or both of the com0a1:0 bits are set, the oc0a output overrides the normal port functionality of the i/o pin it is con- nected to. however, note that the data direction register (ddr) bit corresponding to oc0a pin must be set in order to enable the output driver. 10-bit t/c prescaler timer/countern clock source clk i/o clk tns asn csn0 csn1 csn2 clk tns /8 clk tns /64 clk tns /128 clk tns /1024 clk tns /256 clk tns /32 0 psrn clear clk tn 0 1 xtal2 exclk 0 1 oscillator xtal1 bit 76 5 4 3 210 com0a1 com0a0 ? ? ? ? wgm01 wgm00 tccr0a read/write r/w r/w r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
101 7728g?avr?06/10 attiny87/attiny167 when oc0a is connected to the pin, the func tion of the com0a1:0 bits depends on the wgm01:0 bit setting. table 10-1 shows the com0a1:0 bit functionality when the wgm01:0 bits are set to a normal or ctc mode (non-pwm). table 10-2 shows the com0a1:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 94 for more details. table 10-3 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 ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 95 for more details. ? bit 5:2 ? res: reserved bits these bits are reserved in the atti ny87/167 and will always read as zero. table 10-1. compare output mode, non-pwm mode com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc0a on compare match. 1 0 clear oc0a on compare match. 1 1 set oc0a on compare match. table 10-2. compare output mode, fast pwm mode (1) com0a1 com0a0 description 00 normal port operation, oc0a disconnected. 01 10 clear oc0a on compare match. set oc0a at bottom (non-inverting mode). 11 set oc0a on compare match. clear oc0a at bottom (inverting mode). table 10-3. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 00 normal port operation, oc0a disconnected. 01 10 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting. 11 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting.
102 7728g?avr?06/10 attiny87/attiny167 ? 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, see table 10-4 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes ( see ?modes of operation? on page 92. ). notes: 1. max = 0xff, 2. bottom = 0x00. 10.11.1 timer/counter0 control register b ? tccr0b ? bit 7 ? foc0a: force output compare a the foc0a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibi lity with future devices, this bit must be set to zero when tccr0b is written when operati ng in pwm mode. when writing a logical one to the foc0a bit, an immediate compare match is forced on the waveform generation unit. the oc0a out- put is changed according to its com0a1:0 bits setting. note that the foc0a bit is implemented as a strobe. therefore it is the value present in the com0a1:0 bits that deter- mines the effect of the forced compare. a foc0a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero. ? bit 6:3 ? res: reserved bits these bits are reserved in the atti ny87/167 and will always read as zero. ? bit 2:0 ? cs02:0: clock select table 10-4. waveform generation mode bit description mode wgm01 (ctc0) wgm00 (pwm0) timer/counter mode of operation top update of ocr0a at tov0 flag set on (1)(2) 0 0 0 normal 0xff immediate max 1 0 1 pwm, phase correct 0xff top bottom 2 1 0 ctc ocr0a immediate max 3 1 1 fast pwm 0xff top max bit 76 5 4 3 210 foc0a ? ? ? ? cs02 cs01 cs00 tccr0b read/write w r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
103 7728g?avr?06/10 attiny87/attiny167 the three clock select bits select the clock source to be used by the timer/counter, see table 10-5 . 10.11.2 timer/counter0 register ? tcnt0 the timer/counter register gives direct access, both for read and write operations, to the timer/counter unit 8-bit counter. writing to t he tcnt0 register blocks (removes) the com- pare match on the following timer clock. modify ing the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0x register. 10.11.3 output compare register a ? ocr0a the output compare register a contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0a pin. 10.11.4 asynchronous status register ? assr ? bit 7 ? res: reserved bit this bit is reserved in the attiny 87/167 and will always read as zero. ? bit 6 ? exclk: enable external clock input when exclk is written to one, and asynchronous clock is selected, the external clock input buffer is enabled and an external clock can be in put on xtal1 pin instead of an external crys- tal. writing to exclk should be done before asynchronous operation is selected. note that the crystal oscillator will only run when this bit is zero. table 10-5. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped). 001clk t 0 s (no prescaling) 010clk t 0 s /8 (from prescaler) 011clk t 0 s /32 (from prescaler) 100clk t 0 s /64 (from prescaler) 101clk t 0 s /128 (from prescaler) 110clk t 0 s /256 (from prescaler) 111clk t 0 s /1024 (from prescaler) bit 76543210 tcnt07 tcnt06 tcnt05 tcnt04 tcnt03 tcnt02 tcnt01 tcnt00 tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 bit 76543210 ocr0a7 ocr0a6 ocr0a5 ocr0a4 ocr0 a3 ocr0a2 ocr0a1 ocr0a0 ocr0a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 bit 7654 321 0 ? exclk as0 tcn0ub ocr0aub ? tcr0aub tcr0bub assr read/write r r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0
104 7728g?avr?06/10 attiny87/attiny167 ? bit 5 ? as0: asynchronous timer/counter0 when as0 is written to zero, timer/counter0 is clocked from the i/o clock, clki/o and the timer/counter0 acts as a synchronous peripheral. when as0 is written to one, time r/counter0 is clock ed from the low-freque ncy crystal oscilla- tor ( see ?low-frequency crysta l oscillator? on page 29. ) or from external clock on xtal1 pin ( see ?external clock? on page 30. ) depending on exclk setting. when the value of as0 is changed, the contents of tcnt0, ocr0a, and tccr0a might be corrupted. as0 also acts as a flag: timer/counter0 is clocked from the low-frequency crystal or from external clock only if the calib rated internal rc oscillator or the internal watc hdog oscillator is used to drive the system clock. after setting as0, if the switching is available, as0 remains to 1, else it is forced to 0. ? bit 4 ? 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 hardware. a logical zero in this bit indicates that tcnt0 is ready to be updated with a new value. ? bit 3 ? ocr0aub: output comp are 0 register a update busy when timer/counter0 operates asynchronously and ocr0a is written, this bit becomes set. when ocr0a has been updated from the temporary storage register, this bit is cleared by hardware. a logical zero in this bit indicates that ocr0a is ready to be updated with a new value. ? bit 2 ? res: reserved bit this bit is reserved in the attiny 87/167 and will always read as zero. ? bit 1 ? tcr0aub: timer/counter0 control register a update busy when timer/counter0 operates asynchronously and tccr0a is written, this bit becomes set. when tccr0a has been updated from the temporary storage register, this bit is cleared by hardware. a logical zero in this bit indicates that tccr0a is r eady to be updat ed with a new value. ? bit 0 ? tcr0bub: timer/counter0 control register b update busy when timer/counter0 operates asynchronously and tccr0b is written, this bit becomes set. when tccr0b has been updated from the temporary storage register, this bit is cleared by hardware. a logical zero in this bit indicates that tccr0b is r eady to be updat ed with a new value. if a write is performed to any of the four 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 readin g tcnt0, ocr0a, tccr0a an d tccr0b are different. when reading tcnt0, the actual timer value is read. when reading ocr0a, tccr0a or tccr0b the value in the temporary storage register is read.
105 7728g?avr?06/10 attiny87/attiny167 10.11.5 timer/counter0 interrupt mask register ? timsk0 ? bit 7:2 ? res: reserved bits these bits are reserved in the atti ny87/167 and will always read as zero. ? bit 1 ? ocie0a: timer/counter0 output compare match a interrupt enable when the ocie0a bit is written to one and the i-bit in the status register is set (one), the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is exe- cuted if a compare match in timer/counter0 occurs, i.e., when the ocf0a bit is set in the timer/counter0 interrupt flag register ? tifr0. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one and the i-bi t 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, i.e., when th e tov0 bit is set in the timer/counter0 inter- rupt flag register ? tifr0. 10.11.6 timer/counter0 interrupt flag register ? tifr0 ? bit 7:2 ? res: reserved bits these bits are reserved in the atti ny87/167 and will always read as zero. ? bit 1 ? ocf0a: output compare flag 0 a the ocf0a bit is set (one) when a compare match occurs between the timer/counter0 and the data in ocr0a ? output compare register0. ocf0a is cleared by hardware when exe- cuting the corresponding interrupt handling vector. alternatively, ocf0a is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0 (timer/counter0 compare match inter- rupt enable), and ocf0a are set (one), the timer/counter0 compare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the tov0 bit is set (one) when an overflow oc curs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interr upt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sreg i-bit, toie0a (timer/counter0 overflow interrupt enable), and tov0 are set (one), the timer/counter0 overflow interrupt is executed. in pwm mode, this bit is set when timer/counter0 changes counting direction at 0x00. bit 76543210 ??????ocie 0 atoie 0 timsk 0 read/write r r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 ??????ocf 0 atov 0 tifr 0 read/write r r r r r r r/w r/w initial value 00000000
106 7728g?avr?06/10 attiny87/attiny167 10.11.7 general timer/counter control register ? gtccr ? bit 1 ? psr0: prescaler reset timer/counter0 when this bit is one, the timer/counter0 presca ler will be reset. this bit is normally cleared immediately by hardware. if the bit is written when timer/counter0 is operating in asynchro- nous mode, the bit will remain one until the prescaler has been reset. the bit will not be cleared by hardware if the tsm bit is set. refer to the description of the ?bit 7 ? tsm: timer/counter synchronization mode? on page 109 for a description of the timer/counter synchronization mode. bit 7 6 5 4 3 2 1 0 tsm ? ? ? ? ? psr0 psr1 gtccr read/write r/w r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
107 7728g?avr?06/10 attiny87/attiny167 11. timer/counter1 prescaler 11.1 overview most bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number. 11.1.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 prescale d 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. 11.1.2 prescaler reset the prescaler is free running, i.e., operates in dependently of the clock select logic of the timer/counter. since the prescaler is not affe cted by the timer/counter?s clock select, the state of the prescaler w ill have implications for situations where a prescaled cl ock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 syst em clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for syn chronizing the timer/counter to program execu- tion. however, care must be taken if the other timer/counter that shares the same prescaler also uses prescaling. a prescale r reset will affect the prescaler period for all timer/counters it is connected to. 11.1.3 external clock source an external clock source applied to the t1 pin can be used as timer/counter clock (clk t 1). the t1 pin is sampled once every system clock cycle by the pin synchronization logic. the synchronized (sampled) signal is then passed through the edge detector. figure 11-1 shows a functional equivalent block diagram of the t1 synchronization and edge detector logic. the registers are clocked at the positive 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 pulse for each positive (csn2:0 = 7) or negative (csn2:0 = 6) edge it detects. figure 11-1. t1 pin sampling tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o
108 7728g?avr?06/10 attiny87/attiny167 the synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the t1 pin to the counter is updated. enabling and disabling of the clock input must be done when t1 has been stable for at least one system clock cycle, otherwise it is a ri sk that a false timer/counter clock pulse is generated. each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the system clock frequency (f extclk 109 7728g?avr?06/10 attiny87/attiny167 11.2 timer/counter1 prescalers register description 11.2.1 general timer/counter control register ? gtccr ? 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 psr1 bits is kept, hence keeping the corresponding prescaler reset signals asserted. this ensure s that the corresponding timer/counters are halted and can be configured to the same value without the risk of one of them advancing dur- ing configuration. when the tsm bit is written to zero, the psr0 and psr1 bits are cleared by hardware, and the timer/counters start counting simultaneously. ? bit 0 ? psr1: prescaler reset timer/counter1 when this bit is one, timer/coun ter1 prescaler will be reset. this bit is normally cleared imme- diately by hardware, except if the tsm bit is set. bit 7 6 5 4 3 2 1 0 tsm ? ? ? ? ? psr0 psr1 gtccr read/write r r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
110 7728g?avr?06/10 attiny87/attiny167 12. 16-bit timer/counter1 the 16-bit timer/counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. the main features are: 12.1 features ? true 16-bit design (i.e., allows 16-bit pwm) ? two independent output compare units ? four controlled output pins per output compare unit ? 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 pu lse width modulator (pwm) ? variable pwm period ? frequency generator ? external event counter ? four independent interrupt sources (tov1, ocf1a, ocf1b, and icf1) 12.2 overview many register and bit references in this section are written in general form. ? a lower case ?n? replaces the timer/counter number, in this case 1. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt1 for accessing timer/counter1 counter value and so on. ? a lower case ?x? replaces the output compare unit channel, in this case a or b. however, when using the register or bit defines in a program, the precise form must be used, i.e., ocr1a for accessing timer/counter1 output compare channel a value and so on. ? a lower case ?i? replaces the index of the output compare output pin, in this case u, v, w or x. however, when using the register or bit defines in a program, the precise form must be used. a simplified block diagram of the 16-bit timer/counter is shown in figure 12-1 . for the actual placement of i/o pins, refer to ?pin configuration? on page 5 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?16-bit timer/counter register description? on page 132 .
111 7728g?avr?06/10 attiny87/attiny167 figure 12-1. 16-bit timer/coun ter1 block diagram (1) note: 1. refer to figure 1-2 on page 5 , table 9-6 on page 81 , and table 9-3 on page 76 for timer/counter1 pin placement and description. 12.2.1 registers the timer/counter (tcnt1), output compare registers (ocr1a/b), and input capture reg- ister (icr1) 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 112 . the timer/counter control registers (tccr1a/b) are 8-bit registers and have no cpu access restrictions. interrupt requests (abbreviated to int.req. in the figure) signals are all visible in the timer interrupt flag register (tifr1). all interrupts are individually masked with the timer interrupt mask register (timsk1). tifr1 and timsk1 are not shown in the figure. icfn (int.req.) tovn (int.req.) clock select timer/counter databus ocrna ocrnb icrn = = tcntn waveform generation waveform generation ocnau ocnav ocnaw ocnbu ocnbv ocnbw noise canceler = fixed top values edge detector control logic = 0 top bottom count clear direction ocfna (int.req.) ocfnb (int.req.) tccrna tccrnb tccrnc icpn ( from analog comparator ouput ) tn edge detector ( from prescaler ) clk tn ocnbx ocnax
112 7728g?avr?06/10 attiny87/attiny167 the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the tn pin. the clock select logic bloc k 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 ). the double buffered output compare registers (ocr1a/b) are compared with the timer/counter value at all time. the result of the compare can be used by the waveform gen- erator to generate a pwm or variable frequency output on the output compare pins see ?output compare units? on page 119. . the compare match event will also set the compare match flag (ocf1a/b) which can be used to generate an output compare interrupt request. the input capture register can capture the ti mer/counter value at a given external (edge triggered) event on either the input capture pin (icp1) or on the analog comparator pins ( see ?anacomp - analog comparator? on page 211. ). the input capture unit includes a digital filter- ing unit (noise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocr1a register, the icr1 register, or by a set of fixed values. when using ocr1a as top value in a pwm mode, the ocr1a register can not be used for gener- ating a pwm output. however, the top value will in this case be double buffered allowing the top value to be changed in run time. if a fixed top value is required, the icr1 register can be used as an alternative, freeing the ocr1a to be used as pwm output. 12.2.2 definitions the following definitions are used extensively throughout the section: 12.3 accessing 16-bit registers the tcnt1, ocr1a/b, and icr1 are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write oper- ations. 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 cop- ied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary register for the high byte. reading the ocr1a/b 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. bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its maximum when it becomes 0xffff (decimal 65,535). 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 val- ues: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocr1a or icr1 register. the assignment is dependent of the mode of operation.
113 7728g?avr?06/10 attiny87/attiny167 12.3.1 code examples 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 access- ing the ocr1a/b and icr1 registers. note t hat when using ?c?, the compiler handles the 16-bit access. note: 1. the example code assumes that the pa rt specific header file is included. the assembly code example returns the tcnt1 value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessi ng 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 ac cess outside the interr upt will be corrupted. therefore, when both the main code and the interrupt code update the temporary register, the main code must dis- able the interrupts during the 16-bit access. assembly code examples (1) ... ; set tcnt 1 to 0x01ff ldi r17,0x01 ldi r16,0xff sts tcnt1h,r17 sts tcnt1l,r16 ; read tcnt1 into r17:r16 lds r16,tcnt1l lds r17,tcnt1h ... c code examples (1) unsigned int i; ... /* set tcnt 1 to 0x01ff */ tcnt1 = 0x1ff; /* read tcnt 1 into i */ i = tcnt1; ...
114 7728g?avr?06/10 attiny87/attiny167 the following code examples show how to do an atomic read of the tcnt1 register contents. reading any of the ocr1a/b or icr1 registers can be done by using the same principle. note: 1. the example code assumes that the pa rt specific header file is included. the assembly code example returns the tcnt1 value in the r17:r16 register pair. assembly code example (1) tim16_readtcnt1: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcnt1 into r17:r16 lds r16,tcnt1l lds r17,tcnt1h ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcnt1( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* read tcnt 1 into i */ i = tcnt1; /* restore global interrupt flag */ sreg = sreg; return i; }
115 7728g?avr?06/10 attiny87/attiny167 the following code examples show how to do an atomic write of the tcnt1 register contents. writing any of the ocr1a/b or icr1 register s can be done by using the same principle. note: 1. the example code assumes that the pa rt specific header file is included. the assembly code example requires that the r17:r16 register pair contains the value to be written to tcnt1. 12.3.2 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 writ- ten, 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. 12.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 wh ich is controlled by the clock select (cs12:0) bits located in the timer/counter control regi ster b (tccr1b). for deta ils on clock sources and prescaler, see ?timer/counter1 prescaler? on page 107 . assembly code example (1) tim16_writetcnt1: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcnt 1 to r17:r16 sts tcnt1h,r17 sts tcnt1l,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcnt1( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* set tcnt 1 to i */ tcnt1 = i; /* restore global interrupt flag */ sreg = sreg; }
116 7728g?avr?06/10 attiny87/attiny167 12.5 counter unit the main part of the 16-bit timer/counter is the programmable 16-bit bi-directional counter unit. figure 12-2 shows a block diagram of the counter and its surroundings. figure 12-2. counter unit block diagram signal description (internal signals): count increment or decrement tcnt1 by 1. direction select between increment and decrement. clear clear tcnt1 (set all bits to zero). clk t 1 timer/counter clock. top signalize that tcnt1 has reached maximum value. bottom signalize that tcnt1 has re ached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcnt1h) containing the upper eight bits of the counter, and counter low (tcnt1l) containing the lower eight bits. the tcnt1h register can only be indirectly accessed by the cpu. when the cpu does an access to the tcnt1h i/o location, t he cpu accesses the high byte temporary regis- ter (temp). the temporary register is updated with the tcnt1h value when the tcnt1l is read, and tcnt1h is updated with the temporary register value when tcnt1l is written. this allows the cpu to read or write the entire 16 -bit counter value within one clock cycle via the 8-bit data bus. it is important to notice that there are special cases of writing to the tcnt1 register when the counter is counting that will give unpredictable resu lts. 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 decre- mented at each timer clock (clk t 1). the clk t 1 can be generated from an external or internal clock source, selected by the clock select bits (cs12:0). when no clock source is selected (cs12:0 = 0) the timer is stopped. however, the tcnt1 value can be accessed by the cpu, independent of whether clk t 1 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the se tting of the waveform generation mode bits (wgm13:0) located in the timer/counter control registers a and b (tccr1a and tccr1b). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc1a/b. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 122 . 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
117 7728g?avr?06/10 attiny87/attiny167 the timer/counter overflow flag (tov1) is set according to the mode of operation selected by the wgm13:0 bits. tov1 can be used for generating a cpu interrupt. 12.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 multiple events, can be applied via the icp1 pin or alternatively, via the analog-comparator unit. the time-stamps can then be used to ca lculate 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 12-3 . the elements of the block diagram that are not directly a part of the input capture unit are gray shaded. figure 12-3. input capture unit block diagram when a change of the logic level (an event) occurs on the input capture pin (icp1), alterna- tively on the analog comparator output (aco), and this change confirms to the setting of the edge detector, a capture will be tr iggered. when a captur e is triggered, the 16-bit value of the counter (tcnt1) is written to the input capture register (icr1). the input capture flag (icf1) is set at the same system clock as th e tcnt1 value is copied into icr1 register. if enabled (icie1 = 1), the input capture flag generates an input capture interrupt. the icf1 flag is automatically cleared when the interrupt is executed. alternatively the icf1 flag can be cleared by software by writing a logical one to its i/o bit location. reading the 16-bit value in the input capture regi ster (icr1) is done by first reading the low byte (icr1l) and then the high byte (icr1h). when the low byte is read the high byte is cop- ied into the high byte temporary register (temp). when the cpu reads the icr1h i/o location it will access the temp register. the icr1 register can only be written when using a waveform generat ion mode that utilizes the icr1 register for defining the counter?s top value. in these cases the waveform genera- tion mode (wgm13:0) bits must be set before the top value can be written to the icr1 write icrn (16-bit register) icrnh (8-bit) temp (8-bit) data bus (8-bit) icrnl (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) icf1n (int.req.) noise canceler edge detector acic icncn icesn icpn analog comparator aco
118 7728g?avr?06/10 attiny87/attiny167 register. when writing the icr1 register the high byte must be written to the icr1h i/o loca- tion before the low byte is written to icr1l. for more information on how to access the 16-bit registers refer to ?accessing 16-bit regis- ters? on page 112 . 12.6.1 input capture trigger source the main trigger source for the input capture unit is the input capture pin (icp1). only 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 (icp1) and the analog comparator output (aco) inputs are sam- pled using the same technique as for the t1 pin ( figure 11-1 on page 107 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabled unless the timer/counter is set in a waveform generation mode that uses icr1 to define top. an input capture can be triggered by softwar e by controlling the port of the icp1 pin. 12.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 (icnc1) bit in timer/counter control register b (tccr1b). when enabled the noise canceler introduces additional four system clock cycles of delay fr om a change applied to the input, to the update of the icr1 register. the noise canceler uses the system clock and is therefore not affected by the prescaler. 12.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 betwee n two events is critical. if the processor has not read the captured value in the icr1 regist er before the next ev ent occurs, the icr1 will be overwritten with a new valu e. in this case the result of the capture will be incorrect. when using the input capture interrupt, the icr1 register should be read as early in the inter- rupt handler routine as possible. even though t he 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 e dge sensing must be done as early as possible after the icr1 register has been read. after a change of the edge, the input capture flag (icf1) must be cleared by software (writing a logical one to the i/o bit location). for measuring frequency only, the clearing of the icf1 flag is not required (if an interrupt handler is used).
119 7728g?avr?06/10 attiny87/attiny167 12.7 output compare units the 16-bit comparator continuously compares tcnt1 with the output compare register (ocr1a/b). if tcnt equals ocr1a/b the compar ator signals a match. a match will set the output compare flag (ocf1a/b) at the next timer clock cycle. if enabled (ocie1a/b = 1), the output compare flag generates an output compare interrupt. the ocf1a/b flag is automati- cally cleared when the interrupt is executed. al ternatively the ocf1a/b flag can be cleared by software by writing a logical one to its i/o bit locations. the waveform generator uses the match signal to generate an output according to operating mode set by the waveform gener- ation mode (wgm13:0) bits and compare output mode (com1a/b1:0) bits. the top and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( see ?modes of operation? on page 122. ) a special feature of output compare unit a allows it to define the timer/counter top value (i.e., counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 12-4 shows a block diagram of the output com pare unit. the elements of the block dia- gram that are not directly a part of the output compare unit are gray shaded. figure 12-4. output compare unit, block diagram the ocr1a/b register is double buffered when using any of the twelve pulse width modula- tion (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr1a/b compare register to either top or bottom of the counting sequence. the syn- chronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf.(8-bit) ocnxv ocnxu ocnxw temp (8-bit) data bus (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 ocnxx
120 7728g?avr?06/10 attiny87/attiny167 the ocr1a/b register access ma y seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocr1a/b buffer register, and if double buff- ering is disabled the cpu will access the oc r1a/b directly. the co ntent of the ocr1a/b (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automatically as the tcnt1 and icr1 register). therefore ocr1a/b 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 ocr1a/b registers must be done via the temp register since the compare of all 16 bits is done continuously. the high byte (ocr1a/bh) 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 (ocr1a/bl) is written to the lo wer eight bits, the high byte will be copied into the upper 8-bits of either the ocr1a/b buffer or ocr1a/b 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 112 . 12.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 compar e (foc1a/b) bit. forcing compare match will not set the ocf1a/b flag or reload/clear the timer, but the oc1a/bi pins will be updated as if a real compare match had occurred (the com1a/b1:0 bits settings define whether the oc1a/bi pins are set, cleared or toggled - if the respective ocnxi bit is set). 12.7.2 compare match bloc king by tcnt1 write all cpu writes to the tcnt1 register will blo ck any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr1a/b to be initial- ized to the same value as tcnt1 without triggering an interrupt when the timer/counter clock is enabled. 12.7.3 using the output compare unit since writing tcnt1 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt1 when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcnt1 equals the ocr1a/b value, the compare match will be missed, resulting in incorrect waveform generation. do not write the tcnt1 equal to top in pwm modes with variable top values. the compare match for th e top will be ignored a nd the counter will con- tinue to 0xffff. similarly, do not write the tcnt1 value equal to bottom when the counter is downcounting. the setup of the oc1a/b should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc1a/b value is to use the force output compare (foc1a/b) strobe bits in normal mo de. the oc1a/b register keeps its value even when changing between waveform generation modes. be aware that the com1a/b1:0 bits are not double buffered together with the compare value. changing the com1a/b1:0 bits will take effect immediately. 12.8 compare match output unit the compare output mode (com1a/b1:0) bits have two functions. the waveform generator uses the com1a/b1:0 bits for defining the output compare (oc1a/b) state at the next com- pare match. secondly the com1a/b1:0 and ocnxi bits control the oc1a/bi pin output source.
121 7728g?avr?06/10 attiny87/attiny167 figure 12-6 shows a simplified schematic of the logic affected by the com1a/b1:0 and ocnxi 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 com1a/b1:0 and ocnxi bits are shown. when referring to the oc1a/b state, the reference is for the internal oc1a/b regist er, not the oc1a/bi pin. if a system reset occur, the oc1a/b register is reset to ?0?. figure 12-5. compare match output 19 pb1 / oc1bu ddb1 pinb1 1 0 portb1 oc1bu ( * ) ( * ) oc1xi: tccr1d register bit 17 pb3 / oc1bv ddb3 1 0 portb3 com1b0 com1b1 oc1bv ( * ) 13 pb5 / oc1bw ddb5 1 0 portb5 com1a0 com1a1 ocf1a oc1bw ( * ) pinb3 pinb5 11 pb7 / oc1bx ddb7 1 0 portb7 oc1bx ( * ) pinb7 waveform generation waveform generation wgm13 foc1b top bottom foc1a wgm12 wgm11 wgm10 12 pb6 / oc1ax ddb6 1 0 portb6 oc1ax ( * ) pinb6 14 pb4 / oc1aw ddb4 1 0 portb4 oc1aw ( * ) pinb4 18 pb2 / oc1av ddb2 1 0 portb2 oc1av ( * ) pinb2 20 pb0 / oc1au ddb0 1 0 portb0 oc1au ( * ) pinb0 count clear tcnt1 16-bit counter = direction ocr1a 16-bit register = ocr1b 16-bit register ocf1b
122 7728g?avr?06/10 attiny87/attiny167 figure 12-6. compare match output logic 12.8.1 compare output function the general i/o port function is overridden by the output compare (oc1a/b) from the wave- form generator if either of the com1a/b1:0 bits are set and if ocnxi respective bit is set in tccr1d register. however, the oc 1a/bi pin direction (input or ou tput) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc1a/bi pin (ddr_oc1a/bi) must be set as output before the oc1a/b 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 12-1 , table 12-2 and table 12-3 for details. the design of the output compare pin logic allows initialization of the oc1a/b state before the output is enabled. note that some com1a/b1:0 bit settings are reserved for certain modes of operation. see ?16-bit timer/counter register description? on page 132. the com1a/b1:0 bits have no effect on the input capture unit. 12.8.2 compare output mode and waveform generation the waveform generator uses the com1a/b1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com1a/b1:0 = 0 tells the waveform generator that no action on the oc1a/b register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 12-1 on page 132 . for fast pwm mode refer to table 12-2 on page 133 , and for phase correct and phase and frequency correct pwm refer to table 12-3 on page 133 . a change of the com1a/b1:0 bits state will have effect at the first compare match after the bits are written. for non-pwm modes, the acti on can be forced to have immediate effect by using the foc1a/b strobe bits. 12.9 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm13:0) and compare output mode (com1a/b1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com1a/b1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com1a/b1:0 bits control whether the output should be set, cleared port dq dq ocnxi pin ocnx dq waveform generator comnx1 ocnxi comnx0 0 1 data bus focnx clk i/o ddr
123 7728g?avr?06/10 attiny87/attiny167 or toggle at a compare match ( see ?compare match output unit? on page 120. ). the ocnxi bits over control the setting of the com1a/b1:0 bits as shown in figure 12-6 on page 122 . for detailed timing information refer to ?timer/counter timing diagrams? on page 130 . 12.9.1 normal mode the simplest mode of operation is the normal mode (wgm13:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit valu e (max = 0xffff) and then restarts from the bottom (0x0000). in normal oper ation the timer/coun ter overflow flag (tov1) will be set in the same timer clock cycle as the tcnt1 become s zero. the tov1 flag in this case behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer over- flow interrupt that automatically clears the tov1 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. however, observe that the maximum interval between the external events must not exceed the resolution of the counter. if the inter- val between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 12.9.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm13:0 = 4 or 12), the ocr1a or icr1 register are used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt1) matches either the ocr1a (wgm13:0 = 4) or the icr1 (wgm13:0 = 12). the ocr1a or icr1 define the top value for the counter, hence also its res- olution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 12-7 . the counter value (tcnt1) increases until a compare match occurs with either ocr1a or icr1, and then counter (tcnt1) is cleared. figure 12-7. ctc mode, timing diagram tcntn ocnai (toggle) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 4 period 2 3 (comna1:0 = 1)
124 7728g?avr?06/10 attiny87/attiny167 an interrupt can be generated at each time the counter value reaches the top value by either using the ocf1a or icf1 flag according to the register used to define the top value. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr1a or icr1 is lower than the current value of tcnt1, the counter will miss the compar e match. the counter will then have to count to its maximum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is not desirable. an alternative will then be to use the fast pwm mode using ocr1a for defining top (wgm13:0 = 15) since the ocr1a then will be double buffered. for generating a waveform output in ctc mode, the oc1a output can be set to toggle its log- ical level on each compare match by setting the compare output mode bits to toggle mode (com1a1:0 = 1). the oc1a value will not be visi ble on the port pin unless the data direction for the pin is set to output (ddr_oc1a = 1) and oc1ai is set. the waveform generated will have a maximum frequency of f oc 1 a = f clk_i/o /2 when ocr1a 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 tov1 flag is set in the sa me timer clock cycle that the counter counts from max to 0x0000. 12.9.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm13:0 = 5, 6, 7, 14, or 15) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (oc1a/b) is set on the compare match between tcnt1 and ocr1a/b, and cleared at top. in inverting com- pare output mode output is cleared on compare match and set at top. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct and phase and frequency correct pwm modes that use dual-slope opera- tion. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high fre quency allows physically small sized external components (coils, capacitors), hence reduces total system cost. the pwm resolution for fast pwm can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2- bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (i cr1 or ocr1a set to max). the pwm resolution in bits can be calculated by using the following equation: f ocna f clk_i/o 2 n 1 ocrna + () ?? -------------------------------------------------------- = r fpwm top 1 + () log 2 () log ---------------------------------- - =
125 7728g?avr?06/10 attiny87/attiny167 in fast pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 5, 6, or 7), the value in icr1 (wgm13:0 = 14), or the value in ocr1a (wgm13:0 = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 12-8 . the figure shows fast pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustra ting the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1a/b and tcnt1. the oc1a/b inte rrupt flag will be set when a compare match occurs. figure 12-8. fast pwm mode, timing diagram the timer/counter overflow flag (tov1) is se t each time the counter reaches top. in addi- tion the oc1a or icf1 flag is set at the sa me timer clock cycle as tov1 is set when either ocr1a or icr1 is used for de fining the top value. if one of the interrupts are enabled, the interrupt handler routine can be used for updating the top and compare values. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a com pare match will never occur between the tcnt1 and the ocr1a/b. note that when using fixed top values the unused bits are masked to zero when any of the ocr1a/b registers are written. the procedure for updating icr1 differs from updating ocr1a when used for defining the top value. the icr1 register is not double buffered. this means that if icr1 is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new icr1 value written is lower than the current value of tcnt1. the result will then be that the counter will miss the compare match at the top value. the counter will then have to count to the max value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. the ocr1a register however, is double buffered. this feature allows the ocr1a i/o location to be written anytime. when the ocr1a i/o location is written the value written will be put into the ocr1a buffer re gister. the ocr1a compar e register will then be updated with the value in the buffer register at the next timer clock cycle the tcnt1 matches top. the update is done at the same timer clock cycle as the tcnt1 is cleared and the tov1 flag is set. 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 ocnxi ocnxi (comnx1:0 = 2) (comnx1:0 = 3)
126 7728g?avr?06/10 attiny87/attiny167 using the icr1 register for defining top work s well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. how- ever, if the base pwm frequency is actively changed (by changing the top value), using the ocr1a as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow generation of pwm waveforms on the oc1a/b pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1a/b1:0 to three (see table 12-2 on page 133 ). the actual oc1a/b value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_oc1a/b) and oc1a/bi is set. the pwm waveform is generated by setting (or clearing) the oc1a/b register at the compare match between ocr1a/b and tcnt1, and clearing (or setting) the oc1a/b 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 ocr1a/b register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr1a/b is set equal to bottom (0x0000) the output w ill be a narrow spike for each top+1 timer clock cycle. setting the ocr1a/b equal to top will result in a constant high or low output ( depending on t he polarity of the output set by the com1a/b1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc1a to toggle its logical level on each compare match (com1a1:0 = 1). the wave- form generated will have a maximum frequency of f oc 1 a = f clk_i/o /2 when ocr1a is set to zero (0x0000). this feature is similar to the oc1a toggle in ctc mode, except the double buf- fer feature of the output compare unit is enabled in the fast pwm mode. 12.9.4 phase correct pwm mode the phase correct pulse width modulation or phase correct pwm mode (wgm13:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency correct pwm mode, based on a 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 (oc1a/b) is cleared on the compare match between tcnt1 and ocr1a/b while upcounting, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the sy mmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated by using the following equation: f ocnxpwm f clk_i/o n 1 top + () ? ------------------------------------- = r pcpwm top 1 + () log 2 () log ---------------------------------- - =
127 7728g?avr?06/10 attiny87/attiny167 in phase correct pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 1, 2, or 3), the value in icr1 (wgm13:0 = 10), or the value in ocr1a (wgm13:0 = 11). the counter has then reached the top and changes the count direction. the tcnt1 value will be equal to top for one timer clock cycle. the timing diagram for th e phase correct pwm mode is shown on figure 12-9 . the figure shows phase correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1a/b and tcnt1. the oc1a/b inte rrupt flag will be set when a compare match occurs. figure 12-9. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time the counter reaches bottom. when either ocr1a or icr1 is used for defining the top value, the oc1a or icf1 flag is set accordingly at the same timer clock cycle as the ocr1a/b registers are updated with the double buffer value (at top). the interrupt flags can be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a com pare match will never occur between the tcnt1 and the ocr1a/b. note that when using fixed top values, the unused bits are masked to zero when any of the ocr1a/b registers are written. as the third period shown in figure 12-9 illustrates, changing the top actively while the timer/count er is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocr1a/b register. since the ocr1a/b update occurs at top, the pwm period starts and ends at top. this implies that the length of the falling slope is determined by the previous top value, while the length of the rising slope is determined by the new top value. when these two values differ the two slopes of the pe riod will differ in length. the difference in length gives the unsymmetrical result on the output. 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 ocnxi ocnxi (comnx1:0 = 2) (comnx1:0 = 3)
128 7728g?avr?06/10 attiny87/attiny167 it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value while the ti mer/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 oc1a/b pins. setting the com1a/b1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1a/b1:0 to three (see table on page 133 ). the actual oc1a/b value w ill only be visible on the port pin if the data direction for the port pin is set as output (ddr_oc1a/b) and oc1a/bi is set. the pwm waveform is gener- ated by setting (or clearing) the oc1a/b regi ster at the compare match between ocr1a/b and tcnt1 when the counter increments, and clearing (or setting) the oc1a/b register at compare match between ocr1a/b and tcnt1 when the counter decrements. the pwm fre- quency 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 ocr1a/b register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1a/b is set equal to bot- tom the output will be continuo usly low and if set equal to top the output will be continuously high for non-inverted pwm mode. for inverted pwm the output will have the opposite logic values. 12.9.5 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency correct pwm mode (wgm13:0 = 8 or 9) provides a high resolution phase and frequency correct pwm waveform generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (oc1a/b) is cleared on the compare match between tcnt1 and ocr1a/b while upcounting, and set on the compare match while downcounting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower max- imum operation frequency compared to the single-slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the main difference between the phase corr ect, and the phase and frequency correct pwm mode is the time the ocr1a/b register is updated by the ocr1a/b buffer register, (see fig- ure 12-9 and figure 12-10 ). the pwm resolution for the phase and frequency correct pwm mode can be defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated using the following equation: f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------------- = r pfcpwm top 1 + () log 2 () log ---------------------------------- - =
129 7728g?avr?06/10 attiny87/attiny167 in phase and frequency correct pwm mode the counter is incremented until the counter value matches either the value in icr1 (wgm13:0 = 8), or the value in ocr1a (wgm13:0 = 9). the counter has then re ached the top and change s the count direction. the tcnt1 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct and fre- quency correct pwm mode is shown on figure 12-10 . the figure shows phase and frequency correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a hist ogram for illustrating the dual-s lope operation. the diagram includes non-inverted and inverted pwm output s. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1a/b and tcnt1. the oc1a/b interrupt flag will be set wh en a compare match occurs. figure 12-10. phase and frequency correct pwm mode, timing diagram the timer/counter overflow flag (tov1) is set at the same timer clock cycle as the ocr1a/b registers are updated with the double buffer value (at bottom). when either ocr1a or icr1 is used for defining the top value, the oc1a or icf1 flag set when tcnt1 has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a com pare match will never occur between the tcnt1 and the ocr1a/b. as figure 12-10 shows the output generated is, in contrast to the phase correct mode, sym- metrical in all periods. since the ocr1a/b registers are updated at bottom, the length of the rising and the falling slopes will always be e qual. this gives symmet rical output pulses and is therefore frequency correct. using the icr1 register for defining top work s well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. how- ever, if the base pwm frequency is actively changed by changing the top value, using the ocr1a as top is clearly a better choice due to its double buffer feature. 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 ocnxi ocnxi (comnx1:0 = 2) (comnx1:0 = 3)
130 7728g?avr?06/10 attiny87/attiny167 in phase and frequency correct pwm mode, the compare units allow generation of pwm waveforms on the oc1a/b pins. setting the com1a/b1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1a/b1:0 to three (see table on page 133 ). the actual oc1a/b value will on ly be visible on the port pin if the data direction for the po rt pin is set as output (ddr_ oc1a/b) and oc1a/bi is set. the pwm waveform is generated by setting (or clearing) the oc1a/b register at the compare match between ocr1a/b and tcnt1 when the counter increments, and clearing (or setting) the oc1a/b register at compare match between ocr1a/b and tcnt1 when the counter decrements. the pwm frequency for the output when using phase and frequency correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1a/b register represents special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1a/b is set equal to bot- tom the output will be cont inuously low and if set equal to to p the output will be set to high for non-inverted pwm mode. for inverted pwm the output will have the opposite logic values. 12.10 timer/counte r timing diagrams the timer/counter is a synchronous design and the timer clock (clk t 1) 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 ocr1a/b register is updated with the ocr1a/b buffer value (only for modes utilizin g double buffering). figure 12-11 shows a timing diagram for the setting of ocf1a/b. figure 12-11. timer/counter timing diagram, setting of ocf1a/b, no prescaling figure 12-12 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
131 7728g?avr?06/10 attiny87/attiny167 figure 12-12. timer/counter timing diagram, setting of ocf1a/b, with prescaler (f clk_i/o /8) figure 12-13 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode the ocr1a/b register is updated at bottom. the timing diagrams will be the same, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tov1 flag at bottom. figure 12-13. timer/counter timing diagram, no prescaling figure 12-14 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
132 7728g?avr?06/10 attiny87/attiny167 figure 12-14. timer/counter timing dia gram, with prescaler (f clk_i/o /8) 12.11 16-bit timer/counter register description 12.11.1 timer/counter1 control register a ? tccr1a ? bit 7:6 ? com1a1:0: compare output mode for channel a ? bit 5:4 ? com1b1:0: compare output mode for channel b the com1a1:0 and com1b1:0 control the output compare pins (oc1ai and oc1bi respec- tively) behavior. if one or both of the com1a1:0 bits are written to one, the oc1ai output overrides the normal port functionality of the i /o pin it is connected to. if one or both of the com1b1:0 bit are written to one, the oc1bi output overrides the normal port functionality of the i/o pin it is connected to. however, note th at the data direction register (ddr) bit and oc1xi bit (tccr1d) corresponding to the oc1ai or oc1bi pin must be set in order to enable the output driver. when the oc1ai or oc1bi is connected to the pi n, the function of the com1a/b1:0 bits is dependent of the wgm13:0 bits setting. table 12-1 shows the com1a/b1:0 bit functionality when the wgm13:0 bits are set to a normal or a ctc mode (non-pwm). tovn (fpwm) and icf n (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 ? ? wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 12-1. compare output mode, non-pwm oc1ai oc1bi com1a1 com1b1 com1a0 com1b0 description 0x x normal port operation, oc1a/oc1b disconnected. 1 00 0 1 toggle oc1a/oc1b on compare match. 10 clear oc1a/oc1b on compare match (set output to low level). 1 1 set oc1a/oc1b on compare match (set output to high level).
133 7728g?avr?06/10 attiny87/attiny167 table 12-2 shows the com1a/b1:0 bit functionality when the wgm13:0 bits are set to the fast pwm mode. note: 1. a special case occurs when ocr1a/oc r1b equals top and com1a1/com1b1 is set. in this case the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 124. for more details. table 12-3 shows the com1a/b1:0 bit functionality when the wgm13:0 bits are set to the phase correct or the phase and frequency correct, pwm mode. note: 1. a special case occurs when oc1a/o c1b equals top and com1a1/com1b1 is set. see ?phase correct pwm mode? on page 126. for more details. ? bit 3:2 ? reserved bits these bits are reserved for future use. table 12-2. compare output mode, fast pwm (1) oc1ai oc1bi com1a1 com1b1 com1a0 com1b0 description 0x x normal port operation, oc1a/oc1b disconnected. 10 0 10 1 wgm13=0: normal port operation, oc1a/oc1b disconnected. wgm13=1: toggle oc1a on compare match, oc1b reserved. 11 0 clear oc1a/oc1b on compare match set oc1a/oc1b at top 11 1 set oc1a/oc1b on compare match clear oc1a/oc1b at top table 12-3. compare output mode, phase correct and phase and frequency correct pwm (1) oc1ai oc1bi com1a1 com1b1 com1a0 com1b0 description 0x x normal port operation, oc1a/oc1b disconnected. 10 0 10 1 wgm13=0: normal port operation, oc1a/oc1b disconnected. wgm13=1: toggle oc1a on compare match, oc1b reserved. 11 0 clear oc1a/oc1b on compare match when up-counting. set oc1a/oc1b on compare match when downcounting. 11 1 set oc1a/oc1b on compare match when up-counting. clear oc1a/oc1b on compare match when downcounting.
134 7728g?avr?06/10 attiny87/attiny167 ? bit 1:0 ? wgm11:0: waveform generation mode combined with the wgm13:2 bits found in the tccr1b register, these bits control the count- ing sequence of the counter, the source for maximum (top) counter value, and what type of waveform generation to be used, see table 12-4 . 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 122. ). note: 1. the ctc1 and pwm11:0 bit definition names are obsolete. use the wgm12:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. table 12-4. waveform generation mode bit description (1) mode wgm13 wgm12 (ctc1) wgm11 (pwm11) wgm10 (pwm10) timer/counter mode of operation top update of ocr1a/b at tov1 flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 30011 pwm, phas e correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocr1a immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff top top 6 0 1 1 0 fast pwm, 9-bit 0x01ff top top 7 0 1 1 1 fast pwm, 10-bit 0x03ff top top 81000 pwm, phase and frequency correct icr1 bottom bottom 91001 pwm, phase and frequency correct ocr1a bottom bottom 10 1 0 1 0 pwm, phase correct icr1 top bottom 11 1 0 1 1 pwm, phase correct ocr1a top bottom 12 1 1 0 0 ctc icr1 immediate max 13 1 1 0 1 (reserved) ? ? ? 141110 fast pwm icr1top top 15 1 1 1 1 fast pwm ocr1a top top
135 7728g?avr?06/10 attiny87/attiny167 12.11.2 timer/counter1 control register b ? tccr1b ? bit 7 ? icnc1: input capture noise canceler setting this bit (to one) activates the input capture noise canceler. when the noise canceler is activated, the input from the input capture pi n (icp1) is filtered. the filter function requires four successive equal valued samples of the icp1 pin for changing its output. the input cap- ture is therefore dela yed by four osc illator cycles when the noise canceler is enabled. ? bit 6 ? ices1: input capture edge select this bit selects which edge on the input capture pin (icp1) that is used to trigger a capture event. when the ices1 bit is written to zero, a falling (negative) edge is used as trigger, and when the ices1 bit is written to one, a risi ng (positive) edge w ill trigger the capture. when a capture is triggered according to the ices1 setting, the counter value is copied into the input capture regist er (icr1). the event will also se t the input capture flag (icf1), and this can be used to cause an input capture interrupt, if this interrupt is enabled. when the icr1 is used as top value (see description of the wgm13:0 bits located in the tccr1a and the tccr1b register), the icp1 is disconnected and consequently the input capture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuri ng compatibility wit h future devices, this bit must be written to zero wh en tccr1b is written. ? bit 4:3 ? wgm13:2: waveform generation mode see tccr1a register description. ? bit 2:0 ? cs12:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see fig- ure 12-11 and figure 12-12 . bit 7654 3210 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 table 12-5. clock select bit description cs12 cs11 cs10 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 t1 pin. clock on falling edge. 1 1 1 external clock source on t1 pin. clock on rising edge.
136 7728g?avr?06/10 attiny87/attiny167 if external pin modes are used for the timer/c ounter1, transitions on the t1 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 12.11.3 timer/counter1 control register c ? tccr1c ? bit 7 ? foc1a: force output compare for channel a ? bit 6 ? foc1b: force output compare for channel b the foc1a/foc1b bits are only active when the wgm13:0 bits specifies a non-pwm mode. however, for ensuring compatibilit y with future devices, these bits must be set to zero when tccr1a is written when operating in a pwm mode. when writing a logical one to the foc1a/foc1b bit, an immediate compare match is forced on the waveform generation unit. the oc1nx output is changed according to its com1a/b1:0 and oc1nx bits setting. note that the foc1a/foc1b bits are implemented as strobes. therefore it is the value present in the com1a/b1:0 bits that determine the effect of the forced compare. a foc1a/foc1b strobe will not gener ate any interrupt nor will it cl ear the timer in clear timer on compare match (ctc) mode using ocr1a as top. the foc1a/foc1b bits are always read as zero. 12.11.4 timer/counter1 control register d ? tccr1d ? bit 7:4 ? oc1bi: output compare pin enable for channel b the oc1bi bits enable the output compare pins of channel b as shown in figure 12-6 on page 122 . ? bit 3:0 ? oc1ai: output compare pin enable for channel a the oc1ai bits enable the output compare pins of channel a as shown in figure 12-6 on page 122 . bit 7 6 5 4 3 2 1 0 foc1a foc1b ? ? ? ? ? ? tccr1c read/write r/w r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 oc1bx oc1bw oc1bv oc1bu oc1ax oc1aw oc1av oc1au tccr1d 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
137 7728g?avr?06/10 attiny87/attiny167 12.11.5 timer/counter1 ? tcnt1h and tcnt1l the two timer/counter i/o locations (tcnt1h and tcnt1l, combined tcnt1) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 112. modifying the counter (tcnt1) while the counter is running introduces a risk of missing a compare match between tcnt1 and one of the ocr1a/b registers. writing to the tcnt1 register blocks (remov es) the compare match on the following timer clock for all compare units. 12.11.6 output compare register a ? ocr1ah and ocr1al 12.11.7 output compare register b ? ocr1bh and ocr1bl the output compare registers contain a 16-bit value that is continuously compared with the counter value (tcnt1). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc1a/b pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cpu writes to these registers, the access is performed using an 8-bit temporary high byte register (tem p). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 112. 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 value00000000 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 value00000000 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
138 7728g?avr?06/10 attiny87/attiny167 12.11.8 input capture register ? icr1h and icr1l the input capture is updated with the counter (tcnt1) value each time an event occurs on the icp1 pin (or optionally on the analog comparator output for timer/counter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 112. 12.11.9 timer/counter1 interrupt mask register ? timsk1 ? bit 7..6 ? reserved bits these bits are reserved for future use. ? bit 5 ? icie1: 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 ?interrupt vectors in attiny87/167? on page 59. ) is executed when the icf1 flag, located in tifr1, is set. ? bit 4..3 ? reserved bits these bits are reserved for future use. ? bit 2 ? ocie1b: 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 correspond- ing interrupt vector ( see ?interrupt vectors in attiny87/167? on page 59. ) is executed when the ocf1b flag, located in tifr1, is set. ? bit 1 ? ocie1a: 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 correspond- ing interrupt vector ( see ?interrupt vectors in attiny87/167? on page 59. ) is executed when the ocf1a flag, located in tifr1, is set. ? bit 0 ? toie1: timer/counter 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 vec- tor ( see ?interrupt vectors in attiny87/167? on page 59. ) is executed when the tov1 flag, located in tifr1, is set. 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 bit 76543210 ? ? icie1 ? ? ocie1b ocie1a toie1 timsk1 read/write r r r/w r r r/w r/w r/w initial value00000000
139 7728g?avr?06/10 attiny87/attiny167 12.11.10 timer/counter1 interr upt flag register ? tifr1 ? bit 7..6 ? reserved bits these bits are reserved for future use. ? bit 5 ? icf1: input capture flag this flag is set when a capture event occurs on the icp1 pin. when the input capture register (icr1) is set by the wgm13:0 to be used as the top value, the icf1 flag is set when the counter reaches the top value. icf1 is automatically cleared when the input capture interrupt vector is executed. alterna- tively, icf1 can be cleared by writing a logic one to its bit location. ? bit 4..3 ? reserved bits these bits are reserved for future use. ? bit 2 ? ocf1b: output compare b match flag this flag is set in the timer clock cycle after the counter (tcnt1) value matches the output compare register b (ocr1b). note that a forced output compare (foc 1b) strobe will not set the ocf1b flag. ocf1b is automatically cleared when the output compare match b interrupt vector is exe- cuted. alternatively, ocf1b can be cleared by writing a logic one to its bit location. ? bit 1 ? ocf1a: output compare a match flag this flag is set in the timer clock cycle after the counter (tcnt1) value matches the output compare register a (ocr1a). note that a forced output compare (foc 1a) strobe will not set the ocf1a flag. ocf1a is automatically cleared when the output compare match a interrupt vector is exe- cuted. alternatively, ocf1a can be cleared by writing a logic one to its bit location. ? bit 0 ? tov1: timer/counter overflow flag the setting of this flag is dependent of the wgm13:0 bits setting. in normal and ctc modes, the tov1 flag is set when the timer overflows. refer to table 12-4 on page 134 for the tov1 flag behavior when using another wgm13:0 bit setting. tov1 is automatically cleared when the timer/counter1 overflow interrupt vector is exe- cuted. alternatively, tov1 can be cleared by writing a logic one to its bit location. bit 76543210 ? ? icf1 ? ? ocf1b ocf1a tov1 tifr1 read/write r r r/w r r r/w r/w r/w initial value00000000
140 7728g?avr?06/10 attiny87/attiny167 13. spi - serial peripheral interface the serial peripheral interface (spi) allows high-speed synchronous data transfer between the attiny87/167 and peripheral devices or between several avr devices. the attiny87/167 spi includes the following features: 13.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 figure 13-1. spi block diagram (1) note: 1. refer to figure 1.6 on page 5 , and table 9-3 on page 76 for spi pin placement. spi2x spi2x divider /2/4/8/16/32/64/128 clk io
141 7728g?avr?06/10 attiny87/attiny167 the interconnection between master and slave cpus with spi is shown in figure 13-2 . the system 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. mas- ter and slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the sck line to interchange data. data is always shifted from master to slave on the master out ? slave in, mosi, line, and from slave to mas- ter on the master in ? slav e out, miso, line. after each data packet, the master will synchronize the slave by pu lling high the slave select, ss , line. when configured as a master, the spi interface has no automatic control of the ss line. this must be handled by user software before communication can start. when this is done, writing a byte to the spi data register starts the spi clock generator, and the hardware shifts the eight bits into the slave. after shifting one byte, the spi clock generator stops, setting the end of transmission flag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift the next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be kept in the bu ffer 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 trans- mission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr register is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr before reading the incoming data. the last incoming byte will be kept in the buffer register for later use. figure 13-2. spi master-slave interconnection the system is single buffered in the transmit direction 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 completed. when receiving data, however, a received character must be read from the spi data register before the next character has been completely shifted in. otherwise, the first byte is lost. in spi slave mode, the control logic will sample th e incoming signal of the sck pin. to ensure correct sampling of the clock signal, the freq uency of the spi clock should never exceed f clkio /4. shift enable
142 7728g?avr?06/10 attiny87/attiny167 when the spi is enabled, the data direction of the mosi, miso, sck, and ss pins is overrid- den according to table 13-1 . for more details on automatic port overrides, refer to ?alternate port functions? on page 72 . note: 1. see ?alternate functions of port b? on page 81 for a detailed description of how to define the direction of the user defined spi pins. the following code examples show how to initia lize the spi as a master and how to perform a simple transmission. ddr_spi in the examples must be replaced by t he actual data direction register controlling the spi pins. dd_mosi, dd_miso and dd_sck mu st be replaced by the actual data direc- tion bits for these pins. e.g. if mosi is placed on pin pb2, replace dd_mosi with ddb2 and ddr_spi with ddrb. table 13-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
143 7728g?avr?06/10 attiny87/attiny167 note: 1. the example code assumes that the pa rt specific header file is included. assembly code example (1) spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< 144 7728g?avr?06/10 attiny87/attiny167 the following code examples show how to initia lize the spi as a slave and how to perform a simple reception. note: 1. the example code assumes that the pa rt specific header file is included. assembly code example (1) spi_slaveinit: ; set miso output, all others input ldi r17,(1< 145 7728g?avr?06/10 attiny87/attiny167 13.2 ss pin functionality 13.2.1 slave mode when the spi is configured as a slave, the slave select (ss) pin is always input. when ss is held low, the spi is activated, and miso becomes an output if configured so by the user. all other pins are inputs. when ss is driven high, all pins are inputs, and the spi is passive, which means that it will not receive in coming data. note that the spi logic will be reset once the ss pin is driven high. the ss pin is useful for packet/byte synchronizati on to keep the slave bit counter synchronous with the master clock generator. when the ss pin is driven high, t he spi slave will immediately reset the send and receive logic, and drop any partially received data in the shift register. 13.2.2 master mode when the spi is configured as a master (mstr in spcr is set), the user can determine the direction of the ss pin. if ss is configured as an output, the pin is a gener al output pin which does not affect the spi system. typically, the pin will be driving the ss pin of the spi slave. if ss is configured as an input, it must be held high to ensure master spi operation. if the ss pin is driven low by peripheral circuitry when the spi is configured as a master with the ss pin defined as an input, the spi system interprets this as another master selecting the spi as a slave and starting to send data to it. to avoid bus contention, the spi system takes the follow- ing actions: 1. the mstr bit in spcr is cleared and the spi system becomes a slave. as a result of the spi becoming a slave, the mosi and sck pins become inputs. 2. the spif flag in spsr is set, and if the spi interrupt is enabled, and the i-bit in sreg is set, the interrup t routine will be executed. thus, when interrupt-driven spi transmission is used in master mode, and there exists a pos- sibility that ss is driven low, the interr upt should always check that the mstr bit is still set. if the mstr bit has been cleared by a slave select, it must be set by the user to re-enable spi master mode. 13.2.3 spi control register ? spcr ? bit 7 ? spie: spi interrupt enable this bit causes the spi interrupt to be executed if spif bit in the spsr register is set and 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 en abled. this bit must be set to enable any spi operations. 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 value 00000000
146 7728g?avr?06/10 attiny87/attiny167 ? 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 us er will then have to set mstr to re-enable spi master mode. ? bit 3 ? cpol: clock polarity when this bit is written to one, sck is high w hen idle. when cpol is written to zero, sck is low when idle . refer to figure 13-3 and figure 13-4 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 13-3 and figure 13-4 for an example. the cpol functionality is summarized below: ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the device configured as a master. spr1 and spr0 have no effect on the slave. the relationship between sck and the clk io frequency f clkio is shown in the following table: table 13-2. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 13-3. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample table 13-4. relationship between sck and the oscillator frequency spi2x spr1 spr0 sck frequency 000 f clkio / 4 001 f clkio / 16 010 f clkio / 64 011 f clkio / 128 100 f clkio / 2 101 f clkio / 8 110 f clkio / 32 111 f clkio / 64
147 7728g?avr?06/10 attiny87/attiny167 13.2.4 spi status register ? spsr ? bit 7 ? spif: spi interrupt flag when a serial transfer is complete, the spif flag is set. an interrupt is generated if spie in spcr is set and global interrupts are enabled. if ss is an input and is driven low when the spi is in master mode, this will al so set the spif flag. spif is clear ed by hardware when executing the corresponding interrupt handling vector. alternatively, the spif bit is cleared by first read- ing the spi status register with spif set, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the wcol bit is set if the spi data register (spdr) is written during a data transfer. the wcol bit (and the spif bit) are cleared by first reading the spi status register with wcol set, and then accessing the spi data register. ? bit 5..1 ? res: reserved bits these bits are reserved bits in the at tiny87/167 and will always read as zero. ? bit 0 ? spi2x: double spi speed bit when this bit is written logic one the spi s peed (sck frequency) will be doubled when the spi is in master mode (see table 13-4 ). this means that the mi nimum sck period will be two cpu clock periods. when the spi is configured as slave, the spi is only guaranteed to work at f clkio /4 or lower. the spi interface on the attiny87/167 is also used for program memory and eeprom down- loading or uploading. see ?serial downloading? on page 238 for serial programming and verification. 13.2.5 spi data register ? spdr ? bits 7:0 - spd7:0: spi data 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 reg- ister causes the shift register receive buffer to be read. bit 76543210 spif wcol ? ? ? ? ? spi2x spsr read/write r r r rrrrr/w initial value 00000000 bit 76543210 spd7spd6spd5spd4spd3spd2spd1spd0spdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value xxxxxxxxundefined
148 7728g?avr?06/10 attiny87/attiny167 13.3 data modes there are four combinations of sck phase and polarity with respect to serial data, which are determined by control bits cpha and cpol. the spi data transfer formats are shown in fig- ure 13-3 and figure 13-4 . data bits are shifted out and latched in on opposite edges of the sck signal, ensuring sufficient time for data si gnals to stabilize. this is clearly seen by sum- marizing table 13-2 and table 13-3 , as done below: figure 13-3. spi transfer format with cpha = 0 figure 13-4. spi transfer format with cpha = 1 table 13-5. cpol functionality leading edge trai ling edge spi mode cpol=0, cpha=0 sample (rising) setup (falling) 0 cpol=0, cpha=1 setup (rising) sample (falling) 1 cpol=1, cpha=0 sample (falling) setup (rising) 2 cpol=1, cpha=1 setup (falling) sample (rising) 3 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)
149 7728g?avr?06/10 attiny87/attiny167 14. usi ? universal serial interface 14.1 features ? two-wire synchronous data tr ansfer (master or slave) ? three-wire synchronous data transfer (master or slave) ? data received interrupt ? wakeup from idle mode ? in two-wire mode: wake-up from all sleep modes, including power-down mode ? two-wire start condition detect or with interr upt capability 14.2 overview the universal serial interface, or usi, provides the basic hardware resources needed for serial communication. combined with a minimum of control software, the usi allows signifi- cantly higher transfer rates and uses less code space than solutions based on software only. interrupts are included to minimize the processor load. a simplified block diagram of the usi is shown on figure 14-1 for the actual placement of i/o pins, refer to ?pin configuration? on page 5 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-speci fic i/o register and bit locations are listed in the ?register descriptions? on page 156 . figure 14-1. universal serial interface, block diagram the 8-bit usi data register is directly access ible via the data bus and contains the incoming and outgoing data. the register has no buffering so the data must be read as quickly as possi- ble to ensure that no data is lost. the usi data register is a serial shift register and the most significant bit that is the output of the serial shif t register is connected to one of two output pins depending of the wire mode configuration. data bus usipf usitc usiclk usics0 usics1 usioif usioie usidc usisif usiwm0 usiwm1 usisie bit7 two-wire clock control unit do (output only) di/sda (input/open drain) usck/scl (input/open drain) 4-bit counter usidr usisr dq le usicr clock hold tim0 comp bit0 [1] 3 0 1 2 3 0 1 2 0 1 2 usidb
150 7728g?avr?06/10 attiny87/attiny167 a transparent latch is inserted between the usi data register output and output pin, which delays the change of data output to the opposite clock edge of the data input sampling. the serial input is always sampled from the data input (di) pin independent of the configuration. the 4-bit counter can be both read and written via the data bus, and can generate an overflow interrupt. both the usi data register and the counter are clocked simultaneously by the same clock source. this allows the counter to coun t the number of bits received or transmitted and generate an interrupt when the transfer is comp lete. note that when an external clock source is selected the counter counts both clock edges. in this case the counter counts the number of edges, and not the number of bits. the clock can be selected from three different sources: the usck pin, timer/counter0 compare match or from software. the two-wire clock control unit can generate an interrupt when a start condition is detected on the two-wire bus. it can also generate wait st ates by holding the clock pin low after a start condition is detected, or after the counter overflows. 14.3 functional descriptions 14.3.1 three-wire mode the usi three-wire mode is compliant to the serial peripheral interface (spi) mode 0 and 1, but does not have the slave select (ss ) pin functionality. however, this feature can be imple- mented in software if necessary. pin names used by this mode are: di, do, and usck. figure 14-2. three-wire mode operat ion, simplified diagram figure 14-2 shows two usi units operating in three-wire mode, one as master and one as slave. the two usi data register are interconnected in such way that after eight usck clocks, the data in each register are interchanged. the same clock also increments the usi?s 4-bit counter. the counter overflow (interr upt) flag, or usioif, can therefore be used to determine when a transfer is completed. slave master bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 do di usck bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 do di usck portxn
151 7728g?avr?06/10 attiny87/attiny167 the clock is generated by the master device software by toggling the usck pin via the port register or by writing a on e to the usitc bit in usicr. figure 14-3. three-wire mode, timing diagram the three-wire mode timing is shown in figure 14-3 at the top of the figure is a usck cycle reference. one bit is shifted into the usi data register (usidr) for each of these cycles. the usck timing is shown for both external clock mo des. in external clock mode 0 (usics0 = 0), di is sampled at positive edges, and do is ch anged (data register is shifted by one) at nega- tive edges. external clock mode 1 (usics0 = 1) uses the opposite edges versus mode 0, i.e., samples data at negative and changes the output at positive edges. the usi clock modes cor- responds to the spi data mode 0 and 1. referring to the timing diagram ( figure 14-3 ), a bus transfer involves the following steps: 1. the slave device and master device sets up its data output and, depending on the protocol used, enables its output driver (mark a and b). the output is set up by writ- ing the data to be transmitted to the usi data register. enabling of the output is done by setting the corresponding bit in the port data direction register. note that point a and b does not have any specific order, but both must be at least one half usck cycle before point c where the data is sampled. this must be done to ensure that the data setup requirement is satisfied. the 4-bit counter is reset to zero. 2. the master generates a clock pulse by software toggling the usck line twice (c and d). the bit value on the slave and master?s data input (di) pin is sampled by the usi on the first edge (c), and the data output is changed on the opposite edge (d). the 4-bit counter will count both edges. 3. step 2. is repeated eight times for a complete register (byte) transfer. 4. after eight clock pulses (i.e., 16 clock ed ges) the counter will overflow and indicate that the transfer is completed. the data bytes transferred must now be processed before a new transfer can be initiated. the overflow interrupt will wake up the proces- sor if it is set to idle mode. depending of the protocol used the slave device can now set its output to high impedance. 14.3.2 spi master operation example the following code demonstrates how to use the usi module as a spi master: spitransfer: sts usidr,r16 ldi r16,(1< 152 7728g?avr?06/10 attiny87/attiny167 sts usicr,r16 lds r16, usisr sbrs r16, usioif rjmp spitransfer_loop lds r16,usidr ret the code is size optimized using only eight in structions (+ ret). the code example assumes that the do and usck pins are enabled as output in the ddra or ddrb register. the value stored in register r16 prior to the function is called is transferred to the slave device, and when the transfer is completed the data received from the slave is stored back into the r16 register. the second and third instructions clears the usi counter overflow flag and the usi counter value. the fourth and fifth instruction set three-wire mode, positive edge shift register clock, count at usitc strobe, and toggle usck. the loop is repeated 16 times. the following code demonstrates how to use the usi module as a spi master with maximum speed (fsck = fck/4): spitransfer_fast: sts usidr,r16 ldi r16,(1< 153 7728g?avr?06/10 attiny87/attiny167 14.3.3 spi slave operation example the following code demonstrates how to use the usi module as a spi slave: init: ldi r16,(1< 154 7728g?avr?06/10 attiny87/attiny167 figure 14-4. two-wire mode operation, simplified diagram figure 14-4 shows two usi units operating in two-wire mode, one as master and one as slave. it is only the physical layer that is shown since the system operation is highly depen- dent of the communication scheme used. the main differences between the master and slave operation at this level, is the serial clock generation which is always done by the master, and only the slave uses the clock control unit. clock generation must be implemented in software, but the shift operation is done automatically by both devices. note that only clocking on nega- tive edge for shifting data is of practical use in this mode. the slave can insert wait states at start or end of transfer by forcing the scl clock low. this means that the master must always check if the scl line was actually released after it has generated a positive edge. since the clock also increments the counter, a counter overflow can be used to indicate that the transfer is completed. the clock is generated by the master by toggling the usck pin via the port register. the data direction is not given by the physical layer. a protocol, like the one used by the twi-bus, must be implemented to control the data flow. figure 14-5. two-wire mode, typical timing diagram master slave bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 sda scl bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 two-wire clock control unit hold scl portxn sda scl vcc p s address 1 - 7 8 9 r/w ack ack 1 - 8 9 data ack 1 - 8 9 data sda scl a b d e c f
155 7728g?avr?06/10 attiny87/attiny167 referring to the timing diagram ( figure 14-5 ), a bus transfer involves the following steps: 1. the a start condition is generated by the master by forcing the sda low line while the scl line is high (a). sda can be forced low either by writing a zero to bit 7 of the shift register, or by setting the corresponding bit in the port register to zero. note that the usi data register bit must be set to one for the output to be enabled. the slave device?s start detector logic (figure 14-6.) detects the start condition and sets the usisif flag. the flag can generate an interrupt if necessary. 2. in addition, the start detect or will hold the scl lin e low after the mast er has forced an negative edge on this line (b). this allows the slave to wake up from sleep or com- plete its other tasks before setting up the usi data register to receive the address. this is done by clearing the start condition flag and reset the counter. 3. the master set the first bit to be transferred and releases the scl line (c). the slave samples the data and shift it into the usi data register at the positive edge of the scl clock. 4. after eight bits are transferred containing slave address and data direction (read or write), the slave counter overflows and the sc l line is forced low (d). if the slave is not the one the master has addressed, it releases the scl line and waits for a new start condition. 5. if the slave is addressed it holds the sda line low during the acknowledgment cycle before holding the scl line low again (i.e., the counter register must be set to 14 before releasing scl at (d)). depending of the r/w bit the master or slave enables its output. if the bit is set, a master read operation is in progress (i.e., the slave drives the sda line) the slave can hold the scl line low after the acknowledge (e). 6. multiple bytes can now be transmitted, all in same direction, until a stop condition is given by the master (f). or a new start condition is given. if the slave is not able to receive more data it does not acknowledge the data byte it has last received. when the master does a read operation it must terminate the operation by force the acknowledge bit low after the last byte transmitted. figure 14-6. start condition detector, logic diagram 14.3.5 start condition detector the start condition detector is shown in figure 14-6. the sda line is delayed (in the range of 50 to 300 ns) to ensure valid sampling of the scl line. the start condition detector is only enabled in two-wire mode. the start condition detector is working asynch ronously and can therefore wake up the proces- sor from the power-down sleep mode. however, the protocol used might have restrictions on the scl hold time. therefore, when using this feature in this case the oscillator start-up time set by the cksel fuses (see ?clock systems and their distribution? on page 24 ) must also be taken into the consideration. refer to the usisif bit description on page 157 for further details. sda scl write( usisif) clock hold usisif dq clr dq clr
156 7728g?avr?06/10 attiny87/attiny167 14.4 alternative usi usage when the usi unit is not used for serial communication, it can be set up to do alternative tasks due to its flexible design. 14.4.1 half-duplex asynchronous data transfer by utilizing the usi data register in three-wire mode, it is possible to implement a more com- pact and higher performance uart than by software only. 14.4.2 4-bit counter the 4-bit counter can be used as a stand-alone counter with overflow interrupt. note that if the counter is clocked externally, both clock edges will generate an increment. 14.4.3 12-bit timer/counter combining the usi 4-bit counter and timer/counter0 allows them to be used as a 12-bit counter. 14.4.4 edge triggered external interrupt by setting the counter to maximum value (f) it ca n function as an additional external interrupt. the overflow flag and interrupt enable bit are then used for the external interrupt. this fea- ture is selected by the usics1 bit. 14.4.5 software interrupt the counter overflow interrupt can be used as a software interrupt triggered by a clock strobe. 14.5 register descriptions 14.5.1 usidr ? usi data register ? bits 7:0 ? usid7..0: usi data when accessing the usi data re gister (usidr) the serial register can be accessed directly. if a serial clock occurs at the same cycle the r egister is written, the register will contain the value written and no shift is performed. a (left) shift operation is performed depending of the usics1..0 bits setting. the shift operation can be controlled by an external clock edge, by a timer/counter0 compare match, or directly by software using the usiclk strobe bit. note that even when no wire mode is selected (usiwm1..0 = 0) both the external data input (di/sda) and the external clock input (usck/scl) can still be used by the usi data register. the output pin in use, do or sda depending on the wire mode, is connected via the output latch to the most significant bit (bit 7) of the data register. the output latch is open (transpar- ent) during the first half of a se rial clock cycle when an external clock source is selected (usics1 = 1), and constantly open when an internal clock source is used (usics1 = 0). the output will be changed immediat ely when a new msb written as long as the latc h is open. the latch ensures that data input is sampled and data output is changed on opposite clock edges. bit 7 6 5 4 3 2 1 0 usid7 usid6 usid5 usid4 usid3 usid2 usid1 usid0 usidr 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
157 7728g?avr?06/10 attiny87/attiny167 note that the corresponding data direction register to the pin must be set to one for enabling data output from the usi data register. 14.5.2 usibr ? usi buffer register ? bits 7:0 ? usi d 7..0: usi buffer the content of the serial register is loaded to the usi buffer register when the transfer is completed, and instead of accessing the usi data register (the serial register) the usi data buffer can be accessed when the cpu reads the received data. this gives the cpu time to handle other program tasks too as the controlling of the usi is not so timing critical. the usi flags as set same as when reading the usidr register. 14.5.3 usisr ? usi status register the status register contains interrupt flags, line status flags and the counter value. ? bit 7 ? usisif: start condition interrupt flag when two-wire mode is selected, the usisif flag is set (to one) when a start condition is detected. when output disable mode or three-wire mode is selected and (usicsx = 11 b & usiclk = 0) or (usics = 10 b & usiclk = 0), any edge on the sck pin sets the flag. an interrupt will be generated when the flag is set while the usisie bit in usicr and the global interrupt enable flag are set. the flag will only be cleared by writing a logical one to the usisif bit. clearing this bit will release the st art detection hold of us cl in two-wire mode. a start condition interr upt will wakeup the processor from all sleep modes. ? bit 6 ? usioif: counter overflow interrupt flag this flag is set (one) when the 4-bit counter over flows (i.e., at the transition from 15 to 0). an interrupt will be generated when the flag is set while the usioie bit in usicr and the global interrupt enable flag are set. the flag will only be cleared if a one is wr itten to the usioif bit. clearing this bit will release the counter overfl ow hold of scl in two-wire mode. a counter overflow interrup t will wakeup the processor from idle sleep mode. ? bit 5 ? usipf: stop condition flag when two-wire mode is selected, the usipf flag is set (one) when a stop condition is detected. the flag is cleared by writing a one to this bit. note that this is not an interrupt flag. this signal is useful when implementing two-wire bus master arbitration. ? bit 4 ? usidc: data output collision this bit is logical one when bit 7 in the usi data register differs from the physical pin value. the flag is only valid when two-wire mode is us ed. this signal is useful when implementing two-wire bus master arbitration. bit 7 6 5 4 3 2 1 0 usib7 usib6 usib5 usib4 usib3 usib2 usib1 usib0 usibr read/write r r r r r r r r initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 usisif usioif usipf u sidc usicnt3 usicnt2 usicnt1 usicnt0 usisr read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
158 7728g?avr?06/10 attiny87/attiny167 ? bits 3:0 ? usicnt3..0: counter value these bits reflect the current 4-bit counter val ue. the 4-bit counter value can directly be read or written by the cpu. the 4-bit counter increments by one for each clock generated either by the external clock edge detector, by a timer/counter0 compare matc h, or by software using usiclk or usitc strobe bits. the clock source depends of the sett ing of the usics1..0 bits. for external clock operation a special feature is added that allows the clock to be generated by writing to the usitc strobe bit. this feature is enabled by write a one to the usiclk bit while setting an external clock source (usics1 = 1). note that even when no wire mode is selected (usiwm1..0 = 0) the external clock input (usck/scl) are can still be used by the counter. 14.5.4 usicr ? usi control register the control register includes interrupt enable control, wire mode setting, clock select setting, and clock strobe. ? bit 7 ? usisie: start condition interrupt enable setting this bit to one enables the start condition detector interrupt. if there is a pending inter- rupt when the usisie a nd the global inte rrupt enable flag is set to one, this will immediately be executed. refer to the usisif bit description on page 157 for further details. ? bit 6 ? usioie: counter overflow interrupt enable setting this bit to one enables the counter overflow interrupt. if there is a pending interrupt when the usioie and the global interrupt enable flag is set to one, this will immediately be executed. refer to the usioif bit desc ription on page 157 for further details. ? bit 5:4 ? usiwm1:0: wire mode these bits set the type of wire mode to be used. basically only the function of the outputs are affected by these bits. data and clock inputs are not affected by the mode selected and will always have the same function. the counter and usi data register can therefore be clocked externally, and data input sampled, even when outputs are disabled. the relations between usiwm1:0 and the usi operation is summarized in table 14-1 . bit 7 6 5 4 3 2 1 0 usisie usioie usiwm1 usiwm0 us ics1 usics0 usiclk usitc usicr read/write r/w r/w r/w r/w r/w r/w w w initial value 0 0 0 0 0 0 0 0
159 7728g?avr?06/10 attiny87/attiny167 note: 1. the di and usck pins are renamed to serial data (sda) and serial clock (scl) respec- tively to avoid confusion between the modes of operation. ? bit 3:2 ? usics1:0: clock source select these bits set the clock source for the usi data register and counter. the data output latch ensures that the output is changed at the opposite edge of the sampling of the data input (di/sda) when using external clock sour ce (usck/scl). when software strobe or timer/counter0 compare match clock option is selected, the output latch is transparent and therefore the output is changed immediately. clearing the usics1:0 bits enables software strobe option. when using this option, writing a one to the usiclk bit clocks both the usi data register and the counter. for external cl ock source (usics1 = 1), the usiclk bit is no longer used as a strobe, but selects between external clocking and software clocking by the usitc strobe bit. table 14-2 on page 160 shows the relationship between the usics1..0 and usiclk setting and clock source used for the usi data register and the 4-bit counter. table 14-1. relations between usiwm1..0 and the usi operation usiwm1 usiwm0 description 0 0 outputs, clock hold, and start detector disabled. port pins operates as normal. 01 three-wire mode. uses do, di, and usck pins. the data output (do) pin overrides the corresponding bit in the port register in this mode. however, the corresponding ddr bit still controls the data direction. when the port pin is set as in put the pins pull-up is controlled by the port bit. the data input (di) and serial clock (usck) pins do not affect the normal port operation. when operating as master, clock pulses are software generated by toggling the port register, while the data direction is set to output. the usitc bit in the usicr register can be used for this purpose. 10 two-wire mode. uses sda (di) and scl (usck) pins (1) . the serial data (sda) and the serial clock (scl) pins are bi-directional and uses open-collector output drives. the ou tput drivers are enabled by setting the corresponding bit for sda and scl in the ddr register. when the output driver is enabled for the sda pin, the output driver will force the line sda low if the output of the usi data register or the corresponding bit in the port register is zero. otherwise the sda line will not be driven (i.e., it is released). when the scl pin output driver is enabled the scl line will be forced low if the corresponding bit in the port register is zero, or by the start detector. otherwise the scl line will not be driven. the scl line is held low when a start detector detects a start condition and the output is enabled. clearing the start condition flag (usisif) releases the line. the sda and scl pin inputs is not affected by enabling this mode. pull-ups on the sda and scl port pin are disabled in two-wire mode. 11 two-wire mode. uses sda and scl pins. same operation as for the two-wire mode described above, except that the scl line is also held low when a counter overflow occurs, and is held low until the counter overflow flag (usioif) is cleared.
160 7728g?avr?06/10 attiny87/attiny167 ? bit 1 ? usiclk: clock strobe writing a one to this bit location strobes the usi data register to shift one step and the coun- ter to increment by one, provided that the usics1..0 bits are set to zero and by doing so the software clock strobe option is selected. the output will chan ge immediately when the clock strobe is executed, i.e., in the same instruction cycle. the value shifted into the usi data reg- ister is sampled th e previous instruction cycle. the bit will be read as zero. when an external clock source is selected (usics1 = 1), the usiclk function is changed from a clock strobe to a clock select register. setting the usiclk bit in this case will select the usitc strobe bit as clock source for the 4-bit counter (see table 14-2 ). ? bit 0 ? usitc: toggle clock port pin writing a one to this bit location toggles the usck/scl value either from 0 to 1, or from 1 to 0. the toggling is independent of the setting in the data direction register, but if the port value is to be shown on the pin the ddb2 must be set as output (to one). this feature allows easy clock generation when impl ementing master devices. th e bit will be read as zero. when an external clock source is selected (u sics1 = 1) and the usiclk bit is set to one, writing to the usitc strobe bit w ill directly clock the 4- bit counter. this a llows an early detec- tion of when the transfer is done when operating as a master device. table 14-2. relations between the usics1..0 and usiclk setting usics1 usics0 usiclk usi data register clock source 4-bit counter clock source 0 0 0 no clock no clock 001 software clock strobe (usiclk) software clock strobe (usiclk) 01x timer/counter0 compare match timer/counter0 compare match 1 0 0 external, positive edge external, both edges 1 1 0 external, negative edge external, both edges 1 0 1 external, positive edge software clock strobe (usitc) 1 1 1 external, negative edge software clock strobe (usitc)
161 7728g?avr?06/10 attiny87/attiny167 14.5.5 usipp ? usi pin position ? bits 7:1 ? res: reserved bits these bits are reserved bits in the attiny87/167 and always reads as zero. ? bit 0 ? usipos: usi pin position setting or clearing this bit changes the usi pin position. bit 76543210 -------usiposusipp read/writerrrrrrrr/w initial value00000000 table 14-3. usi pin position usipos usi pin position 0 portb (default) di, sda pb0 - (pcint8/oc1au) do pb1 - (pcint9/oc1bu) usck, scl pb2 - (pcint10/oc1av) 1 port a (alternate) di, sda pa4 - (pcint4/adc4/icp1/mosi) do pa2 - (pcint2/adc2/oc0a/miso) usck, scl pa5 - (pcint5/adc5/t1/sck)
162 7728g?avr?06/10 attiny87/attiny167 15. lin / uart - local intercon nect network controller or uart the lin (local interconnect network) is a seri al communications protocol which efficiently supports the control of mechatronics nodes in distributed automotive applications. the main properties of the lin bus are: ? single master with multiple slaves concept ? low cost silicon implem entation based on common uart/sci interface ? self synchronization with on-chip oscillator in slave node ? deterministic signal transmissi on with signal propagation time computable in advance ? low cost single- wire implementation ? speed up to 20 kbit/s. lin provides a cost efficient bus communication where the ba ndwidth and versatility of can are not required. the specification of the line driver/receiver needs to match the iso9141 nrz-standard. if lin is not required, the controller alternatively can be programmed as universal asynchro- nous serial receiver and transmitter (uart). 15.1 lin features ? hardware implementation of lin 2.1 (lin 1.3 compatibility) ? small, cpu efficient and independent master /slave routines based on ?lin work flow concept? of lin 2.1 specification ? automatic lin header handling and fi ltering of irrelevant lin frames ? automatic lin response handling ? extended lin error detection and signaling ? hardware frame time-out detection ? ?break-in-data? support capability ? automatic re-synchronization to ensure proper frame integrity ? fully flexible extended frames support capabilities 15.2 uart features ? full duplex operation (independent se rial receive and transmit processes) ? asynchronous operation ? high resolution baud rate generator ? hardware support of 8 data bits, odd/ even/no parity bit, 1 stop bit frames ? data over-run and fr aming error detection
163 7728g?avr?06/10 attiny87/attiny167 15.3 lin protocol 15.3.1 master and slave a lin cluster consists of one master ta sk and several slave tasks. a master node contains the master task as well as a slave task. a ll other nodes contain a slave task only. figure 15-1. lin cluster with one master node and ?n? slave nodes the master task decides when and which frame shall be transferred on the bus. the slave tasks provide the data transported by each frame. both the master task and the slave task are parts of the frame handler 15.3.2 frames a frame consists of a header (provided by the master task) and a response (provided by a slave task). the header consists of a break and sync pattern follow ed by a protected identifier. the identifier uniquely defines the purpose of the frame. the slave task appointed for provid- ing the response associated with the identifier transmits it. the respons e consists of a data field and a checksum field. figure 15-2. master and slave tasks behavior in lin frame the slave tasks waiting for the dat a associated with the identifier receives the response and uses the data transported after verifying the checksum. figure 15-3. structure of a lin frame master task slave task master node slave task slave node 1 slave task slave node n lin bus master task slave task 1 slave task 2 header response header response break field sync field checksum field data-0 field field identifier protected data-n field break delimiter response space inter-byte space inter-frame space response header frame slot each byte field is transmitted as a serial byte, lsb first.
164 7728g?avr?06/10 attiny87/attiny167 15.3.3 data transport two types of data may be transported in a frame; signals or diagnostic messages. ? signals signals are scalar values or byte arrays that are packed into the data field of a frame. a signal is always present at the same position in the data field for all frames with the same identifier. ? diagnostic messages diagnostic messages are transported in fr ames with two reserved identifiers. the interpretation of the data field depends on the data field itself as well as the state of the communicating nodes. 15.3.4 schedule table the master task (in the master node) transmits frame headers based on a schedule table. the schedule table specifies the identifiers for each header and the interval between the start of a frame and the start of the following frame. the master application may use different schedule tables and select among them. 15.3.5 compatibility with lin 1.3 lin 2.1 is a super-set of lin 1.3. a lin 2.1 master node can handle clusters consisting of both lin 1.3 slaves and/or lin 2.1 slaves. the master will then av oid requesting the new lin 2.1 f eatures from a lin 1.3 slave: ? enhanced checksum, ? re-configuration and diagnostics, ? automatic baud rate detection, ? "response error" status monitoring. lin 2.1 slave nodes can not operate with a lin 1.3 master node (e.g. the lin1.3 master does not support the enhanced checksum). the lin 2.1 physical layer is backwards compatib le with the lin1.3 physical layer. but not the other way around. the lin 2.1 physical layer sets greater requirements, i.e. a master node using the lin 2.1 physical layer can operate in a lin 1.3 cluster. 15.4 lin / uart controller the lin/uart controller is divided in three main functions: ? tx lin header function, ? rx lin header function, ? lin response function. these functions mainly use two services: ?rx service, ?tx service. because these two services are basically uart services, the c ontroller is also able to switch into an uart function.
165 7728g?avr?06/10 attiny87/attiny167 15.4.1 lin overview the lin/uart controller is designed to match as closely as possible to the lin software appli- cation structure. the lin software application is developed as independent tasks, several slave tasks and one master task (c.f. section 15.3.4 on page 164 ). the attiny87/167 con- forms to this perspective. the only link between the master task and the slave task will be at the cross-over point where the interrupt routin e is called once a new identifier is available. thus, in a master node, housing both master and slave task, the tx lin header function will alert the slave task of an identifier presence. in the same way, in a slave node, the rx lin header function will aler t the slave task of an identifier presence. when the slave task is warned of an identifier presence, it has first to analyze it to know what to do with the response. hardware flags identify the presence of one of the specific identifiers from 60 (0x3c) up to 63 (0x3f). for lin communication, only four interrupts need to be managed: ? lidok: new lin identifier available, ? lrxok: lin response received, ? ltxok: lin response transmitted, ? lerr: lin error(s). the wake-up management can be automated using the uart wake-up capability and a node sending a minimum of 5 low bits (0xf0) for lin 2.1 and 8 low bits (0x80) for lin 1.3. pin change interrupt on lin wake-up signal can be also used to exit the device of one of its sleep modes. extended frame identifiers 62 (0x3e) and 63 (0x3f) are reserved to allow the embedding of user-defined message formats and future lin formats. the byte transfer mode offered by the uart will ensure the upwards compatibility of lin slaves with accommodation of the lin protocol. 15.4.2 uart overview the lin/uart controller can also function as a conventional uart. by default, the uart operates as a full duplex controller. it has local loop back circuitry for test purposes. the uart has the ability to buffer one character for transmit and two for receive. the receive buffer is made of one 8-bit serial register followed by one 8-bit independent buffer register. automatic flag management is implemented when the application puts or gets characters, thus reducing the software overhead. because transmit and receive services are independent, the user can save one device pin when one of the two serv ices is not used. the uart has an enhanced baud rate generator providing a maximum error of 2% whatever the clock frequency and the targeted baud rate.
166 7728g?avr?06/10 attiny87/attiny167 15.4.3 lin/uart controller structure figure 15-4. lin/uart controller block diagram 15.4.4 lin/uart command overview figure 15-5. lin/uart command dependencies buffer fsm rx get byte frame time-out synchronization monitoring rxd tx put byte finite state machine txd baud_rate prescaler sample /bit clk io data fifo idok rxok recommended way txok tx header rx header or lin abort byte transfer rx byte tx byte lin uart full duplex disable automatic return possible way response tx response rx
167 7728g?avr?06/10 attiny87/attiny167 15.4.5 enable / disable setting the lena bit in lincr register enabl es the lin/uart controller. to disable the lin/uart controller, lena bit must be written to 0. no wait states are implemented, so, the disable command is taken into account immediately. 15.4.6 lin commands clearing the lcmd[2] bit in lincr register enables lin commands. as shown in table 15-1 on page 167 , four functions controlled by the lcmd[1..0] bits of lincr register are available (c.f. figure 15-5 on page 166 ). 15.4.6.1 rx header / lin abort function this function (or state) is mainly the withdrawal mode of the controller. when the controller has to execute a master task, this state is the start point before enabling a tx header command. when the controller has only to execute sl ave tasks, lin header detection/acquisition is enabled as background function. at the end of such an acquisition (rx header function), auto- matically the appropriate flags are set, and in lin 1.3, the lindlr register is set with the uncoded length value. this state is also the start point before enabling the tx or the rx response command. a running function (i.e. tx header, tx or rx response ) can be aborted by clearing lcmd[1..0] bits in lincr register ( see ?break-in-data? on page 177. ). in this case, an abort flag - labort - in linerr register will be se t to inform the other software tasks. no wait states are implemented, so, the abort command is taken into account immediately. rx header function is responsible for: ? the break field detection, ? the hardware re-synchronization analyzing the synch field, ? the reception of the protected identifier field, the parity control and the update of the lindlr register in case of lin 1.3, ? the starting of the frame_time_out, ? the checking of the lin communication integrity. table 15-1. lin/uart command list lena lcmd[2] lcmd[1] lcmd[0] command comment 0 x x x disable peripheral 1 0 0 0 rx header - lin abort lin withdrawal 1 tx header lcmd[2..0]=000 after tx 1 0 rx response lcmd[2..0]=000 after rx 1 tx response lcmd[2..0]=000 after tx 1 0 0 byte transfer no crc, no time out ltxdl=lrxdl=0 (lindlr: read only register) 10 rx byte 0 1 tx byte 1 1 full duplex
168 7728g?avr?06/10 attiny87/attiny167 15.4.6.2 tx header function in accordance with the lin protocol, only the master task must enable this function. the header is sent in the appropriate timed slots at the programmed baud rate (c.f. linbrr & lin- btr registers). the controller is responsible for: ? the transmission of the break field - 13 dominant bits, ? the transmission of the synch field - character 0x55, ? the transmission of the protected identifier field. it is the full content of the linidr register (automatic check bits included). at the end of this transmission, the controller automatically returns to rx header / lin abort state (i.e. lcmd[1..0] = 00) after setting the appropriate flags. this function leaves the control- ler in the same setting as after the rx header function. this means that, in lin 1.3, the lindlr register is set with the uncoded length value at the end of the tx header function. during this function, the contro ller is also responsible for: ? the starting of the frame_time_out, ? the checking of the lin communication integrity. 15.4.6.3 rx & tx response functions these functions are initiated by the slave task of a lin node. they must be used after sending an header (master task) or after receiving an header (considered as belonging to the slave task). when the tx response order is sent, the transmission begins. a rx response order can be sent up to the reception of the last serial bit of the first byte (before the stop-bit). in lin 1.3, the header slot configures the lindlr register. in lin 2.1, the user must configure the lindlr register, either lrxdl[3..0] for rx response either ltxdl[3..0] for tx response . when the command starts, the controller checks the lin13 bit of the lincr register to apply the right rule for computing the checksum. checksum calculation over the data bytes and the protected identifier byte is called enhanc ed checksum and it is used for communica- tion with lin 2.1 slaves. checksum calculation over the data bytes on ly is called classic checksum and it is used for comm unication with lin 1.3 slaves. note that identifiers 60 (0x3c) to 63 (0x3f) shall alwa ys use classic checksum. at the end of this reception or transmission, the controller automatically returns to rx header / lin abort state (i.e. lcmd[1..0] = 00) after setting the appropriate flags. if an lin error occurs, the reception or the tr ansmission is stopped, the appropriate flags are set and the lin bus is left to recessive state. during these functions, the controller is responsible for: ? the initialization of the checksum operator, ? the transmission or the reception of ? n ? data with the update of the checksum calculation, ? the transmission or the checking of the checksum field, ? the checking of the frame_time_out, ? the checking of the lin communication integrity. while the controller is send ing or receiving a response, break and synch fields can be detected and the identifier of this new header will be recorded. of course, specific errors on the previous response will be maintain ed with this identifier reception.
169 7728g?avr?06/10 attiny87/attiny167 15.4.6.4 handling data of lin response a fifo data buffer is used for data of the lin response. after setting all parameters in the lin- sel register, repeated accesses to the lindat register perform data read or data write (c.f. ?data management? on page 179 ). note that lrxdl[3..0] and ltxdl[3..0] are not linked to the data access. 15.4.7 uart commands setting the lcmd[2] bit in linenr register enables uart commands. tx byte and rx byte services are independent as shown in table 15-1 on page 167 . ? byte transfer: the uart is selected but both rx and tx services are disabled, ? rx byte: only the rx service is enable but tx service is disabled, ? tx byte: only the tx service is enable but rx service is disabled, ? full duplex: the uart is selected and both rx and tx services are enabled. this combination of services is controlled by the lcmd[1..0] bits of linenr register (c.f. fig- ure 15-5 on page 166 ). 15.4.7.1 data handling the fifo used for lin communication is dis abled during uart accesses. lrxdl[3..0] and ltxdl[3..0] values of lindlr register are then irrelevant. lindat register is then used as data register and linsel register is not relevant. 15.4.7.2 rx service once this service is enabled, th e user is warned of an in-com ing character by the lrxok flag of linsir register. reading lindat register automatically clears the flag and makes free the second stage of the buffer. if the user consider s that the in-coming character is irrelevant with- out reading it, he directly can clear the fl ag (see specific flag management described in section 15.6.2 on page 182 ). the intrinsic structure of the rx service offers a 2-byte buffer. the fist one is used for serial to parallel conversion, the second one receives the result of the conversion. this second buffer byte is reached reading lindat register. if the 2- byte buffer is full, a new in-coming character will overwrite the second one already recorded. an ovrerr error in linerr register will then accompany this character when read. a ferr error in linerr register will be set in case of framing error. 15.4.7.3 tx service if this service is enabled, the user sends a char acter by writing in lindat register. automati- cally the ltxok flag of linsir register is cl eared. it will rise at the end of the serial transmission. if no new character has to be sent, ltxok flag can be cleared separately (see specific flag management described in section 15.6.2 on page 182 ). there is no transmit buffering. no error is detected by this service.
170 7728g?avr?06/10 attiny87/attiny167 15.5 lin / uart description 15.5.1 reset the avr core reset logic signal also resets the lin/uart controller. another form of reset exists, a software reset controlled by lswres bi t in lincr register. this self-reset bit per- forms a partial reset as shown in table 15-2 . 15.5.2 clock the i/o clock signal (clk i/o ) also clocks the lin/uart contro ller. it is its unique clock. 15.5.3 lin protocol selection lin13 bit in lincr register is used to select the lin protocol: ? lin13 = 0 (default): lin 2.1 protocol, ? lin13 = 1: lin 1.3 protocol. the controller checks the lin13 bit in comp uting the checksum (e nhanced checksum in lin2.1 / classic checksum in lin 1.3). this bit is irrelevant for uart commands. table 15-2. reset of lin/uart registers register name reset value lswres value comment lin control reg. lincr 0000 0000 b 0000 0000 b x=unknown u=unchanged lin status & interrupt reg. linsir 0000 0000 b 0000 0000 b lin enable interrupt reg. linenir 0000 0000 b xxxx 0000 b lin error reg. linerr 0000 0000 b 0000 0000 b lin bit timing reg. linbtr 0010 0000 b 0010 0000 b lin baud rate reg. low linbrrl 0000 0000 b uuuu uuuu b lin baud rate reg. high linbrrh 0000 0000 b xxxx uuuu b lin data length reg. lindlr 0000 0000 b 0000 0000 b lin identifier reg. linidr 1000 0000 b 1000 0000 b lin data buffer selection linsel 0000 0000 b xxxx 0000 b lin data lindat 0000 0000 b 0000 0000 b
171 7728g?avr?06/10 attiny87/attiny167 15.5.4 configuration depending on the mode (lin or uart), lconf[ 1..0] bits of the lincr register set the con- troller in the following configuration ( table 15-3 ): the lin configuration is independent of the programmed lin protocol. the listening mode connects the internal tx lin and the internal rx lin together. in this mode, the txlin output pin is disabled and the rxlin input pin is always enabled. the same scheme is available in uart mode. figure 15-6. listening mode 15.5.5 busy signal lbusy bit flag in linsir register is the image of the busy signal. it is set and cleared by hardware. it signals that the controller is busy with lin or uart communication. 15.5.5.1 busy signal in lin mode figure 15-7. busy signal in lin mode table 15-3. configuration table versus mode mode lconf[1..0] configuration lin 00 b lin standard configuration (default) 01 b no crc field detection or transmission 10 b frame_time_out disable 11 b listening mode uart 00 b 8-bit data, no parity & 1 stop-bit 01 b 8-bit data, even parity & 1 stop-bit 10 b 8-bit data, odd parity & 1 stop-bit 11 b listening mode, 8-bit data, no parity & 1 stop-bit 1 0 txlin rxlin internal tx lin internal rx lin listen break field sync field checksum field data-0 field field identifier protected data-n field response header frame slot lin bus lidok node providing the master task node providing a slave task lcmd=tx header ltxok or lrxok lcmd=tx or rx response 1) lbusy 3) lbusy 2) lbusy node providing neither the master task, neither a slave task
172 7728g?avr?06/10 attiny87/attiny167 when the busy signal is set, some registers are locked, user writing is not allowed: ? ?lin control register? - lincr - except lcmd[2..0], lena & lswres, ? ?lin baud rate registers? - linbrrl & linbrrh, ? ?lin data length register? - lindlr, ? ?lin identifier register? - linidr, ? ?lin data register? - lindat. if the busy signal is set, the only available commands are: ? lcmd[1..0] = 00 b , the abort command is taken into account at the end of the byte, ? lena = 0 and/or lcmd[2] = 0, the kill co mmand is taken into ac count immediately, ? lswres = 1, the reset command is taken into account immediately. note that, if another command is entered during busy signal, the new command is not vali- dated and the lovrerr bit flag of the linerr register is set. the on-going transfer is not interrupted. 15.5.5.2 busy signal in uart mode during the byte transmission, t he busy signal is set. this locks some registers from being written: ? ?lin control register? - lincr - except lcmd[2..0], lena & lswres, ? ?lin data register? - lindat. the busy signal is not generated during a byte reception. 15.5.6 bit timing 15.5.6.1 baud rate generator the baud rate is defined to be the transfer rate in bits per second (bps): ? baud: baud rate (in bps), ? f clk i/o : system i/o clock frequency, ? ldiv[11..0]: contents of linbrrh & linbrrl registers - (0-4095), the pre-scaler receives clk i/o as input clock. ? lbt[5..0]: least significant bits of - linbtr register- (0-63) is the number of samplings in a lin or uart bit (default value 32). equation for calculating baud rate: baud = fclk i/o / lbt[5..0] x (ldiv[11..0] + 1) equation for setting lindiv value: ldiv[11..0] = ( fclk i/o / lbt[5..0] x baud ) - 1 note that in reception a majority vote on three samplings is made. 15.5.6.2 re-synchronization in lin mode when waiting for rx header, lbt[5..0] = 32 in linbtr register. the re-synchronization begins when the break is detected. if the break size is not in the range (1 0.5 bits min., 28 bits max. ? 13 bits nominal), the break is refu sed. the re-synchroniza tion is done by adjust- ing lbt[5..0] value to the synch field of the received header (0x55). then the protected identifier is sampled using the new value of lbt[5..0].
173 7728g?avr?06/10 attiny87/attiny167 the re-synchronization implemented in the controller tolerates a clock deviation of 20% and adjusts the baud rate in a 2% range. the new lbt[5..0] value will be used up to the end of the response. th en, the lbt[5..0] will be reset to 32 for the next header. the linbtr register can be used to (sof tware) re-calibrate the clock oscillator. the re-synchronization is not performed if the lin node is enabled as a master. 15.5.6.3 handling lbt[5..0] ldisr bit of linbtr register is used to: ? disable the re-synchronization (for instance in the case of lin master node), ? to enable the setting of lbt[5..0] (to manually adjust the baud rate especially in the case of uart mode). a minimum of 8 is required for lbt[5..0] due to the sampling operation. note that the lena bit of lincr register is important for this handling (see figure 15-8 on page 173 ). figure 15-8. handling lbt[5..0] 15.5.7 data length section 15.4.6 ?lin commands? on page 167 describes how to set or how are automatically set the lrxdl[3..0] or ltxdl[3..0] fields of lindlr register before receiving or transmitting a response. in the case of tx re sponse the lrxdl[3..0] will be used by the hardw are to coun t the number of bytes already successfully sent. in the case of rx response the ltxdl[3..0] will be used by the hardw are to coun t the number of bytes already successfully received. if an error occurs, this information is useful to the programmer to recover the lin messages. 15.5.7.1 data length in lin 2.1 ? if ltxdl[3..0]=0 only the checksum will be sent, ? if lrxdl[3..0]=0 the first byte receiv ed will be interprete d as the checksum, ? if ltxdl[3..0] or lrxdl[3..0] >8, values will be forced to 8 after t he command setting and before sending or receiving of the first byte. write in linbtr register lena ? (lincr bit 4) ldisr to write =0 =0 =1 lbt[5..0] forced to 0x20 ldisr forced to 0 enable re-synch. in lin mode lbt[5..0] = lbt[5..0] to write (lbt[5..0] min =8) ldisr forced to 1 disable re-synch. in lin mode =1
174 7728g?avr?06/10 attiny87/attiny167 15.5.7.2 data length in lin 1.3 ? lrxdl and ltxdl fields are both hardware updated before setting lidok by decoding the data length code contained in the received protected identifier (lrxdl = ltxdl). ? via the above mechanism, a length of 0 or >8 is not possible. 15.5.7.3 data length in rx response figure 15-9. lin2.1 - rx response - no error ? the user initializes lrxdl field before setting the rx response command, ? after setting the rx response command, ltxdl is reset by hardware, ? lrxdl field will remain unchanged during rx (during busy signal), ? ltxdl field will count the number of received bytes (during busy signal), ? if an error occurs, rx stops, the correspond ing error flag is set and ltxdl will give the number of received bytes without error, ? if no error occurs, lrxok is set after th e reception of the checksum, lrxdl will be unchanged (and ltxdl = lrxdl). 15.5.7.4 data length in tx response figure 15-10. lin1.3 - tx response - no error ? the user initializes ltxdl field before setting the tx response command, ? after setting the tx response command, lrxdl is reset by hardware, ? ltxdl will remain unchanged duri ng tx (during busy signal), ? lrxdl will count the number of tran smitted bytes (during busy signal), data-0 data-1 data-2 data-3 checksum lindlr=0x?4 lcmd2..0=000 b lin bus lrxdl (*) 4 1 ?0 lbusy ltxdl (*) 234 1 st byte 2 nd byte 3 rd byte 4 th byte lidok lrxok lcmd=rx response (*) : lrxdl & ltxdl updated by user data-0 data-1 data-2 data-3 checksum lcmd2..0=000 b lin bus lbusy 1 st byte 2 nd byte 3 rd byte 4 th byte lidok ltxok 1 40 lrxdl (*) 234 lcmd=tx response (*) : lrxdl & ltxdl updated by rx response or tx response task ltxdl (*) 4
175 7728g?avr?06/10 attiny87/attiny167 ? if an error occurs, tx stops, the correspondi ng error flag is set and lrxdl will give the number of transmitted bytes without error, ? if no error occurs, ltxok is set after t he transmission of the checksum, ltxdl will be unchanged (and lrxdl = ltxdl). 15.5.7.5 data length after error figure 15-11. tx response - error note: information on response (ex: error on byte) is only available at the end of the serializa- tion/de-serialization of the byte. 15.5.7.6 data length in uart mode ? the uart mode forces lrxdl and ltxdl to 0 and disables the writing in lindlr register, ? note that after reset, lrxdl and ltxdl are also forced to 0. 15.5.8 xxok flags there are three xxok flags in linsir register: ? lidok: lin identifier ok it is set at the end of the header, either by the tx header function or by the rx header. in lin 1.3, before generating lidok, the controller updates the lrxdl & ltxdl fields in lindlr register. it is not driven in uart mode. ? lrxok: lin rx response complete it is set at the end of the response by the rx response function in lin mode and once a character is received in uart mode. ? ltxok: lin tx response complete it is set at the end of the response by the tx response function in lin mode and once a character has been sent in uart mode. these flags can generate interrupts if the corres ponding enable interrupt bit is set in the line- nir register (see section 15.5.13 ?interrupts? on page 178 ). data-0 data-1 lcmd2..0=000 b lin bus lbusy 1 st byte 2 nd byte 3 rd byte lerr 1 40 lrxdl 2 lcmd=tx response ltxdl 4 data-2 error
176 7728g?avr?06/10 attiny87/attiny167 15.5.9 xxerr flags lerr bit of the linsir register is an logical ?or? of all the bits of linerr register (see sec- tion 15.5.13 ?interrupts? on page 178 ). there are eight flags: ? lberr = lin bit error. a unit that is sending a bit on the bus also monitors the bus. a li n bit error will be flagged when the bit value that is monitored is different from the bit value that is sent. after detection of a lin bit error the transmission is aborted. ? lcerr = lin checksum error. a lin checksum error will be flagged if the in verted modulo-256 sum of all received data bytes (and the protected identifier in lin 2.1) added to the checksum does not result in 0xff. ? lperr = lin parity error (identifier). a lin parity error in the identifier field will be flagged if the value of the parity bits does not match with the identifier value. (see lp[1:0] bits in section 15.6.8 ?lin identifier register - linidr? on page 186 ). a lin slave application does not distinguish between corrupted parity bits and a corrupted identifier. the hardware does not undertake any correction. however, the lin slave application has to solve this as: - known identifier (parity bits corrupted), - or corrupted identifier to be ignored, - or new identifier. ? lserr = lin synchronization error. a lin synchronization error will be flagged if a slave detects the edges of the synch field outside the given tolerance. ? lferr = lin framing error. a framing error will be flagged if dominant stop bit is sampled. same function in uart mode. ? ltoerr = lin time out error. a time-out error will be flagged if the mess age frame is not fully completed within the maximum length t frame_maximum by any slave task upon transmission of the synch and identifier fields (see section 15.5.10 ?frame time out? on page 177 ). ? loverr = lin overrun error. overrun error will be flagged if a new command (other than lin abor t) is entered while ?busy signal? is present. in uart mode, an overrun error will be flagged if a received byte overwr ites the byte stored in the serial input buffer. ? labort lin abort transfer reflects a previous lin abort command (lcmd[2..0 ] = 000) while ?busy signal? is present. after each lin error, the lin controller stops its previous activity and returns to its withdrawal mode (lcmd[2..0] = 000 b ) as illustrated in figure 15-11 on page 175 . writing 1 in lerr of linsir register resets lerr bit and all the bits of the linerr register.
177 7728g?avr?06/10 attiny87/attiny167 15.5.10 frame time out according to the lin protocol, a frame time-out error is flagged if: t frame > t frame_maximum . this feature is implemented in the lin/uart controller. figure 15-12. lin timing and frame time-out 15.5.11 break-in-data according to the lin protocol, the lin/uart controller can detect the break/sync field sequence even if the break is partially superimposed with a byte of the response. when a break/sync field sequence happens, the transfer in progress is aborted and the processing of the new frame starts. ? on slave node(s), an error is generated (i.e. lberr in case of tx response or lferr in case of rx response ). information on data error is also available, refer to the section 15.5.7.5 . ? on master node, the user (code) is responsible for this aborting of frame. to do this, the master task has first to abort the on-goi ng communication (clearing lcmd bits - lin abort command) and then to apply the tx header command. in this case, the abort error flag - labort - is set. on the slave node, the break detection is proc essed with the synchronization setting avail- able when the lin/uart controller processed the (aborted) response. but the re-synchronization restarts as usual. due to a possible difference of timing reference between the break field and the rest of the frame, the time-out values can be slightly inaccurate. 15.5.12 checksum the last field of a frame is the checksum. in lin 2.1, the checksum contains the inverted eight bit sum with carry over all data bytes and the protected identifier. this calculation is called enhanced checksum. in lin 1.3, the checksum contains the inverted eight bit sum with carry over all data bytes. this calculation is called classic checksum. break field sync field checksum field data-0 field field identifier protected data-n field t response t header t frame t header_maximum t header_maximum + t response_maximum 1.4 x t header_nominal 1.4 x t response_nominal t response_maximum t frame_maximum = = = maximun before time-out t header_nominal t header_nominal + t response_nominal 34 x t bit 10 ( number_of_data + 1 ) x t bit t response_nominal t frame_nominal = = = nominal checksum 255 unsigned char data n 0 n ?? ?? ?? ?? protected id. + ?? ?? ?? ?? unsigned char data n 0 n ?? ?? ?? ?? protected id. + ?? ?? ?? ?? 8 ? ?? ?? ?? ?? + ? ? ? ? ? ? ? ? ? =
178 7728g?avr?06/10 attiny87/attiny167 frame identifiers 60 (0x3c) to 61 (0x3d) shall always use classic checksum. 15.5.13 interrupts as shown in figure 15-13 on page 178 , the four communication flags of the linsir register are combined to drive two interrupts. each of these flags have their respective enable interrupt bit in linenir register. (see section 15.5.8 ?xxok flags? on page 175 and section 15.5.9 ?xxerr flags? on page 176 ). figure 15-13. lin interrupt mapping 15.5.14 message filtering message filtering based upon the whole identifier is not implemented. only a status for frame headers having 0x3c, 0x3d, 0x3e and 0x3f as id entifier is available in the linsir register. checksum 255 unsigned char data n 0 n ?? ?? ?? ?? unsigned char data n 0 n ?? ?? ?? ?? 8 ? ?? ?? ?? ?? + ?? ?? ?? ?? ? = lidok linsir.2 ltxok linsir.1 lrxok linsir.0 labort linerr.7 ltoerr linerr.6 loverr linerr.5 lerr linsir.3 lin tc lenerr lferr linerr.4 lserr linerr.3 lperr linerr.2 lcerr linerr.1 lberr linerr.0 lin err lenidok linenir.2 lentxok linenir.1 lenrxok linenir.0 linenir.3 table 15-4. frame status lidst[2..0] frame status 0xx b no specific identifier 100 b 60 (0x3c) identifier 101 b 61 (0x3d) identifier 110 b 62 (0x3e) identifier 111 b 63 (0x3f) identifier
179 7728g?avr?06/10 attiny87/attiny167 the lin protocol says that a message with an identifier from 60 (0x3c) up to 63 (0x3f) uses a classic checksum (sum over the data bytes only) . software will be responsible for switching correctly the lin13 bit to provide/check this expe cted checksum (the insertion of the id field in the computation of the crc is set - or not - just after entering the rx or tx response command). 15.5.15 data management 15.5.15.1 lin fifo data buffer to preserve register allocation, the lin data buffer is seen as a fifo (with address pointer accessible). this fifo is accessed via the lindx[2..0] field of linsel register through the lindat register. lindx[2..0], the data index, is the address pointer to the required data byte. the data byte can be read or written. the data index is automatically incremented after each lindat access if the lainc (active low) bit is cleared. a roll-over is implemented, after data index=7 it is data index=0. otherwise, if lainc bit is set, the data index needs to be written (updated) before each lindat access. the first byte of a lin frame is stored at the data index=0, the second one at the data index=1, and so on. nevertheless, linsel must be initialized by the user before use. 15.5.15.2 uart data register the lindat register is the data register (no buffering - no fifo ). in write access, lindat will be for data out and in read ac cess, lindat will be for data in. in uart mode the linsel register is unused. 15.5.16 ocd support when a debugger break occurs, the state machine of the lin/uart controller is stopped (included frame time-out) and further communication may be corrupted.
180 7728g?avr?06/10 attiny87/attiny167 15.6 lin / uart regi ster description table 15-5. lin/uart register bits summary name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 lincr lswres lin13 lconf1 lconf0 lena lcmd2 lcmd1 lcmd0 0r/w0r/w0r/w0r/w0r/w0r/w0r/w0r/w linsir lidst2 lidst1 lidst0 lbusy lerr lidok ltxok lrxok 0r0r0r0r0r/w one 0r/w one 0r/w one 0r/w one linenir ????lenerrlenidoklentxoklenrxok 0r0r0r0r0r/w0r/w0r/w0r/w linerr labort ltoerr loverr lferr lserr lperr lcerr lberr 0r0r0r0r0r0r0r0r linbtr ldisr lbt5 lbt4 lbt3 lbt2 lbt1 lbt0 0 r/w 0 r 1r/(w)0r/(w)0r/(w)0r/(w)0r/(w)0r/(w) linbrrl ldiv7 ldiv6 ldiv5 ldiv4 ldiv3 ldiv2 ldiv1 ldiv0 0r/w0r/w0r/w0r/w0r/w0r/w0r/w0r/w linbrrh ????ldiv11ldiv10ldiv9ldiv8 0r0r0r0r0r/w0r/w0r/w0r/w lindlr ltxdl3 ltxdl2 ltxdl1 ltxdl0 lrxdl3 lrxdl2 lrxdl1 lrxdl0 0r/w0r/w0r/w0r/w0r/w0r/w0r/w0r/w linidr lp1 lp0 lid5/ldl1 lid4/ldl0 lid3 lid2 lid1 lid0 1 r 0 r 0r/w0r/w0r/w0r/w0r/w0r/w linsel ????lainclindx2lindx1lindx0 0r0r0r0r0r/w0r/w0r/w0r/w lindat ldata7 ldata6 ldata5 ldata4 ldata3 ldata2 ldata1 ldata0 0r/w0r/w0r/w0r/w0r/w0r/w0r/w0r/w
181 7728g?avr?06/10 attiny87/attiny167 15.6.1 lin control register - lincr ? bit 7 - lswres: software reset ? 0 = no action, ? 1 = software reset (this bit is self-reset at the end of the reset procedure). ? bit 6 - lin13: lin 1.3 mode ? 0 = lin 2.1 (default), ? 1 = lin 1.3. ? bit 5:4 - lconf[1:0]: configuration a. lin mode (default = 00): ? 00 = lin standard configurat ion (listen mode ?off?, crc ?on? & frame_time_out ?on?, ? 01 = no crc, no frame_time_out (listen mode ?off?), ? 10 = no frame_time_out (listen mode ?off? & crc ?on?), ? 11 = listening mode (crc ?o n? & frame_time_out ?on?). b. uart mode (default = 00): ? 00 = 8-bit, no parity (listen mode ?off?), ? 01 = 8-bit, even parity (listen mode ?off?), ? 10 = 8-bit, odd parity (listen mode ?off?), ? 11 = listening mode, 8-bit, no parity. ? bit 3 - lena: enable ? 0 = disable (both lin and uart modes), ? 1 = enable (both lin and uart modes). ? bit 2:0 - lcmd[2..0]: command and mode the command is only available if lena is set. ? 000 = lin rx header - lin abort, ? 001 = lin tx header, ? 010 = lin rx response, ? 011 = lin tx response, ? 100 = uart rx & tx byte disable, ? 11x = uart rx byte enable, ? 1x1 = uart tx byte enable. bit 7 6543210 lswres lin13 lconf1 lconf0 lena lcmd2 lcmd1 lcmd0 lincr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value0 0000000
182 7728g?avr?06/10 attiny87/attiny167 15.6.2 lin status and interrupt register - linsir ? bits 7:5 - lidst[2:0]: identifier status ? 0xx = no specific identifier, ? 100 = identifier 60 (0x3c), ? 101 = identifier 61 (0x3d), ? 110 = identifier 62 (0x3e), ? 111 = identifier 63 (0x3f). ? bit 4 - lbusy: busy signal ? 0 = not busy, ? 1 = busy (receiving or transmitting). ? bit 3 - lerr: error interrupt it is a logical or of linerr register bits. th is bit generates an interrupt if its respective enable bit - lenerr - is set in linenir. ?0 = no error, ? 1 = an error has occurred. the user clears this bit by writing 1 in order to reset this interrupt. resetting lerr also resets all linerr bits. in uart mode, this bit is also cleared by reading lindat. ? bit 2 - lidok: identifier interrupt this bit generates an interrupt if its respective enable bit - lenidok - is set in linenir. ? 0 = no identifier, ? 1 = slave task: identifier present, master task: tx header complete. the user clears this bit by writing 1, in order to reset this interrupt. ? bit 1 - ltxok: transmit performed interrupt this bit generates an interrupt if its respective enable bit - lentxok - is set in linenir. ?0 = no tx, ?1 = tx respon se complete. the user clears this bit by writing 1, in order to reset this interrupt. in uart mode, this bit is al so cleared by writing lindat. bit 76543210 lidst2 lidst1 lidst0 lbusy l err lidok ltxok lrxok linsir read/writerrrrr/ wone r/wone r/wone r/wone initial value00000000
183 7728g?avr?06/10 attiny87/attiny167 ? bit 0 - lrxok: receive performed interrupt this bit generates an interrupt if its respective enable bit - lenrxok - is set in linenir. ? 0 = no rx ? 1 = rx response complete. the user clears this bit by writing 1, in order to reset this interrupt. in uart mode, this bit is also cleared by reading lindat. 15.6.3 lin enable interrupt register - linenir ? bits 7:4 - reserved bits these bits are reserved for future use. for co mpatibility with future devices, they must be written to zero when linenir is written. ? bit 3 - lenerr: enable error interrupt ? 0 = error interrupt masked, ? 1 = error interrupt enabled. ? bit 2 - lenidok: enable identifier interrupt ? 0 = identifier interrupt masked, ? 1 = identifier interrupt enabled. ? bit 1 - lentxok: enable transmit performed interrupt ? 0 = transmit performed interrupt masked, ? 1 = transmit performed interrupt enabled. ? bit 0 - lenrxok: enable receive performed interrupt ? 0 = receive performed interrupt masked, ? 1 = receive performed interrupt enabled. 15.6.4 lin error register - linerr ? bit 7 - labort: abort flag ? 0 = no warning, ? 1 = lin abort command occurred. this bit is cleared when lerr bit in linsir is cleared. bit 7654 3 2 1 0 - - - - lenerr lenidok len txok lenrxok linenir read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 labort ltoerr loverr lferr lserr lperr lcerr lberr linerr read/writerrrrrrrr initial value00000000
184 7728g?avr?06/10 attiny87/attiny167 ? bit 6 - ltoerr: frame_time_out error flag ?0 = no error, ? 1 = frame_time_out error. this bit is cleared when lerr bit in linsir is cleared. ? bit 5 - loverr: overrun error flag ?0 = no error, ? 1 = overrun error. this bit is cleared when lerr bit in linsir is cleared. ? bit 4 - lferr: framing error flag ?0 = no error, ? 1 = framing error. this bit is cleared when lerr bit in linsir is cleared. ? bit 3 - lserr: synchronization error flag ?0 = no error, ? 1 = synchronization error. this bit is cleared when lerr bit in linsir is cleared. ? bit 2 - lperr: parity error flag ?0 = no error, ? 1 = parity error. this bit is cleared when lerr bit in linsir is cleared. ? bit 1 - lcerr: checksum error flag ?0 = no error, ? 1 = checksum error. this bit is cleared when lerr bit in linsir is cleared. ? bit 0 - lberr: bit error flag ?0 = no error, ? 1 = bit error. this bit is cleared when lerr bit in linsir is cleared. 15.6.5 lin bit timing register - linbtr ? bit 7 - ldisr: disable bit timing re synchronization ? 0 = bit timing re-synchronization enabled (default), ? 1 = bit timing re-synchronization disabled. bit 7654321 0 ldisr - lbt5 lbt4 lbt3 lbt2 lbt1 lbt0 linbtr read/write r/w r r/(w) r/(w) r/(w) r/(w) r/(w) r/(w) initial value0010000 0
185 7728g?avr?06/10 attiny87/attiny167 ? bits 5:0 - lbt[5:0]: lin bit timing gives the number of samples of a bit. sample-time = (1 / f clk i/o ) x (ldiv[11..0] + 1) default value: lbt[6:0]=32 ? min. value: lbt[6:0]=8 ? max. value: lbt[6:0]=63 15.6.6 lin baud rate register - linbrr ? bits 15:12 - reserved bits these bits are reserved for future use. for co mpatibility with future devices, they must be written to zero when linbrr is written. ? bits 11:0 - ldiv[11:0]: scaling of clk i/o frequency the ldiv value is used to scale the entering clk i/o frequency to achieve appropriate lin or uart baud rate. 15.6.7 lin data length register - lindlr ? bits 7:4 - ltxdl[3:0]: lin transmit data length in lin mode, this field gives the number of bytes to be transmitted (clamped to 8 max). in uart mode this field is unused. ? bits 3:0 - lrxdl[3:0]: lin receive data length in lin mode, this field gives the number of bytes to be received (clamped to 8 max). in uart mode this field is unused. bit 76543210 ldiv7 ldiv6 ldiv5 ldiv4 ldiv3 ldiv2 ldiv1 ldiv0 linbrrl ----ldiv11ldiv10ldiv9ldiv8linbrrh bit 151413121110 9 8 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ltxdl3 ltxdl2 ltxdl1 ltxdl0 lrxdl3 lrxdl2 lrxdl1 lrxdl0 lindlr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
186 7728g?avr?06/10 attiny87/attiny167 15.6.8 lin identifier register - linidr ? bits 7:6 - lp[1:0]: parity in lin mode: lp0 = lid4 ^ lid2 ^ lid1 ^ lid0 lp1 = ! ( lid1 ^ lid3 ^ lid4 ^ lid5 ) in uart mode this field is unused. ? bits 5:4 - ldl[1:0]: lin 1.3 data length in lin 1.3 mode: ? 00 = 2-byte response, ? 01 = 2-byte response, ? 10 = 4-byte response, ? 11 = 8-byte response. in uart mode this field is unused. ? bits 3:0 - lid[3:0]: lin 1.3 identifier in lin 1.3 mode: 4-bit identifier. in uart mode this field is unused. ? bits 5:0 - lid[5:0]: lin 2.1 identifier in lin 2.1 mode: 6-bit identifier (no length transported). in uart mode this field is unused. 15.6.9 lin data buffer selection register - linsel ? bits 7:4 - reserved bits these bits are reserved for future use. for co mpatibility with future devices, they must be written to zero when linsel is written. bit 76 5 4 3210 lp1 lp0 lid5 / ldl1 lid4 / ldl0 lid3 lid2 lid1 lid0 linidr read/write r r r/w r/w r/w r/w r/w r/w initial value00 0 0 0000 bit 76543210 ----lainc lindx2 lindx1 lindx0 linsel read/write - - - - r/w r/w r/w r/w initial value- - - - 0000
187 7728g?avr?06/10 attiny87/attiny167 ? bit 3 - lainc : auto increment of data buffer index in lin mode: ? 0 = auto incrementation of fifo data buffer index (default), ? 1 = no auto incrementation. in uart mode this field is unused. ? bits 2:0 - lindx 2:0: fifo lin data buffer index in lin mode: location (index) of the lin response data byte into the fifo data buffer. the fifo data buffer is accessed through lindat. in uart mode this field is unused. 15.6.10 lin data register - lindat ? bits 7:0 - ldata[7:0]: lin data in / data out in lin mode: fifo data buffer port. in uart mode: data register (no data buffer - no fifo). ? in write access, data out. ? in read access, data in. bit 76543210 ldata7 ldata6 ldata5 ldata4 ldata3 ldata2 ldata1 ldata0 lindat read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
188 7728g?avr?06/10 attiny87/attiny167 16. isrc - current source 16.1 features ? 100a constant current source ? 10% absolute accuracy the attiny87/167 features a 100a 10% current source. up on request, the current is flow- ing through an external resistor. the voltage can be measured on the dedicated pin shared with the adc. using a resistor in serie with a 0.5% tolerance is recommended. to protect the device against big values, the adc must be conf igured with avcc as internal reference to per- form the first measurement. afterwards, another internal reference can be chosen according to the previous measured value to refine the result. when isrcen bit is set, the isrc pin sources 100a. otherwise this pin keeps its initial function. figure 16-1. current source block diagram 16.2 typical applications 16.2.1 lin current source during the configuration of a lin node in a clus ter, it may be necessary to attribute dynami- cally an unique physical address to every cluster node. the way to do it is not described in the lin protocol. the current source offers an excellent solution to associate a physical address to the applica- tion supported by the lin node. a full dynamic node configuration can be used to set-up the lin nodes in a cluster. attiny87/167 proposes to have an external resi stor used in conjunction with the current source. the device measures the voltage to the boundaries of the resistance via the analog to digital converter. the resulting voltage defines the physical address that the communication handler will use when the node will participate in lin communication. avcc adc input external resistor isrcen adcn/ isrc 100 ua
189 7728g?avr?06/10 attiny87/attiny167 in automotive applications, distributed voltages are very disturbed. the internal current source solution of attiny87/167 immunizes the address detection the against any kind of volt- age variations. note: 1. 5v range: max r load 30k 3v range: max r load 15k table 16-1. example of resistor values(5%) for a 8-address system (avcc = 5v (1) ) physical address resistor value r load (ohm) typical measured voltage (v) minimum reading with a 2.56v ref typical reading with a 2.56v ref maximum reading with a 2.56v ref 0 1 000 0.1 40 1 2 200 0.22 88 2 3 300 0.33 132 3 4 700 0.47 188 4 6 800 0.68 272 5 10 000 1 400 6 15 000 1.5 600 7 22 000 2.2 880 table 16-2. example of resistor values(1%) for a 16-address system (avcc = 5v (1) ) physical address resistor value r load (ohm) typical measured voltage (v) minimum reading with a 2.56v ref typical reading with a 2.56v ref miximum reading with a 2.56v ref 01 000 0.1 384045 1 1 200 0.12 46 48 54 2 1500 0.15 57 60 68 3 1800 0.18 69 72 81 4 2200 0.22 84 88 99 5 2700 0.27 104 108 122 6 3300 0.33 127 132 149 7 4700 0.47 181 188 212 8 6 800 0.68 262 272 306 9 8 200 0.82 316 328 369 10 10 000 1.0 386 400 450 11 12 000 1.2 463 480 540 12 15 000 1.5 579 600 675 13 18 000 1.8 694 720 810 14 22 000 2.2 849 880 989 15 27 000 2.7 1023 1023 1023
190 7728g?avr?06/10 attiny87/attiny167 16.2.2 current source for low cost transducer an external transducer based on a variable resistor can be connected to the current source. this can be, for instance: ? a thermistor, or temperature-sensitive resistor, used as a temperature sensor, ? a cds photoconductive cell, or luminosity-sensi tive resistor, used as a luminosity sensor, ?... using the current source with this type of tr ansducer eliminates the need for additional parts otherwise required in resistor network or wheatstone bridge. 16.2.3 voltage reference for external devices an external resistor used in conjunction with the current source can be used as voltage refer- ence for external devices. using a resistor in serie with a lower tolerance than the current source accuracy ( 2%) is recommended. table 16-2 gives an example of voltage references using standard values of resistors. 16.2.4 threshold reference for internal analog comparator an external resistor used in conjunction with the current source can be used as threshold ref- erence for internal analog comparator ( see ?anacomp - analog comparator? on page 211. ). this can be connected to ain0 (negative analog compare input pin) as well as ain1 (positive analog compare input pin). using a resistor in serie with a lower tolerance than the current source accuracy ( 2%) is recommended. table 16-2 gives an example of threshold references using standard values of resistors. 16.3 control register 16.3.1 amiscr ? analog miscellaneous control register ? bit 0 ? isrcen: current source enable writing this bit to one enables the current source as shown in figure 16-1 . it is recommended to use didr register bit function when isrcen is set. it also recommended to turn off the cur- rent source as soon as possible ( ex: once the adc measurement is done). bit 76543210 - - - - - arefen xrefen isrcen amiscr read/write rrrrrr/wr/wr/w initial value 00000000
191 7728g?avr?06/10 attiny87/attiny167 17. adc ? analog to digital converter 17.1 features ? 10-bit resolution ? 1.0 lsb integral non-linearity ? 2 lsb absolute accuracy ? 13 - 260 s conversion time (low - high resolution) ? up to 15 ksps at maximum resolution ? 11 multiplexed single ended input channels ? 8 differential input pairs with selectable gain ? temperature sensor input channel ? voltage from internal curr ent source driving (isrc) ? optional left adjustment for adc result readout ? 0 - avcc adc input voltage range ? selectable 1.1v / 2.56v adc voltage reference ? free running or single conversion mode ? adc start conversion by auto tr iggering on interrupt sources ? interrupt on adc conversion complete ? sleep mode no ise canceler ? unipolar / bipolar input mode ? input polarity reversal mode 17.2 overview the attiny87/167 features a 10-bit successive approximation adc. the adc is connected to a 11-channel analog multiplexer which allows 16 differential voltage input combinations and 11 single-ended voltage inputs constructed from the pins pa7..pa0 or pb7..pb4. the differen- tial input is equipped with a programmable gain st age, providing amplification steps of 8x or 20x on the differential input voltage before the a/d conversion. the single-ended voltage inputs refer to 0v (agnd). the adc contains a sample and hold circuit wh ich 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 17-1 . internal reference voltages of nominally 1.1v or 2.56v are provided on-chip. alternatively, avcc can be used as reference voltage for single ended channels. there are also options to output the internal 1.1v or 2.56v reference voltages or to input an external voltage reference and turn-off the internal voltage reference. these options are selected using the refs[1:0] bits of the admux control register and usin g arefen and xrefen bits of the amiscr con- trol register.
192 7728g?avr?06/10 attiny87/attiny167 figure 17-1. analog to digital converter block schematic adc0 adc1 adc2 isrc / adc3 adc4 adc5 adc6 adc8 adc9 adc10 temperature sensor bandgap reference avcc / 4 agnd avcc neg. input mux. mux. pos. input mux. x8 / x20 gain amplifier adc multiplexer output 10-bit dac sample & hold comparator conversion logic mux. decoder adc data register ( adch / adcl ) adc control & status register a & b ( adcsra/adcsrb ) adc multiplexer select ( admux ) analog misc. ( amiscr ) prescaler adc[9..0] adts[2..0] adps[2..0] refs0 adlar aden bin adsc adate adie adc conversion complete irq interrupt flags start adif adif refs1 trigger select mux[4..0] arefen xrefen 8-bit data bus internal 2.56 / 1.1v reference adc7 aref xref
193 7728g?avr?06/10 attiny87/attiny167 17.3 operation the adc converts an analog input voltage to a 10-bit digital value through successive approx- imation. the minimum value represents agnd and the maximum value represents the voltage on avcc, the voltage refrence on aref pin or an internal 1.1v / 2.56v voltage reference. the voltage reference for the adc may be selected by writing to the refs[1..0] bits in admux and arefen bit in amiscr. the avcc supp ly, the aref pin or an internal 1.1v / 2.56v voltage reference may be selected as the adc voltage reference. the analog input channel and differential gain are se lected by writing to the mux[4..0] bits in admux register. any of the 11 adc input pi ns adc[10..0] can be selected as single ended inputs to the adc. the positive and negative inputs to the differential gain amplifier are described in table 17-5 . if differential channels are selected, the differential gain stage amplifies the voltage difference between the selected input pair by the selected gain factor 8x or 20x, according to the setting of the mux[4..0] bits in admux register. this amplified value then becomes the analog input to the adc. if single ended channels are used , the gain amplifier is bypassed altogether. the on-chip temperature sensor is selected by writing the code defined in table 17-5 to the mux[4..0] bits in admux register when its de dicated adc channel is used as an adc input. a specific adc chan nel (defined in table 17-5 ) is used to measure the voltage to the boundar- ies of an external resistance flowing by a cu rrent driving by the internal current source (isrc). the adc is enabled by setting the adc enable bit, aden in adcsra register. voltage refer- ence and input chann el 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 presented in the adc data registers, adch and adcl. by default, the result is presented ri ght adjusted, but can optionally be presented left adjusted by setting the adlar bit in admux register. if the result is left adjusted and no more than 8-bi t 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 read, and a conversion completes before adch is read, neither register is updated and the re sult from the conversi on is lost. when adch is read, adc access to the adch and adcl 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 reading of adch and adcl, the inter- rupt will trigger even if the result is lost.
194 7728g?avr?06/10 attiny87/attiny167 17.4 starting a conversion a single conversion is started by writing a lo gical one to the adc start conversion bit, adsc. this bit stays high as long as the conversion 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 conversion befo re performing t he channel change. alternatively, a conversion can be triggered automatically by various sources. auto triggering is enabled by setting the adc auto trigger enabl e bit, adate in adcsra register. the trig- ger source is selected by setting the adc tri gger select bits, adts in adcsrb register (see description of the adts bits for a list of the trigger sources). when a positive edge occurs on the selected trigger signal, the adc prescaler is reset and a conversion is started. this pro- vides a method of starting conver sions at fixed intervals. if t he trigger signal still is set when the conversion completes, a new conversion will not be started. if another positive edge occurs on the trigger signal duri ng conversion, the edge will be igno red. note that an interrupt flag will be set even if the specific interrupt is disabled or the global interrupt enable bit in sreg register is cleared. a conversion can thus be triggered without causing an interrupt. however, the interrupt flag must be cleared in order to trigger a new conversion at the next interrupt event. figure 17-2. adc auto trigger logic using the adc interrupt flag as a trigger s ource makes the adc start a new conversion as soon as the ongoing conversion has finished. th e adc then operates in free running mode, constantly sampling and updating the adc data r egister. the first conversion must be started by writing a logical one to the adsc bit in ad csra register. in this mode the adc will perform successive conversions independently of whether the adc interrupt flag, adif is cleared or not. if auto triggering is enabled, single conversi ons can be started by writing adsc in adcsra register to one. adsc can also be used to determine if a conversion is in progress. the adsc bit will be read as one during a conversion, inde pendently of how the conversion was started. adsc adif source 1 source n adts[2:0] conversion logic adc prescaler start clk adc clk io . . . . . . . . . . . . edge detector adate
195 7728g?avr?06/10 attiny87/attiny167 17.5 prescaling and conversion timing figure 17-3. adc prescaler by default, the successive approximation circui try requires an input clock frequency between 50 khz and 200 khz to get maximum resolution. if a lower resolution than 10 bits is needed, the input clock frequency to the adc can be higher than 200 khz to get a higher sample rate. the adc module contains a prescaler, which generates an acceptable adc clock frequency from any cpu frequency above 100 khz. the prescaling is set by the adps bits in adcsra register. the prescaler starts counting from the moment the adc is switched on by setting the aden bit in adcsra register. the prescaler keeps running for as long as the aden bit is set, and is continuously re set when aden is low. when initiating a single ended conversion by setting the adsc bit in adcsra register, the conversion starts at the following rising edge of the adc clock cycle. a normal conversion takes 13 adc clock cycles . the first conversion after the adc is switched on (aden in adcsra register is set) takes 25 adc clock cycles in order to initialize the analog circuitry. the actual sample-and-hold take s place 1.5 adc clock cycles afte r the start of a normal con- version and 14.5 adc clock cycles after the start of an first conversion. when a conversion is complete, the result is written to the adc data registers, and adif is set. in single conver- sion mode, adsc is cleared simultaneously. the software may then set adsc again, and a new conversion will be in itiated on the first ri sing adc clock edge. when auto triggering is used, the prescaler is reset when the trigger event occurs. this assures a fixed delay from the trigger event to the start of conversion. in this mode, the sam- ple-and-hold takes place 2 adc clock cycles after the rising edge on the trigger source signal. three additional cpu clock cycles are used for synchronization logic. in free running mode, a new conversion will be started immediately after the conversion completes, while adsc remains high. for a summary of conversion times, see table 17-1 . 7-bit adc prescaler ck/2 reset clk io aden start ck/4 ck/8 ck/16 ck/32 ck/64 ck/128 adps0 adps1 adps2
196 7728g?avr?06/10 attiny87/attiny167 figure 17-4. adc timing diagram, first conver sion (single conversion mode) figure 17-5. adc timing diagram, single conversion figure 17-6. adc timing diagram, auto triggered conversion sign and msb of result lsb of result dc clock dsc sample & hold dif dch dcl ycle number den 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 sign and msb of result lsb of result dc clock dsc dif dch dcl ycle number 12 one conversion next conversion 3 sample & hold mux and refs update conversion complete mux and refs update 1 2 3 4 5 6 7 8 9 10 11 12 13 sign and msb of result lsb of result dc clock igger ource dif dch dcl ycle number 12 one conversion next conversion conversion complete prescaler reset date prescaler reset sample & hold mux and refs update
197 7728g?avr?06/10 attiny87/attiny167 figure 17-7. adc timing diagram, free running conversion 17.6 changing channel or reference selection the mux[4:0] and refs[1:0] bits in the admux register are single buffered through a tempo- rary register to which the cpu has random access. this ensures that the channels and reference selection only takes place at a sa fe point during the c onversion. 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. continuous updating resumes in th e last adc clock cycle before the conversion completes (adif in adcsra register is set). no te that the conversion starts 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 unt il one adc clock cycle after adsc is written. if auto triggering is used, the exact time of t he triggering event can be indeterministic. special care must be taken when updating the admux register, in order to control which conversion will be affected by the new settings. if both adate and aden is written to one, an interrupt event can occur at any time. if the admux register is changed in this period, the us er cannot tell if the next conversion is based on the old or the new settings. admux can be safely updated in the following ways: a. when adate or aden is cleared. b. during conversion, minimum one adc clock cycle after the trigger event. c. after a conversion, before the interrupt flag used as trigger source is cleared. when updating admux in one of these conditio ns, the new settings will affect the next adc conversion. table 17-1. adc conversion time condition sample & hold (cycles from start of conver sion) conversion time (cycles) first conversion 13.5 cycles 25 cycles normal conversions 1.5 cycles 13 cycles auto triggered conver sions 2 cycles 13.5 cycles 11 12 13 sign and msb of result lsb of result dc clock dsc dif dch dcl ycle number 12 one conversion next conversion 34 conversion complete sample & hold mux and refs update
198 7728g?avr?06/10 attiny87/attiny167 17.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 channel selection may be changed one adc cloc k 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 channel selection may be changed one adc cloc k cycle after writing one to adsc. however, the simplest method is to wait for the first conversion to complete, and then change the chan- nel selection. since the next c onversion has already started aut omatically, the next result will reflect the previous channel selection. subsequent conversions will reflect the new channel selection. 17.6.2 adc voltage reference the voltage reference for the adc (v ref ) indicates the conversion range for the adc. single ended channels that exceed v ref will result in codes close to 0x3ff. v ref can be selected as either avcc, internal 1.1v / 2.56v voltage reference or external aref pin. the first adc con- version result after switching voltage reference source may be inaccurate, and the user is advised to discard this result. 17.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 proce- dure should be used: a. 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. b. enter adc noise reduction mode (or id le mode). the adc will start a conver- sion once the cpu has been halted. c. if no other interrupts occur before the adc conversion completes, the adc inter- rupt 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 com- plete, that interrupt will be executed, a nd an adc conversion complete interrupt request will be generated when the adc conversion completes. 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 entering such sleep modes to av oid excessive power consumption. 17.7.1 analog input circuitry the analog input circuitry for si ngle ended channels is illustra ted in figure 17-8. an analog source applied to adcn is subjected to t he pin capacitance and input leakage of that pin, regardless of whether that channel is select ed as input for the adc. when the channel is selected, the source must drive the s/h c apacitor through the series resistance (combined resistance in the input path).
199 7728g?avr?06/10 attiny87/attiny167 the adc is optimized for analog signals with 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 impedance is used, the sampling time will depend on how long time the source needs to charge the s/h capacitor, with can vary widely. the user is recommended to only use low impedant sources with slowly varying signals, si nce this minimizes the required charge trans- fer to the s/h capacitor. signal components higher than the nyquist frequency (f adc /2) should not be present 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 17-8. analog input circuitry 17.7.2 analog noise canceling techniques digital circuitry inside and outside the device generates 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: a. keep analog signal paths as short as possible. make sure analog tracks run over the analog ground plane, and keep them well away from high-speed switching digital tracks. b. use the adc noise canceler function to reduce induced noise from the cpu. c. if any port pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. 17.7.3 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: ? offset: the deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 lsb). ideal value: 0 lsb. adcn i ih c s/h = 14 pf v cc /2 i il 1..100 ko
200 7728g?avr?06/10 attiny87/attiny167 figure 17-9. 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 17-10. 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
201 7728g?avr?06/10 attiny87/attiny167 figure 17-11. integral non-linearity (inl) ? differential non-linearity (dnl): the maximu m deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 lsb). ideal value: 0 lsb. figure 17-12. differential non-linearity (dnl) ? quantization error: due to the quantization of the input voltage into a finite number of codes, a range of input volta ges (1 lsb wide) will code to th e 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. output code v ref input voltage ideal adc actual adc inl output code 0x3ff 0x000 0 v ref input voltage dnl 1 lsb
202 7728g?avr?06/10 attiny87/attiny167 17.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). the form of the conversion result depends on the type of the conversion as there are three types of conversions: single ended conversion, unipolar differ- ential conversion and bipolar differential conversion. 17.8.1 single ended conversion for single ended conversion, the result is: where v in is the voltage on the selected input pin and v ref the selected voltage reference (see table 17-4 on page 205 and table 17-5 on page 206 ). 0x000 represents analog ground, and 0x3ff represents the selected voltage reference minus one lsb. the result is presented in one-sided form, from 0x3ff to 0x000. 17.8.2 unipolar differential conversion if differential channels and an unipolar input mode 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, and v ref the selected voltage reference (see table 17-4 on page 205 and table 17-5 on page 206 ). the voltage on the positive pin must always be larger than the voltage on the negative pin or otherwise the voltage difference is saturated to zero. the result is presented in one-sided form, from 0x000 (0 d ) to 0x3ff (+1023 d ). the gain is either 8x or 20x. 17.8.3 bipolar differential conversion as default the adc converter operates in the unipolar input mode, but the bipolar input mode can be selected by writing the bin bit in the adcsrb register to one. in the bipolar input mode two-sided voltage differences are allowed and thus the voltage on the negative input pin can also be larger than the voltage on the positive input pin. if differential channels and a bipolar input mode 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, and v ref the selected voltage reference. the result is presented in two?s complement form, from 0x200 (-512 d ) through 0x000 (+0 d ) to 0x1ff (+511 d ). the gain is either 8x or 20x. adc v in 1024 ? v ref ----------------------------- = adc v pos v neg ? () 1024 ? v ref ---------------------------------------------------------- - gain ? = adc v pos v neg ? () 512 ? v ref ------------------------------------------------------- gain ? =
203 7728g?avr?06/10 attiny87/attiny167 however, if the signal is not bipolar by nature (9 bits + sign as the 10th bit), this scheme loses one bit of the converter dynamic range. then, if the user wants to perform the conversion with the maximum dynamic range, the user can perform a quick polarity check of the result and use the unipolar differential conversion with select able differential input pair. when the polarity check is performed, it is suffici ent to read the msb of the result (adc9 in adch register). if the bit is one, the result is negative, and if this bit is zero, th e result is positive. 17.9 temperature measurement the temperature measurement is based on an on-chip temperature sensor that is coupled to a single ended adc input. mux[4..0] bits in ad mux register enables the temperature sensor. the internal 1.1v voltage reference must also be selected for the adc voltage reference source in the temperature sensor measurement. when the temperature sensor is enabled, the adc converter can be used in single conversion mode to measure the voltage over the tem- perature sensor. the measured voltage has a linear relationship to the temperature as described in table 17-2 . the voltage sensitivity is approximately 1 lsb/ c and the accuracy of the temperature mea- surement is 10c using manufacturing cali bration values (ts_gain, ts_offset). the values described in table 17-2 are typical values. however, due to the process variation the temperature sensor output varies from one chip to another. 17.9.1 manufacturing calibration calibration values determined during test are available in the signature row. the temperature in degrees celsius can be calculated using the formula: where: a. adch & adcl are the adc data registers, b. is the temperature sensor gain c. tsoffset is the temperature sensor offset correction term ts_gain is the unsigned fixed point 8-bit temperature sensor gain factor in 1/128th units stored in the signature row ts_offset is the signed twos complement temperature sensor offset reading stored in the signature row. see table 20-1 on page 221 for signature row parameter address. table 17-2. temperature vs. sensor output voltage (typical case): example adc values temperature/c ?40c +25c +85c 0x00f6 0x0144 0c01b8 t adch 8 ? () adcl [] 273 25 ts_offset ? + () ? () 128 ts_gain ------------------------------------------------------------------------------------------------------------------------------- ----------------------- - 25 + =
204 7728g?avr?06/10 attiny87/attiny167 the following code example allows to read signature row data: .equ ts_gain = 0x0007 .equ ts_offset = 0x0005 ldi r30,low(ts_gain) ldi r31,high (ts_gain) rcall read_signature_row mov r17,r16 ; save r16 result ldi r30,low(ts_offset) ldi r31,high (ts_offset) rcall read_signature_row ; r16 holds ts_offset and r17 holds ts_gain read_signature_row: in r16,spmcsr ; wait for spmen ready sbrc r16,spmen ; exit loop here when spmcsr is free rjmp read_signature_row ldi r16,((1< 205 7728g?avr?06/10 attiny87/attiny167 17.11 register description 17.11.1 admux ? adc multiplexer selection register ? bit 7:6 ? refs1:refs0: voltage reference selection bits these bits and arefen bit from the analog mi scellaneous control register (amiscr) select the voltage reference for the adc, as shown in table 17-4 . if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra register is set). wheneve r these bits are change d, the next conversion will take 25 adc clock cycles. if active channels are used, using avcc or an external aref higher than (avcc - 1v) is not recommended, as this will affect adc ac curacy. the internal voltage reference options may not be used if an external voltage is being applied to the aref pin. ? bit 5 ? adlar: adc left adjust result the adlar bit affects the presentation of the adc conversion result in the adc data regis- ter. write one to adlar to left adjust the result. otherwise, the result is right adjusted. changing the adlar bit will affect the adc data register immediately, regardless of any ongoing conversions. for a complete description of this bit, see ?adcl and adch ? the adc data register? on page 208 . ? bits 4:0 ? mux4:0: analog channel and gain selection bits these bits select which combination of analog inputs are connected to the adc. in case of dif- ferential input, gain selection is also made with these bits. refer to table 17-5 for details. if these bits are changed during a conversion, the change will not go into effect until this conversion is complete (adif in adcsra register is set). 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 value00000000 table 17-4. voltage reference selections for adc refs1 refs0 arefen voltage reference (v ref ) selection x 0 0 avcc used as voltage reference, diconnected from aref pin. x 0 1 external voltage reference at aref pin (aref 2.0v) 0 1 0 internal 1.1v voltage reference . 1 1 0 internal 2.56v voltage reference .
206 7728g?avr?06/10 attiny87/attiny167 table 17-5. input channel selections mux[4..0] single ended input positive differential input negative differential input gain 0 0000 adc0 (pa0) na na na 0 0001 adc1 (pa1) 0 0010 adc2 (pa2) 0 0011 adc3 / isrc (pa3) 0 0100 adc4 (pa4) 0 0101 adc5 (pa5) 0 0110 adc6 (pa6) 0 0111 adc7 / aref (pa7) 0 1000 adc8 (pb5) 0 1001 adc9 (pb6) 0 1010 adc10 (pb7) 0 1011 temperature sensor 0 1100 bandgap reference (1.1 v) 0 1101 avcc/4 0 1110 gnd (0v) 0 1111 (reserved) 1 0000 n/a adc0 (pa0) adc1 (pa1) 8x 1 0001 20x 1 0010 adc1 (pa1) adc2 (pa2) 8x 1 0011 20x 1 0100 adc2 (pa2) adc3 (pa3) 8x 1 0101 20x 1 0110 adc4 (pa4) adc5 (pa5) 8x 1 0111 20x 1 1000 adc5 (pa5) adc6 (pa6) 8x 1 1001 20x 1 1010 adc6 (pa6) adc7 (pa7) 8x 1 1011 20x 1 1100 adc8 (pb5) adc9 (pb6) 8x 1 1101 20x 1 1110 adc9 (pb6) adc10 (pb7) 8x 1 1111 20x
207 7728g?avr?06/10 attiny87/attiny167 17.11.2 adcsra ? adc control and status register a ? bit 7 ? aden: adc enable writing this bit to one en ables the adc. by writing 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 normal 13. this first conversion performs initialization of the adc. adsc will read as one as long as a conversi on is in progress. when the conversion is com- plete, it returns to zero. writing zero to this bit has no effect. ? bit 5 ? adate: adc auto trigger enable when this bit is written to on e, auto triggering of the adc is enabled. the adc will start a conversion on a positive edge of the selected trigger signal. the trigger source is selected by setting the adc trigger sele ct bits, adts in adcsrb. ? 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 the adie bit and the i-bit in sreg are set. adif is cleared by hardware when executi ng the corresponding interrupt handling vector. alternatively, adif is cleared by writing a l ogical 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 interrupt is activated. ? bits 2:0 ? adps2:0: adc prescaler select bits these bits determine the division factor between the system clock frequency and the input clock to the adc. bit 76543210 aden adsc adate 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 table 17-6. adc prescaler selections adps2 adps1 adps0 division factor 000 2 001 2 010 4 011 8
208 7728g?avr?06/10 attiny87/attiny167 17.11.3 adcl and adch ? the adc data register 17.11.3.1 adlar = 0 17.11.3.2 adlar = 1 when an adc conversion is complete, the result is found in these two registers. when adcl is read, the adc da ta register is not updated until adch is read. consequently, if the result is left adjusted and no more than 8-bi t 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 adlar is cleared (default), the result is right adjusted. ? adc9:0: adc conversion result these bits represent the result from the conversion, as detailed in ?adc conversion result? on page 202 . 100 16 101 32 110 64 111 128 table 17-6. adc prescaler selections (continued) adps2 adps1 adps0 division factor bit 151413121110 9 8 ? ? ? ? ? ? adc9 adc8 adch adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 adcl 76543210 read/writerrrrrrrr rrrrrrrr initial value 0 0 0 0 0 0 0 0 00000000 bit 151413121110 9 8 adc9 adc8 adc7 adc6 adc5 adc4 adc3 adc2 adch adc1 adc0 ? ? ? ? ? ? adcl 76543210 read/writerrrrrrrr rrrrrrrr initial value 0 0 0 0 0 0 0 0 00000000
209 7728g?avr?06/10 attiny87/attiny167 17.11.4 adcsrb ? adc control and status register b ? bit 7? bin: bipolar input mode the gain stage is working in the unipolar m ode as default, but the bipolar mode can be selected by writing the bin bit in the adcsrb register. in the unipolar mode only one-sided conversions are supported and the voltage on the positive input must always be larger than the voltage on the negative input. otherwise the result is saturated to the voltage reference. in the bipolar mode two-sided conversions are supported and the result is represented in the two?s complement form. in the unipolar mode the resolution is 10 bits and the bipolar mode the resolution is 9 bits + 1 sign bit. ? bit 3 ? res: reserved bit this bit is reserved for future use. for compatib ility with future device s it must be written to zero when adcsrb register is written. ? bits 2:0 ? adts2:0: adc auto trigger source if adate in adcsra register is written to one, the value of these bits selects which source will trigger an adc conversion. if adate is clear ed, the adts2:0 settings will have no effect. a conversion will be triggered by the rising edge of the selected inte rrupt flag. note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. if aden in adcs ra register is set, this will start a conver- sion. switching to free running mode (adts[2:0]=0) will not cause a trigger event, even if the adc interrupt flag is set. 17.11.5 didr0 ? digital input disable register 0 bit 76543210 bin acme acir1 acir0 ? adts2 adts1 adts0 adcsrb read/write r/w r/w r/w r/w r r/w r/w r/w initial value00000000 table 17-7. adc auto trigger so urce selections adts2 adts1 adts0 trigger source 0 0 0 free running mode 0 0 1 analog comparator 0 1 0 external interrupt request 0 0 1 1 timer/counter1 compare match a 1 0 0 timer/counter1 overflow 1 0 1 timer/counter1 compare match b 1 1 0 timer/counter1 capture event 1 1 1 watchdog interrupt request bit 76543210 adc7d / ain1d adc6d / ain0d adc5d adc4d adc3d adc2d adc1d adc0d didr0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
210 7728g?avr?06/10 attiny87/attiny167 ? bits 7:0 ? adc7d:adc0d: adc7 :0 digital input disable when this bit is written logic one, the digital input buffer on the corresponding adc pin is dis- abled. the corresponding pin register bit will always read as zero when this bit is set. when an analog signal is applied to the adc7:0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. 17.11.6 didr1 ? digital input disable register 1 ? bit 7 ? res: reserved bit this bit is reserved for future use. for compatib ility with future device s it must be written to zero when didr1 register is written. ? bits 6..4 ? adc10d..adc8d: adc10..8 digital input disable when this bit is written logic one, the digital input buffer on the corresponding adc pin is dis- abled. the corresponding pin register bit will always read as zero when this bit is set. when an analog signal is applied to the adc10:8 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. ? bits 3:0 - reserved bits these bits are reserved for future use. for compatibility with future devices, they must be writ- ten to zero when didr1 is written. 17.11.7 amiscr ? analog miscellaneous control register ? bits 7:3 ? reserved bits these bits are reserved for future use. for compatibility with future devices, they must be writ- ten to zero when amiscr is written. ? bit 2 ? arefen: external voltage reference input enable when this bit is written logic one, the voltage reference for the adc is input from aref pin as described in table 17.10 on page 204 . if active channels are used, using avcc or an external aref higher than (avcc - 1v) is not recommended, as this will affect adc accuracy. the internal voltage reference options may not be used if an external voltage is being applied to the aref pin. it is recommended to use didr regist er bit function (digital input disable) when arefen is set. ? bit 1 ? xrefen: internal voltage reference output enable when this bit is written logic one, the internal voltage reference 1.1v or 2.56v is output on xref pin as described in table 17.10 on page 204 . it is recommended to use didr register bit function (digital input disable) when xrefen is set. bit 76543210 - adc10d adc9d adc8d - - - - didr1 read/write rr/wr/wr/wrrrr initial value 00000000 bit 76543210 -----arefenxrefen isrcen amiscr read/write rrrrrr/wr/wr/w initial value 00000000
211 7728g?avr?06/10 attiny87/attiny167 18. anacomp - analog comparator the analog comparator compares the input values on the positive pin (ain1) and negative pin (ain0). when the voltage on the positive pin is higher than the voltage on the negative pin, the analog comparator output, aco, is set. the comparator can trigger a separate interrupt, exclusive to the analog comparator. the user can select interrupt triggering on comparator output rise, fall or toggle. a block diagram of the comparator and its surrounding logic is shown in figure 18-1 . figure 18-1. analog comparator block diagram (1)(2) notes: 1. see table 18-2 on page 214 and table 18-3 on page 214 2. refer to figure 1-2 on page 5 and table 9-3 on page 76 for analog comparator pin placement. 18.1 register description 18.1.1 adc control and status register b ? adcsrb ? bit 6 ? acme: analog comparator multiplexer enable when this bit is writte n logic one and the adc is switched off (aden in adcsra is zero), the adc multiplexer selects the positive input to the analog comparator. when this bit is written logic zero, ain1 is applied to the positive input of the analog comparator. when the analog to digital converter (adc) is configured as single ended input channel, it is possible to select any of the adc[10..0] pins to replace the positive input to the analog com- parator. the adc multiplexer (mux[4..0]) is us ed to select this input, and consequently, the adc must be switched o ff to utilize this feature. analog comparator interrupt interrupt sensivity control aco aci acie acis0 acis1 acme acirs aden 16-bit timer/counter input capture ain0 (pa6) ain1 (pa7) refs1 internal 2.56 v reference acir1 acir0 2.56 v 1.28 v 0.64 v 0.32 v acd avcc ( from adc ) refs0 (1) adc multiplexer output bit 7 6543210 bin acme acir1 acir0 ? adts2 adts1 adts0 adcsrb read/write r r/w r/w r/w r r/w r/w r/w initial value 0 0000000
212 7728g?avr?06/10 attiny87/attiny167 ? bits 5, 4 ? acir1, acir0: analog comparator internal voltage reference select when acirs bit is set in adcsra register, these bits select a voltage reference for the nega- tive input to the analog comparator, see table 18-3 on page 214 . 18.1.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 comparator. th is 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 of acsr register. otherwise an interrupt can occur when the bit is changed. ? bit 6 ? acirs: analog comparator internal reference select when this bit is set an internal reference vo ltage replaces the negative input to the analog comparator (c.f. table 18-3 on page 214 ). if acirs is cleared, ain0 is applied to the negative input to the analog comparator. ? bit 5 ? aco: analog comparator output the output of the analog comparator is sy nchronized 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 interrupt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleare d by hardware when executing the corresponding interrupt 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- bit in the status register is set, the analog comparator 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 logi c, making the compar ator utilize the noise canceler and edge select features of the timer/counter1 input capture interrupt. when written logic zero, no con- nection between the analog comparator and the input capture function exists. to make the comparator trigger the timer/counter1 input capture interrupt, the icie1 bit in the timer inter- rupt mask register (timsk1) 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 18-1 . bit 76543210 acd acirs 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 value00n/a00000
213 7728g?avr?06/10 attiny87/attiny167 note: 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. 18.1.3 didr0 ? digital in put disable register 0 ? bits 7,6 ? ain1d, ain0d: ain1d and ain0d digital input disable when this bit is written logic one, the digita l input buffer on the corresponding analog com- pare pin is disabled. the corresponding pin regist er bit will always read as zero when this bit is set. when an analog signal is applied to the ain0/1 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. 18.2 analog comparator inputs 18.2.1 analog compare positive input it is possible to select any of the inputs of the adc positive input multiplexer to replace the positive input to the analog comparator. the adc multiplexer is used to select this input, and consequently, the ad c must be switched off to utilize th is feature. if th e analog comparator multiplexer enable bit (acme in adcsrb register) is set and the adc is switched off (aden in adcsra register is zero), mux[4..0] in admu x register select the input pin to replace the positive input to the analog comparator, as shown in table 18-2 . if acme is cleared or aden is set, ain1 pin is applied to the positive input to the analog comparator. table 18-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. bit 76543210 adc7d / ain1d adc6d / ain0d adc5d adc4d adc3d adc2d adc1d adc0d didr0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
214 7728g?avr?06/10 attiny87/attiny167 18.2.2 analog compare negative input it is possible to select an internal voltage reference to replace the negative input to the analog comparator. the output of a 2-bit dac using the internal voltage reference of the dac is available when acirs bit of acsr register is set. the voltage reference division factor is done by acir[1..0] of adcsrb register. if acirs is cleared, ain0 pin is applied to the negative input to the analog comparator. table 18-2. analog comparator positive input acme aden mux[4..0] anal og comparator positive input - comment 0 x x xxxx b ain1 adc switched on x 1 x xxxx b ain1 1 0 0 0000 b adc0 adc switched off. 1 0 0 0001 b adc1 1 0 0 0010 b adc2 1 0 0 0011 b adc3 / isrc 1 0 0 0100 b adc4 1 0 0 0101 b adc5 1 0 0 0110 b adc6 1 0 0 0111 b adc7 1 0 0 1000 b adc8 1 0 0 1001 b adc9 1 0 0 1010 b adc10 1 0 other this doesn?t make sense - don?t use. table 18-3. analog comparator negative input acirs acir[1..0] refs[1..0] analog comparator negative input - comment 0x xain0 1x 0 0 b 0 1 b 1 0 b reserved 10 0 b 1 1 b 2.56 v - using internal 2.56v voltage reference 10 1 b 1 1 b 1.28 v ( 1 / 2 of 2.56 v) - using internal 2.56v voltage reference 11 0 b 1 1 b 0.64 v ( 1 / 4 of 2.56 v - using internal 2.56v voltage reference 11 1 b 1 1 b 0.32 v ( 1 / 8 of 2.56 v) - using internal 2.56v voltage reference
215 7728g?avr?06/10 attiny87/attiny167 19. debugwire on-chip debug system 19.1 features ? complete program flow control ? emulates all on-chip func tions, both digital and analog, except reset pin ? real-time operation ? symbolic debugging support (both at c and assembler source level, or for other hlls) ? unlimited number of prog ram break points (using software break points) ? non-intrusive operation ? electrical characteristics identical to real device ? automatic configuration system ? high-speed operation ? programming of non-volatile memories 19.2 overview the debugwire on-chip debug system uses a one- wire, bi-directional interface to control the program flow, execute avr instructions in the cpu and to program the different non-volatile memories. 19.3 physical interface when the debugwire enable (dwen) fuse is programmed and lock bits are unpro- grammed, the debugwire system within the target device is activated. the reset port pin is configured as a wire-and (open-drain) bi-directional i/o pin with pull-up enabled and becomes the communication gateway between target and emulator. figure 19-1. the debugwire setup figure 19-1 shows the schematic of a target mcu, with debugwire enabled, and the emula- tor connector. the system clock is not affected by debugwire and will always be the clock source selected by the cksel fuses. when designing a system wher e debugwire will be used, the following observations must be made for correct operation: vcc +1.8 - +5.5v gnd dw (reset) dw
216 7728g?avr?06/10 attiny87/attiny167 ? pull-up resistors on the dw/(reset) line must not be smaller than 10k . the pull-up resistor is not required for debugwire functionality. ? connecting the reset pin directly to vcc will not work. ? capacitors connected to th e reset pin must be disconne cted when using debugwire. ? all external reset sources must be disconnected. 19.4 software break points debugwire supports program memory break po ints by the avr break instruction. setting a break point in atmel avr studio ? will insert a break instructio n in the program memory. the instruction replaced by the break instruction w ill be stored. when program execution is con- tinued, the stored instruction will be executed before continuing from th e program memory. a break can be inserted manu ally by putting the break in struction in the program. the flash must be re-programmed each time a break point is changed. this is automatically handled by avr studio through the debugwire in terface. the use of break points will there- fore reduce the flash data retention. devices used for debugging purposes should not be shipped to end customers. 19.5 limitations of debugwire the debugwire communication pin (dw) is physically located on the same pin as external reset (reset). an external rese t source is therefore not su pported when the debugwire is enabled. the debugwire system accurately emulates all i/o functions when running at full speed, i.e., when the program in the cpu is running. when the cpu is stopped, care must be taken while accessing some of the i/o registers via the debugger (avr studio). a programmed dwen fuse enables some parts of the clock system to be running in all sleep modes. this will increase the power consumption while in sleep. thus, the dwen fuse should be disabled when debugwire is not used. 19.6 debugwire related regi ster in i/o memory the following section describes the registers used with the debugwire. 19.6.1 debugwire data register ? dwdr the dwdr register provides a communication channel from the running program in the mcu to the debugger. this register is only accessible by the debugwire and can therefore not be used as a general purpose register in the normal operations. bit 76543210 dwdr[7:0] dwdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
217 7728g?avr?06/10 attiny87/attiny167 20. flash programming the device provides a self-programming mechanism for downloading and uploading program code by the mcu itself. the self-programming can use any available data interface (i.e. lin, usart, ...) and associated protocol to read c ode and write (program) that code into the pro- gram memory. 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 buffer is filled one word at a ti me 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 buffer before a page erase ? fill temporary page buffer ? perform a page erase ? perform a page write ? alternative 2, fill the buffer after page erase ? perform a page erase ? fill temporary page buffer ? perform a page write if only a part of the page needs to be changed, the rest of the page must be stored (for exam- ple in the temporary page buffer) before the erase, and then be re-written. when using alternative 1, the boot loader provides an effe ctive read-modify-write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alternative 2 is used, it is not possible to read the old data while loading 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. 20.1 self-programming the flash 20.1.1 performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?00000011 b ? 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 will be ignored during this operation. ? the cpu is halted during the page erase operation. 20.1.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 b ? to spmcsr and execute spm within f our 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-eras e after a page write operation or by writing the ctpb bit in spmcsr. it is also erased after a system reset. note that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in th e middle of an spm page load operation, all data loaded will be lost.
218 7728g?avr?06/10 attiny87/attiny167 20.1.3 performing a page write to execute page write, set up the address in the z-pointer, write ?00000101 b ? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation. ? the cpu is halted during the page write operation. 20.2 addressing the flash during self-programming the z-pointer is used to address the spm commands. the z pointer consists of the z-regis- ters zl and zh in the register file. the number of bits actually used is implementation dependent. since the flash is organized in pages (see table 21-7 on page 228 ), the program counter can be treated as having two different sections. one section, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 20-1 . note that the page erase and page write operations are addressed independently. therefore it is of major importance that the software addresses the same page in both the page erase and page write operation. the lpm instruction uses the z-pointer 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 20-1. addressing the flash during spm (1) note: 1. the different variables used in table 20-2 are listed in table 21-7 on page 228 . bit 151413121110 9 8 z15 z14 z13 z12 z11 z10 z9 z8 zh (r31) z7 z6 z5 z4 z3 z2 z1 z0 zl (r30) bit 76543210 program memory 0 1 15 z - pointer bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word page pcword[pagemsb:0]: 00 01 02 pageend page pcword pcpage pcmsb pagemsb program counter
219 7728g?avr?06/10 attiny87/attiny167 20.2.1 store program memory control and status register ? spmcsr the store program memory control and status register contains the control bits needed to control the boot loader operations. ? bit 7 ? res: reserved bit this bit is a reserved bit in the atti ny87/167 and will always read as zero. ? bit 6 ? rwwsb: read-while-write section busy this bit is for compatibility with devices supp orting read-while-write . it will always read as zero in attiny87/167. ? bit 5 ? sigrd: signature row read if this bit is written to one at the same time as spmen, the next lpm instruction within three clock cycles will read a byte from the signa ture row into the de stination register. see ?reading the signature row from software? on page 221. for details. an spm instruction within four cycles after sigrd and spmen are set will have no effect. ? bit 4 ? ctpb: clear temporary page buffer if the ctpb bit is written while filling the te mporary page buffer, the temporary pag e buffer will be cleared and the data will be lost. ? bit 3 ? rflb: read fuse and lock bits an lpm instruction within three cycles after rflb and spmen are set in the spmcsr regis- ter, will read either the lock bits or the fuse bi ts (depending on z0 in the z-pointer) into the destination register. see ?reading the fuse and lock bits from software? on page 220. 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 writ e, 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-c lear upon completion of a page write, or if no spm instruction is exe- cuted within four clock cycles. the cpu is halted during the entire page write operation. ? 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 zpointer. the data in r1 and r0 are ignored. the pgers bit will auto-clear upon completion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation. bit 7654321 0 ? rwwsb sigrd ctpb rflb pgwrt pgers spmen spmcsr read/write r r r r/w r/w r/w r/w r/w initial value0000000 0
220 7728g?avr?06/10 attiny87/attiny167 ? bit 0 ? spmen: self programming enable this bit enables the spm instruction for the nex t four clock cycles. if written to one together with either sigrd, ctpb, rflb, pgwrt, or pgers, the following spm instruction will have a special meaning, see description above. if on ly spmen is written, the following spm instruc- tion will store the value in r1:r0 in the temporary page buffer ad dressed by the z-pointer. the lsb of the z-pointer is ignor ed. the spmen bit will auto-clear upon completion of an spm instruction, or if no spm instruction is exec uted 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 ?10 0001 b ?, ?01 0001 b ?, ?00 1001 b ?, ?00 0101 b ?, ?00 0011 b ? or ?00 0001 b ? in the lower six bits will have no effect. note: only one spm instruction should be active at any time. 20.2.2 eeprom write prevents writing to spmcsr note that an eeprom write operation will bl ock all software programming to flash. reading the fuses and lock bits from software will also be prevented during th e eeprom write opera- tion. it is recommended that the user checks the status bit (eepe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. 20.2.3 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with 0x0001 and set the rflb and spmen bits in spmcsr. when an lpm instruc- tion is executed within three cpu cycles after the rflb and spmen bits are set in spmcsr, the value of the lock bits will be loaded in the destination re gister. the rflb and spmen bits will auto-clear upon completion of reading the lock bits or if no lpm instruction is executed within three cpu cycles or no spm instructi on is executed within four cpu cycles. when rflb and spmen are cleared, lpm will work as described in the in struction set manual. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the rflb and spmen bits in spmcsr. when an lpm instruction is executed within three cycles after the rflb and spmen bits are set in the spmcs r, the value of the fuse low byte (flb) will be loaded in the destination regi ster as shown below. see table 21-5 on page 227 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte (fhb), load 0x0003 in the z-pointer. when an lpm instruction is executed within three cycles after the rflb and spmen bits are set in the spmcsr, the value of the fuse high byte will be loaded in the destinat ion register as shown below. see table 21-4 on page 226 for detailed description and mapping of the fuse high byte. bit 76543210 rd (z=0x0001) ??????lb2lb1 bit 76543210 rd (z=0x0000) flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd (z=0x0003) fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0
221 7728g?avr?06/10 attiny87/attiny167 similarly, when reading the extended fuse byte (efb), load 0x0002 in the z-pointer. when an lpm instruction is executed within three cycles after the rflb and spmen bits are set in the spmcsr, the value of the extended fuse byte will be loaded in the destination register as shown below. see table 21-3 on page 226 for detailed description and mapping of the extended fuse byte. fuse and lock bits that are pr ogrammed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. 20.2.4 reading the signature row from software to read the signature row from software, load the z-pointer with the signature byte address given in table 20-1 on page 221 and set the sigrd and spmen bits in spmcsr. when an lpm instruction is executed wit hin three cpu cycles after the sigrd and spmen bits are set in spmcsr, the signature byte value will be loaded in the de stination register. the sigrd and spmen bits will auto-clear upon completion of reading the signature row lock bits or if no lpm instruction is executed within th ree cpu cycles. when sigrd and spmen are cleared, lpm will work as described in the instruction set manual. note: all other addresses are reserved for future use. bit 76543210 rd (z=0x0002) ???????efb0 table 20-1. signature row addressing signature byte z-pointer address device signature byte 0 0x0000 device signature byte 1 0x0002 device signature byte 2 0x0004 8mhz rc oscillator calibration byte 0x0001 tsoffset - temp sensor offset 0x0005 tsgain - temp sensor gain 0x0007
222 7728g?avr?06/10 attiny87/attiny167 20.2.5 preventing flash corruption during periods of low vcc, the flash program can be corrupted because the supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situations when the voltage is too low. ? first, a regular write sequence to the flash requires a minimum voltage to operate correctly. ? secondly, the cpu itself can execute instructions incorrectly, if the supply voltage for executing instructions is too low. flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. 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 vcc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write opera- tion will be completed provided that the power supply voltage is sufficient. 2. keep the avr core in power-down sleep mode during periods of low vcc. this will prevent the cpu from attempting to decode and execute instructions, effectively pro- tecting the spmcsr register and thus the flash from unintentional writes. 20.2.6 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 20-2 shows the typical pro- gramming time for flash accesses from the cpu. table 20-2. spm programming time symbol min programming ti me max programming time flash write (page erase, page write, and write lock bits by spm) 3.7 ms 4.5 ms
223 7728g?avr?06/10 attiny87/attiny167 20.2.7 simple assembly code example for a boot loader note that the rwwsb bit will always be read as zero in attiny87/167. nevertheless, it is recommended to check this bit as shown in the code example, to ensure compatibility with devices supporting read-while-write. ;- 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 ;- 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 .equ pagesizeb = pagesize*2 ; agesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcsrval, (1< 224 7728g?avr?06/10 attiny87/attiny167 ld r1, y+ cpse r0, r1 rjmp error sbiw loophi:looplo, 1 ; use subi for pagesizeb<=256 brne rdloop ; to ensure compatibility with devices supporting read-while-write ; return to rww section ; verify that rww section is safe to read return: in temp1, spmcsr sbrs temp1, rwwsb ; if rwwsb is set, the rww section is not ready yet ret ; clear temporary page buffer ldi spmcsrval, (1< 225 7728g?avr?06/10 attiny87/attiny167 21. memory programming 21.1 program and data memory lock bits the attiny87/167 provides two lock bits which can be left unprogrammed (?1?) or can be pro- grammed (?0?) to obtain the additional features listed in table 21-2 . the lock bits can only be erased to ?1? with the chip erase command. the attiny87/167 has no separate boot loader section. note: ?1? means unprogrammed, ?0? means programmed. notes: 1. program the fuse bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed 21.2 fuse bits the attiny87/167 has three fuse bytes. table 21-3 , table 21-4 & table 21-5 describe briefly the functionality of all the fuses and how they are mapped into the fuse bytes. the spm instruction is enabled for the whole flash if the selfprgen fuse is programmed (?0?), otherwise it is disabled. table 21-1. lock bit byte (note:) lock bit byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) 5 ? 1 (unprogrammed) 4 ? 1 (unprogrammed) 3 ? 1 (unprogrammed) 2 ? 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) table 21-2. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verifica tion of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1)
226 7728g?avr?06/10 attiny87/attiny167 note that the fuses are read as logical zero, ?0?, if they are programmed. notes: 1. see ?alternate functions of port b? on page 81. for description of rstdisbl fuse. 2. the spien fuse is not accessible in serial programming mode. 3. see ?watchdog timer control register - wdtcr? on page 57. for details. 4. see table 22-5 on page 247 for bodlevel fuse coding. table 21-3. extended fuse byte fuse extended byte bit no description default value ? 7 ? 1 (unprogrammed) ? 6 ? 1 (unprogrammed) ? 5 ? 1 (unprogrammed) ? 4 ? 1 (unprogrammed) ? 3 ? 1 (unprogrammed) ? 2 ? 1 (unprogrammed) ? 1 ? 1 (unprogrammed) selfprgen 0 self programming enable 1 (unprogrammed) table 21-4. fuse high byte fuse high byte bit no de scription default value rstdisbl (1) 7 external reset disable 1 (unprogrammed) dwen 6 debugwire enable 1 (unprogrammed) spien (2) 5 enable serial program and data downloading 0 (programmed, spi programming enabled) wdton (3) 4 watchdog timer always on 1 (unprogrammed) eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) bodlevel2 (4) 2 brown-out detector trigger level 1 (unprogrammed) bodlevel1 (4) 1 brown-out detector trigger level 1 (unprogrammed) bodlevel0 (4) 0 brown-out detector trigger level 1 (unprogrammed)
227 7728g?avr?06/10 attiny87/attiny167 notes: 1. the default value of sut1..0 results in maximum start-up time for the default clock source. see table 4-4 on page 27 for details. 2. the default setting of cksel3..0 results in internal rc oscillator @ 8 mhz. see table 4-3 on page 27 for details. 3. the ckout fuse allows the system clock to be output on portb5. see ?clock output buf- fer? on page 31. for details. 4. see ?system clock prescaler? on page 37. for details. 21.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 programmin g mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuse s are also latched on power-up in normal mode. 21.3 signature bytes all atmel microcontrollers have a three-byte si gnature 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. table 21-5. fuse low byte fuse low byte bit no description default value ckdiv8 (4) 7 divide clock by 8 0 (programmed) ckout (3) 6 clock output 1 (unprogrammed) 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 1 (unprogrammed) (2) cksel0 0 select clock source 0 (programmed) (2) table 21-6. signature bytes device address value signature byte description at t i n y 8 7 0 0x1e indicates manufactured by atmel 1 0x93 indicates 8 kb flash memory 2 0x87 indicates attiny87 device when address 1 contains 0x93 at t i n y 1 6 7 0 0x1e indicates manufactured by atmel 1 0x94 indicates 16 kb flash memory 2 0x87 indicates attiny167 device when address 1 contains 0x94
228 7728g?avr?06/10 attiny87/attiny167 21.4 calibration byte the attiny87/167 has a byte calib ration value for the internal rc oscillator. this byte resides in the high byte of address 0x000 in the signature address space. during reset, this byte is automatically written into the osccal regist er to ensure correct frequency of the calibrated rc oscillator. 21.5 page size 21.6 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 attiny87/167. pulses are assumed to be at least 250 ns unless otherwise noted. 21.6.1 signal names in this section, some pins of the attiny87/167 are referenced by signal names describing their functionality during parallel programming, see figure 21-1 and figure 21-9 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action execut ed when the xtal1 pin is given a positive pulse. the bit coding is shown in figure 21-11 . when pulsing wr or oe , the command loaded determines the action executed. the different commands are shown in figure 21-12 . table 21-7. number of words in a page and no. of pages in the flash device flash size page size pcword no. of pages pcpage pcmsb attiny87 4k words 64 words pc[5:0] 64 pc[11:6] 11 attiny167 8k words 64 words pc[5:0] 128 pc[12:6] 12 table 21-8. number of words in a page and no. of pages in the eeprom device eeprom size page size pcword no. of pages pcpage eeamsb at t i n y 8 7 at t i n y 1 6 7 512 bytes 4 bytes eea[1:0] 128 eea[8:2] 8
229 7728g?avr?06/10 attiny87/attiny167 figure 21-1. parallel programming note: vcc - 0.3v < avcc < vcc + 0.3v, however, avcc should always be within 4.5 - 5.5v table 21-9. pin name mapping signal name in programming mode pin name i/o function wr pb0 i write pulse (active low). xa0 pb1 i xtal1 action bit 0 xa1 / bs2 pb2 i - xtal1 action bit 1 - byte select 2 (?0? selects low byte, ?1? selects 2?nd high byte) pagel / bs1 pb3 i - program memory and eeprom data page load - byte select 1 (?0? selects low byte, ?1? selects high byte) pb4 i xtal1 (clock input) oe pb5 i output enable (active low). rdy / bsy pb6 o 0: device is busy programming, 1: device is ready for new command. +12v pb7 i - reset (active low) - parallel programming mode (+12v). data pa7-pa0 i/o bi-directional data bus (output when oe is low). vcc +4.5 - +5.5v gnd pb0 pb1 pb2 pb3 pa7 - pa0 data reset / pb7 xtal1 / pb4 +12 v xa0 xa1 / bs2 pagel / bs1 wr pb6 rdy / bsy avcc +4.5 - +5.5v oe pb5
230 7728g?avr?06/10 attiny87/attiny167 table 21-10. pin values used to enter programming mode pin symbol value pagel / bs1 prog_enable[3] 0 xa1 / bs2 prog_enable[2] 0 xa0 prog_enable[1] 0 wr prog_enable[0] 0 table 21-11. xa1 and xa0 coding xa1 xa0 action when xtal1 is pulsed 00 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 21-12. command byte bit coding command byte command executed 1000 0000 b chip erase 0100 0000 b write fuse bits 0010 0000 b write lock bits 0001 0000 b write flash 0001 0001 b write eeprom 0000 1000 b read signature bytes and calibration byte 0000 0100 b read fuse and lock bits 0000 0010 b read flash 0000 0011 b read eeprom
231 7728g?avr?06/10 attiny87/attiny167 21.7 parallel programming 21.7.1 enter programming mode the following algorithm puts the devi ce in parallel programming mode: 1. apply 4.5 - 5.5v between vcc and gnd. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 21-10 on page 230 to ?0000 b ? and wait at least 100 ns. 4. apply 11.5 - 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. 5. wait at least 50 s before sending a new command. 21.7.2 considerations for efficient programming the loaded command and address are retained in the device during programming. for effi- cient 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 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) and 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. 21.7.3 chip erase the chip erase will erase 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 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 ?1,0 ?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000 b ?. 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.
232 7728g?avr?06/10 attiny87/attiny167 21.7.4 programming the flash the flash is organized in pages, see table 21-7 on page 228 . when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be programmed simultaneously. the following proc edure describes how to program the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?1,0?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000 b ?. 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 (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?0,1?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 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 ?0,1?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 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 21-3 for signal waveforms) f. repeat b through e until the entire buffer is filled or unt il all data within th e page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages wit hin the flash. this is illustrated in figure 21-2 on page 233 . note that if less than eight bits are required to address words in the page (pagesize < 256), the most sig- nificant bit(s) in the address low byte are used to address the page when performing a page write.
233 7728g?avr?06/10 attiny87/attiny167 g. load address high byte 1. set xa1, xa0 to ?0,0?. this enables address loading. 2. set bs1 to ?1?. this selects high address. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. program page 1. give wr a negative pulse. this starts programming of the entire page of data. rdy/bsy goes low. 2. wait until rdy/bsy goes high (see figure 21-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 ?1,0?. this enables command loading. 2. set data to ?0000 0000 b ?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write signals are reset. figure 21-2. addressing the flash which is organized in pages note: 1. pcpage and pcword are listed in 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
234 7728g?avr?06/10 attiny87/attiny167 figure 21-3. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters refer to the programming description above. 21.7.5 programming the eeprom the eeprom is organi zed in pages, see table 21-8 on page 228 . when programming the eeprom, the program data is latched into a page buffer. this allows one page of data to be programmed simultan eously. the programming algorithm for the eeprom data memory is as follows (refer to ?programming the flash? on page 232 for details on command, address and data loading): a: load command ?0001 0001 b ?. g: load address high byte (0x00 - 0xff). b: load address low byte (0x00 - 0xff). c: load data (0x00 - 0xff). e: latch data (give pagel a positive pulse). k: repeat a through e until the entire buffer is filled. l: program eeprom page 1. set bs1 to ?0?. 2. give wr a negative pulse. this starts pr ogramming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page (see figure 21-4 for signal waveforms). rdy/bsy wr oe reset +12v 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 / bs2 xa0 pagel / bs1 xtal1 xx xx xx abcdebcdegh f
235 7728g?avr?06/10 attiny87/attiny167 figure 21-4. programming the eeprom waveforms 21.7.6 reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 232 for details on command and address loading): 1. a: load command ?0000 0010 b ?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 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?. 21.7.7 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to ?programming the flash? on page 232 for details on command and address loading): 1. a: load command ?0000 0011 b ?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. 21.7.8 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 232 for details on command and data loading): 1. a: load command ?0100 0000 b ?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. 0x11 addr. high addr. low data addr. low data xx rdy/bsy wr oe reset +12v data xa1 / bs2 xa0 pagel / bs1 xtal1 xx agb cebc el k
236 7728g?avr?06/10 attiny87/attiny167 21.7.9 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 232 for details on command and data loading): 1. a: load command ?0100 0000 b ?. 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. 21.7.10 programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to ?programming the flash? on page 232 for details on command and data loading): 1. a: load command ?0100 0000 b ?. 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 ?1?. 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. figure 21-5. programming the fuses waveforms 21.7.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 232 for details on command and data loading): 1. a: load command ?0010 0000 b ?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is pro- grammed (lb1 and lb2 is programmed), it is not possible to re-program the lock bits by any external programming mode. 3. give wr a negative pulse and wait for rdy/bsy to go high. 4. the lock bits can only be cleared by executing chip erase. 0x40 data xx data xa1 / bs2 xa0 pagel / bs1 ac 0x40 data xx ac write fuse low byte write fuse high byte 0x40 data xx ac write extended fuse byte rdy/bsy wr oe reset +12v xtal1
237 7728g?avr?06/10 attiny87/attiny167 21.7.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 232 for details on command loading): 1. a: load command ?0000 0100 b ?. 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?. figure 21-6. mapping between bs1, bs2 and the fuse and lock bits during read 21.7.13 reading the signature bytes the algorithm for reading the signature bytes is as follows (refer to ?programming the flash? on page 232 for details on command and address loading): 1. a: load command ?0000 1000 b ?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 21.7.14 reading the 8 mhz rc oscillator calibration byte the algorithm for reading the 8 mhz rc oscillato r calibration byte is as follows (refer to ?pro- gramming the flash? on page 232 for details on command and address loading): 1. a: load command ?0000 1000 b ?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the 8 mhz rc oscillator ca libration byte can now be read at data. 4. set oe to ?1?. bs2 data 0 1 bs2 extended fuse byte fuse low byte 0 1 fuse high byte lock bits bs1 0 1
238 7728g?avr?06/10 attiny87/attiny167 21.7.15 reading the temperature sensor parameter bytes the algorithm for reading the temperature sensor parameter bytes is as follows (refer to ?pro- gramming the flash? on page 232 for details on command and address loading): 1. a: load command ?0000 1000 b ?. 2. b: load address low byte, 0x0003 or 0x0005. 3. set oe to ?0?, and bs1 to ?1?. the temperature sensor parameter byte can now be read at data. 4. set oe to ?1?. 21.8 serial downloading both the flash and eeprom memory 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 (output). after reset is set low, the programming enable instruction needs to be exe- cuted first before program/erase operations can be executed. note: in table 21-13 , the pin mapping for spi programming is listed. not all parts use the spi pins dedicated for the internal spi interface. figure 21-7. serial programming and verify (note:) note: if the device is clocked by the internal oscillator, it is no need to connect a clock source to the xtal1 pin when programming the eeprom, an auto-erase cycl e is built into the self-timed program- ming operation (in the serial mode only ) and there is no need to first execute the chip erase instruction. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into 0xff. table 21-13. pin mapping serial programming symbol pin name i/o function mosi pa4 i serial data in miso pa2 o serial data out sck pa5 i serial clock vcc +2.7 - +5.5v gnd pa4 pa2 pa5 mosi miso sck reset / pb7
239 7728g?avr?06/10 attiny87/attiny167 depending on cksel fuses, a valid clock must be present. th e minimum low a nd high peri- ods for the serial clock (sck) input are defined as follows: low : > 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz hi gh : > 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz 21.8.1 serial programming algorithm when writing serial data to the attiny87/167, data is clocked on the rising edge of sck. when reading data from the at tiny87/167, data is clocked on the falling edge of sck. see figure 21-7 and figure 21-8 for timing details. to program and verify the attiny87/167 in the serial programming mode, the following sequence is recommended (see four byte instruction formats in table 21-15 on page 240 ): 1. power-up sequence: apply power between vcc and gnd while reset and sck are set to ?0?. in some systems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. 2. wait for at least 20 ms and enable serial programming by sending the programming enable serial instruction to pin mosi. 3. the serial programming instructions will no t work if the communic ation is out of syn- chronization. when in sync. the second byte (0x53), will echo back when issuing the third byte of the programming enable instruction. whether the echo is correct or not, all four bytes of the instruction must be transmitted. if the 0x53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 5 lsb of the address and data together with the load pro- gram memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. the pro- gram memory page is stored by loading the write program memory page instruction with the 6 msb of the address. if polling (rdy/bsy) is not used, the user must wait at least t wd_flash before issuing the next page. (see table 21-14 ) accessing the serial programming interface before the flash write operation completes can result in incor- rect programming. 5. a: the eeprom array is programmed one byte at a time by supplying the address and data together with the appropriate write instructio n. an eeprom memory loca- tion is first automatically erased before new data is written. if polling (rdy/bsy) is not used, the user must wait at least t wd_eeprom before issuing the next byte. (see table 21-14 ) in a chip erased device, no 0xffs in the data file(s) need to be programmed. b: the eeprom array is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 2 lsb of the address and data together with the load eeprom memory page instru ction. the eeprom memory page is stored by loading the write eeprom memory page instruction with the 6 msb of the address. when using eeprom page access only byte locations loaded with the load eeprom memory page in struction is altere d. the remaining locations remain unchanged. if polling (rdy/bsy) is not used, the used must wait at least t wd_eeprom before issuing the next page (see table 21-8 ). in a chip erased device, no 0xff 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.
240 7728g?avr?06/10 attiny87/attiny167 7. at the end of the pr ogramming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. tu r n v c c p o w e r o f f. 21.8.2 serial programming instruction set table 21-15 on page 240 and figure 21-8 on page 242 describes the instruction set table 21-14. minimum wait delay before writing the next flash or eeprom location symbol minimum wait delay t wd_flash 4.5 ms t wd_eeprom 4.0 ms t wd_erase 4.0 ms t wd_fuse 4.5 ms table 21-15. serial programming instruction set instruction/operation instruction format byte 1 byte 2 byte 3 byte4 programming enable 0xac 0x53 0x00 0x00 chip erase (program memory/eeprom) 0xac 0x80 0x00 0x00 poll rdy/bsy 0xf0 0x00 0x00 data byte out load instructions load extended address byte (1) 0x4d 0x00 extended add. 0x00 load program memory page, high byte 0x48 add. msb add. lsb high data byte in load program memory page, low byte 0x40 add. msb add. lsb low data byte in load eeprom memory page (page access) 0xc1 0x00 0000 000aa b data byte in read instructions read program memory, high byte 0x28 add. msb add. lsb high data byte out read program memory, low byte 0x20 add. msb add. lsb low data byte out read eeprom memory 0xa0 0x00 00aa aaaa data byte out read lock bits 0x58 0x00 0x00 data byte out read signature byte 0x30 0x00 0000 000aa data byte out read fuse bits 0x50 0x00 0x00 data byte out read fuse high bits 0x58 0x08 0x00 data byte out read extended fuse bits 0x50 0x08 0x00 data byte out read calibration byte 0x38 0x00 0x00 data byte out write instructions (6) write program memory page 0x4c add. msb add. lsb 0x00
241 7728g?avr?06/10 attiny87/attiny167 notes: 1. not all instructions are applicable for all parts. 2. a = address 3. bits are programmed ?0?, unprogrammed ?1?. 4. to ensure future compatibility, unused fuses and lock bits should be unprogrammed (?1?). 5. refer to the corresponding section for fuse and lock bits, calibration and signature bytes and page size. 6. instructions accessing program memory use a word address. this address may be random within the page range. 7. see http://www.atmel.com/avr for application notes regarding programming and programmers. if the lsb in rdy/bsy data byte out is ?1?, a program ming operation is still pending. wait until this bit returns ?0? before the ne xt instruction is carried out. within the same page, the low data byte must be loaded prior to the high data byte. after data is lo aded to the page buffer, pr ogram the eeprom page, see figure 21-8 on page 242 . write eeprom memory 0xc0 0x00 00aa aaaa b data byte in write eeprom memory page (page access) 0xc2 0x00 00aa aa00 b 0x00 write lock bits 0xac 0xe0 0x00 data byte in write fuse bits 0xac 0xa0 0x00 data byte in write fuse high bits 0xac 0xa8 0x00 data byte in write extended fuse bits 0xac 0xa4 0x00 data byte in table 21-15. serial programming instruction set (continued) instruction/operation instruction format byte 1 byte 2 byte 3 byte4
242 7728g?avr?06/10 attiny87/attiny167 figure 21-8. serial programming instruction example 21.9 serial programming characteristics figure 21-9. serial programming waveforms for characteristics of the spi module, see ?spi timing characteristics? on page 253. byte 1 byte 2 byte 3 byte 4 bit 15 b addr. msb addr. lsb 0 byte 1 byte 2 byte 3 byte 4 bit 15 b addr. msb addr. msb 0 page buffer page number program memory / eeprom memory serial programming instruction page offset load program memory page (high/low byte) / load eeprom memory page (page access) write program memory page / write eeprom memory page page 0 page 1 page 2 page n-1 msb msb lsb lsb serial clock input (sck) serial data input (mosi) (miso) sample serial data output
243 7728g?avr?06/10 attiny87/attiny167 22. electrical characteristics note: all characteristics contained in this data sheet are based on simulation and characterization of attiny87/167 avr microcon - trollers manufactured in a typical process technology. these va lues are preliminary values representing design targets, and wil l be updated after characterization of actual automotive silicon. 22.1 absolute m aximum ratings* notes: 1. maximum current per port = 30ma 2. functional corruption may occur . 22.2 dc characteristics operating temperature.................................? 40c 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 vcc+0.5v voltage on reset with respect to ground.... ? 0.5v to +13.0v voltage on vcc with respect to ground.............. ? 0.5v to 6.0v dc current per i/o pin ............................................... 40.0 ma dc current vcc and gnd pins................................. 200.0 ma injection current at vcc = 0v to 5v (2) ...................... 5.0ma (1) t a = -40c to +125c, vcc = 2.7v to 5.5v (unless otherwise noted) symbol parameter condition min. typ. (1) max. units v il input low voltage except xtal1 and reset pins - 0.5 0.2 vcc (2) v v il1 xtal1 pin - external clock selected - 0.5 0.1 vcc (2) v v il2 reset pin - 0.5 0.2 vcc (2) v v il3 reset pin as i/o - 0.5 0.2 vcc (2) v v ih input high voltage except xtal1 and reset pins 0.7 vcc (3) vcc + 0.5 v v ih1 xtal1 pin - external clock selected 0.8 vcc (3) vcc + 0.5 v v ih2 reset pin 0.9 vcc (3) vcc + 0.5 v v ih3 reset pin as i/o 0.7 vcc (3) vcc + 0.5 v v ol output low voltage (4) (ports a, b,) i ol = 10 ma, vcc = 5v i ol = 5 ma, vcc = 3v 0.6 0.5 v v oh output high voltage (5) (ports a, b) i oh = ? 10 ma, vcc = 5v i oh = ? 5 ma, vcc = 3v 4.3 2.5 v
244 7728g?avr?06/10 attiny87/attiny167 notes: 1. ?typ.", typical values at 25c. maximum values are characterized values and not test limits in production. 2. "max.? means the highest value where the pin is guaranteed to be read as low. 3. ?min.? means the lowest value where the pin is guaranteed to be read as high. 4. although each i/o port can sink more than the test conditions (10 ma at vcc= 5v, 5 ma at vcc = 3v) under steady state con- ditions (non-transient), the following must be observed: - the sum of all iol, for all ports, should not exceed 120 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. 5. although each i/o port can source more than the test conditio ns (10 ma at vcc = 5v, 5 ma at vcc = 3v) under steady state conditions (non-transient), th e following must be observed: - the sum of all ioh, for all ports, should not exceed 120 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. 6. values using methods described in ?minimizing power consumption? on page 45 . power reduction is enabled (prr = 0xff) and there is no i/o drive. 7. bod disabled. i il input leakage current i/o pin vcc = 5.5v, pin low (absolute value) < 0.05 1 a i ih input leakage current i/o pin vcc = 5.5v, pin high (absolute value) < 0.05 1 a r rst reset pull-up resistor 30 60 k r pu i/o pin pull-up resistor 20 50 k i cc power supply current (6) active mode (external clock) 16 mhz, vcc = 5v 10 13 ma 8 mhz, vcc = 5v 5.5 7.0 ma 8 mhz, vcc = 3v 2.8 3.5 ma 4 mhz, vcc = 3v 1.8 2.5 ma power supply current (6) idle mode (external clock) 16 mhz, vcc = 5v 3.5 5.0 ma 8 mhz, vcc = 5v 1.8 2.5 ma 8 mhz, vcc = 3v 1 1.5 ma 4 mhz, vcc = 3v 0.5 0.8 ma power supply current (7) power-down mode wdt enabled, vcc = 5v 7 100 a wdt disabled, vcc = 5v 0.18 70 a wdt enabled, vcc = 3v 5 70 a wdt disabled, vcc = 3v 0.15 45 a v acio analog comparator input offset voltage vcc = 5v v in = vcc/2 -10 10 40 mv i aclk analog comparator input leakage current vcc = 5v v in = vcc/2 -50 50 na t acid analog comparator propagation delay common mode vcc/2 vcc = 2.7v 170 ns vcc = 5.0v 180 ns t a = -40c to +125c, vcc = 2.7v to 5.5v (unless otherwise noted) (continued) symbol parameter condition min. typ. (1) max. units
245 7728g?avr?06/10 attiny87/attiny167 22.3 speed grades figure 22-1. maximum frequency vs. vcc, attiny87/167 22.4 clock characteristics 22.4.1 calibrated internal rc oscillator accuracy 22.4.2 external clock drive waveforms figure 22-2. external clock drive waveforms safe operating area 4.5v 2.7v 5.5v 8 mhz 16 mhz frequency voltage table 22-1. calibration and accuracy of internal rc oscillator frequency vcc temperature accuracy factory calibration 8.0 mhz 3v 25c 2% maximum deviation 8.0 mhz 2.7v ?40c/+125c 10% 5.5v ?40c/+125c 10% v il1 v ih1
246 7728g?avr?06/10 attiny87/attiny167 22.4.3 external clock drive 22.5 reset characteristics note: 1. before rising, the supply has to be between vpormin and vpormax to ensure a reset. table 22-2. external clock drive symbol parameter vcc = 2.7 - 5.5v vcc = 4.5 - 5.5v units min. max. min. max. 1/t clcl oscillator frequency 0 8 0 16 mhz t clcl clock period 125 62.5 ns t chcx high time 50 25 ns t clcx low time 50 25 ns t clch rise time 1.6 0.5 ms t chcl fall time 1.6 0.5 ms t clcl change in period from one clock cycle to the next 22% table 22-3. external reset characteristics symbol parameter condition min typ max units v rst reset pin threshold voltage v cc = 5v 0.1 vcc 0.9 vcc v t rst minimum pulse width on reset pin v cc = 5v 2.5 s v bg bandgap reference voltage v cc = 2.7v, t a =25c 1.0 1.1 1.2 v t bg bandgap reference start-up time v cc = 2.7v, t a =25c 40 70 s i bg bandgap reference current consumption v cc = 2.7v, t a =25c 15 a table 22-4. power on reset characteristics symbol parameter min typ max units v pot power-on reset threshold voltage (rising) 1.4 v power-on reset threshold voltage (falling) (1) 1.0 1.3 1.6 v v pormax vcc max. start voltage to ensure internal power-on reset signal 0.4 v v pormin vcc min. start voltage to ensure internal power-on reset signal ?0.1 v v ccrr vcc rise rate to ensure power-on reset 0.01 v/ms v rst reset pin threshold voltage 0.1 vcc 0.9 vcc v
247 7728g?avr?06/10 attiny87/attiny167 notes: 1. v bot may be below nominal minimum operating voltage for some devices. for devices where this is the case, the devi ce is tested down to vcc = v bot during the production test. this guarantees that a brown-out reset will occur before vcc drops to a voltage where cor- rect operation of the microcontroller is no lo nger guaranteed. the test is performed using bodlevel = 101 for low operating voltage and bodlevel = 100 for high operating voltage. 22.6 internal voltage characteristics table 22-5. bodlevel fuse coding bodlevel 2:0 fuses min. v bot (1) typ. v bot max. v bot units 1 1 1 b bod disabled 1 1 0 b 1.7 1.8 2.0 v 1 0 1 b 2.5 2.7 2.9 1 0 0 b 4.1 4.3 4.5 0 1 1 b reserved 0 1 0 b 0 0 1 b 0 0 0 b table 22-6. brown-out characteristics symbol parameter min. typ. max. units v hyst brown-out detector hysteresis 80 mv t bod min pulse width on brown-out reset 2 s table 22-7. internal voltage refe rence characteristics symbol parameter condition min. typ. max. units v bg bandgap reference voltage vcc = 4.5 t a =25c 1.0 1.1 1.2 v t bg bandgap reference start-up time vcc = 4.5 t a =25c 40 70 s i bg bandgap reference current consumption vcc = 4.5 t a =25c 10 a
248 7728g?avr?06/10 attiny87/attiny167 22.7 current source characteristics 22.8 adc characteristics table 22-8. current source characteristics symbol parameter condition min. typ. max. units i isrc current vcc = 2.7 v / 5.5 v t =-40c / +125c 94 106 a t isrc current source start-up time vcc = 4.5 t a = 25c 60 s table 22-9. adc characteristics, single ended channels (-40c/+125c) symbol parameter condi tion min typ max units resolution single ended conversion 10 bits tue absolute accuracy vcc = 4v, vref = 4v, adc clock = 200 khz 2.0 3.5 lsb inl integral non linearity vcc = 4v, vref = 4v, adc clock = 200 khz 0.6 2.0 lsb dnl differential non linearity vcc = 4v, vref = 4v, adc clock = 200 khz 0.3 0.8 lsb gain error vcc = 4v, vref = 4v, adc clock = 200 khz -6.0 -2.5 2.0 lsb offset error vcc = 4v, vref = 4v, adc clock = 200 khz -3.5 1.5 3.5 lsb v ref ref voltage 2.56 avcc v input bandwidth 38.5 khz v int internal voltage 2.4 2.56 2.7 v r ref reference input resistance 32 k r ain analog input resistance 100 m
249 7728g?avr?06/10 attiny87/attiny167 table 22-10. adc characteristics, differe ntial channels (-40c/+125c) symbol parameter condition min typ max units resolution differential conversion 8 tue absolute accuracy gain = 8x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz 1.0 3.0 lsb gain = 20x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz 1.5 3.5 gain = 8x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz 2.0 4.5 gain = 20x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz 2.0 6.0 inl integral non linearity gain = 8x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.2 1.0 lsb gain = 20x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.4 1.5 gain = 8x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.5 2.0 gain = 20x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz 1.6 5.0 dnl differential non linearity gain = 8x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.3 0.8 lsb gain = 20x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.3 0.8 gain = 8x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.4 0.8 gain = 20x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz 0.6 1.6 gain error gain = 8x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz -3.0 1.0 3.0 lsb gain = 20x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz -4.0 1.5 4.0 gain = 8x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz -5.0 -2.5 0.0 gain = 20x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz -4.0 -0.5 4.0
250 7728g?avr?06/10 attiny87/attiny167 22.9 parallel programmi ng characteristics figure 22-3. parallel programming timing, including some general timing requirements offset error gain = 8x or 20x, bipolar v ref = 4v, vcc = 5v adc clock = 200 khz -2.0 0.5 2.0 lsb gain = 8x or 20x, unipolar v ref = 4v, vcc = 5v adc clock = 200 khz -2.0 0.5 2.0 v ref reference voltage 2.56 avcc - 0.5 v vdiff input differential voltage -vref/gain +vref/gain v avcc analog supply voltage vcc - 0.3 vcc + 0.3 v vin input voltage differential conversion 0 avcc v adc conversion output -511 +511 lsb input bandwidth differential conversion 4 khz vint internal voltage reference 2.4 2.56 2.7 v rref reference input resistance 32 k rain analog input resistance 100 m table 22-10. adc characteristics, differential channels (-40c/+125c) (continued) symbol parameter condition min typ max units rdy/bsy wr data & contol (data, xa0, xa1/bs2, pagel/bs1) xtal1 t xhxl t wlwh t rlrh t dvxh t xldx t plwl t wlrh t plbx t bvph t xlwl t wlbx t bvwl
251 7728g?avr?06/10 attiny87/attiny167 figure 22-4. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 22-3 (i.e., t dvxh , t xhxl , and t xldx ) also apply to loading operation. figure 22-5. parallel programming timing, reading sequence (within the same page) with timing requirements (note:) note: the timing requirements shown in figure 22-3 (i.e., t dvxh , t xhxl , and t xldx ) also apply to read- ing operation. xtal1 xlxh t addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data agel/bs1 xa0 xa1/bs2 load address (low byte) load data (low byte) load data (high byte) load address (low byte) xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data agel/bs1 xa0 xa1/bs2 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bvdv t oldv t xlol t ohdz
252 7728g?avr?06/10 attiny87/attiny167 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. table 22-11. 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 bvph bs1 valid before pagel high 67 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 4.5 ms t wlrh_ce wr low to rdy/bsy high for chip erase (2) 7.5 9 ms t xlol xtal1 low to oe low 0 ns 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
253 7728g?avr?06/10 attiny87/attiny167 22.10 spi timing characteristics see figure 22-6 and figure 22-7 for details. note: in spi programming mode the minimum sck high/low period is: - 2 t clcl for f ck < 12 mhz - 3 t clcl for f ck >12 mhz figure 22-6. spi interface timing requirements (master mode) table 22-12. spi timing parameters description mode min. typ. max. 1 sck period master see table 13-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 t ck 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 mosi (data output) sck (cpol = 1) miso (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 61 22 3 45 8 7
254 7728g?avr?06/10 attiny87/attiny167 figure 22-7. spi interface timing requirements (slave mode) miso (data output) sck (cpol = 1) mosi (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 10 11 11 12 13 14 17 15 9 x 16 18
255 7728g?avr?06/10 attiny87/attiny167 23. decoupling capacitors the operating frequency (i.e. system clock) of the processor determines in 95% of cases the value needed for microcontroller decoupling capacitors. the hypotheses used as first evaluation for decoupling capacitors are: ? the operating frequency ( f op ) supplies itself the maximum peak levels of noise. the main peaks are located at f op and 2 ? f op . ? an smc capacitor connected to 2 micro-vias on a pcb has the following characteristics: ? 1.5 nh from the connection of the capacitor to the pcb, ? 1.5 nh from the capacitor intrinsic inductance. figure 23-1. capacitor description according to the operating frequency of the pr oduct, the decoupling capacitances are chosen considering the frequencies to filter, f op and 2 ? f op . the relation between frequencies to cut and decoupling characteristics are defined by: and where: ? l: the inductance equivalent to the global inductance on the vcc/gnd lines. ?c 1 & c 2 : decoupling capacitors (c 1 = 4 ? c 2 ). then, in normalized value range, the decoupling capacitors become: these decoupling capacitors must to be implem ented as close as possible to each pair of power supply pins: ? 16-17 for logic sub-system, ? 5-6 for analogical sub-system. nevertheless, a bulk capacitor of 10-47 f is also needed on the power distribution network of the pcb, near the power source. for further information, please refer to application notes avr040 ?emc design consider- ations? and avr042 ?hardware design considerations? on the atmel web site. table 23-1. decoupling capacitors vs. frequency f op , operating frequency c 1 c 2 16 mhz 33 nf 10 nf 12 mhz 56 nf 15 nf 10 mhz 82 nf 22 nf 8 mhz 120 nf 33 nf 6 mhz 220 nf 56 nf 4 mhz 560 nf 120 nf pcb capacitor 1.5 nh 0.75 nh 0.75 nh f op 1 2 lc 1 ---------------------- - = 2 f op ? 1 2 lc 2 ---------------------- - =
256 7728g?avr?06/10 attiny87/attiny167 24. typical characteristics the data contained in this section is largely based on simulations and characterization of sim- ilar devices in the same process and design methods. thus, the data should be treated as indications of how th e part will behave. the following charts show typical behavior. these 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 pi ns may be estimated (for one pin) as c l * vcc*f where c l = load capacitance, vcc = operating volt age 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 consumptio n 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. 24.1 active supply current figure 24-1. active supply current vs. low frequency (0.1 - 1.0 mhz) active supply current vs. low frequency prr=0x ff / a td on 0 0.2 0.4 0.6 0.8 1 1.2 1.4 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 frequency (mhz) i cc (ma) 6 5.5 5 4.5 4 3.6 3.3 3 2.7 2.4 2.1 2 1.8 1.6
257 7728g?avr?06/10 attiny87/attiny167 figure 24-2. active supply current vs. frequency ( 1 mhz) figure 24-3. active supply current vs. v cc (internal rc osc illator, 8 mhz) active supply current vs. v cc internal rc oscillator 8mhz (no atd influence) 0 1 2 3 4 5 6 7 8 9 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 150 125 85 25 -40
258 7728g?avr?06/10 attiny87/attiny167 figure 24-4. active supply current vs. v cc (internal rc osc illator, 128 khz) 24.2 idle supply current figure 24-5. idle supply current vs. frequency ( 1 mhz) active supply current vs. v cc internal rc oscillator 128 khz / atd on 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0.2 1.522.533.544.555.5 v cc (v) i cc (ma) 150 125 85 25 -40 idle supply current vs. frequency no power reduction ena bled 0 1 2 3 4 5 6 7 8 9 10 02468101214161820 frequency (mhz) i cc (ma) 6 5.5 5 4.5 4 3.6 3.3 3 2.7 2.4
259 7728g?avr?06/10 attiny87/attiny167 figure 24-6. idle supply current vs. v cc (internal rc osc illator, 8 mhz) figure 24-7. idle supply current vs. v cc (internal rc osc illator, 128 khz) idle supply current vs. v cc interna l rc oscilla tor 8mhz 0 0.5 1 1.5 2 2.5 3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 150 125 85 25 -40 idle supply current vs. v cc interna l rc oscilla tor 125 khz 0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 1.52 2.533.54 4.555.5 v cc (v) i cc (ma) 150 125 85 25 -40
260 7728g?avr?06/10 attiny87/attiny167 24.3 supply current of i/o modules the table below can be used to calculate the additional current consumption for the different i/o modules idle mode. the enabling or disabling of the i/o modules are controlled by the power reduction register. see section 5.9.3 ?prr ? power reduction register? on page 47 for details. 24.4 power-down supply current figure 24-8. power-down supply current vs. v cc (watchdog timer disabled) table 24-1. additional current consumption for the different i/o modules (absolute values) module vcc = 5.0 v freq. = 16 mhz vcc = 5.0 v freq. = 8 mhz vcc = 3.0 v freq. = 8 mhz vcc = 3.0 v freq. = 4 mhz units lin/uart 0.77 0.37 0.20 0.10 ma spi 0.31 0.14 0.08 0.04 ma timer-1 0.28 0.13 0.08 0.04 ma timer-0 0.41 0.20 0.10 0.05 ma usi 0.14 0.05 0.04 0.02 ma adc 0.48 0.22 0.10 0.05 ma power-down supply current vs. v cc wa tchdog timer disa bled 0 5 10 15 20 25 30 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 150 125 85 25 -40
261 7728g?avr?06/10 attiny87/attiny167 figure 24-9. power-down supply current vs. v cc (watchdog timer enabled) 24.5 pin pull-up figure 24-10. i/o pin pull-up resistor current vs. input voltage (v cc = 2.7v) power-down supply current vs. v cc wa tchdog timer ena bled 0 5 10 15 20 25 30 35 40 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 150 125 85 25 -40 i/o pin pull-up resistor current vs. input voltage vcc = 2.7 v -10 0 10 20 30 40 50 60 70 80 90 0 0.5 1 1.5 2 2.5 3 v op (v) i op (ua) 150 125 85 25 -40
262 7728g?avr?06/10 attiny87/attiny167 figure 24-11. i/o pin pull-up resistor current vs. input voltage (v cc = 5v) figure 24-12. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 2.7v) i/o pin pull-up resistor current vs. input voltage vcc = 5.0 v -20 0 20 40 60 80 100 120 140 160 0123456 v op (v) i op (ua) 150 125 85 25 -40 reset pull-up resistor current vs. reset pin voltage vcc = 2.7 v -10 0 10 20 30 40 50 60 70 00.511.522.53 v reset (v) i reset (ua) 150 125 85 25 -40
263 7728g?avr?06/10 attiny87/attiny167 figure 24-13. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 5v) 24.6 pin driver strength figure 24-14. i/o pin output voltage vs. sink current (v cc = 3v) reset pull-up resistor current vs. reset pin voltage vcc = 5.0 v -20 0 20 40 60 80 100 120 01 234 56 v reset (v) i reset (ua) 150 125 85 25 -40 i/o pin output voltage vs. sink current vcc = 3.0 v 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 0 2 4 6 8 1012141618 i ol (ma) v ol (v) 150 125 85 25 -40
264 7728g?avr?06/10 attiny87/attiny167 figure 24-15. i/o pin output voltage vs. sink current (v cc = 5v) figure 24-16. i/o pin output voltage vs. source current (v cc = 3v) i/o pin output voltage vs. sink current vcc = 5.0v 0 0.2 0.4 0.6 0.8 1 1.2 0 5 10 15 20 25 i ol (ma) v ol (v) 150 125 85 25 -40 i/o pin output voltage vs. source current vcc = 3.0 v 0 0.5 1 1.5 2 2.5 3 0 2 4 6 8 101214161820 i oh (ma) v oh (v) 150 125 85 25 -40
265 7728g?avr?06/10 attiny87/attiny167 figure 24-17. i/o pin output voltage vs. source current (v cc = 5v) 24.7 internal oscillator speed figure 24-18. calibrated 8.0 mhz rc osc illator frequency vs. vcc i/o pin output voltage vs. source current vcc = 5.0 v 3.7 3.9 4.1 4.3 4.5 4.7 4.9 5.1 0 2 4 6 8 101214161820 i oh (ma) v oh (v) 150 125 85 25 -40
266 7728g?avr?06/10 attiny87/attiny167 figure 24-19. calibrated 8.0 mhz rc oscillator frequency vs. osccal value 24.8 current consumption in reset figure 24-20. reset supply current vs. vcc, frequencies 0.1 - 1.0 mhz (excluding currentthrough the reset pull-up) reset supply current vs. v cc excluding current through the reset pullup 0 0.05 0.1 0.15 0.2 0.25 0.3 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 frequency (mhz) i cc (ma) 6 5.5 5 4.5 4 3.6 3.3 3 2.7 2.4 2.1 2 1.8 1.6
267 7728g?avr?06/10 attiny87/attiny167 figure 24-21. reset supply current vs. vcc, frequencies 1 mhz (excluding current through the reset pull-up) reset supply current vs. v cc excluding current through the reset pullup 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 0 2 4 6 8 101214161820 frequency (mhz) i cc (ma) 6 5.5 5 4.5 4 3.6 3.3 3 2.7 2.4 2.1 2 1.8 1.6
268 7728g?avr?06/10 attiny87/attiny167 25. register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page (0xff) reserved (0xfe) reserved (0xfd) reserved (0xfc) reserved (0xfb) reserved (0xfa) reserved (0xf9) reserved (0xf8) reserved (0xf7) reserved (0xf6) reserved (0xf5) reserved (0xf4) reserved (0xf3) reserved (0xf2) reserved (0xf1) reserved (0xf0) reserved (0xef) reserved (0xee) reserved (0xed) reserved (0xec) reserved (0xeb) reserved (0xea) reserved (0xe9) reserved (0xe8) reserved (0xe7) reserved (0xe6) reserved (0xe5) reserved (0xe4) reserved (0xe3) reserved (0xe2) reserved (0xe1) reserved (0xe0) reserved (0xdf) reserved (0xde) reserved (0xdd) reserved (0xdc) reserved (0xdb) reserved (0xda) reserved (0xd9) reserved (0xd8) reserved (0xd7) reserved (0xd6) reserved (0xd5) reserved (0xd4) reserved (0xd3) reserved (0xd2) lindat ldata7 ldata6 ldata5 ldata4 ldata3 ldata2 ldata1 ldata0 page 186 (0xd1) linsel ? ? ? ? /lainc lindx2 lindx1 lindx0 page 186 (0xd0) linidr lp1 lp0 lid5 / ldl1 lid4 / ldl0 lid3 lid2 lid1 lid0 page 186 (0xcf) lindlr ltxdl3 ltxdl2 ltxdl1 ltxdl0 lrxdl3 lrxdl2 lrxdl1 lrxdl0 page 185 (0xce) linbrrh ? ? ? ? ldiv11 ldiv10 ldiv9 ldiv8 page 185 (0xcd) linbrrl ldiv7 ldiv6 ldiv5 ldiv4 ldiv3 ldiv2 ldiv1 ldiv0 page 185 (0xcc) linbtr ldisr ? lbt5 lbt4 lbt3 lbt2 lbt1 lbt0 page 184 (0xcb) linerr labort ltoerr loverr lferr lserr lperr lcerr lberr page 183 (0xca) linenir ? ? ? ? lenerr lenidok lentxok lenrxok page 183 (0xc9) linsir lidst2 lidst1 lidst0 lbus y lerr lidok ltxok lrxok page 182 (0xc8) lincr lswres lin13 lconf1 lconf0 lena lcmd2 lcmd1 lcmd0 page 181 (0xc7) reserved (0xc6) reserved (0xc5) reserved (0xc4) reserved (0xc3) reserved (0xc2) reserved (0xc1) reserved (0xc0) reserved (0xbf) reserved
269 7728g?avr?06/10 attiny87/attiny167 (0xbe) reserved (0xbd) reserved (0xbc) usipp usipos page 161 (0xbb) usibr usib7 usib6 usib5 usib4 usib3 usib2 usib1 usib0 page 157 (0xba) usidr usid7 usid6 usid5 usid4 usid3 usid2 usid1 usid0 page 156 (0xb9) usisr usisif usioif usipf usidc usicnt3 usicnt2 usicnt1 usicnt0 page 157 (0xb8) usicr usisie usioie usiwm1 usiwm0 u sics1 usics0 usiclk usitc page 158 (0xb7) reserved (0xb6) assr ? exclk as0 tcn0ub ocr0aub ? tcr0aub tcr0bub page 103 (0xb5) reserved (0xb4) reserved (0xb3) reserved (0xb2) reserved (0xb1) reserved (0xb0) reserved (0xaf) reserved (0xae) reserved (0xad) reserved (0xac) reserved (0xab) reserved (0xaa) reserved (0xa9) reserved (0xa8) reserved (0xa7) reserved (0xa6) reserved (0xa5) reserved (0xa4) reserved (0xa3) reserved (0xa2) reserved (0xa1) reserved (0xa0) reserved (0x9f) reserved (0x9e) reserved (0x9d) reserved (0x9c) reserved (0x9b) reserved (0x9a) reserved (0x99) reserved (0x98) reserved (0x97) reserved (0x96) reserved (0x95) reserved (0x94) reserved (0x93) reserved (0x92) reserved (0x91) reserved (0x90) reserved (0x8f) reserved (0x8e) reserved (0x8d) reserved (0x8c) reserved (0x8b) ocr1bh ocr1b15 ocr1b14 ocr1b13 ocr1b1 2 ocr1b11 ocr1b10 ocr1b9 ocr1b8 page 137 (0x8a) ocr1bl ocr1b7 ocr1b6 ocr1b5 ocr1b4 ocr1b3 ocr1b2 ocr1b1 ocr1b0 page 137 (0x89) ocr1ah ocr1a15 ocr1a14 ocr1a13 ocr1a1 2 ocr1a11 ocr1a10 ocr1a9 ocr1a8 page 137 (0x88) ocr1al ocr1a7 ocr1a6 ocr1a5 ocr1a4 ocr1a3 ocr1a2 ocr1a1 ocr1a0 page 137 (0x87) icr1h icr115 icr114 icr113 icr112 icr111 icr110 icr19 icr18 page 138 (0x86) icr1l icr17 icr16 icr15 icr14 icr13 icr12 icr11 icr10 page 138 (0x85) tcnt1h tcnt115 tcnt114 tcnt113 tcnt112 tcnt111 tcnt110 tcnt19 tcnt18 page 137 (0x84) tcnt1l tcnt17 tcnt16 tcnt15 tcnt14 tcnt13 tcnt12 tcnt11 tcnt10 page 137 (0x83) tccr1d oc1bx oc1bw oc1bv oc1bu oc1ax oc1aw oc1av oc1au page 136 (0x82) tccr1c foc1a foc1b ? ? ? ? ? ? page 136 (0x81) tccr1b icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 page 135 (0x80) tccr1a com1a1 com1a0 com1b1 com1b0 ? ?wgm11wgm10 page 132 (0x7f) didr1 ? adc10d adc9d adc8d ? ? ? ? page 210 (0x7e) didr0 adc7d/ain1d adc6d/ain0d adc5d adc4d adc3d adc2d adc1d adc0d page 209 , page 213 (0x7d) reserved address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
270 7728g?avr?06/10 attiny87/attiny167 (0x7c) admux refs1 refs0 adlar mux 4 mux3 mux2 mux1 mux0 page 205 (0x7b) adcsrb bin acme acir1 acir0 ? adts2 adts1 adts0 page 209 , page 211 (0x7a) adcsra aden adsc adate adif adie adps2 adps1 adps0 page 207 (0x79) adch - / adc9 - / adc8 - / adc7 - / adc6 - / adc5 - / adc4 adc9 / adc3 adc8 / adc2 page 208 (0x78) adcl adc7 / adc1 adc6 / adc0 adc5 / - adc4 / - adc3 / - adc2 / - adc1 / - adc0 / page 208 (0x77) amiscr ? ? ? ? ? arefen xrefen isrcen page 190 , page 190 (0x76) reserved (0x75) reserved (0x74) reserved (0x73) reserved (0x72) reserved (0x71) reserved (0x70) reserved (0x6f) timsk1 ? ?icie1 ? ? ocie1b ocie1a toie1 page 138 (0x6e) timsk0 ? ? ? ? ? ? ocie0a toie0 page 105 (0x6d) reserved (0x6c) pcmsk1 pcint15 pcint14 pcint13 pcint12 pcint11 pcint10 pcint9 pcint8 page 65 (0x6b) pcmsk0 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 page 66 (0x6a) reserved (0x69) eicra ? ? ? ?isc11isc10isc01isc00 page 63 (0x68) pcicr ? ? ? ? ? ? pcie1 pcie0 page 64 (0x67) reserved (0x66) osccal cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 page 37 (0x65) reserved (0x64) prr ? ? prlin prspi prtim1 prtim0 prusi pradc page 47 (0x63) clkselr ? cout csut1 csut0 csel3 csel2 csel1 csel0 page 40 (0x62) clkcsr clkcce ? ? clkrdy clkc3 clkc2 clkc1 clkc0 page 38 (0x61) clkpr clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 page 38 (0x60) wdtcr wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 page 57 0x3f (0x5f) sreg ithsvnz c page 9 0x3e (0x5e) sph sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 page 11 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 page 11 0x3c (0x5c) reserved 0x3b (0x5b) reserved 0x3a (0x5a) reserved 0x39 (0x59) reserved 0x38 (0x58) reserved 0x37 (0x57) spmcsr ? rwwsb sigrd ctpb rflb pgwrt pgers spmen page 219 0x36 (0x56) reserved ? ? ? ? ? ? ? ? 0x35 (0x55) mcucr ?bodsbodsepud ? ? ? ? page 46 , page 75 0x34 (0x54) mcusr ? ? ? ? wdrf borf extrf porf page 52 0x33 (0x53) smcr ? ? ? ? ?sm1sm0se page 46 0x32 (0x52) reserved 0x31 (0x51) dwdr dwdr7 dwdr6 dwdr5 dwdr4 dwdr3 dwdr2 dwdr1 dwdr0 page 216 0x30 (0x50) acsr acd acirs aco aci acie acic acis1 acis0 page 212 0x2f (0x4f) reserved 0x2e (0x4e) spdr spd7 spd6 spd5 spd4 spd3 spd2 spd1 spd0 page 147 0x2d (0x4d) spsr spif wcol ? ? ? ? ?spi2x page 147 0x2c (0x4c) spcr spie spe dord mstr cpol cpha spr1 spr0 page 145 0x2b (0x4b) gpior2 gpior27 gpior26 gpior25 gpior24 gpior23 gpior22 gpior21 gpior20 page 23 0x2a (0x4a) gpior1 gpior17 gpior16 gpior15 gpior14 gpior13 gpior12 gpior11 gpior10 page 23 0x29 (0x49) reserved 0x28 (0x48) ocr0a ocr0a7 ocr0a6 ocr0a5 ocr0a4 ocr0a3 ocr0a2 ocr0a1 ocr0a0 page 103 0x27 (0x47) tcnt0 tcnt07 tcnt06 tcnt05 tcnt04 tcnt03 tcnt02 tcnt01 tcnt00 page 103 0x26 (0x46) tccr0b foc0a ? ? ? ? cs02 cs01 cs00 page 102 0x25 (0x45) tccr0a com0a1 com0a0 ? ? ? ?wgm01wgm00 page 100 0x24 (0x44) reserved 0x23 (0x43) gtccr tsm ? ? ? ? ? psr0 psr1 page 106 , page 109 0x22 (0x42) eearh (1) ? ? ? ? ? ? ?eear8 page 21 0x21 (0x41) eearl eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 page 21 0x20 (0x40) eedr eedr7 eedr6 eedr5 eedr4 eedr3 eedr2 eedr1 eedr0 page 22 0x1f (0x3f) eecr ? ? eepm1 eepm0 eerie eempe eepe eere page 22 0x1e (0x3e) gpior0 gpior07 gpior06 gpior05 gpior04 gpior03 gpior02 gpior01 gpior00 page 23 0x1d (0x3d) eimsk ? ? ? ? ? ?int1int0 page 63 0x1c (0x3c) eifr ? ? ? ? ? ? intf1 intf0 page 64 0x1b (0x3b) pcifr ? ? ? ? ? ? pcif1 pcif0 page 65 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
271 7728g?avr?06/10 attiny87/attiny167 notes: 1. address bits exceeding eeamsb ( table 21-8 on page 228 ) are don?t care. 2. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. 3. i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be ch ecked by using the sbis and sbic instructions. 4. some of the status flags are cleared by writing a logical o ne to them. note that, unlike most other avrs, the cbi and sbi instructions will only operate on the specif ied bit, and can therefore be used on regi sters containing such status flags. the cbi and sbi instructions work wit h registers 0x00 to 0x1f only. 5. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 mu st be added to these addresses. the attiny87/167 is a com- plex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x 60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. 0x1a (0x3a) reserved 0x19 (0x39) reserved 0x18 (0x38) reserved 0x17 (0x37) reserved 0x16 (0x36) tifr1 ? ?icf1 ? ? ocf1b ocf1a tov1 page 139 0x15 (0x35) tifr0 ? ? ? ? ? ?ocf0atov0 page 105 0x14 (0x34) reserved 0x13 (0x33) reserved 0x12 (0x32) portcr ? ? bbmb bbma ? ? pudb puda page 75 0x11 (0x31) reserved 0x10 (0x30) reserved 0x0f (0x2f) reserved 0x0e (0x2e) reserved 0x0d (0x2d) reserved 0x0c (0x2c) reserved 0x0b (0x2b) reserved 0x0a (0x2a) reserved 0x09 (0x29) reserved 0x08 (0x28) reserved 0x07 (0x27) reserved 0x06 (0x26) reserved 0x05 (0x25) portb portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 page 86 0x04 (0x24) ddrb ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 page 86 0x03 (0x23) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 page 86 0x02 (0x22) porta porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 page 86 0x01 (0x21) ddra dda7 dda6 dda5 dda4 dda3 dda2 dda1 dda0 page 86 0x00 (0x20) pina pina7 pina6 pina5 pina4 pina3 pina2 pina1 pina0 page 86 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
272 7728g?avr?06/10 attiny87/attiny167 26. instruction set summary mnemonics operands description operation flags #clock 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 0xff ? rd z,c,n,v 1 neg rd two?s complement rd 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd rd ? (0xff - k) z,n,v 1 inc rd increment rd rd + 1 z,n,v 1 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 0xff none 1 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 regi ster is set if (rr(b)=1) pc pc + 2 or 3 none 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 none 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 none 1/2/3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 none 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 none 1/2 breq k branch if equal if (z = 1) then pc pc + k + 1 none 1/2 brne k branch if not equal if (z = 0) then pc pc + k + 1 none 1/2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 none 1/2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 none 1/2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 none 1/2 brlo k branch if lower if (c = 1) then pc pc + k + 1 none 1/2 brmi k branch if minus if (n = 1) then pc pc + k + 1 none 1/2 brpl k branch if plus if (n = 0) then pc pc + k + 1 none 1/2 brge k branch if greater or equal, signed if (n v= 0) then pc pc + k + 1 none 1/2 brlt k branch if less than zero, signed if (n v= 1) then pc pc + k + 1 none 1/2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 none 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 none 1/2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 none 1/2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 none 1/2 brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 none 1/2 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 none 1/2 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 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
273 7728g?avr?06/10 attiny87/attiny167 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 zero flag z 0 z 1 sei global interrupt enable i 1i1 cli global interrupt disable i 0 i 1 ses set signed test flag s 1s1 cls clear signed test flag s 0 s 1 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 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 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 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 mnemonics operands description operation flags #clock
274 7728g?avr?06/10 attiny87/attiny167 27. ordering information notes: 1. green and rohs packaging. 2. tape and reel with dry-pack delivery. 3. current revision is revision e, previous revision d part number are attiny87-15sz, attiny87-15mz, attiny87-15-xz and attiny167-15mz, attiny167-15mz, attiny167-15xz 28. packaging information ordering code (3) speed (mhz) power supply (v) package (1)(2) operation range attiny87-a15sz 16 2.7 - 5.5 tg ?40 to +125c attiny87-a15mz pn attiny87-a15xz 6g attiny167-a15sz 16 2.7 - 5.5 tg ?40 to +125c attiny167-a15mz pn ATTINY167-A15XZ 6g package type tg 20-pin, 0.300? wide, plastic gull-wing small outline (eiaj soic) pn 32-pad, quad flat no lead (qfn) 6g 20-pin, 4.5 mm wide, thin shrink small outline package (tssop)
275 7728g?avr?06/10 attiny87/attiny167 28.1 soic20
276 7728g?avr?06/10 attiny87/attiny167 28.2 qfn32
277 7728g?avr?06/10 attiny87/attiny167 28.3 tssop20
278 7728g?avr?06/10 attiny87/attiny167 29. errata 29.1 errata summary 29.1.1 attiny87/167 revc ? gain control of the crystal oscillator. ? ?disable clock source ? command remains enabled. 29.1.2 attiny87/167 revb (date code >1208) ? gain control of the crystal oscillator. ?? disable clock source ? command remains enabled. ? lin break delimiter. 29.1.3 attiny167 reva (date code >1207) ? crc calculation of diagnostic frames in lin 2.x. ? gain control of the crystal oscillator. ?? disable clock source ? command remains enabled. ? comparison between adc inputs and voltage references. ? register bits of didr1. ? lin break delimiter. 29.2 errata description 1. crc calculation of diagnostic frames in lin 2.x. diagnostic frames of lin 2.x use ?classic checksum? calculation. unfortunately, the setting of the checksum model is enabled when the h eader is transmitted/received. usually, in lin 2.x the lin/uart controller is initialized to process ?enhanced checksums? and a slave task does not know what kind of fram e it will work on before checking the id. problem fix / workaround. this workaround is to be implemented only in case of transmission/reception of diagnostic frames. a. slave task of master node: before enabling the header, the master must set the appropriate lin13 bit value in lincr register. b. for slaves nodes, the workaround is in 2 parts: ? before enabling the response, use the following function: void lin_wa_head( void ) { unsigned char temp; temp = linbtr; lincr = 0x00 ; // it is not a reset ! linbtr = ( 1 < 279 7728g?avr?06/10 attiny87/attiny167 ? once the response is received or sent (having rxok or txok as well as lerr), use the following function: void lin_wa_tail( void ) { lincr = 0x00 ; // it is not a reset ! linbtr = 0x00 ; lincr = ( 0 < 16 mhz) doesn ?t latch its gain control (cksel/csel[2..0] bits): a. the ? recover system clock source ? command doesn?t returns csel[2..0] bits. b. the gain control ca n be modified on the fly if clkselr changes. problem fix / workaround . a. no workaround. b. as soon as possible, afte r any clkselr modification, re-w rite the appropriate crystal oscillator setting (csel[3]=1 and csel [2..0] / csut[1..0] bits) in clkselr. code example: ; select crystal oscillator ( 16mhz crystal, fast rising power) ldi temp1,(( 0x0f < workaround ... sts clkselr, temp1 ; ...
280 7728g?avr?06/10 attiny87/attiny167 3. ? disable clock source ? command remains enabled. in the dynamic clock switch module, the ? disable clock source ? command remains run- ning after disabling the targeted clock source (the clock source is set in the clkselr register). problem fix / workaround. after a ? disable clock source ? command, reset the clkcsr register writing 0x80. code example: ; select crystal oscillator ldi temp1,( 0x0f < workaround ... sts clkcsr,temp2 4. comparison between adc inputs and voltage references. in the analog comparator module, comparing any adc input (adc[10..0]) with voltage references (2.56v, 1.28v, 1.10v, 0.64v or 0.32v) fails. regardless , ain1 input can be compared with the voltage references and any adc input can be compared with ain0 input. problem fix / workaround. do not use this configuration. 5. register bits of didr1. adc8d, adc9d and adc10d (digital input dis able) initially located at bit 4 up to 6 are instead located at bit 0 up to 2. these register bits are also in write only mode. problem fix / workaround. allow for the change in bit locations and the access mode restriction.
281 7728g?avr?06/10 attiny87/attiny167 6. lin break delimitter in slave mode, a break fiel d detection error can occur under fo llowing conditions. the problem occurs if 2 conditions occur simultaneously: a. the dominant part of the break is (n+0.5)*tbit long wit h n=13, 14,15, ... b. the recessive part of the break (br eak delimiter) is equal to 1*tbit. (see note below) the break_high is not detected, and the 2nd bit of the sync field is interpreted as the break delimiter. the error is detected as a framing error on the first bits of the pid or on subsequent data or a checksum error. there is no error if break_high is greater than 1*tbit + 18%. there is no problem in master mode. note: lin2.1 protocol specification paragraph 2.3.1. 1 break field says: ?a break field is always gener- ated by the master task(in the master node) an d it shall be at least 13 nominal bit times of dominant value, followed by a break delimiter, as shown in figure 29-1 . the break delimiter shall be at least one nominal bit time long. ? figure 29-1. the break field workaround none fr a me bre a k protected identifier field bre a k field d a t a 1 inter- b yte s p a ce inter- b yte s p a ce bre a k delimiter d a t a 2d a t a n check su m s ync field he a der re s pon s e re s pon s e s p a ce
282 7728g?avr?06/10 attiny87/attiny167 30. revision history please note that the referring page numbers in this section are referring to this document. the referring revision in this section are referring to the document revision. 30.1 changes from 7728f - 05/10 to 7728g 06/10 1. power on reset values updated 30.2 changes from 7728e - 04/10 to 7728f 05/10 1. clock characteristics updated 30.3 changes from 7728d - 07/09 to 7728e 04/10 1. ordering information with new part nu mbers for silicon revision d updated 2. errata updated 3. revision history updated 30.4 changes from 7728c - 05/09 to 7728d 07/09 1. isrc updated 2. brown-out updated 3. analog comparator updated 4. temperature sensor updated 30.5 changes from 7728b - 04/09 to 7728c 05/09 1. attiny87 devices added. 2. updated ?adc characteristics? on page 248 . 3. updated adc parameter. 30.6 changes from 7728a - 07/08 to 7728b 04/09 1. added attiny87 specification ( table 1-1 on page 2 , table 3-1 on page 15 , table 7-1 on page 59 , table 21-6 on page 227 , table 21-7 on page 228 , table 21-8 on page 228 and ?ordering information? on page 274 ). 2. updated figure 18-1 on page 211 and table 18-3 on page 214 in analog comparator chapter. 3. updated didr1 register on page 210 and in register summary paragraph. 4. updated ?errata? on page 278 . 30.7 document creation revision: 7728a - 07/08
7728g?avr?06/10 headquarters international atmel corporation 2325 orchard parkway san jose, ca 95131 usa tel: 1(408) 441-0311 fax: 1(408) 487-2600 atmel asia unit 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 europe le krebs 8, rue jean-pierre timbaud bp 309 78054 saint-quentin-en-yvelines cedex france tel: (33) 1-30-60-70-00 fax: (33) 1-30-60-71-11 atmel japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel: (81) 3-3523-3551 fax: (81) 3-3523-7581 product contact web site www.atmel.com technical support avr@atmel.com sales contact www.atmel.com/contacts literature requests www.atmel.com/literature disclaimer: the information in this document is provided in connection with atmel products. no license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in atmel?s terms and condi- tions of sale located on atmel?s web site, atmel assumes no li ability whatsoever and disclaims any express, implied or statutor y warranty relating to its products including, but not limited to, the implied warranty of merchantability, fitness for a particu lar purpose, or non-infringement. in no event shall atmel be liable for any direct, indirect, consequential, punitive, special or i nciden- tal damages (including, without limitation, damages for loss of profits, business interruption, or loss of information) arising out of the use or inability to use this document, even if atme l has been advised of the possibility of such damages. atmel makes no representations or warranties with respect to the accuracy or comp leteness of the contents of this document and reserves the rig ht to make changes to specifications and product descriptions at any time without notice. atmel does not make any commitment to update the information contained her ein. unless specifically provided otherwise, atmel products are not suitable for, and shall not be used in, automotive applications. atmel?s products are not int ended, authorized, or warranted for use as components in applications in tended to support or sustain life. ? 2010 atmel corporation. all rights reserved. atmel ? , atmel logo and combinations thereof, avr ? , avr ? logo, avr studio ? and others are reg- istered trademarks or trademarks of atmel corporation or its subsidiaries. other terms and product names may be trademarks of o thers.


▲Up To Search▲   

 
Price & Availability of ATTINY167-A15XZ

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]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X