ATMEGA8 ATMEL
Document overview
- Manufacturer or author: Provided By digicamel.com
- PDF pages: 331
Technical content
Features
- High-performance, Low-power Atmel®AVR® 8-bit Microcontroller Advanced RISC Architecture – 130 Powerful Instructions – Most Single-clock Cycle Execution – 32 × 8 General Purpose Working Registers – Fully Static Operation – Up to 16MIPS Throughput at 16MHz – On-chip 2-cycle Multiplier High Endurance Non-volatile Memory segments – 8Kbytes of In-System Self-pro grammable Flash program memory – 512Bytes EEPROM – 1Kbyte Internal SRAM – Write/Erase Cycles: 10,000 Flash/100,000 EEPROM – Data retention: 20 years at 85°C/100 years at 25°C (1) – Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation – Programming Lock for Software Security Peripheral Features – Two 8-bit Timer/Counters with Se parate Prescaler, one Compare Mode – One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode – Real Time Counter with Separate Oscillator – Three PWM Channels – 8-channel ADC in TQFP and QFN/MLF package Eight Channels 10-bit Accuracy – 6-channel ADC in PDIP package Six Channels 10-bit Accuracy – Byte-oriented Two-wi re Serial Interface – Programmable Serial USART – Master/Slave SPI Serial Interface – Programmable Watchdog Timer with Separate On-chip Oscillator – On-chip Analog Comparator Special Microcontroller Features – Power-on Reset and Programmable Brown-out Detection – Internal Calibrated RC Oscillator – External and Internal Interrupt Sources – Five Sleep Modes: Idle, ADC Noise Re duction, Power-save, Power-down, and Standby I/O and Packages – 23 Programmable I/O Lines – 28-lead PDIP, 32-lead TQFP, and 32-pad QFN/MLF Operating Voltages – 2.7V - 5.5V (ATmega8L) – 4.5V - 5.5V (ATmega8) Speed Grades – 0 - 8MHz (ATmega8L) – 0 - 16MHz (ATmega8) Power Consumption at 4Mhz, 3V, 25C – Active: 3.6mA – Idle Mode: 1.0mA – Power-down Mode: 0.5µA 8-bit Atmel with 8KBytes In- System Programmable Flash ATmega8 ATmega8L Rev.2486AA–AVR–02/2013
2486AA–AVR–02/2013 ATmega8(L) Pin Configurations (INT1) PD3 (XCK/T0) PD4 GND VCC GND VCC (XTAL1/TOSC1) PB6 (XTAL2/TOSC2) PB7 PC1 (ADC1) PC0 (ADC0) ADC7 GND AREF ADC6 AVCC PB5 (SCK) (T1) PD5 (AIN0) PD6 (AIN1) PD7 (ICP1) PB0 (OC1A) PB1 (SS/OC1B) PB2 (MOSI/OC2) PB3 (MISO) PB4 PD2 (INT0) PD1 (TXD) PD0 (RXD) PC6 (RESET) PC5 (ADC5/SCL) PC4 (ADC4/SDA) PC3 (ADC3) PC2 (ADC2) TQFP Top View (RESET) PC6 (RXD) PD0 (TXD) PD1 (INT0) PD2 (INT1) PD3 (XCK/T0) PD4 VCC GND (XTAL1/TOSC1) PB6 (XTAL2/TOSC2) PB7 (T1) PD5 (AIN0) PD6 (AIN1) PD7 (ICP1) PB0 PC5 (ADC5/SCL) PC4 (ADC4/SDA) PC3 (ADC3) PC2 (ADC2) PC1 (ADC1) PC0 (ADC0) GND AREF AVCC PB5 (SCK) PB4 (MISO) PB3 (MOSI/OC2) PB2 (SS/OC1B) PB1 (OC1A) PDIP MLF Top View (INT1) PD3 (XCK/T0) PD4 GND VCC GND VCC (XTAL1/TOSC1) PB6 (XTAL2/TOSC2) PB7 PC1 (ADC1) PC0 (ADC0) ADC7 GND AREF ADC6 AVCC PB5 (SCK) (T1) PD5 (AIN0) PD6 (AIN1) PD7 (ICP1) PB0 (OC1A) PB1 (SS/OC1B) PB2 (MOSI/OC2) PB3 (MISO) PB4 PD2 (INT0) PD1 (TXD) PD0 (RXD) PC6 (RESET) PC5 (ADC5/SCL) PC4 (ADC4/SDA) PC3 (ADC3) PC2 (ADC2) NOTE: The large center pad underneath the MLF packages is made of metal and internally connected to GND. It should be soldered or glued to the PCB to ensure good mechanical stability. If the center pad is left unconneted, the package might loosen from the PCB.
2486AA–AVR–02/2013 ATmega8(L) Overview The Atmel®AVR® ATmega8 is a low-power CMOS 8-bit microcontroller based on the AVR RISC architecture. By executing powerf ul instructions in a single clock cycle, the ATmega8 achieves throughputs approaching 1MIPS per MHz, allowing the system designer to optimize power con- sumption versus processing speed. Block Diagram Figure 1. Block Diagram INTERNAL OSCILLATOR OSCILLATOR WATCHDOG TIMER MCU CTRL. & TIMING OSCILLATOR TIMERS/ COUNTERS INTERRUPT UNIT STACK POINTER EEPROM SRAM STATUS REGISTER USART PROGRAM COUNTER PROGRAM FLASH INSTRUCTION REGISTER INSTRUCTION DECODER PROGRAMMING LOGIC SPI ADC INTERFACE COMP . INTERFACE PORTC DRIVERS/BUFFERS PORTC DIGITAL INTERFACE GENERAL PURPOSE REGISTERS X Y Z ALU PORTB DRIVERS/BUFFERS PORTB DIGITAL INTERFACE PORTD DIGITAL INTERFACE PORTD DRIVERS/BUFFERS XTAL1 XTAL2 CONTROL LINES VCC GND MUX & ADC AGND AREF PC0 - PC6 PB0 - PB7 PD0 - PD7 AVR CPU TWI RESET
2486AA–AVR–02/2013 ATmega8(L) The Atmel®AVR® core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two inde- pendent registers to be accessed in one single in struction executed in one clock cycle. The resulting architecture is more code efficient wh ile achieving throughputs up to ten times faster than conventional CISC microcontrollers. The ATmega8 provides the following features: 8 Kbytes of In-System Programmable Flash with Read-While-Write capabilities, 512 bytes of EEPROM, 1 Kbyte of SRAM, 23 general purpose I/O lines, 32 general purpose working registers, three flexible Timer/Counters with compare modes, internal and external interrupts, a seri al programmable USART, a byte oriented Two- wire Serial Interface, a 6-channel ADC (eight channels in TQFP and QFN/MLF packages) with 10-bit accuracy, a programmable Watchdog Timer with Internal Os cillator, an SPI serial port, and five software selectable power saving modes. The Idle mode stops the CPU while allowing the SRAM, Timer/Counters, SPI port, and interr upt system to continue functioning. The Power- down mode saves the register contents but freezes the Oscillator, disabling all other chip func- tions until the next Interrupt or Hardware Reset. In Power-save mode, the asynchronous timer continues to run, allowing the user to maintain a timer base while the rest of the device is sleep- ing. The ADC Noise Reduction mode stops the CPU and all I/O modules except asynchronous timer and ADC, to minimize switching noise during ADC conversions. In Standby mode, the crystal/resonator Oscillator is running while the re st of the device is sleeping. This allows very fast start-up combined with low-power consumption. The device is manufactured using Atmel’s high density non-volatile memory technology. The Flash Program memory can be reprogrammed In-System through an SPI serial interface, by a conventional non-volatile memory programmer, or by an On-chip boot program running on the AVR core. The boot program can use any interface to download the application program in the Application Flash memory . Software in the Boot Flash Sect ion will continue to run while the Application Flash Section is updated, providi ng true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel ATmega8 is a powerful microcontroller that provides a highly-flexible and cost-effective solution to many embedded control applications. The ATmega8 is supported with a full suite of program and system development tools, including C compilers, macro assemblers, program simulators, and evaluation kits. Disclaimer Typical values contained in this datasheet ar e based on simulations and characterization of other AVR microcontrollers manufactured on the same process technology. Minimum and Maxi- mum values will be available after the device is characterized.
2486AA–AVR–02/2013 ATmega8(L) Pin Descriptions VCC Digital supply voltage. GND Ground. Port B (PB7..PB0) XTAL1/XTAL2/TOSC1/ TOSC2 Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pi ns that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running. Depending on the clock selection fuse settings, PB6 can be used as input to the inverting Oscil- lator amplifier and input to the internal clock operating circuit. Depending on the clock selection fuse settings, PB7 can be used as output from the inverting Oscillator amplifier. If the Internal Calibrated RC Oscillator is used as chip clock source, PB7..6 is used as TOSC2..1 input for the Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set. The various special features of Port B are elaborated in “Alternate Functions of Port B” on page 58 and “System Clock and Clock Options” on page 25. Port C (PC5..PC0) Port C is an 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. As inputs, Port C pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not running. PC6/RESET If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that the electrical char- acteristics of PC6 differ from those of the other pins of Port C. If the RSTDISBL Fuse is unprogrammed, PC6 is used as a Reset input. A low level on this pin for longer than the minimum pulse length will generate a Reset, even if the clock is not running. The minimum pulse length is given in Table 15 on page 38. Shorter pulses are not guaranteed to generate a Reset. The various special features of Port C are elaborated on page 61. Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port D output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. As inputs, Port D pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port D also serves the functions of various special features of the ATmega8 as listed on page 63. RESET Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. The minimum pulse length is given in Table 15 on page 38. Shorter pulses are not guaranteed to generate a reset.
2486AA–AVR–02/2013 ATmega8(L) externally connected to V CC, even if the ADC is not used. If the ADC is used, it should be con- nected to VCC through a low-pass filter. Note that Port C (5..4) use digital supply voltage, VCC. AREF AREF is the analog reference pin for the A/D Converter. ADC7..6 (TQFP and QFN/MLF Package Only) In the TQFP and QFN/MLF package, ADC7..6 serve as analog inputs to the A/D converter. These pins are powered from the analog supply and serve as 10-bit ADC channels.
2486AA–AVR–02/2013 ATmega8(L) Resources A comprehensive set of development tools, app lication notes and datasheets are available for download on http://www.atmel.com/avr. Note: 1. Data Retention Reliability Qualification results show that the pr ojected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.
2486AA–AVR–02/2013 ATmega8(L) About Code Examples This datasheet contains simple code examples that briefly show how to use various parts of the device. These code examples assume that the part specific header file is included before compi- lation. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details.
memories, perform calculations, control peripherals, and handle interrupts. Figure 2. Block Diagram of the AVR MCU Architecture in every clock cycle. The Program memory is In-System Reprogrammable Flash memory. and the result is stored back in the Register File – in one clock cycle.
2486AA–AVR–02/2013 ATmega8(L) can also be used as an address pointer for look up tables in Flash Program memory. These added function registers are the 16-bit X-register , Y-register, and Z-register, described later in this section. The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic opera- tion, the Status Register is updated to reflect information about the result of the operation. The Program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address space. Most AVR instructions have a single 16-bit word for- mat. Every Program memory address contains a 16-bit or 32-bit instruction. Program Flash memory space is divided in two sections, the Boot program section and the Application program section. Both sections have dedicated Loc k Bits for write and read/write protection. The SPM instruction that writes into the Application Flash memory section must reside in the Boot program section. During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the to tal SRAM size and the usage of the SRAM. All user programs must initialize the SP in the reset routine (before subroutines or interrupts are executed). The Stack Pointer SP is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its control registers in the I/O space with an additional global interrupt enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector posi- tion. The lower the Interrupt Vector address, the higher the priority. The I/O memory space contains 64 addresses for CPU peripheral functi ons 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.
2486AA–AVR–02/2013 ATmega8(L) Arithmetic Logic Unit – ALU The high-performance Atmel ®AVR® ALU operates in direct connection with all the 32 general purpose working registers. Within a single cl ock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. The ALU operations are divided into three main categories – arithmetic, logical, and bit-functions. Some implementa- tions of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. For a detailed description, see “Instruction Set Summary” on page 311. Status Register The Status Register contains information about the result of the most recently executed arithme- tic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software. 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 inter- rupt enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by the application with the SEI and CLI instructions, as described in the Instruction Set Reference. Bit 6 – T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (B it STore) use the T-bit as source or desti- nation for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. Bit 5 – H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful in BCD arithmetic. See the “Instruction Set Description” for detailed information. Bit 4 – S: Sign Bit, S = N V The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement 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 suppor ts two’s complement arithmetics. See the “Instruction Set Description” for detailed information. Bit 2 – N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the “Instruction Set Description” for detailed information. B i t 76543210 I T H S V N Z C SREG 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
address registers X, Y and Z are defined as described in Figure 4. Figure 4. The X-register, Y -register and Z-Register automatic increment, and automatic decrement (see the Instruction Set Reference for details). popped from the Stack with return from subroutine RET or return from interrupt RETI. source for the chip. No internal clock division is used.
15 XH XL 0
15 YH YL 0
15 ZH ZL 0
2486AA–AVR–02/2013 ATmega8(L) When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are dis- abled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed. There are basically two types of interrupts. The fi rst type is triggered by an event that sets the Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vec- tor in order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the global interrupt enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the global interrupt enable bit is set, and will then be executed by order of priority. The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. Note that the Status Register is not automatica lly stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software. When using the CLI instruction to disable interrupts, the interrup ts will be immediately disabled. No interrupt will be executed af ter the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example shows how this can be used to avoid interrupts during the timed EEPROM write sequence. Assembly Code Example in r16, SREG ; store SREG value cli ; disable interrupts during timed sequence sbiEECR, EEMWE ; start EEPROM write sbiEECR, EEWE outSREG, r16 ; restore SREG value (I-bit) C Code Example char cSREG; cSREG = SREG;/* store SREG value */ /* disable interrupts during timed sequence */ _CLI(); EECR |= (1<<EEMWE); /* start EEPROM write */ EECR |= (1<<EEWE); SREG = cSREG; /* restore SREG value (I-bit) */
2486AA–AVR–02/2013 ATmega8(L) When using the SEI instruction to enable interr upts, the instruction following SEI will be exe- cuted before any pending interrupts, as shown in the following example. Interrupt Response Time The interrupt execution response for all the enabled Atmel ®AVR® interrupts is four clock cycles minimum. After four clock cycles, the Program Vector address for the actual interrupt handling routine is executed. During this 4-clock cycl e 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 occurs during execution of a multi-cycle instruction, this instruction is com- pleted 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 addi- tion to the start-up time from the selected sleep mode. A return from an interrupt handling routine take s four clock cycles. During these four clock cycles, the Program Counter (2 bytes) is popped back from the Stack, the Stack Pointer is incre- mented by 2, 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) */
tions, Boot Program section and Application Program section.
- “Memory Programming” on page 215 contains a detailed description on Flash Program-
ming in SPI- or Parallel Programming mode. LPM – Load Program memory instruction description). Figure 7. Program Memory Map
internal data SRAM access is performed in two clkCPU cycles as described in Figure 9. Figure 9. On-chip Data SRAM Access Cycles in SPI- or Parallel Programming mode. The EEPROM Access Registers are accessible in the I/O space. In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to “The EEPROM Control Register – EECR” on page 20 for details on this.
2486AA–AVR–02/2013 ATmega8(L) The EEPROM Address Register – EEARH and EEARL Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the ATmega8 and will always read as zero. Bits 8..0 – EEAR8..0: EEPROM Address The EEPROM Address Registers – EEARH and EEARL – specify the EEPR OM address in the 512bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed. The EEPROM Data Register – EEDR 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 Regi ster. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR. The EEPROM Control Register – EECR Bits 7..4 – Res: Reserved Bits These bits are reserved bits in the Atmel ®AVR® ATmega8 and will always read as zero. 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 inter- rupt when EEWE is cleared. Bit 2 – EEMWE: EEPROM Master Write Enable The EEMWE bit determines whether setting EEWE to one causes the EEPROM to be written. When EEMWE is set, setting EEWE within four cl ock cycles will write data to the EEPROM at the selected address If EEMWE is zero, sett ing EEWE will have no e ffect. When EEMWE has been written to one by software, hardware clears th e bit to zero after four clock cycles. See the description of the “Bit 1 – EEWE: EEPROM Write Enable” for an EEPROM write procedure. Bit 1 – EEWE: EEPROM Write Enable The EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM. When address and data are correctly set up, the EEWE bit must be written to one to write the value into the EEPROM. The EEMWE bit must be written to one be fore a logical one is written to EEWE, oth- B i t 1 51 41 31 21 11 0 9 8 EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL 76543210 R e a d / W r i t e RRRRRRR R / W R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 0000000X XXXXXXXX B i t 76543210 MSB LSB EEDR Read/Write R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 00000000 B i t 76543210 – – – – EERIE EEMWE EEWE EERE EECR Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 X 0
- Wait until EEWE becomes zero
- Wait until SPMEN in SPMCR becomes zero
- Write new EEPROM address to EEAR (optional)
- Write new EEPROM data to EEDR (optional)
- Write a logical one to the EEMWE bit while writing a zero to EEWE in EECR
- Within four clock cycles after setting EEMWE, write a logical one to EEWE
must check that the Flash programming is co mpleted before initiating a new EEPROM write. during all the steps to avoid these problems. the CPU is halted for two cycles before the next instruction is executed. next instruction is executed. progress, it is neither possible to read the EEPROM, nor to change the EEAR Register. gramming time for EEPROM access from the CPU. Table 1. EEPROM Programming Time
2486AA–AVR–02/2013 ATmega8(L) The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (for example by disabling inter- rupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash boot loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish. Assembly Code Example EEPROM_write: ; Wait for completion of previous write sbic EECR,EEWE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to data register out EEDR,r16 ; Write logical one to EEMWE sbi EECR,EEMWE ; Start eeprom write by setting EEWE sbi EECR,EEWE ret C Code Example void EEPROM_write(unsigned int uiAddress, unsigned char ucData) /* Wait for completion of previous write */ while(EECR & (1<<EEWE)) /* Set up address and data registers */ EEAR = uiAddress; EEDR = ucData; /* Write logical one to EEMWE */ EECR |= (1<<EEMWE); /* Start eeprom write by setting EEWE */ EECR |= (1<<EEWE);
2486AA–AVR–02/2013 ATmega8(L) The next code examples show assembly and C functions for reading the EEPROM. The exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. EEPROM Write during Power-down Sleep Mode When entering Power-down sleep mode whil e an EEPROM write operation is active, the EEPROM write operation will continue, and will complete before the Write Access time has passed. However, when the writ e operation is completed, the Oscillator continues running, and as a consequence, the device does not enter Power-down entirely. It is therefore recommended to verify that the EEPROM write operation is completed before entering Power-down. Preventing EEPROM Corruption During periods of low V CC, the EEPROM data can be corrupted because the supply voltage is too low for the CPU and the EEPROM to operate properly. These issues are the same as for board level systems using EEPROM, and the same design solutions should be applied. An EEPROM data corruption can be caused by two situations when the voltage is too low. First, a regular write sequence to the EEPROM requires a minimum voltage to operate correctly. Sec- ond, the CPU itself can execute instructions incorrectly, if the supply voltage is too low. EEPROM data corruption can easily be avoided by following this design recommendation: Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal Brown-out Detector (BOD). If the detection level of the internal BOD does not match the needed detection level, an external low V CC Reset Protec- Assembly Code Example EEPROM_read: ; Wait for completion of previous write sbic EECR,EEWE rjmp EEPROM_read ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Start eeprom read by writing EERE sbi EECR,EERE ; Read data from data register in r16,EEDR ret C Code Example unsigned char EEPROM_read(unsigned int uiAddress) /* Wait for completion of previous write */ while(EECR & (1<<EEWE)) /* Set up address register */ EEAR = uiAddress; /* Start eeprom read by writing EERE */ EECR |= (1<<EERE); /* Return data from data register */ return EEDR;
2486AA–AVR–02/2013 ATmega8(L) tion circuit can be used. If a reset occurs whil e a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. I/O Memory The I/O space definition of the ATmega8 is shown in “Register Summary” on page 309. All Atmel®AVR® ATmega8 I/Os and peripherals are placed in the I/O space. The I/O locations are accessed by the IN and OUT instructions, transferring data between the 32 general purpose working registers and the I/O space. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. Refer to the “Instruction Set Sum- mary” on page 311 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. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bi ts in the I/O Register, writi ng a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers 0x00 to 0x1F only. The I/O and Peripherals Control Registers are explained in later sections.
only available while the chip is clocked on the Internal Oscillator. start-up time. The number of WDT Oscillator cycles used for each time-out is shown in Table 3. “10” (1MHz Internal RC Oscillator, slowly rising power). Table 2. Device Clocking Options Select Table 3. Number of Watchdog Oscillator Cycles
used to drive other clock buffers. capacitor values given by the manufacturer should be used. Figure 11. Crystal Oscillator Connections range. The operating mode is selected by the fuses CKSEL3..1 as shown in Table 4. Table 4. Crystal Oscillator Operating Modes
- These options are intended for use with ceramic resonators and will ensure frequency stability
itors. The internal capacitors have a nominal value of 36pF. Table 5. Start-up Times for the Crystal Oscillator Clock Selection Table 6. Start-up Times for the Low-frequency Crystal Oscillator Clock Selection
11 Reserved
between XTAL1 and GND, thereby removing the need for an external capacitor. Figure 12. External RC Configuration range. The operating mode is selected by the fuses CKSEL3..0 as shown in Table 7. Table 7. External RC Oscillator Operating Modes Table 8. Start-up Times for the External RC Oscillator Clock Selection
frequency selected, this calibration gives a frequency within ±3% of the nominal frequency. bration value, see the section “Calibration Byte” on page 218. Table 10. PB6 (XTAL1/TOSC1) and PB7(XTAL2/TOSC2) can be used as either general I/O pins Table 9. Internal Calibrated RC Oscillator Operating Modes Table 10. Start-up Times for the Internal Calibrated RC Oscillator Clock Selection
more than 10% above the nominal frequency. Otherwise, the EEPROM or Flash write may fail. ing to other values is not guaranteed, as indicated in Table 11. Table 11. Internal RC Oscillator Frequency Range
- To run the device on an exte rnal clock, the CKSEL Fuses mu st be programmed to “0000”.
XTAL1 and GND, and XTAL2 and GND. Figure 13. External Clock Drive Configuration MCU is kept in Reset during such changes in the clock frequency. internal capacitors on XTAL1 and XTAL2, thereb y removing the need for external capacitors. source to TOSC1 is not recommended. Table 12. Start-up Times for the External Clock Selection
tion to the application’s requirements. and executes from the Reset Vector. the ATmega8, as the TOSC and XTAL inputs share the same physical pins. tion. The figure is helpful in selecting an appropriate sleep mode. The MCU Control Register contains control bits for power management. These bits select between the five available sleep modes as shown in Table 13. Table 13. Sleep Mode Select
000 I d l e
010 P o w e r - d o w n
011 P o w e r - s a v e
100 R e s e r v e d
101 R e s e r v e d
110 S t a n d b y
2486AA–AVR–02/2013 ATmega8(L) Idle Mode When the SM2..0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing SPI, USART, Analog Comparator, ADC, Two-wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system to continue operating. This sleep mode basically halts clk CPU and clkFLASH, while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow and USART Transmit Complete interrupts. If wake-up from the Analog Comparator interrupt is not required, the Analog Comparator can be powered down by setting the ACD bit in the Analog Comparator Control and Status Regist er – ACSR. This will reduce power consumption in Idle mode. If t he ADC is enabled, a conversion starts automati- cally when this mode is entered. ADC Noise Reduction Mode When the SM2..0 bits are written to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode, stopping the CPU but allowing the ADC, the external interrupts, the Two-wire Serial Interface address watch, Timer/Counter2 and the Watchdog to continue operating (if enabled). This sleep mode basically halts clk I/O, clkCPU, and clkFLASH, while allowing the other clocks to run. This improves the noise environment for the AD C, enabling higher resolution measurements. If the ADC is enabled, a conversion starts automatically when this mode is entered. Apart form the ADC Conversion Complete interrupt, only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface address match interrupt, a Timer/Counter2 interrupt, an SPM/EEPROM ready interrupt, or an external level interrupt on INT0 or INT1, can wake up the MCU from ADC Noise Reduction mode. Power-down Mode When the SM2..0 bits are written to 010, the SLEEP instruction makes the MCU enter Power- down mode. In this mode, the External Oscillator is stopped, while the external interrupts, the Two-wire Serial Interface address watch, and the Watchdog continue operating (if enabled). Only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface address match interrupt, or an external level interrupt on INT0 or INT1, can wake up the MCU. This sleep mode basically halts all generated clocks, allowi ng operation of asynchronous mod- ules only. Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU. Refer to “External Interrupts” on page 66 for details. When waking up from Power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined by the same CKSEL Fuses that define the Reset Time-out period, as described in “Clock Sources” on page 26. Power-save Mode When the SM2..0 bits are written to 011, the SLEEP instruction makes the MCU enter Power- save mode. This mode is identical to Power-down, with one exception: If Timer/Counter2 is clocked asynchronously, that is, the AS2 bit in ASSR is set, Timer/Counter2 will run during sleep. The device can wake up from either Timer Overflow or Output Compare event from Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in TIMSK, and the global interrupt enable bit in SREG is set. If the asynchronous timer is NOT clocked asyn chronously, Power-down mode is recommended instead of Power-save mode because the contents of the registers in the asynchronous timer should be considered undefined after wake-up in Power-save mode if AS2 is 0. This sleep mode basically halts all clocks except clk ASY, allowing operation only of asynchronous modules, including Timer/Counter 2 if clocked asynchronously.
- If AS 2 bit in ASSR is set
- Only level interrupt INT1 and INT0
consideration when trying to achieve the lowest possible power consumption. for details on ADC operation. configure the Analog Comparator. Table 14. Active Clock Domains and Wake-up Sources in the Different Sleep Modes
2486AA–AVR–02/2013 ATmega8(L) Brown-out Detector If the Brown-out Detector is not needed in the application, this module should be turned off. If the Brown-out Detector is enabled by the BODEN Fuse, it will be enabled in all sleep modes, and hence, always consume power. In the deeper slee p modes, this will contribute significantly to the total current consumption. Refer to “Brown-out Detection” on page 40 for details on how to configure the Brown-out Detector. Internal Voltage Reference The Internal Voltage Referenc e will be enabled when needed by the Brown-out Detector, the Analog Comparator or the ADC. If these modules are disabled as described in the sections above, the internal voltage reference will be disabled and it w ill not be consuming power. When turned on again, the user must allow the reference to start up before the output is used. If the reference is kept on in sleep mode, the output can be used immediately. Refer to “Internal Volt- age Reference” on page 42 for details on the start-up time. Watchdog Timer If the Watchdog Timer is not needed in the application, this module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this will contribute signific antly to the total current consump- tion. Refer to “Watchdog Timer” on page 43 for details on how to configure the Watchdog Timer. Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The most important thing is then to ensure that no pins drive resistive loads. In sleep modes where the both the I/O clock (clk I/O) and the ADC clock (clk ADC) are stopped, the input buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. Refer to the section “Digital Input Enable and Sleep Modes” on page 55 for details on which pins are enabled. If the input buffer is enabled and the input signal is left floating or have an analog signal level close to V CC/2, the input buffer will use excessive power.
2486AA–AVR–02/2013 ATmega8(L) System Control and Reset Resetting the AVR During Reset, all I/O Registers are set to their in itial values, and the program starts execution from the Reset Vector. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the boot section or vice versa. The circuit diagram in Figure 14 on page 38 shows the Reset Logic. Table 15 on page 38 defines the electrical parameters of the reset circuitry. The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not require any clock source to be running. After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the power to reach a stable level before normal operation starts. The time-out period of the delay counter is defined by the user through the CKSEL Fuses. The different selec- tions for the delay period are presented in “Clock Sources” on page 26. Reset Sources The ATmega8 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 Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled Brown-out Reset. The MCU is reset when the supply voltage V CC is below the Brown-out Reset threshold (VBOT) and the Brown-out Detector is enabled
Figure 14. Reset Logic
- V BOT may be below nominal minimum operating voltage for some devices. For devices where
Table 15. Reset Characteristics
43 for details on operation of the Watchdog Timer. Figure 19. Watchdog Reset During Operation These bits are reserved bits in the ATmega8 and always read as zero. This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag. occurs, the source of the reset can be found by examining the Reset Flags.
to the ADC is generated from the internal bandgap reference.
- When the BOD is enabled (by programming the BODEN Fuse)
- When the bandgap reference is connected to the Analog Comparator (by setting the
conditions above to ensure that the reference is turned off before entering Power-down mode. Table 16. Internal Voltage Reference Characteristics
Timer. The Watchdog Timer is also reset when it is disabled and when a Chip Reset occurs. Reset Vector. For timing details on the Watchdog Reset, refer to page 41. Figure 20. Watchdog Timer These bits are reserved bits in the ATmega8 and will always read as zero.
- In the same operation, write a logic one to WDCE and WDE. A logic one must be written
- Within the next four clock cycles, write a logic 0 to WDE. This disables the Watchdog
The following code example shows one assembly and one C function for turning off the WDT. ally) so that no interrupts will occur during execution of these functions. Table 17. Watchdog Timer Prescale Select
2486AA–AVR–02/2013 ATmega8(L) Timed Sequences for Changing the Configuration of the Watchdog Timer The sequence for changing the Watchdog Timer configuration differs slightly between the safety levels. Separate procedures are described for each level. Safety Level 1 (WDTON Fuse Unprogrammed) In this mode, the Watchdog Timer is initially disabled, but can be enabled by writing the WDE bit to 1 without any restriction. A timed sequence is needed when changing the Watchdog Time-out period or disabling an enabled Watchdog Timer. To disable an enabled Watchdog Timer and/or changing the Watchdog Time-out, the following procedure must be followed: 1. In the same operation, write a logic one to WDCE and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit 2. Within the next four clock cycles, in the same operation, write the WDE and WDP bits as desired, but with the WDCE bit cleared Safety Level 2 (WDTON Fuse Programmed) In this mode, the Watchdog Timer is always enabled, and the WDE bit will always read as one. A timed sequence is needed when changing the Watchdog Time-out period. To change the Watchdog Time-out, the following procedure must be followed: 1. In the same operation, write a logical one to WDCE and WDE. Even though the WDE always is set, the WDE must be written to one to start the timed sequence Within the next four clock cycles, in the same operation, write the WDP bits as desired, but with the WDCE bit cleared. The value written to the WDE bit is irrelevant. Assembly Code Example WDT_off: ; reset WDT WDR ; Write logical one to WDCE and WDE in r16, WDTCR ori r16, (1<<WDCE)|(1<<WDE) out WDTCR, r16 ; Turn off WDT ldi r16, (0<<WDE) out WDTCR, r16 ret C Code Example void WDT_off(void) /* reset WDT */ _WDR(); /* Write logical one to WDCE and WDE */ WDTCR |= (1<<WDCE) | (1<<WDE); /* Turn off WDT */ WDTCR = 0x00;
- When the IVSEL bit in GICR is set, Interrupt Vectors will be moved to the start of the boot
Table 18. Reset and Interrupt Vectors
Table 19. Reset and Interrupt Vectors Placement
2486AA–AVR–02/2013 ATmega8(L) When the BOOTRST Fuse is unprogrammed, the boot section size set to 2Kbytes and the IVSEL bit in the GICR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: AddressLabelsCode Comments $000 rjmp RESET ; Reset handler $001 RESET:ldi r16,high(RAMEND); Main program start $002 out SPH,r16 ; Set Stack Pointer to top of RAM $003 ldi r16,low(RAMEND) $004 out SPL,r16 $005 sei ; Enable interrupts $006 <instr> xxx .org $c01 $c01 rjmp EXT_INT0 ; IRQ0 Handler $c02 rjmp EXT_INT1 ; IRQ1 Handler $c12 rjmp SPM_RDY ; Store Program Memory Ready Handler When the BOOTRST Fuse is programmed and the boot section size set to 2Kbytes, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: AddressLabelsCode Comments .org $001 $001 rjmp EXT_INT0 ; IRQ0 Handler $002 rjmp EXT_INT1 ; IRQ1 Handler $012 rjmp SPM_RDY ; Store Program Memory Ready Handler .org $c00 $c00 rjmp RESET ; Reset handler $c01 RESET:ldi r16,high(RAMEND); Main program start $c02 out SPH,r16 ; Set Stack Pointer to top of RAM $c03 ldi r16,low(RAMEND) $c04 out SPL,r16 $c05 sei ; Enable interrupts $c06 <instr> xxx
2486AA–AVR–02/2013 ATmega8(L) When the BOOTRST Fuse is programmed, the boot section size set to 2Kbytes, and the IVSEL bit in the GICR Register is set before any in terrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: AddressLabels Code Comments .org $c00 $c00 rjmp RESET ; Reset handler $c01 rjmp EXT_INT0 ; IRQ0 Handler $c02 rjmp EXT_INT1 ; IRQ1 Handler $c12 rjmp SPM_RDY ; Store Program Memory Ready Handler $c13 RESET: ldi r16,high(RAMEND); Main program start $c14 out SPH,r16 ; Set Stack Pointer to top of RAM $c15 ldi r16,low(RAMEND) $c16 out SPL,r16 $c17 sei ; Enable interrupts $c18 <instr> xxx Moving Interrupts Between Application and Boot Space The General Interrupt Control Register controls the placement of the Interrupt Vector table. General Interrupt Control Register – GICR Bit 1 – IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (z ero), the Interrupt Vectors are pl aced at the star t of the Flash memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual address of the start of the boot Flash section is deter- mined by the BOOTSZ Fuses. Refer to the section “Boot Loader Support – Read-While-Write Self-Programming” on page 202 for details. To avoid unintentional changes of Interrupt Vector tables, a special write procedure must be followed to change the IVSEL bit: 1. Write the Interrupt Vector Change Enable (IVCE) bit to one 2. Within four cycles, write the desired valu e to IVSEL while writing a zero to IVCE Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE is set, and they remain disabl ed until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status Register is unaffected by the automatic disabling. Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is pro- grammed, interrupts are disabled while executing from the Application section. If Interrupt Vectors are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled while executing from the Boot Loader section. Refer to the section “Boot Loader Support – Read-While-Write Self-Programming” on page 202 for details on Boot Lock Bits. B i t 76543210 INT1 INT0 – – – – IVSEL IVCE GICR Read/Write R/W R/W R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0
2486AA–AVR–02/2013 ATmega8(L) Bit 0 – IVCE: Interrupt Vector Change Enable The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the IVSEL description above. See Code Example below. Assembly Code Example Move_interrupts: ; Enable change of Interrupt Vectors ldi r16, (1<<IVCE) out GICR, r16 ; Move interrupts to boot Flash section ldi r16, (1<<IVSEL) out GICR, r16 ret C Code Example void Move_interrupts(void) /* Enable change of Interrupt Vectors */ GICR = (1<<IVCE); /* Move interrupts to boot Flash section */ GICR = (1<<IVSEL);
Introduction All AVR ports have true Read-Modi fy-Write functionality when used as general digital I/O ports. teristics – TA = -40°C to 85°C” on page 235 for a complete list of parameters. Figure 21. I/O Pin Equivalent Schematic and bit locations are listed in “Register Description for I/O Ports” on page 65. I/O location is read only, while the Data Register and the Data Direction Register are read/write.
- Refer to the individual module sections for a full description of the alternate functions.
other pins in the port as general digital I/O.
a functional description of one I/O port pin, here generically called Pxn. Figure 22. General Digital I/O(1) PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address. active, even if no clocks are running.
= 0b11) as an intermediate step. Table 20 summarizes the control signals for the pin value. pd,max and tpd,min, respectively. Figure 23. Synchronization when Reading an Externally Applied Pin Value Table 20. Port Pin Configurations
between ½ and 1-½ system clock period depending upon the time of assertion. clock. In this case, the delay tpd through the synchronizer is 1 system clock period. Figure 24. Synchronization when Reading a Software Assigned Pin Value
2486AA–AVR–02/2013 ATmega8(L) The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. Note: 1. For the assembly program, two temporary re gisters are used to minimize the time from pull- ups are set on pins 0, 1, 6, and 7, until the di rection bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers Digital Input Enable and Sleep Modes As shown in Figure 22 on page 52, 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 Control- ler in Power-down mode, Power-save mode, and Standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to V CC/2. SLEEP is overridden for port pins enabled as Exte rnal Interrupt pins. If the External Interrupt Request is not enabled, SLEEP is active also fo r these pins. SLEEP is also overridden by vari- ous other alternate functions as described in “Alternate Port Functions” on page 56. If a logic high level (“one”) is present on an Asynchronous External Interrupt pin configured as “Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the external interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned sleep modes, as the clamping in these sleep modes produces the requested logic change. Assembly Code Example (1) ... ; Define pull-ups and set outputs high ; Define directions for port pins out PORTB,r16 out DDRB,r17 ; Insert nop for synchronization nop ; Read port pins in r16,PINB ... C Code Example(1) unsigned char i; ... /* Define pull-ups and set outputs high */ /* Define directions for port pins */ /* Insert nop for synchronization*/ _NOP(); /* Read port pins */ i = PINB; ...
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. accidentally configured as an output. serves as a generic description applicable to all port pins in the AVR microcontroller family. Figure 25. Alternate Port Functions
internally in the modules having the alternate function. Table 21. Generic Description of Overriding Signals for Alternate Functions enabled when {DDxn, PORTxn, PUD} = 0b010. DDxn, PORTxn, and PUD Register bits. the Output driver is enabled by the DDxn Register bit. port Value is controlled by the PORTxn Register bit. regardless of the setting of the PORTxn Register bit. state (Normal mode, sleep modes). the alternate function will use its own synchronizer. and can be used bi-directionally.
figuring the Pin” on page 52 for more details about this feature. The Port B pins with alternate functions are shown in Table 22. crystal Oscillator. When used as a clock pin, the pin can not be used as an I/O pin. mode, a crystal Oscillator is connected to this pin, and the pin cannot be used as an I/O pin. If PB7 is used as a clock pin, DDB7, PORTB7 and PINB7 will all read 0. Oscillator. When used as a clock pin, the pin can not be used as an I/O pin. mode, a crystal Oscillator is connected to this pin, and the pin can not be used as an I/O pin. If PB6 is used as a clock pin, DDB6, PORTB6 and PINB6 will all read 0. Table 22. Port B Pins Alternate Functions
2486AA–AVR–02/2013 ATmega8(L) SCK – Port B, Bit 5 SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input r egardless of the setting of DDB5. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit. MISO – Port B, Bit 4 MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a Master, this pin is configured as an input r egardless of the setting of DDB4. When the SPI is enabled as a Slave, the data direction of this pi n is controlled by DDB4. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit. MOSI/OC2 – Port B, Bit 3 MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input r egardless of the setting of DDB3. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB3. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB3 bit. OC2, Output Compare Match Output: The PB3 pin can serve as an external output for the Timer/Counter2 Compare Match. The PB3 pin has to be configured as an output (DDB3 set (one)) to serve this function. The OC2 pin is also the output pin for the PWM mode timer function. S S /OC1B – Port B, Bit 2 SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB2. 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 DDB2. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB2 bit. OC1B, Output Compare Match output: The PB2 pin can serve as an external output for the Timer/Counter1 Compare Match B. The PB2 pin has to be configured as an output (DDB2 set (one)) to serve this function. The OC1B pin is also the output pin for the PWM mode timer function. OC1A – Port B, Bit 1 OC1A, Output Compare Match output: The PB1 pin can serve as an external output for the Timer/Counter1 Compare Match A. The PB1 pin has to be configured as an output (DDB1 set (one)) to serve this function. The OC1A pin is also the output pin for the PWM mode timer function. ICP1 – Port B, Bit 0 ICP1 – Input Capture Pin: The PB0 pin can act as an Input Capture Pin for Timer/Counter1. Table 23 on page 60 and Table 24 on page 60 relate the alternate functions of Port B to the overriding signals shown in Figure 25 on page 56. SPI MSTR INPUT and SPI SLAVE OUTPUT constitute the MISO signal, while MOSI is divided into SPI MSTR OUTPUT and SPI SLAVE INPUT.
- EXT means that the external RC Oscillator or an external clock is selected (by the CKSEL
Table 23. Overriding Signals for Alternate Functions in PB7..PB4 Table 24. Overriding Signals for Alternate Functions in PB3..PB0
The Port C pins with alternate functions are shown in Table 25. pin, and the part will have to re ly on Power-on Reset and Brown- out Reset as its reset sources. pin can not be used as an I/O pin. If PC6 is used as a reset pin, DDC6, PORTC6 and PINC6 will all read 0. Table 25. Port C Pins Alternate Functions
Table 26. Overriding Signals for Alternate Functions in PC6..PC4 Table 27. Overriding Signals for Alternate Functions in PC3..PC0(1)
The Port D pins with alternate functions are shown in Table 28. T1, Timer/Counter1 counter source. T0, Timer/Counter0 counter source. INT1, External Interrupt source 1: The PD3 pin can serve as an external interrupt source. INT0, External Interrupt source 0: The PD2 pin can serve as an external interrupt source. this pin is configured as an output regardless of the value of DDD1. to be an input, the pull-up can still be controlled by the PORTD0 bit. overriding signals shown in Figure 25 on page 56. Table 28. Port D Pins Alternate Functions
Table 29. Overriding Signals for Alternate Functions PD7..PD4 Table 30. Overriding Signals for Alternate Functions in PD3..PD0
2486AA–AVR–02/2013 ATmega8(L) Register Description for I/O Ports The Port B Data Register – PORTB The Port B Data Direction Register – DDRB The Port B Input Pins Address – PINB The Port C Data Register – PORTC The Port C Data Direction Register – DDRC The Port C Input Pins Address – PINC The Port D Data Register – PORTD The Port D Data Direction Register – DDRD The Port D Input Pins Address – PIND B i t 76543210 PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 PORTB R e a d / W r i t e R / WR / WR / WR / WR / WR / WR / WR / W I n i t i a l V a l u e 00000000 B i t 76543210 DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 DDRB R e a d / W r i t e R / WR / WR / WR / WR / WR / WR / WR / W I n i t i a l V a l u e 00000000 B i t 76543210 PINB7 PINB6 PINB5 PINB4 PI NB3 PINB2 PINB1 PINB0 PINB R e a d / W r i t e RRRRRRRR Initial Value N/A N/A N/A N/A N/A N/A N/A N/A B i t 76543210 – PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 PORTC R e a d / W r i t e R R / WR / WR / WR / WR / WR / WR / W I n i t i a l V a l u e 00000000 B i t 76543210 – DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 DDRC R e a d / W r i t e R R / WR / WR / WR / WR / WR / WR / W I n i t i a l V a l u e 00000000 B i t 76543210 – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 PINC R e a d / W r i t e RRRRRRRR Initial Value 0 N/A N/A N/A N/A N/A N/A N/A B i t 76543210 PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 PORTD R e a d / W r i t e R / WR / WR / WR / WR / WR / WR / WR / W I n i t i a l V a l u e 00000000 B i t 76543210 DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 DDRD R e a d / W r i t e R / WR / WR / WR / WR / WR / WR / WR / W I n i t i a l V a l u e 00000000 B i t 76543210 PIND7 PIND6 PIND5 PIND4 PI ND3 PIND2 PIND1 PIND0 PIND R e a d / W r i t e RRRRRRRR Initial Value N/A N/A N/A N/A N/A N/A N/A N/A
sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle mode.
- The MCU will wake up if the input has the require d level during this sampling or if it is held
plete the wake up to trigger the level interrupt. executing instruction to generate an interrupt. Table 31. Interrupt 1 Sense Control
interrupt are defined in Table 32. The value on the INT0 pin is sampled before detecting edges. Request 1 is executed from the INT1 Interrupt Vector. Request 0 is executed from the INT0 Interrupt Vector. Table 32. Interrupt 0 Sense Control
2486AA–AVR–02/2013 ATmega8(L) Bit 6 – INTF0: External Interrupt Flag 0 When an event on the INT0 pin triggers an interrupt request, INTF0 becomes set (one). If the I- bit in SREG and the INT0 bit in GICR 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. Th is flag is always cleared when INT0 is configured as a level interrupt.
tions are listed in the “8-bit Timer/Counter Register Description” on page 71. Figure 26. 8-bit Timer/Counter Block Diagram the figure since these registers are shared by other timer units. Timer/Counter0 counter value and so on. The definitions in Table 33 are also used extensively throughout this datasheet. Table 33. Definitions
“Timer/Counter0 and Timer/Counter1 Prescalers” on page 73. block diagram of the counter and its surroundings. Figure 27. Counter Unit Block Diagram counter clear or count operations. ware. A new counter value can be written anytime. figure shows the count sequence close to the MAX value.
Timer/Counter unit 8-bit counter. Interrupt Enable), and TOV0 are set (one), the Timer/Counter0 Overflow interrupt is executed. Table 34. Clock Select Bit Description
clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024). is transparent in the high period of the internal system clock. (CSn2:0 = 6) edge it detects. Figure 30. T1/T0 Pin Sampling from an edge has been applied to the T1/T0 pin to the counter is updated. one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
An external clock source can not be prescaled. Figure 31. Prescaler for Timer/Counter0 and Timer/Counter1(1) When this bit is written to one, the Timer/Counter1 and Timer/Counter0 prescaler will be reset. reset of this prescaler will affect both timers. This bit will always be read as zero.
2486AA–AVR–02/2013 ATmega8(L) 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: True 16-bit Design (that is, allows 16-bit PWM) Two Independent Output Compare Units Double Buffered Output Compare Registers One Input Capture Unit Input Capture Noise Canceler Clear Timer on Compare Match (Auto Reload) Glitch-free, Phase Correct Pulse Width Modulator (PWM) Variable PWM Period Frequency Generator External Event Counter Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1) Overview Most register and bit references in this sect ion are written in general form. A lower case “n” replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit channel. However, when using the register or bit defines in a program, the precise form must be used, that is, TCNT1 for accessing Timer/Counter1 counter value and so on. A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 32 on page 76. For the actual placement of I/O pins, refer to “Pin Configurations” on page 2. CPU accessible I/O Regis- ters, 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 96.
Figure 32. 16-bit Timer/Counter Block Diagram(1) ters are shared by other timer units. Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request.
Canceler) for reducing the chance of capturing noise spikes. as an alternative, freeing the OCR1A to be used as PWM output. the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. Table 35. Definitions BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.
2486AA–AVR–02/2013 ATmega8(L) of a 16-bit register is read by the CPU, the High byte of the 16-bit register is copied into the tem- porary 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. The following code examples show how to access the 16-bit Timer Registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCR1A/B and ICR1 Registers. Note that when using “C”, the compiler handles the 16-bit access. Note: 1. See “About Code Examples” on page 8 The assembly code example returns the TCNT1 value in the r17:r16 Register pair. It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit Timer Regis- ters, then the result of the a ccess outside the interrupt will be corrupted. Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. The following code examples show how to do an atomic read of the TCNT1 Register contents. Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Assembly Code Example (1) ... ; Set TCNT1 to 0x01FF ldir17,0x01 ldir16,0xFF outTCNT1H,r17 outTCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ... C Code Example(1) unsigned int i; ... /* Set TCNT1 to 0x01FF */ TCNT1 = 0x1FF; /* Read TCNT1 into i */ i = TCNT1; ...
2486AA–AVR–02/2013 ATmega8(L) Note: 1. See “About Code Examples” on page 8 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 in r16,TCNT1L in r17,TCNT1H ; Restore Global Interrupt Flag outSREG,r18 ret C Code Example(1) unsigned int TIM16_ReadTCNT1( void ) unsigned char sreg; unsigned int i; /* Save Global Interrupt Flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNT1 into i */ i = TCNT1; /* Restore Global Interrupt Flag */ SREG = sreg; return i;
2486AA–AVR–02/2013 ATmega8(L) The following code examples show how to do an atomic write of the TCNT1 Register contents. Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Note: 1. See “About Code Examples” on page 8 The assembly code example requires that the r17:r16 Register pair contains the value to be writ- ten to TCNT1. 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. Timer/Counter Clock Sources The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the clock select logic which is controlled by the clock select (CS12:0) bits located in the Timer/Counter Control Register B (TCCR1B). For details on cl ock sources and prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers” on page 73. Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 33 on page 81 shows a block diagram of the counter and its surroundings. Assembly Code Example(1) TIM16_WriteTCNT1: ; Save Global Interrupt Flag in r18,SREG ; Disable interrupts cli ; Set TCNT1 to r17:r16 outTCNT1H,r17 outTCNT1L,r16 ; Restore Global Interrupt Flag outSREG,r18 ret C Code Example(1) void TIM16_WriteTCNT1( unsigned int i ) unsigned char sreg; unsigned int i; /* Save Global Interrupt Flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNT1 to i */ TCNT1 = i; /* Restore Global Interrupt Flag */ SREG = sreg;
Figure 33. Counter Unit Block Diagram the sections where they are of importance. (WGM13:0) located in the Timer/Counter Control Registers A and B (TCCR1A and TCCR1B). ing sequences and waveform generation, see “Modes of Operation” on page 87. the WGM13:0 bits. TOV1 can be used for generating a CPU interrupt. tiple events, can be applied via the ICP1 pin or alternatively, via the Analog Comparator unit.
signal applied. Alternatively the time-stamps can be used for creating a log of the events. small “n” in register and bit names indicates the Timer/Counter number. Figure 34. Input Capture Unit Block Diagram by writing a logical one to its I/O bit location. tion before the Low byte is written to ICR1L.
2486AA–AVR–02/2013 ATmega8(L) 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 sampled using the same technique as for the T1 pin ( Figure 30 on page 73 ). 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 enabl ed unless the Timer/Counter is set in a Wave- form Generation mode that uses ICR1 to define TOP. An Input Capture can be triggered by software by controlling the port of the ICP1 pin. 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 addi- tional four system clock cycles of delay from a change applied to the input, to the update of the ICR1 Register. The noise canceler uses the sy stem clock and is therefore not affected by the prescaler. Using the Input Capture Unit The main challenge when using the Input Capture unit is to assign enough processor capacity for handling the incoming events. The time between two events is critical. If the processor has not read the captured value in th e ICR1 Register before the nex t event occurs, the ICR1 will be overwritten with a new value. In this case the result of the capture will be incorrect. When using the Input Capture interrupt, the ICR1 Register should be read as early in the inter- rupt handler routine as possible. Even though the Input Capture interrupt has relatively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. Using the Input Capture unit in any mode of operation when the TOP value (resolution) is actively changed during operation, is not recommended. Measurement of an external signal’s duty cycle requires that the trigger edge is changed after each capture. Changing the edge sensing must be done as early as possible after the 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). Output Compare Units The 16-bit comparator continuously compares TCNT1 with the Output Compare Register (OCR1x). If TCNT equals OCR1x the comparator signals a match. A match will set the Output Compare Flag (OCF1x) at the next timer clock cycle . If enabled (OCIE1x = 1), the Output Com- pare Flag generates an Output Compare interrupt. The OCF1x Flag is automatically cleared when the interrupt is executed. Alternatively the OCF1x Flag can be cleared by software by writ- ing a logical one to its I/O bit location. The waveform generator uses the match signal to generate an output according to operating mode set by the Waveform Generation mode (WGM13:0) bits and Compare Output mode (COM1x1:0) bits. The TOP and BOTTOM signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation (see “Modes of Operation” on page 87). A special feature of Output Compare unit A allows it to define the Timer/Counter TOP value (that is counter resolution). In addition to the counter resolution, the TOP value defines the period time for waveforms generated by the waveform generator.
2486AA–AVR–02/2013 ATmega8(L) Force Output Compare In non-PWM Waveform Generation modes, the match output of the comparator can be forced by writing a one to the Force Output Compare (FOC1x) bit. Forcing Compare Match will not set the OCF1x Flag or reload/clear the timer, but the OC1x pin will be updated as if a real Compare Match had occurred (the COM1x1:0 bits settings de fine whether the OC1x pin is set, cleared or toggled). Compare Match Blocking by TCNT1 Write All CPU writes to the TCNT1 Register will block any Compare Match that occurs in the next timer clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT1 when using any of the Output Compare channels, independent of whether the Timer/Counter is running or not. If the value written to TCNT1 equals the OCR1x value, the Compare Match will be missed, resulting in incorrect wave- form generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP values. The Compare Match for the TOP w ill be ignored and the counter will continue to 0xFFFF. Similarly, do not write the TCNT1 value equal to BOTTOM when the counter is downcounting. The setup of the OC1x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC1x value is to use the Force Output Com- pare (FOC1x) strobe bits in Normal mode. The OC1x Register keeps its value even when changing between Waveform Generation modes. Be aware that the COM1x1:0 bits are not doubl e buffered together with the compare value. Changing the COM1x1:0 bits will take effect immediately. Compare Match Output Unit The Compare Output mode (COM1x1:0) bits have two functions. The waveform generator uses the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next Compare Match. Secondly the COM1x1:0 bits control the OC1x pin output source. Figure 36 on page 86 shows a simplified schematic of the logic affected by the COM1x1:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by the COM1x1:0 bits are shown. When referring to the OC1x state, the reference is for the internal OC1x Register, not the OC1x pin. If a System Reset occur, the OC1x Register is reset to “0”.
Figure 36. Compare Match Output Unit, Schematic Table 38 on page 97 for details. ation. See “16-bit Timer/Counter Register Description” on page 96. The COM1x1:0 bits have no effect on the Input Capture unit.
2486AA–AVR–02/2013 ATmega8(L) Compare Output Mode and Waveform Generation The waveform generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM1x1:0 = 0 tells the waveform generator that no action on the OC1x Register is to be performed on the next Compare Match. For compare output actions in the non-PWM modes refer to Table 36 on page 96 . For fast PWM mode refer to Table 37 on page 96, and for phase correct and phase and frequency correct PWM refer to Table 38 on page 97. A change of the COM1x1:0 bits state will have effect at the first Compare Match after the bits are written. For non-PWM modes, the action can be fo rced to have immediate effect by using the FOC1x strobe bits. Modes of Operation The mode of operation (that is, the behavior of the Timer/Counter and the Output Compare pins) is defined by the combination of the Waveform Generation mode (WGM13:0) and Compare Out- put mode (COM1x1:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM1x1:0 bits control whether the PWM out- put generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes the COM1x1:0 bits control whether the output should be set, cleared or toggle at a Compare Match. See “Compare Match Output Unit” on page 85. For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 94. Normal Mode The simplest mode of operation is the Normal mode (WGM13:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOV1) will be set in the same timer clock cycle as the TCNT1 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 overflow interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by soft- ware. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Input Capture unit is easy to use in Normal mode. However, observe that the maximum interval between the external events must not exceed the resolution of the counter. If the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. The Output Compare units can be used to generat e interrupts at some given time. Using the Output Compare to gene rate waveforms in Norm al mode is not recommended, since this will occupy too much of the CPU time. Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register are used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT1) matches either the OCR1A (WGM13:0 = 4) or the ICR1 (WGM13:0 = 12). The OCR1A or ICR1 define the top value for the counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the oper- ation of counting external events. The timing diagram for the CTC mode is shown in Figure 37 on page 88 . The counter value (TCNT1) increases until a Compare Match occurs with either OCR1A or ICR1, and then counter (TCNT1) is cleared.
Figure 37. CTC Mode, Timing Diagram imum value (0xFFFF) and wrap around starting at 0x0000 before the Compare Match can occur. using OCR1A for defining TOP (WGM13:0 = 15) since the OCR1A then will be double buffered. The N variable represents the prescaler factor (1, 8, 64, 256, or 1024). counter counts from MAX to 0x0000. tors), hence reduces total system cost.
when a Compare Match occurs. Figure 38. Fast PWM Mode, Timing Diagram dler routine can be used for updating the TOP and compare values. Compare Registers, a Compare Match will neve r occur between the TCNT1 and the OCR1x. OCR1x Registers are written. update is done at the same timer clock cycle as the TCNT1 is cleared and the TOV1 Flag is set.
2486AA–AVR–02/2013 ATmega8(L) 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. However, if the base PWM frequency is actively change d (by changing the TOP value), using the OCR1A as TOP is clearly a better choice due to its double buffer feature. In fast PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins. Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM1x1:0 to 3. See Table 37 on page 96 . The actual OC1x value will only be visible on the port pin if the data direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at the Compare Match between OCR1x and TCNT1, and clearing (or setting) the OC1x Register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x Register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the out- put will be a narrow spike for eac h TOP+1 timer clock cycle. Se tting the OCR1x equal to TOP will result in a const ant high or low output (depending on the polarity of the output set by the COM1x1:0 bits). A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by set- ting OC1A to toggle its logical level on each Compare Match (COM1A1:0 = 1). This applies only if OCR1A is used to define the TOP value (WGM 13:0 = 15). The waveform generated will have a maximum frequency of f OC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). This feature is similar to the OC1A toggle in CTC mode, except the double buffer feature of the Output Com- pare unit is enabled in the fast PWM mode. 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 (OC1x) is cleared on the Compare Match between TCNT1 and OCR1x while upcounting, and set on the Compare Match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope operation. However, due to the symmetric feat ure 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-bit, 9-bit, 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 reso- lution in bits can be calculated by using the following equation: In phase correct PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1 (WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11). The counter has then reached the TOP and changes the count direction. The TCNT1 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 39 on page 91. The figure shows phase correct PWM mode when OC R1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histogram for illustrating the dual-slope opera- fOCnxPWM fclk_I/O RPCPWM TOP 1+log
OC1x Interrupt Flag will be set when a Compare Match occurs. Figure 39. Phase Correct PWM Mode, Timing Diagram reaches the TOP or BOTTOM value. Compare Registers, a Compare Match will neve r occur between the TCNT1 and the OCR1x. TOP value there are practically no differences between the two modes of operation.
2486AA–AVR–02/2013 ATmega8(L) the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the output will be continuously low and if set equal to TOP the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A is used to define the TOP value (WMG13:0 = 11) and COM1A1:0 = 1, the OC1A out- put will toggle with a 50% duty cycle. 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 reso lution phase and frequency correct PWM wave- form generation option. The phase and frequency correct PWM mode is, like the phase correct PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the Compare Match between TCNT1 and OCR1x while upcounting, and set on the Compare Match while downcounting. In inverting Compare Output mode, the operation is inverted. The dual-slope operation gives a lower maximum operation fre- quency compared to the single-slope operation. Howe ver, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. The main difference between the phase correct, and the phase and frequency correct PWM mode is the time the OCR1x Register is updated by the OCR1x Buffer Register, (see Figure 39 on page 91 and Figure 40 on page 93). 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 OCR1 A set to MAX). The PWM resolution in bits can be calculated using the following equation: 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 reac hed the TOP and ch anges the count di rection. The TCNT1 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency correct PWM mode is shown on Figure 40 on page 93 . The figure shows phase and frequency correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a Compare Match occurs. fOCnxPCPWM fclk_I/O RPFCPWM TOP 1+log
Figure 40. Phase and Frequency Correct PWM Mode, Timing Diagram is used for defining the TOP value, the OC1A or ICF1 Flag set when TCNT1 has reached TOP. Compare Registers, a Compare Match will never occur between the TCNT1 and the OCR1x. TOP is clearly a better choice due to its double buffer feature.
- The actual OC1x value will only be visible on the port pin if the data direction for the port pin
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
2486AA–AVR–02/2013 ATmega8(L) 16-bit Timer/Counter Register
Description
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 (OC1A and OC1B respec- tively) behavior. If one or both of the COM1A1:0 bits are written to one, the OC1A output overrides the normal port functionality of the I/O pin it is connected to. If one or both of the COM1B1:0 bit are written to one, the OC1B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit correspond- ing to the OC1A or OC1B pin must be set in order to enable the output driver. When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits is depen- dent of the WGM13:0 bits setting. Table 36 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to a normal or a CTC mode (non-PWM). Table 37 shows the COM1x1: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, bu t the set or clear is done at BOTTOM. See “Fast PWM Mode” on page 88 for more details B i t 7654 3 2 1 0 COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 TCCR1A Read/Write R/W R/W R/W R/W W W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Table 36. Compare Output Mode, Non-PWM 0 0 Normal port operation, OC1A/OC1B disconnected. Table 37. Compare Output Mode, Fast PWM(1) 0 0 Normal port operation, OC1A/OC1B disconnected. settings, normal port operation, OC1A/OC1B disconnected.
rect or the phase and frequency correct, PWM mode. The FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWM mode. FOC1A/FOC1B bit, an immediate Compare Match is forced on the waveform generation unit. COM1x1:0 bits that determine the effect of the forced compare. on Compare Match (CTC) mode using OCR1A as TOP. The FOC1A/FOC1B bits are always read as zero. of Pulse Width Modulation (PWM) modes (see “Modes of Operation” on page 87). Table 38. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM 0 0 Normal port operation, OC1A/OC1B disconnected. settings, normal port operation, OC1A/OC1B disconnected. OC1A/OC1B on Compare Match when downcounting. OC1A/OC1B on Compare Match when downcounting. Table 39. Waveform Generation Mode Bit Description
therefore delayed by four Oscillator cycles when the noise canceler is enabled. when the ICES1 bit is written to one, a rising (positive) edge will trigger the capture. can be used to cause an Input Capture Interrupt, if this interrupt is enabled. written to zero when TCCR1B is written. See TCCR1A Register description. 41 on page 94 and Figure 42 on page 94. Table 39. Waveform Generation Mode Bit Description (Continued)
pare Match between TCNT1 and one of the OCR1x Registers. Table 40. Clock Select Bit Description
2486AA–AVR–02/2013 ATmega8(L) The Output Compare Registers contain a 16-bit value that is continuously compared with the counter value (TCNT1). A match can be used to generate an Output Compare Interrupt, or to generate a waveform output on the OC1x pin. The Output Compare Registers are 16-bit in size. To ensure that both the high and Low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary High byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers” on page 77. Input Capture Register 1 – 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 Cap- ture can be used for defining the counter TOP value. The Input Capture Register is 16-bit in size. To ensure that both the high and Low bytes are read simultaneously when the CPU accesses these regi sters, the access is performed using an 8-bit temporary High byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers” on page 77. Timer/Counter Interrupt Mask Register – TIMSK (1) Note: 1. This register contains interrupt control bits for several Timer/Counters, but only Timer1 bits are described in this section. The remaining bits are described in their respective timer sections Bit 5 – TICIE1: Timer/Counter1, Input Capture Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Input Capture Interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 46) is executed when the ICF1 Flag, located in TIFR, is set. Bit 4 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare A match interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 46 ) is executed when the OCF1A Flag, located in TIFR, is set. Bit 3 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare B match interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 46 ) is executed when the OCF1B Flag, located in TIFR, is set. Bit 2 – TOIE1: Timer/Counter1, Overflow Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Overflow Interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 46) is executed when the TOV1 Flag, located in TIFR, is set. B i t 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 I n i t i a l V a l u e 00000000 B i t 76543210 OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 TIMSK Read/Write R/W R/W R/W R/W R/W R/W R R/W I n i t i a l V a l u e 00000000
2486AA–AVR–02/2013 ATmega8(L) Timer/Counter Interrupt Flag Register – TIFR (1) Note: 1. This register contains flag bits for severa l Timer/Counters, but only Timer1 bits are described in this section. The remaining bits are described in their respective timer sections Bit 5 – ICF1: Timer/Count er1, Input Capture Flag This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register (ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 Flag is set when the coun- ter reaches the TOP value. ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICF1 can be cleared by writing a logic one to its bit location. Bit 4 – OCF1A: Timer/Counter1, Output Compare A Match Flag This flag is set in the timer clock cycle afte r the counter (TCNT1) value matches the Output Compare Register A (OCR1A). Note that a Forced Output Compare (FOC1A) 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 3 – OCF1B: Timer/Counter1, Output Compare B Match Flag This flag is set in the timer clock cycle afte r the counter (TCNT1) value matches the Output Compare Register B (OCR1B). Note that a Forced Output Compare (FOC1B) 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 2 – TOV1: Timer/Counter1, Overflow Flag The setting of this flag is dependent of the WGM13:0 bits setting. In normal and CTC modes, the TOV1 Flag is set when the timer overflows. Refer to Table 39 on page 97 for the TOV1 Flag behavior when using another WGM13:0 bit setting. TOV1 is automatically cleared when the Timer/C ounter1 Overflow Interrupt Vector is executed. Alternatively, TOV1 can be cleared by writing a logic one to its bit location. B i t 76543210 OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 TIFR Read/Write R/W R/W R/W R/W R/W R/W R R/W I n i t i a l V a l u e 00000000
tions are listed in the “8-bit Timer/Counter Register Description” on page 114. Figure 45. 8-bit Timer/Counter Block Diagram
request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR). TIMSK are not shown in the figure since these registers are shared by other timer units. which can be used to generate an Output Compare interrupt request. Timer/Counter2 counter value and so on). The definitions in Table 41 are also used extensively throughout the document. “Timer/Counter Prescaler” on page 120. Table 41. Definitions BOTTOM The counter reaches the BOTT OM when it becomes zero (0x00). MAX The counter reaches its MAXimum wh en it becomes 0xFF (decimal 255).
46 shows a block diagram of the counter and its surrounding environment. Figure 46. Counter Unit Block Diagram “Modes of Operation” on page 108. the WGM21:0 bits. TOV2 can be used for generating a CPU interrupt.
2486AA–AVR–02/2013 ATmega8(L) 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 (FOC2) bit. Forcing Compare Match will not set the OCF2 Flag or reload/clear the timer, but the OC2 pin will be updated as if a real Compare Match had occurred (the COM21:0 bits settings define whether the OC2 pin is set, cleared or toggled). Compare Match Blocking by TCNT2 Write All CPU write operations to the TCNT2 Register will block any Compare Match that occurs in the next timer clock cycle, even when the timer is stopped. This feature allows OCR2 to be initialized to the same value as TCNT2 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT2 when using the Output Compare channel, independently of whether the Timer/Counter is running or not. If the value written to TCNT2 equals the OCR2 value, the Compare Match will be missed, resulting in incorrect waveform gen- eration. Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is downcounting. The setup of the OC2 should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC2 value is to use the Force Output Compare (FOC2) strobe bit in Normal mode. The OC2 R egister keeps its value even when changing between waveform generation modes. Be aware that the COM21:0 bits are not double buffered together with the compare value. Changing the COM21:0 bits will take effect immediately.
the COM21:0 bits for defining the Output Compare (OC2) state at the next Compare Match. reference is for the internal OC2 Register, not the OC2 pin. Figure 48. Compare Match Output Unit, Schematic pin. The port override function is independent of the Waveform Generation mode. operation. See “8-bit Timer/Counter Register Description” on page 114.
2486AA–AVR–02/2013 ATmega8(L) Compare Output Mode and Waveform Generation The Waveform Generator uses the COM21:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM21:0 = 0 tells the waveform generator that no action on the OC2 Register is to be performed on the next Compare Match. For compare output actions in the non- PWM modes refer to Table 43 on page 115. For fast PWM mode, refer to Table 44 on page 115, and for phase correct PWM refer to Table 45 on page 116. A change of the COM21:0 bits state will have effect at the first Compare Match after the bits are written. For non-PWM modes, the action can be fo rced to have immediate effect by using the FOC2 strobe bits. Modes of Operation The mode of operation (that is, the behavior of the Timer/Counter and the Output Compare pins) is defined by the combination of the Waveform Generation mode (WGM21:0) and Compare Out- put mode (COM21:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM21:0 bits control whether the PWM out- put generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes the COM21:0 bits control whether the output should be set, cleared, or toggled at a Compare Match (see “Compare Match Output Unit” on page 107). For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 112. Normal Mode The simplest mode of operation is the Normal mode (WGM21:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bot- tom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV2 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare unit can be used to generate interrupts at some given time. Using the Out- put Compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time.
plifies the operation of counting external events. Figure 49. CTC Mode, Timing Diagram The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). counter counts from MAX to 0x00.
sized external components (coils, capacitors), and therefore reduces total system cost. In fast PWM mode, the counter is incremented until the counter value matches the MAX value. matches between OCR2 and TCNT2. Figure 50. Fast PWM Mode, Timing Diagram rupt is enabled, the interrupt handler routine can be used for updating the compare value. ter is cleared (changes from MAX to BOTTOM). The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
Compare unit is enabled in the fast PWM mode. waveform generation option. The phase correct PWM mode is based on a dual-slope operation. timer clock cycle. The timing diagram fo r the phase correct PWM mode is shown on Figure 51. line marks on the TCNT2 slopes represent compare matches between OCR2 and TCNT2. Figure 51. Phase Correct PWM Mode, Timing Diagram
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). inverted PWM mode. For inverted PWM the output will have the opposite logic values. count sequence close to the MAX value in all modes other than phase correct PWM mode. Figure 52. Timer/Counter Timing Diagram, no Prescaling
Note: 1. The CTC2 and PWM2 bit definition names are now obsolete. Use the WGM21:0 definitions. are set, the OC2 output overrides the normal port functionality of the I/O pin it is connected to. in order to enable the output driver. Table 42. Waveform Generation Mode Bit Description Table 43. Compare Output Mode, Non-PWM Mode Table 44. Compare Output Mode, Fast PWM Mode(1)
01 R e s e r v e d
introduces a risk of missing a Compare Match between TCNT2 and the OCR2 Register. generate a waveform output on the OC2 pin. Table 45. Compare Output Mode, Phase Correct PWM Mode Table 46. Clock Select Bit Description
2486AA–AVR–02/2013 ATmega8(L) Asynchronous Operation of the Timer/Counter Asynchronous Status Register – ASSR Bit 3 – AS2: Asynchronous Timer/Counter2 When AS2 is written to zero , Timer/Counter 2 is clocked from the I/O clock, clk I/O. When AS2 is written to one, Timer/Counter 2 is clocked from a crystal Oscillator connected to the Timer Oscil- lator 1 (TOSC1) pin. When the value of AS2 is changed, the contents of TCNT2, OCR2, and TCCR2 might be corrupted. Bit 2 – TCN2UB: Timer/Counter2 Update Busy When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set. When TCNT2 has been updated from the temporary storage register, this bit is cleared by hard- ware. A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value. Bit 1 – OCR2UB: Output Co mpare Register2 Update Busy When Timer/Counter2 operates asynchronously and OCR2 is written, this bit becomes set. When OCR2 has been updated from the temporary storage register, this bit is cleared by hard- ware. A logical zero in this bit indicates that OCR2 is ready to be updated with a new value. Bit 0 – TCR2UB: Timer/Counter Control Register2 Update Busy When Timer/Counter2 operates asynchronously and TCCR2 is written, this bit becomes set. When TCCR2 has been updated from the temporary storage register, this bit is cleared by hard- ware. A logical zero in this bit indicates that TCCR2 is ready to be updated with a new value. If a write is performed to any of the three Timer/Counter2 Registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur. The mechanisms for reading TCNT2, OCR2, and TCCR2 are different. When reading TCNT2, the actual timer value is read. When reading OC R2 or TCCR2, the value in the temporary stor- age register is read. Asynchronous Operation of Timer/Counter2 When Timer/Counter2 operates asynchronously, some considerations must be taken. Warning: When switching between asynchronous and synchronous clocking of Timer/Counter2, the Timer Registers TCNT2, OCR2, and TCCR2 might be corrupted. A safe procedure for switching clock source is: 1. Disable the Timer/Counter2 interrupts by clearing OCIE2 and TOIE2 2. Select clock source by setting AS2 as appropriate 3. Write new values to TCNT2, OCR2, and TCCR2 4. To switch to asynchronous operatio n: Wait for TCN2UB, OCR2UB, and TCR2UB 5. Clear the Timer/Counter2 Interrupt Flags 6. Enable interrupts, if needed The Oscillator is optimized fo r use with a 32.768kHz watch crystal. Applying an external clock to the TOSC1 pin may result in incorrect Timer/Counter2 operation. The CPU main clock frequency must be more than four times the Oscillator frequency When writing to one of the r egisters TCNT2, OCR2, or TCCR2, the value is transferred to a temporary register, and latched after two positive edges on TOSC1. The user should not B i t 76543 2 1 0 – – – – AS2 TCN2UB OCR2UB TCR2UB ASSR R e a d / W r i t e RRRR R / W R R R Initial Value 0 0 0 0 0 0 0 0
2486AA–AVR–02/2013 ATmega8(L) write a new value before the contents of the temporary register have been transferred to its destination. Each of the three mentioned registers have their individual temporary register, which means that, for example, writing to TCNT2 does not disturb an OCR2 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 TCNT2, OCR2, or TCCR2, the user must wait until the written register has been updated if Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode before the changes are effective. This is particularly important if the Output Compare2 interrupt is used to wake up the device, since the Output Compare function is disabled during writing to OCR2 or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode before the OCR2UB bit returns to zero, the device will never receive a Compare Match interrupt, and the MCU will not wake up If Timer/Counter2 is used to wake the device up from Power-save mode, precautions must be taken if the user wants to re-enter one of these modes: The interrupt logic needs one TOSC1 cycle to be reset. If the time between wake-up and re-entering sleep mode is less than one TOSC1 cycle, the interrupt will not occur, and the device will fail to wake up. If the user is in doubt whether the time before re-entering Power-save or Extended Standby mode is sufficient, the following algorithm can be used to ensure that one TOSC1 cycle has elapsed: 1. Write a value to TCCR2, TCNT2, or OCR2 2. Wait until the corresponding Update Busy Flag in ASSR returns to zero 3. Enter Power-save or Extended Standby mode When the asynchronous operati on is selected, the 32.768kHZ Oscillator for Timer/Counter2 is always running, except in Power-down and Standby modes. After a Power-up Reset or Wake-up from Power-down or Standby mode, the user should be aware of the fact that this Oscillator might take as long as one second to stabilize. The user is advised to wait for at least one second before using Timer/Counter2 after Power-up or Wake-up from Power-down or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost after a wake-up from Power-down or Standby mode due to unstable clock signal upon start- up, no matter whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin Description of wake up from Power-save or Extended Standby mode when the timer is clocked asynchronously: When the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value. After wake-up, the MCU is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction following SLEEP Reading of the TCNT2 Register shortly after wake-up from Power-save may give an incorrect result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2 must be done through a register synchronized to the internal I/O clock domain. Synchronization takes place for every rising TOSC1 edge. When waking up from Power- save mode, and the I/O clock (clk I/O) again becomes active, TCNT2 will read as the previous value (before entering sleep) until the next rising TOSC1 edge. The phase of the TOSC clock after waking up from Power-save mode is essentially unpredictable, as it depends on the wake-up time. The recommended procedure for reading TCNT2 is thus as follows: 1. Write any value to either of the registers OCR2 or TCCR2 2. Wait for the corresponding Update Busy Flag to be cleared 3. Read TCNT2
2486AA–AVR–02/2013 ATmega8(L) During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous timer takes three processor cycles plus one timer cycle. The timer is therefore advanced by at least one before the processor can read the timer value causing the setting of the Interrupt Flag. The Output Compare Pin is changed on the timer clock and is not synchronized to the processor clock Timer/Counter Interrupt Mask Register – TIMSK Bit 7 – OCIE2: Timer/Counter2 Output Compare Match Interrupt Enable When the OCIE2 bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare Match interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter2 occurs (that is, when the OCF2 bit is set in the Timer/Counter Interrupt Flag Register – TIFR). Bit 6 – TOIE2: Timer/Counter2 Overflow Interrupt Enable When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter2 occurs (that is, when the TOV2 bit is set in the Timer/Counter Inter- rupt Flag Register – TIFR). Timer/Counter Interrupt Flag Register – TIFR Bit 7 – OCF2: Output Compare Flag 2 The OCF2 bit is set (one) when a Compare Match occurs between the Timer/Counter2 and the data in OCR2 – Output Compare Register2. OCF2 is cleared by hardware when executing the corresponding interrupt Handling Vector. Alternatively, OCF2 is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE2 (Timer/Counter2 Compare Match Interrupt Enable), and OCF2 are set (one), the Timer/Counter2 Compare Match Interrupt is executed. Bit 6 – TOV2: Timer/Counter2 Overflow Flag The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hard- ware when executing the corresponding interrupt Handling Vector. Alternatively, TOV2 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE2 (Timer/Counter2 Overflow Interrupt Enable), and TOV2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In PWM mode, this bit is set when Timer/Counter2 changes counting direction at 0x00. B i t 76543210 OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 TIMSK Read/Write R/W R/W R/W R/W R/W R/W R R/W I n i t i a l V a l u e 00000000 B i t 76543210 OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 TIFR Read/Write R/W R/W R/W R/W R/W R/W R R/W I n i t i a l V a l u e 00000000
Figure 56. Prescaler for Timer/Counter2 ing an external clock source to TOSC1 is not recommended. clkT2S/128, clkT2S/256, and clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected. the prescaler has been reset.
Figure 57. SPI Block Diagram(1)
- The system consists of two Shift Registers, and a Master clock generator. The SPI Master
initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave.
kept in the Buffer Register for later use. incoming data. The last incoming byte will be kept in the Buffer Register for later use. Figure 58. SPI Master-Slave Interconnection erwise, the first byte is lost. Table 47. SPI Pin Overrides(1)
8 BIT SHIFT REGISTER
2486AA–AVR–02/2013 ATmega8(L) The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission. DDR_SPI in the examples mu st be replaced by the actual Data Direction Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. For example if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB. Note: 1. See “About Code Examples” on page 8 Assembly Code Example(1) SPI_MasterInit: ; Set MOSI and SCK output, all others input out DDR_SPI,r17 ; Enable SPI, Master, set clock rate fck/16 out SPCR,r17 ret SPI_MasterTransmit: ; Start transmission of data (r16) out SPDR,r16 Wait_Transmit: ; Wait for transmission complete sbis SPSR,SPIF rjmp Wait_Transmit ret C Code Example(1) void SPI_MasterInit(void) /* Set MOSI and SCK output, all others input */ /* Enable SPI, Master, set clock rate fck/16 */ void SPI_MasterTransmit(char cData) /* Start transmission */ SPDR = cData; /* Wait for transmission complete */ while(!(SPSR & (1<<SPIF)))
2486AA–AVR–02/2013 ATmega8(L) The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Note: 1. See “About Code Examples” on page 8 Assembly Code Example(1) SPI_SlaveInit: ; Set MISO output, all others input ldi r17,(1<<DD_MISO) out DDR_SPI,r17 ; Enable SPI ldi r17,(1<<SPE) out SPCR,r17 ret SPI_SlaveReceive: ; Wait for reception complete sbis SPSR,SPIF rjmp SPI_SlaveReceive ; Read received data and return in r16,SPDR ret C Code Example(1) void SPI_SlaveInit(void) /* Set MISO output, all others input */ DDR_SPI = (1<<DD_MISO); /* Enable SPI */ SPCR = (1<<SPE); char SPI_SlaveReceive(void) /* Wait for reception complete */ while(!(SPSR & (1<<SPIF))) /* Return data register */ return SPDR;
2486AA–AVR–02/2013 ATmega8(L) SS Pin Functionality Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs except MISO which can be user configured as an output, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high. The SS pin is useful for packet/byte synchronizat ion to keep the Slave bit counter synchronous with the master clock generator. When the SS pin is driven high, the SPI Slave will immediately reset the send and receive logic, and drop any partially received data in the Shift Register. Master Mode When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI Slave. If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin defined as an input, the SPI syst em interprets this as another Master selecting the SPI as a Slave and starting to send data to it. To avoid bus contention, the SPI system takes the following actions: 1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possi- bility that SS is driven low, the interrup t 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. 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 the if the global interrupt enable bit in SREG is set. Bit 6 – SPE: SPI Enable When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. Bit 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. B i t 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 I n i t i a l V a l u e 00000000
Table 48. CPOL Functionality
0 Rising Falling
1 Falling Rising
Table 49. CPHA Functionality
0 Sample Setup
Table 50. Relationship Between SCK and the Oscillator Frequency
SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). and then accessing the SPI Data Register. These bits are reserved bits in the ATmega8 and will always read as zero. ing or uploading. See page 230 for Serial Programming and verification. ter causes the Shift Register Receive buffer to be read. Table 51. CPOL and CPHA Functionality
Registers and I/O pins are shown in bold. Figure 61. USART Block Diagram(1)
2486AA–AVR–02/2013 ATmega8(L) The dashed boxes in the block diagram separate the three main parts of the USART (listed from the top): Clock generator, Transmitter and Receiver. Control Registers are shared by all units. The clock generation logic consists of synchronization logic for external clock input used by syn- chronous slave operation, and the baud rate generator. The XCK (transfer clock) pin is only used by synchronous transfer mode. The Transmitter consists of a single write buffer, a serial Shift Register, Parity Generator and control logic for handling different serial frame formats. The write buffer allows a continuous transfer of data without any delay between frames. The Receiver is the most complex part of the USART module due to its clock and data recovery units. The recovery units are used for asynchronous data reception. In addition to the recovery units, the Receiver includes a parity checker, control logic, a Shift Register and a two level receive buffer (UDR). The Receiver supports the same frame formats as the Transmitter, and can detect Frame Error, Data OverRun and Parity Errors. AVR USART vs. AVR UART – Compatibility The USART is fully compatible with the AVR UART regarding: Bit locations inside all USART Registers Baud Rate Generation Transmitter Operation Transmit Buffer Functionality Receiver Operation However, the receive bu ffering has two improvements that will affect the comp atibility in some special cases: A second Buffer Register has been added. The two Buffer Registers operate as a circular FIFO buffer. Therefore the UDR must only be read once for each incoming data! More important is the fact that the Error Flags (FE and DOR) and the ninth data bit (RXB8) are buffered with the data in the receive buffer. Therefore the status bits must always be read before the UDR Register is read. Otherwise the error status will be lost since the buffer state is lost The Receiver Shift Register can now act as a th ird buffer level. This is done by allowing the received data to remain in the serial Shift Register (see Figure 61 on page 129) if the Buffer Registers are full, until a new start bit is detected. The USART is therefore more resistant to Data OverRun (DOR) error conditions The following control bits have changed name, but have same functionality and register location: CHR9 is changed to UCSZ2 OR is changed to DOR Clock Generation The clock generation logic generates the base clock for the Transmitter and Receiver. The USART supports four modes of clock operation: normal asynchronous, double speed asynchro- nous, Master synchronous and Slave Synchron ous mode. The UMSEL bit in USART Control and Status Register C (UCSRC) selects between asynchronous and synchronous operation. Double speed (Asynchronous mode only) is cont rolled by the U2X found in the UCSRA Regis- ter. When using Synchronous mode (UMSEL = 1), the Data Direction Register for the XCK pin (DDR_XCK) controls whether the clock source is internal (Master mode) or external (Slave mode). The XCK pin is only active when using Synchronous mode. Figure 62 on page 131 shows a block diagram of the clock generation logic.
Figure 62. Clock Generation Logic, Block Diagram operation. The description in this section refers to Figure 62. UMSEL, U2X and DDR_XCK bits.
for the asynchronous operation. Set this bit to zero when using synchronous operation. this mode is used. For the Transmitter, there are no downsides. section refers to Figure 62 on page 131 for details. add some margin to avoid possible loss of data due to frequency variations. opposite XCK clock edge of the edge the data output (TxD) is changed. Table 52. Equations for Calculating Baud Rate Register Setting
2486AA–AVR–02/2013 ATmega8(L) The USART Character SiZe (UCSZ2:0) bits select the number of data bits in the frame. The USART Parity mode (UPM1:0) bits enable and set the type of parity bit. The selection between one or two stop bits is done by the USART Stop Bit Select (USBS) bit. The Receiver ignores the second stop bit. An FE (Frame Error) will therefore only be detected in the cases where the first stop bit is zero. Parity Bit Calculation The parity bit is calculated by do ing an exclusive-or of all the data bits. If odd parity is used, the result of the exclusive or is inverted. The re lation between the parity bit and data bits is as follows: P even Parity bit using even parity Podd Parity bit using odd parity dn Data bit n of the character If used, the parity bit is located between the last data bit and first stop bit of a serial frame. USART Initialization The USART has to be initialized before any communication can take place. The initialization pro- cess normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. For interrupt driven USART operation, the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the initialization. Before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the re gisters are changed. The TXC Flag can be used to check that the Transmitter has completed all transfers, and the RXC Flag can be used to check that there are no unread data in the receive buffer. Note that the TXC Flag must be cleared before each transmission (before UDR is written) if it is used for this purpose. The following simple USART initialization code examples show one assembly and one C func- tion that are equal in functionality. The exampl es assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. The baud rate is given as a function parameter. For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 Regis- ters. When the function writes to the UCSRC Register, the URSEL bit (MSB) must be set due to the sharing of I/O location by UBRRH and UCSRC. Peven dn 1– d3 d2 d1 d0 0 Podd
2486AA–AVR–02/2013 ATmega8(L) Note: 1. See “About Code Examples” on page 8 More advanced initialization routines can be made that include frame format as parameters, dis- able interrupts and so on. However, many applications use a fixed setting of the Baud and Control Registers, and for these types of appl ications the initialization code can be placed directly in the main routine, or be combined with initialization code for other I/O modules. Assembly Code Example (1) USART_Init: ; Set baud rate out UBRRH, r17 out UBRRL, r16 ; Enable receiver and transmitter ldi r16, (1<<RXEN)|(1<<TXEN) out UCSRB,r16 ; Set frame format: 8data, 2stop bit ldi r16, (1<<URSEL)|(1<<USBS)|(3<<UCSZ0) out UCSRC,r16 ret C Code Example(1) #define FOSC 1843200// Clock Speed #define BAUD 9600 #define MYUBRR FOSC/16/BAUD-1 void main( void ) ... USART_Init ( MYUBRR ); ... void USART_Init( unsigned int ubrr) /* Set baud rate */ UBRRH = (unsigned char)(ubrr>>8); UBRRL = (unsigned char)ubrr; /* Enable receiver and transmitter */ UCSRB = (1<<RXEN)|(1<<TXEN); /* Set frame format: 8data, 2stop bit */ UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
2486AA–AVR–02/2013 ATmega8(L) Data Transmission – The USART Transmitter The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRB Register. When the Transmitter is enabled, the no rmal port operation of the TxD pin is overrid- den by the USART and given the function as t he Transmitter’s serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions. If syn- chronous operation is used, the clock on the XCK pin will be overridden and used as transmission clock. Sending Frames with 5 to 8 Data Bits A data transmission is initiated by loading the transmit buffer with the data to be transmitted. The CPU can load the transmit buffer by writing to the UDR I/O location. The buffered data in the transmit buffer will be moved to the Shift Register when the Shift Register is ready to send a new frame. The Shift Register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. When the Shift Register is loaded with new data, it will transfer one complete frame at the rate given by the Baud Register, U2X bit or by XCK depending on mode of operation. The following code examples show a simple USART transmit function based on polling of the Data Register Empty (UDRE) Flag. When using frames with less than eight bits, the most signif- icant bits written to the UDR are ignored. The USART has to be initialized before the function can be used. For the assembly code, the data to be sent is assumed to be stored in Register R16 Note: 1. See “About Code Examples” on page 8 The function simply waits for the transmit buffer to be empty by checking the UDRE Flag, before loading it with new data to be transmitted. If the Data Register Empty Interrupt is utilized, the interrupt routine writes the data into the buffer. Assembly Code Example(1) USART_Transmit: ; Wait for empty transmit buffer sbis UCSRA,UDRE rjmp USART_Transmit ; Put data (r16) into buffer, sends the data out UDR,r16 ret C Code Example(1) void USART_Transmit( unsigned char data ) /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ) /* Put data into buffer, sends the data */ UDR = data;
2486AA–AVR–02/2013 ATmega8(L) Sending Frames with
9 Data Bits
If 9-bit characters are used (UCSZ = 7), the nint h bit must be written to the TXB8 bit in UCSRB before the Low byte of the character is writte n to UDR. The following code examples show a transmit function that handles 9-bit characters. For the assembly code, the data to be sent is assumed to be stored in registers R17:R16. Note: 1. These transmit functions are written to be gen eral functions. They can be optimized if the con- tents of the UCSRB is static. Th at is, only the TXB8 bit of t he UCSRB Register is used after initialization The ninth bit can be used for indicating an address frame when using multi processor communi- cation mode or for other protocol handling as for example synchronization. Transmitter Flags and Interrupts The USART Transmitter has two flags that indi cate its state: USART Data Register Empty (UDRE) and Transmit Complete (TXC). Both flags can be used for generating interrupts. The Data Register Empty (UDRE) Fl ag indicates whether the transmit buffer is ready to receive new data. This bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the Shift Register. For compat- ibility with future devices, always write this bit to zero when writing the UCSRA Register. When the Data Register empty Interrupt Enable (UDRIE) bit in UCSRB is writte n to one, the USART Data Register Empty Interrupt will be ex ecuted as long as UDRE is set (provided that global interrupts are enabled). UDRE is cleared by writing UDR. When interrupt-driven data transmission is used, the Data Register empty Interrupt routine must either write new data to Assembly Code Example (1) USART_Transmit: ; Wait for empty transmit buffer sbis UCSRA,UDRE rjmp USART_Transmit ; Copy ninth bit from r17 to TXB8 cbi UCSRB,TXB8 sbrc r17,0 sbi UCSRB,TXB8 ; Put LSB data (r16) into buffer, sends the data out UDR,r16 ret C Code Example(1) void USART_Transmit( unsigned int data ) /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ) /* Copy ninth bit to TXB8 */ UCSRB &= ~(1<<TXB8); if ( data & 0x0100 ) UCSRB |= (1<<TXB8); /* Put data into buffer, sends the data */ UDR = data;
2486AA–AVR–02/2013 ATmega8(L) UDR in order to clear UDRE or disable the Data Register empty Interrupt, otherwise a new inter- rupt will occur once the interrupt routine terminates. The Transmit Complete (TXC) Flag bit is set one when the entire frame in the transmit Shift Reg- ister has been shifted out and there are no new data currently present in the transmit buffer. The TXC Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. Th e TXC Flag is useful in half-duplex communication interfaces (like the RS485 standard), where a transmitting application must enter Receive mode and free the communication bus immediately after completing the transmission. When the Transmit Compete Interrupt Enable (TXCIE) bit in UCSRB is set, the USART Transmit Complete Interrupt will be executed when the TXC Flag becomes set (provided that global inter- rupts are enabled). When the transmit complete interrupt is used, the interrupt handling routine does not have to clear the TXC Flag, this is done automatically when the interrupt is executed. Parity Generator The Parity Generator calculates the parity bit for the serial frame data. When parity bit is enabled (UPM1 = 1), the Transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. Disabling the Transmitter The disabling of the Transmitter (setting the TXEN to zero ) will not become effective until ongo- ing and pending transmissions are completed (that is, when the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted). When disabled, the Transmitter will no longer override the TxD pin. Data Reception – The USART Receiver The USART Receiver is enabled by writing the Receive Enable (RXEN) bit in the UCSRB Regis- ter to one. When the Receiver is enabled, the normal pin operation of the RxD pin is overridden by the USART and given the function as the Re ceiver’s serial input. The baud rate, mode of operation and frame format must be set up once before any serial reception can be done. If syn- chronous operation is used, the clock on the XCK pin will be used as transfer clock. Receiving Frames with 5 to 8 Data Bits The Receiver starts data reception when it detects a valid start bit. Each bit that follows the start bit will be sampled at the baud rate or XCK clock, and shifted into the Receive Shift Register until the first stop bit of a frame is received. A seco nd stop bit will be ignored by the Receiver. When the first stop bit is received (that is, a complete serial frame is present in the Receive Shift Reg- ister), the contents of the Shift Register will be mo ved into the receive buffer. The receive buffer can then be read by reading the UDR I/O location. The following code example shows a simple US ART receive function based on polling of the Receive Complete (RXC) Flag. When using frames with less than eight bits the most significant
2486AA–AVR–02/2013 ATmega8(L) bits of the data read from t he UDR will be masked to zero. T he USART has to be initialized before the function can be used. Note: 1. See “About Code Examples” on page 8 The function simply waits for data to be present in the receive buffer by checking the RXC Flag, before reading the buffer and returning the value. Receiving Frames with If 9-bit characters are used (UCSZ=7) the ninth bit must be read from the RXB8 bit in UCSRB before reading the low bits from the UDR. This rule applies to the FE, DOR and PE Status Flags as well. Read status from UC SRA, then data from UDR. R eading the UDR I/O location will change the state of the receive buffer FIFO an d consequently the TXB8, FE, DOR, and PE bits, which all are stored in the FIFO, will change. Assembly Code Example(1) USART_Receive: ; Wait for data to be received sbis UCSRA, RXC rjmp USART_Receive ; Get and return received data from buffer in r16, UDR ret C Code Example(1) unsigned char USART_Receive( void ) /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ) /* Get and return received data from buffer */ return UDR;
2486AA–AVR–02/2013 ATmega8(L) The following code example shows a simple USART receive function that handles both 9-bit characters and the status bits. Note: 1. See “About Code Examples” on page 8 The receive function example reads all the I/O R egisters into the Register File before any com- putation is done. This gives an optimal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. Assembly Code Example(1) USART_Receive: ; Wait for data to be received sbis UCSRA, RXC rjmp USART_Receive ; Get status and ninth bit, then data from buffer in r18, UCSRA in r17, UCSRB in r16, UDR ; If error, return -1 breq USART_ReceiveNoError ldi r17, HIGH(-1) ldi r16, LOW(-1) USART_ReceiveNoError: ; Filter the ninth bit, then return lsr r17 andi r17, 0x01 ret C Code Example(1) unsigned int USART_Receive( void ) unsigned char status, resh, resl; /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ) /* Get status and ninth bit, then data */ /* from buffer */ status = UCSRA; resh = UCSRB; resl = UDR; /* If error, return -1 */ return -1; /* Filter the ninth bit, then return */ resh = (resh >> 1) & 0x01; return ((resh << 8) | resl);
2486AA–AVR–02/2013 ATmega8(L) Receive Compete Flag and Interrupt The USART Receiver has one flag that indicates the Receiver state. The Receive Complete (RXC) Flag indicates if there are unread data present in the receive buf- fer. This flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (that is, does not contain any unread data). If the Receiver is disabled (RXEN = 0), the receive buffer will be flushed and consequently the RXC bit will become zero. When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USART Receive Complete Interrupt will be executed as long as the RXC Flag is se t (provided that global inter- rupts are enabled). When interrupt-driven data reception is used, the receive complete routine must read the received data from UDR in order to clear the RXC Flag, otherwise a new interrupt will occur once the interrupt routine terminates. Receiver Error Flags The USART Receiver has three error flags: Frame Error (FE), Data OverRun (DOR) and Parity Error (PE). All can be accessed by reading UCSRA. Common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. Due to the buffering of the error flags, the UCSRA must be read before the receive buffer (UDR), since reading the UDR I/O location changes the buffer read location. Another equality for the error flags is that they can not be altered by software doing a write to the flag location. However, all flags must be set to zero when the UCSRA is written for upward compatibility of future USART implementations. None of the error flags can generate interrupts. The Frame Error (FE) Flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. The FE Flag is ze ro when the stop bit was correctly read (as one), and the FE Flag will be one when the stop bit was incorrect (zero). This flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. The FE Flag is not affected by the setting of the USBS bit in UCSRC since the Receiver ignores all, except for the first, stop bits. For compatibility with future devices, always set this bit to zero when writing to UCSRA. The Data OverRun (DOR) Flag indicates data loss due to a Receiver buffer full condition. A Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a new start bit is detected. If the DOR Flag is set there was one or more serial frame lost between the frame last read from UDR, and the next frame read from UDR. For compatibility with future devices, always write this bit to zero when writing to UCSRA. The DOR Flag is cleared when the frame received was successfully moved from the Shift Regis- ter to the receive buffer. The Parity Error (PE) Flag indicates that the next frame in the receive buffer had a parity error when received. If parity check is not enabled the PE bit will always be read zero. For compatibil- ity with future devices, always set this bit to zero when writing to UCSRA. For more details see “Parity Bit Calculation” on page 134 and “Parity Checker” . Parity Checker The Parity Checker is active when the high USART Parity mode (UPM1) bit is set. Type of parity check to be performed (odd or even) is selected by the UPM0 bit. When enabled, the Parity Checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. The result of the check is stored in the receive buffer together with the received data and stop bits. The Parity Error (PE) Flag can then be read by software to check if the frame had a parity error. The PE bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (UPM1 = 1). This bit is valid until the receive buffer (UDR) is read.
cleared. The following code example shows how to flush the receive buffer. nal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. denoted zero are samples done when the RxD line is idle (that is, no communication activity). Figure 65. Start Bit Sampling
Table 53) base frequency, the Receiver will not be able to synchronize the frames to the start bit. that Normal Speed mode has higher toleration of baud rate variations. Table 53. Recommended Maximum Receiver Baud Rate Error for Normal Speed Mode Table 54. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode
2486AA–AVR–02/2013 ATmega8(L) The recommendations of the maximum Receiver baud rate error was made under the assump- tion that the Receiver and Transmitter equally divides the maximum total error. There are two possible sources for the Receivers Baud Rate error. The Receiver’s system clock (XTAL) will always have some minor instabilit y over the supply voltage range and the tempera- ture range. When using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. The second source for the error is more controllable. The baud rate generator can not always do an exact division of the system frequency to get the b aud rate wanted. In this case an UBRR value that gives an acceptable low error can be used if possible. Multi-processor Communication Mode Setting the Multi-processor Communication mode (MPCM) bit in UCSRA enables a filtering function of incoming frames received by the USART Receiver. Frames that do not contain address information will be ignored and not put in to the receive buffer. This effectively reduces the number of incoming frames that has to be handled by the CPU, in a system with multiple MCUs that communicate via the same serial bus. The Transmitter is unaffected by the MPCM setting, but has to be used diffe rently when it is a part of a system utilizing the Multi-processor Communication mode. If the Receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indi- cates if the frame contains data or address information. If the Receiver is set up for frames with nine data bits, then the ninth bit (RXB8) is used for identifying address and data frames. When the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. When the frame type bit is zero the frame is a data frame. The Multi-processor Communication mode enables se veral Slave MCUs to receive data from a Master MCU. This is done by first decoding an address frame to find out which MCU has been addressed. If a particular Slave MCU has been addressed, it will receive the following data frames as normal, while the other Slave MCUs will ignore the received frames until another address frame is received. Using MPCM For an MCU to act as a Master MCU, it can use a 9-bit character frame format (UCSZ = 7). The ninth bit (TXB8) must be set when an address frame (TXB8 = 1) or cleared when a data frame (TXB = 0) is being transmitted. The Slave MCUs must in this case be set to use a 9-bit character frame format. The following procedure should be used to exchange data in Multi-processor Communication mode: 1. All Slave MCUs are in Multi-processor Co mmunication mode (MPCM in UCSRA is set) 2. The Master MCU sends an address frame, and all slaves receive and read this frame. In the Slave MCUs, the RXC Flag in UCSRA will be set as normal 3. Each Slave MCU reads the UDR Register and determines if it has been selected. If so, it clears the MPCM bit in UCSRA, otherwise it waits for the next address byte and keeps the MPCM setting 4. The addressed MCU will receive all data fram es until a new address frame is received. The other Slave MCUs, which still have the MPCM bit set, will ignore the data frames 5. When the last data frame is received by the addressed MCU, the addressed MCU sets the MPCM bit and waits for a new address frame from Master. The process then repeats from 2 Using any of the 5-bit to 8-bit character frame formats is possible, but impractical since the Receiver must change between using n and n+1 character frame formats. This makes full- duplex operation difficult since the Transmitter a nd Receiver uses the same character size set- ting. If 5-bit to 8-bit character frames are used, the Transmitter must be set to use two stop bit (USBS = 1) since the first stop bit is used for indicating the frame type.
2486AA–AVR–02/2013 ATmega8(L) Do not use Read-Modify-Write instructions (SBI and CBI) to set or clear the MPCM bit. The MPCM bit shares the same I/O location as the TXC Flag and this might accidentally be cleared when using SBI or CBI instructions. Accessing UBRRH/UCSRC Registers The UBRRH Register shares the same I/O location as the UCSRC Register. Therefore some special consideration must be taken when accessing this I/O location. Write Access When doing a write access of this I/O location, the high bit of the value written, the USART Reg- ister Select (URSEL) bit, controls which one of the two registers that will be written. If URSEL is zero during a write operation, the UBRRH valu e will be updated. If URSEL is one, the UCSRC setting will be updated. The following code examples show how to access the two registers. Note: 1. See “About Code Examples” on page 8 As the code examples illustrate, write accesses of the two registers are relatively unaffected of the sharing of I/O location. Assembly Code Examples(1) ... ; Set UBRRH to 2 ldir16,0x02 outUBRRH,r16 ... ; Set the USBS and the UCSZ1 bit to one, and ; the remaining bits to zero. outUCSRC,r16 ... C Code Examples(1) ... /* Set UBRRH to 2 */ UBRRH = 0x02; ... /* Set the USBS and the UCSZ1 bit to one, and */ /* the remaining bits to zero. */ UCSRC = (1<<URSEL)|(1<<USBS)|(1<<UCSZ1); ...
2486AA–AVR–02/2013 ATmega8(L) Read Access Doing a read access to the UBRRH or the UCS RC Register is a more complex operation. How- ever, in most applications, it is rarely necessary to read any of these registers. The read access is controlled by a timed sequence. Reading the I/O location once returns the UBRRH Register contents. If the register location was read in previous system clock cycle, read- ing the register in the current clock cycle will return the UCSRC contents. Note that the timed sequence for reading the UCSRC is an atomic operation. Interrupts must therefore be controlled (for example, by disabling interrupts globally) during the read operation. The following code example shows how to read the UCSRC Register contents. Note: 1. See “About Code Examples” on page 8 The assembly code example returns the UCSRC value in r16. Reading the UBRRH contents is not an atomic operation and therefore it can be read as an ordi- nary register, as long as the previous instruction did not access the register location. Assembly Code Example(1) USART_ReadUCSRC: ; Read UCSRC in r16,UBRRH in r16,UCSRC ret C Code Example(1) unsigned char USART_ReadUCSRC( void ) unsigned char ucsrc; /* Read UCSRC */ ucsrc = UBRRH; ucsrc = UCSRC; return ucsrc;
2486AA–AVR–02/2013 ATmega8(L) USART Register Register – UDR The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address referred to as USART Data Register or UDR. The Transmit Data Buffer Reg- ister (TXB) will be the destination for data wri tten to the UDR Register location. Reading the UDR Register location will return the contents of the Receive Data Buffer Register (RXB). For 5-bit, 6-bit, or 7-bit characters the upper unused bits will be ignored by the Transmitter and set to zero by the Receiver. The transmit buffer can only be written when the UDRE Flag in the UCSRA Register is set. Data written to UDR when the UDRE Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the Shift Register is empty. Then the data will be seri- ally transmitted on the TxD pin. The receive buffer consists of a two level FIFO . The FIFO will change its state whenever the receive buffer is accessed. Due to this behavior of the receive buffer, do not use Read-Modify- Write instructions (SBI and CBI) on this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of the FIFO. USART Control and Status Register A – UCSRA Bit 7 – RXC: USAR T Receive Complete This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (that is, does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXC bit will become zero. The RXC Flag can be used to generate a Receive Complete interrupt (see description of the “Bit 7 – RXCIE: RX Complete Interrupt Enable” on page 149). Bit 6 – TXC: USART Transmit Complete This flag bit is set when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer (UDR). The TXC Flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC Flag can generate a Transmit Complete interrupt (see descrip- tion of the “Bit 6 – TXCIE: TX Complete Interrupt Enable” on page 149). Bit 5 – UDRE: USART Data Register Empty The UDRE Flag indicates if the transmit buffer (UDR) is ready to receive new data. If UDRE is one, the buffer is empty, and therefore ready to be written. The UDRE Flag can generate a Data Register Empty interrupt (see description of the “Bit 5 – UDRIE: USART Data Register Empty Interrupt Enable” on page 149). UDRE is set after a reset to indicate that the Transmitter is ready. B i t 76543210 RXB[7:0] UDR (Read) TXB[7:0] UDR (Write) Read/Write R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 00000000 B i t 76543210 RXC TXC UDRE FE DOR PE U2X MPCM UCSRA Read/Write R R/W R R R R R/W R/W I n i t i a l V a l u e 00100000
2486AA–AVR–02/2013 ATmega8(L) Bit 4 – FE: Frame Error This bit is set if the next character in the receive buffer had a Frame Error when received (that is, when the first stop bit of the next character in the receive buffer is zero). This bit is valid until the receive buffer (UDR) is read. The FE bit is zero when the stop bit of received data is one. Always set this bit to zero when writing to UCSRA. Bit 3 – DOR: Data OverRun This bit is set if a Data OverRun condition is detected. A Data OverRun occurs when the receive buffer is full (two characters), it is a new char acter waiting in the Receive Shift Register, and a new start bit is detected. This bit is valid until the receive buffer (UDR) is read. Always set this bit to zero when writing to UCSRA. Bit 2 – PE: Parity Error This bit is set if the next character in the receive buffer had a Parity Error when received and the parity checking was enabled at that point (UPM1 = 1). This bit is valid until the receive buffer (UDR) is read. Always set this bit to zero when writing to UCSRA. Bit 1 – U2X: Double the USART transmission speed This bit only has effect for the asynchronous operation. Write this bit to zero when using syn- chronous operation. Writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively dou- bling the transfer rate for asynchronous communication. Bit 0 – MPCM: Multi-processor Communication Mode This bit enables the Multi-processor Communication mode. When the MPCM bit is written to one, all the incoming frames received by the USART Receiver that do not contain address infor- mation will be ignored. The Transmitter is unaffe cted by the MPCM setting. For more detailed information see “Multi-processor Communication Mode” on page 145. USART Control and Status Register B – UCSRB Bit 7 – RXCIE: RX Complete Interrupt Enable Writing this bit to one enables interrupt on the RXC Flag. A US ART Receive Complete interrupt will be generated only if the RXCIE bit is written to one, the Global Interrupt Flag in SREG is writ- ten to one and the RXC bit in UCSRA is set. Bit 6 – TXCIE: TX Complete Interrupt Enable Writing this bit to one enables interrupt on the TXC Flag. A USART Transmit Complete interrupt will be generated only if the TXCIE bit is written to one, the Global Interrupt Flag in SREG is writ- ten to one and the TXC bit in UCSRA is set. Bit 5 – UDRIE: USART Data Register Empty Interrupt Enable Writing this bit to one enables interrupt on the UDRE Flag. A Da ta Register Empty interrupt will be generated only if the UDRIE bit is written to one, the Global Interrupt Flag in SREG is written to one and the UDRE bit in UCSRA is set. Bit 4 – RXEN: Receiver Enable Writing this bit to one enables the USART Receiver. The Receiver will override normal port oper- ation for the RxD pin when enabled. Disabling the Receiver will flush the receive buffer invalidating the FE, DOR and PE Flags. B i t 76543210 RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 UCSRB Read/Write R/W R/W R/W R/W R/W R/W R R/W I n i t i a l V a l u e 00000000
the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted). When disabled, the Transmitter will no longer override the TxD port. acter Size) in a frame the Receiver and Transmitter use. data bits. Must be read before reading the low bits from UDR. with nine data bits. Must be written before writing the low bits to UDR. UBRRH/UCSRC Registers” on page 146 section which describes how to access this register. reading UCSRC. The URSEL must be one when writing the UCSRC. This bit selects between Asynchronous and Synchronous mode of operation. Table 55. UMSEL Bit Settings
0 Asynchronous Operation
1 Synchronous Operation
Receiver will generate a parity va lue for the incoming data and co mpare it to the UPM0 setting. If a mismatch is detected, the PE Flag in UCSRA will be set. acter Size) in a frame the Receiver and Transmitter use. Table 56. UPM Bits Settings Table 57. USBS Bit Settings Table 58. UCSZ Bits Settings
110 R e s e r v e d
and the synchronous clock (XCK). UBRRH/UCSRC Registers” on page 146 section which describes how to access this register. reading UBRRH. The URSEL must be zero when writing the UBRRH. written to zero when UBRRH is written. changed. Writing UBRRL will trigger an immediate update of the baud rate prescaler. Table 59. UCPOL Bit Settings
0 Rising XCK Edge Falling XCK Edge
1 Falling XCK Edge Rising XCK Edge
Table 60. Examples of UBRR Settings for Commonly Used Oscillator Frequencies
Table 61. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued)
Table 62. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued)
Table 63. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued)
contention are inherent in the TWI protocol. Figure 68. TWI Bus Interconnection TWI Terminology The following definitions are frequently encountered in this section. Table 64. TWI Terminology
in order to allow any bus operation. and one valid for bus speeds up to 400kHz. generating start and stop conditions. Figure 69. Data Validity line when the SCL line is high.
SCL line goes high or low, respectively. Figure 74. SCL Synchronization Between Multiple Masters
Figure 75. Arbitration Between Two Masters number of data packets, otherwise the result of the arbitration is undefined.
in a thick line are accessible through the AVR data bus. Figure 76. Overview of the TWI Module
2486AA–AVR–02/2013 ATmega8(L) Bit Rate Generator Unit This unit controls the period of SCL when oper ating in a Master mode. The SCL period is con- trolled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but the CPU clock frequency in the Slave must be at least 16 times higher than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period. The SCL frequency is generated according to the following equation: TWBR = Value of the TWI Bit Rate Register TWPS = Value of the prescaler bits in the TWI Status Register Note: Pull-up resistor values should be selected according to the SCL frequency and the capacitive bus line load. See Table 101 on page 238 for value of pull-up resistor Bus Interface Unit This unit contains the Data and Address Shif t Register (TWDR), a START/STOP Controller and Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted, or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also contains a register containing the (N)ACK bit to be transmitted or received. This (N)ACK Regis- ter is not directly accessible by the application software. However, when receiving, it can be set or cleared by manipulating the TWI Control R egister (TWCR). When in Transmitter mode, the value of the received (N)ACK bit can be determined by the value in the TWSR. The START/STOP Controller is responsible for generation and detection of START, REPEATED START, and STOP conditions. The START/STOP controller is able to detect START and STOP conditions even when the AVR MCU is in one of the sleep modes, enabling the MCU to wake up if addressed by a Master. If the TWI has initiated a transmission as Master, the Arbitration Detection hardware continu- ously monitors the transmission trying to determine if arbitration is in process. If the TWI has lost an arbitration, the Control Unit is informed. Correct action can then be taken and appropriate status codes generated. Address Match Unit The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the TWAR is written to one, all incoming address bits will also be compared against the General Call address. Upon an address match, the Control Unit is informed, allowing correct action to be taken. The TWI may or may not acknowledge it s address, depending on settings in the TWCR. The Address Match unit is able to compare addresses even when the AVR MCU is in sleep mode, enabling the MCU to wake up if addressed by a Master. If another interrupt (for example, INT0) occurs during TWI Power-down address match and wakes up the CPU, the TWI aborts operation and return to it’s idle state. If this cause any problems, ensure that TWI Address Match is the only enabled interrupt when entering Power-down. Control Unit The Control unit monitors the TWI bus and generates responses corresponding to settings in the TWI Control Register (TWCR). When an event requiring the attention of the application occurs on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Sta- tus Register (TWSR) is updated with a stat us code identifying the event. The TWSR only contains relevant status information when the TW I Interrupt Flag is asserted. At all other times, the TWSR contains a special stat us code indicating that no relevant status information is avail- able. As long as the TWINT Flag is set, the SCL line is held low. This allows the application software to complete its tasks before allowing the TWI transmission to continue. SCL frequency CPU Clock frequency 16 2(TWBR) 4 TWPS+
2486AA–AVR–02/2013 ATmega8(L) The TWINT Flag is set in the following situations: After the TWI has transmitted a START/REPEATED START condition After the TWI has transmitted SLA+R/W After the TWI has transmitted an address byte After the TWI has lost arbitration After the TWI has been addressed by own slave address or general call After the TWI has received a data byte After a STOP or REPEATED START has been received while still addressed as a Slave When a bus error has occurred due to an illegal START or STOP condition TWI Register – TWBR Bits 7..0 – TWI Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the Master modes. See “Bit Rate Generator Unit” on page 164 for calculating bit rates. TWI Control Register – TWCR The TWCR is used to control the operation of the TWI. It is used to enable the TWI, to initiate a Master access by applying a START condition to the bus, to generate a Receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the TWDR. It also indicates a write collision if data is attempted written to TWDR while the register is inaccessible. Bit 7 – TWINT: TWI Interrupt Flag This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT Flag is set, the SCL low period is stretched. The TWINT Flag must be cleared by software by writing a logic one to it. Note that this flag is not automati- cally cleared by hardware when executing the interr upt routine. Also note that clearing this flag starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Sta- tus Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this flag. B i t 76543210 TWBR7 TWBR6 TWBR5 TWBR4 TWBR3 TWBR2 TWBR1 TWBR0 TWBR Read/Write R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 00000000 B i t 76543210 TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE TWCR Read/Write R/W R/W R/W R/W R R/W R R/W I n i t i a l V a l u e 00000000
2486AA–AVR–02/2013 ATmega8(L) Bit 6 – TWEA: TWI Enable Acknowledge Bit The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to one, the ACK pulse is generated on the TWI bus if the following conditions are met: 1. The device’s own slave address has been received 2. A general call has been received, while the TWGCE bit in the TWAR is set 3. A data byte has been received in Master Receiver or Slave Receiver mode By writing the TWEA bit to zero, the device can be virtually disconnected from the Two-wire Serial Bus temporarily. Address recognition can then be resumed by writing the TWEA bit to one again. Bit 5 – TWSTA: TWI START Condition Bit The application writes the TWSTA bit to one when it desires to become a Master on the Two- wire Serial Bus. The TWI hardware checks if the bus is available, and generates a START con- dition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition is detected, and then generates a new START condition to claim the bus Master status. TWSTA must be cleared by software when the START condition has been transmitted. Bit 4 – TWSTO: TWI STOP Condition Bit Writing the TWSTO bit to one in Master mode will generate a STOP condition on the Two-wire Serial Bus. When the STOP condition is exec uted on the bus, the TWSTO bit is cleared auto- matically. In Slave mode, setting the TWSTO bit can be used to recover from an error condition. This will not generate a STOP co ndition, but the TWI returns to a well-defined unaddressed Slave mode and releases the SCL and SDA lines to a high impedance state. Bit 3 – TWWC: TWI Write Collision Flag The TWWC bit is set when attempting to write to the TWI Data Register – TWDR when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is high. Bit 2 – TWEN: TWI Enable Bit The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is written to one, the TWI takes control over the I/O pins connected to the SCL and SDA pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the TWI is switched off and all TWI transmissions are terminated, regardless of any ongoing operation. Bit 1 – Res: Reserved Bit This bit is a reserved bit and will always read as zero. Bit 0 – TWIE: TWI Interrupt Enable When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be acti- vated for as long as the TWINT Flag is high. TWI Status Register – TWSR Bits 7..3 – TWS: TWI Status These 5 bits reflect the status of the TWI logic and the Two-wire Serial Bus. The different status codes are described later in this section. Note that the value read from TWSR contains both the 5-bit status value and the 2-bit prescaler value. The application designer should mask the pres- caler bits to zero when checking the Status bits. This makes status checking independent of prescaler setting. This approach is used in this datasheet, unless otherwise noted. B i t 76543210 TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 TWSR R e a d / W r i t e RRRRRR R / W R / W I n i t i a l V a l u e 11111000
This bit is reserved and will always read as zero. These bits can be read and written, and control the bit rate prescaler. contains the last byte received. It is writable while the TWI is not in the process of shifting a byte. ACK bit is controlled automatically by the TWI logic, the CPU cannot access the ACK bit directly. which can be addressed as Slaves by other Masters. enabled) in the received serial address. If a match is found, an interrupt request is generated. Table 65. TWI Bit Rate Prescaler
2486AA–AVR–02/2013 ATmega8(L) 3. The application software should now examine the value of TWSR, to make sure that the START condition was successfully transmitted. If TWSR indicates otherwise, the applica- tion software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load SLA+W into TWDR. Remember that TWDR is used both for address and data. After TWDR has been loaded with the desired SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Whic h value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the applicat ion has cleared TWINT, the TWI will initiate transmission of the address packet 4. When the address packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the address packet has successfully been sent. The status code will also reflec t whether a Slave acknowledged the packet or not 5. The application software should now examine the value of TWSR, to make sure that the address packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an erro r routine. Assuming that the st atus code is as expected, the application must load a data packet into TWDR. Subsequently, a specific value must be written to TWCR, instructing the TWI hardwa re to transmit the data packet present in TWDR. Which value to write is described late r on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet 6. When the data packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a Slave acknowledged the packet or not 7. The application software should now examine the value of TWSR, to make sure that the data packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an erro r routine. Assuming that the st atus code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TW INT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOP condi- tion. Note that TWINT is NOT set after a STOP condition has been sent Even though this example is simple, it shows t he principles involved in all TWI transmissions. These can be summarized as follows: When the TWI has finished an operation and expects application response, the TWINT Flag is set. The SCL line is pulled low until TWINT is cleared When the TWINT Flag is set, the user must update all TWI Registers with the value relevant for the next TWI bus cycle. As an example, TWDR must be loaded with the value to be transmitted in the next bus cycle After all TWI Register updates and other pending application software tasks have been completed, TWCR is written. When writing TWCR, the TWINT bit should be set. Writing a one to TWINT clears the flag. The TWI will then commence executing whatever operation was specified by the TWCR setting In the following an assembly and C implementation of the example is given. Note that the code below assumes that several definitions have been made, for example by using include-files.
2486AA–AVR–02/2013 ATmega8(L) Assembly Code Example C Example Comments 1 ldi r16, (1<<TWINT)|(1<<TWSTA)| (1<<TWEN) out TWCR, r16 (1<<TWEN) Send START condition 2 wait1: in r16,TWCR sbrs r16,TWINT rjmp wait1 while (!(TWCR & (1<<TWINT))) Wait for TWINT Flag set. This indicates that the START condition has been transmitted 3 in r16,TWSR andi r16, 0xF8 cpi r16, START brne ERROR if ((TWSR & 0xF8) != START) ERROR(); Check value of TWI Status Register. Mask prescaler bits. If status different from START go to ERROR ldi r16, SLA_W out TWDR, r16 ldi r16, (1<<TWINT) | (1<<TWEN) out TWCR, r16 TWDR = SLA_W; TWCR = (1<<TWINT) | (1<<TWEN); Load SLA_W into TWDR Register. Clear TWINT bit in TWCR to start transmission of address 4 wait2: in r16,TWCR sbrs r16,TWINT rjmp wait2 while (!(TWCR & (1<<TWINT))) Wait for TWINT Flag set. This indicates that the SLA+W has been transmitted, and ACK/NACK has been received. 5 in r16,TWSR andi r16, 0xF8 cpi r16, MT_SLA_ACK brne ERROR if ((TWSR & 0xF8) != MT_SLA_ACK) ERROR(); Check value of TWI Status Register. Mask prescaler bits. If status different from MT_SLA_ACK go to ERROR ldi r16, DATA out TWDR, r16 ldi r16, (1<<TWINT) | (1<<TWEN) out TWCR, r16 TWDR = DATA; TWCR = (1<<TWINT) | (1<<TWEN); Load DATA into TWDR Register. Clear TWINT bit in TWCR to start transmission of data 6 wait3: in r16,TWCR sbrs r16,TWINT rjmp wait3 while (!(TWCR & (1<<TWINT))) Wait for TWINT Flag set. This indicates that the DATA has been transmitted, and ACK/NACK has been received. 7 in r16,TWSR andi r16, 0xF8 cpi r16, MT_DATA_ACK brne ERROR if ((TWSR & 0xF8) != MT_DATA_ACK) ERROR(); Check value of TWI Status Register. Mask prescaler bits. If status different from MT_DATA_ACK go to ERROR ldi r16, (1<<TWINT)|(1<<TWEN)| (1<<TWSTO) out TWCR, r16 (1<<TWSTO); Transmit STOP condition
2486AA–AVR–02/2013 ATmega8(L) Transmission Modes The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As an example, the TWI can use MT mode to write data into a TWI EEPROM, MR mode to read the data back from the EEPROM. If other masters are present in the system, some of these might transmit data to the TWI, and then SR mode would be used. It is the application software that decides which modes are legal. The following sections describe each of these modes. Possible status codes are described along with figures detailing data transmission in each of the modes. These figures contain the following abbreviations: S: START condition Rs: REPEATED START condition R: Read bit (high level at SDA) W: Write bit (low level at SDA) A: Acknowledge bit (low level at SDA) A : Not acknowledge bit (high level at SDA) Data: 8-bit data byte P: STOP condition SLA: Slave Address In Figure 79 on page 174 to Figure 85 on page 183, circles are used to indicate that the TWINT Flag is set. The numbers in the circles show the status code held in TWSR, with the prescaler bits masked to zero. At these points, actions must be taken by the application to continue or complete the TWI transfer. The TWI transfer is suspended until the TWINT Flag is cleared by software. When the TWINT Flag is set, the status code in TWSR is used to determine the appropriate soft- ware action. For each status code, the required software action and details of the following serial transfer are given in Table 66 on page 173 to Table 69 on page 182. Note that the prescaler bits are masked to zero in these tables. Master Transmitter Mode In the Master Transmitter mode, a number of data bytes are transmitted to a Slave Receiver (see Figure 78 on page 172 ). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero.
Figure 78. Data Transfer in Master Transmitter Mode is detailed in Table 66 on page 173.
mode without losing control of the bus. Table 66. Status codes for Master Transmitter Mode
Figure 79. Formats and States in the Master Transmitter Mode
prescaler bits are zero or are masked to zero. Figure 80. Data Transfer in Master Receiver Mode
mode without losing control over the bus. Table 67. Status codes for Master Receiver Mode
2486AA–AVR–02/2013 ATmega8(L) The upper 7 bits are the address to which the Two-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address. TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the device’s own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is “0” (write), the TWI will operate in SR mode, otherwise ST mode is entered. After its own slave address and the write bit have been received, the TWINT Flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate soft- ware action. The appropriate action to be taken for each status code is detailed in Table 68 on page 179. The Slave Receiver mode may also be entered if arbitration is lost while the TWI is in the Master mode (see states 0x68 and 0x78). If the TWEA bit is reset during a transfer, the TW I will return a “Not Acknowledge” (“1”) to SDA after the next received data byte. This can be used to indicate that the Slave is not able to receive any more bytes. While TWEA is zero, the TWI does not acknowledge its own slave address. However, the Two-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the Two-wire Serial Bus. In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by using the Two-wire Serial Bus clock as a clock source. The part will then wake up from sleep and the TWI will hold the SCL clock low during the wake up and until the TWINT Flag is cleared (by writing it to one). Further data reception will be carri ed out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. Note that the Two-wire Serial Interface Data Register – TWDR does not reflect the last byte present on the bus when waking up from these Sleep modes. TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 0 100 01 0 X
Table 68. Status Codes for Slave Receiver Mode
Figure 83. Formats and States in the Slave Receiver Mode
Figure 84. Data Transfer in Slave Transmitter Mode otherwise it will ignore the general call address. and TWSTO must be written to zero. in the Master mode (see state 0xB0). Serial Bus is still monitored an d address recognition may resume at any time by setting TWEA.
SCL line may be held low for a long time, blocking other data transmissions. present on the bus when waking up from these sleep modes. Table 69. Status Codes for Slave Transmitter Mode
Figure 85. Formats and States in the Slave Transmitter Mode Miscellaneous States There are two status codes that do not correspond to a defined TWI state, see Table 70. set. This occurs between other states, and when the TWI is not involved in a serial transfer. error occurs when a START or STOP condition occurs at an illegal position in the format frame. Table 70. Miscellaneous States
trying to output a one on SDA while another Master outputs a zero will lose the arbitration. This is summarized in Figure 88. Possible status values are given in circles. Figure 88. Possible Status Codes Caused by Arbitration
Figure 89. Analog Comparator Block Diagram
- Refer to “Pin Configurations” on page 2 and Table 28 on page 63 for Analog Comparator pin
description of this bit, see “Analog Comparator Multiplexed Input” on page 188.
ator. See “Internal Voltage Reference” on page 42. synchronization introduces a delay of 1 - 2 clock cycles. rupt Handling Vector. Alternatively, ACI is cleared by writing a logic one to the flag. parator interrupt is activated. When written logic zero, the interrupt is disabled. Register (TIMSK) must be set. different settings are shown in Table 71. Table 71. ACIS1/ACIS0 Settings
- If ACME is cleared or ADEN is set, AIN1 is applied to the negative input to the Analog
Table 72. Analog Comparator Multiplexed Input(1)
2486AA–AVR–02/2013 ATmega8(L) Analog-to- Digital Converter Features 10-bit Resolution 0.5 LSB Integral Non-linearity ±2 LSB Absolute Accuracy 13µs - 260µs Conversion Time Up to 15 kSPS at Maximum Resolution 6 Multiplexed Single Ended Input Channels 2 Additional Multiplexed Single Ended Input Channels (TQFP and QFN/MLF Package only) Optional Left Adjustment for ADC Result Readout 0 - VCC ADC Input Voltage Range Selectable 2.56V ADC Reference Voltage Free Running or Single Conversion Mode Interrupt on ADC Conversion Complete Sleep Mode Noise Canceler The ATmega8 features a 10-bit successive approximation ADC. The ADC is connected to an 8- channel Analog Multiplexer which allows eight single-ended voltage inputs constructed from the pins of Port C. The single-ended voltage inputs refer to 0V (GND). The ADC contains a Sample and Hold circuit whic h ensures that the input voltage to the ADC is held at a constant level during conversion. A block diagram of the ADC is shown in Figure 90 on page 190. The ADC has a separate analog supply voltage pin, AV CC. AVCC must not differ more than ±0.3V from VCC. See the paragraph “ADC Noise Canceler” on page 195 on how to connect this pin. Internal reference voltages of nominally 2.56V or AV CC are provided On-chip. The voltage refer- ence may be externally decoupled at the AREF pin by a capacitor for better noise performance.
Figure 90. Analog to Digital Converter Block Schematic Operation before entering power saving sleep modes. adjusted by setting the ADLAR bit in ADMUX.
ADC access to the ADCH and ADCL Registers is re-enabled. will trigger even if the result is lost. A single conversion is started by writing a l ogical one to the ADC Start Conversion bit, ADSC. progress, the ADC will finish the current conversion before performing the channel change. In Free Running mode, the ADC is constantly sampling and updating the ADC Data Register. Figure 91. ADC Prescaler input clock frequency to the ADC can be higher than 200kHz to get a higher sample rate. from any CPU frequency above 100kHz. The prescaling is set by the ADPS bits in ADCSRA. 25 ADC clock cycles in order to initialize the analog circuitry.
Figure 94. ADC Timing Diagram, Free Running Conversion Table 73. ADC Conversion Time
2486AA–AVR–02/2013 ATmega8(L) Changing Channel or Reference Selection The MUXn and REFS1:0 bits in the ADMUX Register are single buffered through a temporary register to which the CPU has random access. This ensures that the channels and reference selection only takes place at a safe point dur ing the conversion. The channel and reference selection is continuously updated until a conversion is started. Once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the ADC. Con- tinuous updating resumes in the last ADC clock cycle before the conversion completes (ADIF in ADCSRA is set). Note that the conversion star ts on the following rising ADC clock edge after ADSC is written. The user is thus advised not to write new channel or reference selection values to ADMUX until one ADC clock cycle after ADSC is written. If both ADFR and ADEN is written to one, an interrupt event can occur at any time. If the ADMUX Register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. ADMUX can be safely updated in the following ways: 1. When ADFR or ADEN is cleared 2. During conversion, minimum one ADC clock cycle after the trigger event 3. After a conversion, before the Interrupt Flag used as trigger source is cleared When updating ADMUX in one of these conditions, the new settings will affect the next ADC conversion. ADC Input Channels When changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: In Single Conversion mode, always select the channel before starting the conversion. The chan- nel selection may be changed one ADC clock cycle after writing one to ADSC. However, the simplest method is to wait for the conversion to complete before changing the channel selection. In Free Running mode, always select the channel before starting the first conversion. The chan- nel selection may be changed one ADC clock cycle after writing one to ADSC. However, the simplest method is to wait for the first conversion to complete, and then change the channel selection. Since the next conversion has already started automatically, the next result will reflect the previous channel selection. Subsequent conversions will reflect the new channel selection. ADC Voltage Reference The reference voltage for the ADC (V REF) indicates the conversion range for the ADC. Single ended channels that exceed V REF will result in code s close to 0x3FF. V REF can be selected as either AVCC, internal 2.56V reference, or external AREF pin. AVCC is connected to the ADC through a passive switch. The internal 2.56V reference is gener- ated from the internal bandgap reference (V BG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC, and the reference voltage can be made more immune to noise by connecting a capacitor between the AREF pin and ground. V REF can also be measured at the AREF pin with a high impedant voltmeter. Note that V REF is a high impedant source, and only a capacitive load should be connected in a system. If the user has a fixed voltage source connected to the AREF pin, the user may not use the other reference voltage options in the application, as they will be shorted to the external voltage. If no external voltage is applied to the AREF pin, the user may switch between AV CC and 2.56V as reference selection. The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result.
- Make sure that the ADC is enabled and is not busy converting. Single Conversion
- Enter ADC Noise Reduction mode (or Id le mode). The ADC will start a conversion
- If no other interrupts occur before the ADC conversion completes, the ADC interrupt
ing such sleep modes to avoid excessive power consumption. Figure 95. Analog Input Circuitry
- Keep analog signal paths as short as possible. Make sure analog tracks run over the
ground plane, and keep them well away from high-speed switching digital tracks. an LC network as shown in Figure 96.
- Use the ADC noise canceler function to reduce induced noise from the CPU.
- If any ADC [3..0] port pins are used as digital outputs, it is essential that these do not
Figure 96. ADC Power Connections (LSBs). The lowest code is read as 0, and the highest code is read as 2n-1.
Figure 99. Integral Non-linearity (INL) Figure 100. Differential Non-linearity (DNL) a range of input voltages (1 LSB wide) will code to the same value. Always ±0.5 LSB. error, non-linearity, and quantization error. Ideal value: ±0.5 LSB.
0 VREF Input Voltage
1 LSB
Result Registers (ADCL, ADCH). reference voltage is being applied to the AREF pin. The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register. conversion is complete (ADIF in ADCSRA is set). Table 74. Voltage Reference Selections for ADC
01 AVCC with external capacitor at AREF pin
10 R e s e r v e d
Table 75. Input Channel Selections
0000 ADC0
0001 ADC1
0010 ADC2
0011 ADC3
0100 ADC4
0101 ADC5
ADC off while a conversion is in progress, will terminate this conversion. it returns to zero. Writing zero to this bit has no effect. ADC Conversion Complete Interrupt is executed if the ADIE bit and the I-bit in SREG are set.
0110 ADC6
0111 ADC7
Table 75. Input Channel Selections (Continued)
When an ADC conversion is complete, the result is found in these two registers. ADCH. Otherwise, ADCL must be read first, then ADCH. Table 76. ADC Prescaler Selections
2486AA–AVR–02/2013 ATmega8(L) Boot Loader Support – Read- While-Write Self- Programming The Boot Loader Support provides a real Read- While-Write Self-Programming mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible applica- tion software updates controlled by the MCU using a Flash-resident Boot Loader program. The Boot Loader program can use any available data interface and associated protocol to read code and write (program) that code into the Flash memory, or read the code from the Program mem- ory. The program code within the Boot Loader section has the capability to write into the entire Flash, including the Boot Loader Memory. The B oot Loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. The size of the Boot Loader Memory is configurable with fuses and t he Boot Loader has two separate sets of Boot Lock Bits which can be set independently. This gives the user a unique flexibility to select differ- ent levels of protection. Boot Loader Read-While-Write Self-Programming Flexible Boot Memory Size High Security (Separate Boot Lock Bits for a Flexible Protection) Separate Fuse to Select Reset Vector Optimized Page(1) Size Code Efficient Algorithm Efficient Read-Modify-Write Support Note: 1. A page is a section in the Flash consisting of several bytes (see Table 89 on page 218) used during programming. The page organization does not affect normal operation Application and Boot Loader Flash Sections The Flash memory is organized in two main sections, the Application section and the Boot loader section (see Figure 102 on page 204 ). The size of the different sections is configured by the BOOTSZ Fuses as shown in Table 82 on page 213 and Figure 102 on page 204. These two sections can have different level of protection since they have different sets of Lock Bits. Application Section The application section is the section of the Flash that is used for storing the application code. The protection level for the application section can be selected by the application boot Lock Bits (Boot Lock Bits 0), see Table 78 on page 205. The application section can never store any Boot Loader code since the SPM instruction is disabled when executed from the application section. BLS – Boot Loader Section While the application section is used for storing the application code, the The Boot Loader soft- ware must be located in the BLS since the SPM instruction can initiate a programming when executing from the BLS only. The SPM instruct ion can access the entire Flash, including the BLS itself. The protection level for the Boot Loader section can be selected by the Boot Loader Lock Bits (Boot Lock Bits 1), see Table 79 on page 205. Read-While-Write and No Read- While-Write Flash Sections Whether the CPU supports Read-While-Write or if the CPU is halted during a Boot Loader soft- ware update is dependent on which address that is being programmed. In addition to the two sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also divided into two fixed sections, the Read-Whi le-Write (RWW) section and the No Read-While- Write (NRWW) section. The limit between the RWW- and NRWW sections is given in Table 83 on page 214 and Figure 102 on page 204. The main difference between the two sections is: When erasing or writing a page located inside the RWW section, the NRWW section can be read during the operation When erasing or writing a page located inside the NRWW section, the CPU is halted during the entire operation Note that the user software can never read any code that is located inside the RWW section dur- ing a Boot Loader software operation. The syntax “Read-While-Write section” refers to which section that is being programmed (erased or written), not which section that actually is being read during a Boot Loader software update.
is halted during the entire page erase or page write operation. Figure 101. Read-While-Write vs. No Read-While-Write Table 77. Read-While-Write Features
Figure 102. Memory Sections(1) the user a unique flexibility to select different levels of protection. mode 3) does not control reading nor writing by LPM/SPM, if it is attempted.
changed through the serial or parallel programming interface. Table 78. Boot Lock Bit0 Protection Modes (Application Section) Table 79. Boot Lock Bit1 Protection Modes (Boot Loader Section)(1)
bit in the SPMCR Register is cleared. cleared if a page load operation is initiated. This bit is a reserved bit in the ATmega8 and always read as zero. be lost (The page buffer will be cleared when the Read-While-Write section is re-enabled). set, or if no SPM instruction is executed within four clock cycles. Table 80. Boot Reset Fuse
1 Reset Vector = Application Reset (address 0x0000)
0 Reset Vector = Boot Loader Reset (see Table 82 on page 213)
2486AA–AVR–02/2013 ATmega8(L) Bit 2 – PGWRT: Page Write If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes page write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a page write, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire page write operation if the NRWW section is addressed. Bit 1 – PGERS: Page Erase If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes page erase. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 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 if the NRWW section is addressed. Bit 0 – SPMEN: Store Program Memory Enable This bit enables the SPM instruction for the next four clock cycles. If written to one together with either RWWSRE, BLBSET, PGWRT’ or PGERS, the following SPM instruction will have a spe- cial meaning, see description above. If only SPMEN is written, the following SPM instruction will store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of the Z-pointer is ignored. The SPMEN bit will aut o-clear upon completion of an SPM instruction, or if no SPM instruction is executed within four clock cycles. During page erase and page write, the SPMEN bit remains high until the operation is completed. Writing any other combination than “10001”, “01001”, “00101”, “00011” or “00001” in the lower five bits will have no effect. Addressing the Flash During Self- Programming The Z-pointer is used to address the SPM commands. Since the Flash is organized in pages (see Table 89 on page 218), the Program Counter can be treated as having two different sect ions. 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 103 on page 208 . Note that the page erase and page write operations are addressed independently. Therefore it is of major importance that the Boot Loader software addresses the same page in both the page erase and page write operation. Once a program- ming operation is initiated, the address is latched and the Z-pointer can be used for other operations. The only SPM operation that does not use the Z- pointer is Setting the Boot Loader Lock Bits. The content of the Z-pointer is ignored and will have no effect on the operation. The LPM instruction does also use 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. B i t 1 51 41 31 21 11 0 9 8 ZH (R31) Z15 Z14 Z13 Z12 Z11 Z10 Z9 Z8 Z L ( R 3 0 ) Z 7Z 6Z 5Z 4Z 3Z 2Z 1Z 0 76543210
Figure 103. Addressing the Flash during SPM(1)
- PCPAGE and PCWORD are listed in Table 89 on page 218
Alternative 1, fill the buffer before a page erase. Alternative 2, fill the buffer after page erase.
2486AA–AVR–02/2013 ATmega8(L) Performing Page Erase by SPM To execute page erase, set up the address in the Z-pointer, write “X0000011” to SPMCR and execute SPM within four clock cycles after wr iting SPMCR. 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. Page Erase to the RWW section: The NRWW section can be read during the page erase Page Erase to the NRWW section: The CPU is halted during the operation Note: If an interrupt occurs in the timed sequence, the four cycle access cannot be guaranteed. In order to ensure atomic operation, disable interrupts before writing to SPMCSR. Filling the Temporary Buffer (Page Loading) To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write “00000001” to SPMCR and execute SPM within four clock cycles after writing SPMCR. The con- tent of PCWORD in the Z-register is used to address the data in the temporary page buffer. The temporary buffer will auto-erase after a page writ e operation or by writ ing the RWWSRE bit in SPMCR. It is also erased after a System Reset. No te that it is not possible to write more than one time to each address without erasing the temporary buffer. Note: If the EEPROM is written in the middle of an SPM page Load operation, all data loaded will be lost Performing a Page Write To execute page write, set up the address in the Z-pointer, write “X0000101” to SPMCR and execute SPM within four clock cycles after wr iting SPMCR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer must be written to zero during this operation. Page Write to the RWW section: The NRWW section can be read during the page write Page Write to the NRWW section: The CPU is halted during the operation Using the SPM Interrupt If the SPM interrupt is en abled, the SPM interrupt will genera te a constant in terrupt when the SPMEN bit in SPMCR is cleared. This means t hat the interrupt can be used instead of polling the SPMCR Register in software. When using the SPM interrupt, the Interrupt Vectors should be moved to the BLS section to avoid that an in terrupt is accessing the RWW section when it is blocked for reading. How to move the interrupts is described in “Interrupts” on page 46. Consideration While Updating BLS Special care must be taken if the user allows the Boot Loader section to be updated by leaving Boot Lock bit11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the entire Boot Loader, and further software updates might be impossible. If it is not necessary to change the Boot Loader software itself, it is recommended to program the Boot Lock bit11 to protect the Boot Loader software from any internal software changes. Prevent Reading the RWW Section During Self-Programming During Self-Programming (either page erase or page write), the RWW section is always blocked for reading. The user software itself must prevent that this section is addressed during the self programming operation. The RWWSB in the SPMCR will be set as long as the RWW section is busy. During Self-Programming the Interrupt Vector table should be moved to the BLS as described in “Interrupts” on page 46, or the interrupts must be disabled. Before addressing the RWW section after the programming is completed, the user software must clear the RWWSB by writing the RWWSRE. See “Simple Assembly Code Example for a Boot Loader” on page 212 for an example. Setting the Boot Loader Lock Bits by SPM To set the Boot Loader Lock Bits, write the desired data to R0, write “X0001001” to SPMCR and execute SPM within four clock cycles after writ ing SPMCR. The only accessible Lock Bits are the Boot Lock Bits that may prevent the Application and Boot Loader section from any software update by the MCU. B i t 76543210 R0 1 1 BLB12 BLB11 BLB02 BLB01 1 1
2486AA–AVR–02/2013 ATmega8(L) See Table 78 on page 205 and Table 79 on page 205 for how the different settings of the Boot Loader Bits affect the Flash access. If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock bit will be programmed if an SPM instruction is executed within four cy cles after BLBSET and SPMEN are set in SPMCR. The Z-pointer is don’t care during this operation, but for future compatibility it is recommended to load the Z-pointer with 0x0001 (same as used for reading the Lock Bits). For future compatibility It is also recommended to set bits 7, 6, 1, and 0 in R0 to “1” when writing the Lock Bits. When programming the Lock Bits the entire Flash can be read during the operation. EEPROM Write Prevents Writing to SPMCR Note that an EEPROM write operation will block all software programming to Flash. Reading the Fuses and Lock Bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEWE) in the EECR Register and verifies that the bit is cleared before writing to the SPMCR Register. Reading the Fuse and Lock Bits from Software It is possible to read both the Fuse and Lock Bits from software. To read the Lock Bits, load the Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCR. When an LPM instruc- tion is executed within three CPU cycles after the BLBSET and SPMEN bits are set in SPMCR, the value of the Lock Bits will be loaded in t he destination register. The BLBSET 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 instruction is executed within four CPU cycles. When BLB- SET and SPMEN are cleared, LPM will work as described in the Instruction set Manual. The algorithm for reading the Fuse Low bits is similar to the one described above for reading the Lock Bits. To read the Fuse Low bits, load th e Z-pointer with 0x0000 and set the BLBSET and SPMEN bits in SPMCR. When an LPM instruction is executed within three cycles after the BLB- SET and SPMEN bits are set in the SPMCR, the value of the Fuse Low bits (FLB) will be loaded in the destination register as shown below. Refer to Table 88 on page 217 for a detailed descrip- tion and mapping of the fuse low bits. Similarly, when reading the Fuse High bits, load 0x0003 in the Z-pointer. When an LPM instruc- tion is executed within three cycles after the BLBSET and SPME N bits are set in the SPMCR, the value of the Fuse High bits (FHB) will be lo aded in the destination register as shown below. Refer to Table 87 on page 216 for detailed description and mapping of the fuse high bits. Fuse and Lock Bits that are programmed, will be read as zero. Fuse and Lock Bits that are unprogrammed, will be read as one. Preventing Flash Corruption During periods of low V CC, the Flash program can be corrupted because the supply voltage is too low for the CPU and the Flash to operate properly. These issues are the same as for board level systems using the Flash, and the same design solutions should be applied. A Flash program corruption can be caused by two 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. B i t 76543210 Rd – – BLB12 BLB11 BLB02 BLB01 LB2 LB1 B i t 76543210 Rd FLB7 FLB6 FLB5 FLB4 FLB3 FLB2 FLB1 FLB0 B i t 76543210 Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0
- If there is no need for a Boot Loader update in the system, program the Boot Loader Lock
- Keep the AVR RESET active (low) during pe riods of insufficient power supply voltage.
- Keep the AVR core in Power-down sleep mode during periods of low V CC. This will pre-
gramming time for Flash accesses from the CPU. Table 81. SPM Programming Time(1)
2486AA–AVR–02/2013 ATmega8(L) Simple Assembly Code Example for a Boot Loader ;-the routine writes one page of data from RAM to Flash ; the first data location in RAM is pointed to by the Y pointer ; the first data location in Flash is pointed to by the Z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the Do_spm sub routine). Only code inside NRWW section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-It is assumed that either the interrupt table is moved to the Boot ; loader section or that the interrupts are disabled. .equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words .org SMALLBOOTSTART Write_page: ; page erase ldi spmcrval, (1<<PGERS) | (1<<SPMEN) rcallDo_spm ; re-enable the RWW section ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN) rcallDo_spm ; transfer data from RAM to Flash page buffer ldi looplo, low(PAGESIZEB) ;init loop variable ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256 Wrloop: ld r0, Y+ ld r1, Y+ ldi spmcrval, (1<<SPMEN) rcallDo_spm adiw ZH:ZL, 2 sbiw loophi:looplo, 2 ;use subi for PAGESIZEB<=256 brne Wrloop ; execute page write subi ZL, low(PAGESIZEB) ;restore pointer sbci ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256 ldi spmcrval, (1<<PGWRT) | (1<<SPMEN) rcallDo_spm ; re-enable the RWW section ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN) rcallDo_spm ; read back and check, optional ldi looplo, low(PAGESIZEB) ;init loop variable ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256 subi YL, low(PAGESIZEB) ;restore pointer sbci YH, high(PAGESIZEB) Rdloop: lpm r0, Z+ ld r1, Y+ cpse r0, r1 rjmp Error sbiw loophi:looplo, 1 ;use subi for PAGESIZEB<=256 brne Rdloop
Table 82. Boot Size Configuration
and “RWW – Read-While-Write Section” on page 203. Z0: should be zero for all SPM commands, byte select for the LPM instruction. Table 83. Read-While-Write Limit Table 84. Explanation of Different Variables used in Figure 103 on page 208 and the Mapping PCMSB 11 Most significant bit in the Program Counter. ZPCMSB Z12 Bit in Z-register that is mapped to PCMSB. ZPAGEMSB Z5 Bit in Z-register that is mapped to PAGEMSB.
erased to “1” with the Chip Erase command. Table 85. Lock Bit Byte Table 86. Lock Bit Protection Modes(2)
- “1” means unprogrammed, “0” means programmed
read as logical zero, “0”, if they are programmed.
- The CKOPT Fuse functiona lity depends on the setting of the CKSEL bits, see “Clock Sources”
- The default value of BOOTSZ1..0 results in maximum Boot Size. See Table 82 on page 213
- When programming the RSTDISBL Fuse Para llel Programming has to be used to change
Table 86. Lock Bit Protection Modes(2) (Continued) Table 87. Fuse High Byte
- The default setting of CKSEL3..0 result s in internal RC Oscillator @ 1MHz. See Table 2 on
lock bit1 (LB1) is programmed. Program the Fuse Bits before programming the Lock Bits. Table 88. Fuse Low Byte
reside in a separate address space.
- 0x000: 0x1E (indicates manufactured by Atmel)
- 0x001: 0x93 (indicates 8KB Flash memory)
- 0x002: 0x07 (indicates ATmega8 device)
loaded manually, see “Oscillator Calibration Register – OSCCAL” on page 31 for details. Table 89. No. of Words in a Page and no. of Pages in the Flash Table 90. No. of Words in a Page and no. of Pages in the EEPROM
least 250ns unless otherwise noted. following table are referenced by pin names. The XA1/XA0 pins determine the action executed when the XTAL1 pin is given a positive pulse. The bit coding is shown in Table 93 on page 220. Commands are shown in Table 94 on page 220. Figure 104. Parallel Programming Table 91. Pin Name Mapping
Table 92. Pin Values used to Enter Programming Mode Table 93. XA1 and XA0 Coding Table 94. Command Byte Bit Coding Table 91. Pin Name Mapping (Continued)
2486AA–AVR–02/2013 ATmega8(L) Parallel Programming Enter Programming Mode The following algorithm puts the device in Parallel Programming mode: 1. Apply 4.5V - 5.5V between V CC and GND, and wait at least 100µs 2. Set RESET to “0” and toggle XTAL1 at least 6 times 3. Set the Prog_enable pins listed in Table 92 on page 220 to “0000” and wait at least 100ns 4. Apply 11.5V - 12.5V to RESET . Any activity on Prog_enable pins within 100ns after +12V has been applied to RESET, will cause the device to fail entering Programming mode Note, if the RESET pin is disabled by programming the RSTDISBL Fuse, it may not be possible to follow the proposed algorithm above. The same may apply when External Crystal or External RC configuration is selected because it is not possible to apply qualified XTAL1 pulses. In such cases, the following algorithm should be followed: 1. Set Prog_enable pins listed in Table 92 on page 220 to “0000” 2. Apply 4.5V - 5.5V between V CC and GND simultaneously as 11.5V - 12.5V is applied to RESET 3. Wait 100ns 4. Re-program the fuses to ensure that External Clock is selected as clock source (CKSEL3:0 = 0’b0000) and RESET pin is activated (RSTDISBL unprogrammed). If Lock Bits are programmed, a chip erase command must be executed before changing the fuses 5. Exit Programming mode by power the device down or by bringing RESET pin to 0’b0 6. Entering Programming mode with the original algorithm, as described above Considerations for Efficient Programming The loaded command and address are retained in the device during programming. For efficient programming, the following should be considered. The command needs only be loaded once when writing or reading multiple memory locations Skip writing the data value 0xFF , that is t he 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 Chip Erase The Chip Erase will erase the Flash and EEPROM (1) memories plus Lock Bits. The Lock Bits are not reset until the Program memory has been completely erased. The Fuse Bits are not changed. A Chip Erase must be performed before the Flash and/or the EEPROM are reprogrammed. Note: 1. The EEPRPOM memory is preserved duri ng chip erase if the EESAVE Fuse is programmed Load Command “Chip Erase” 1. Set XA1, XA0 to “10”. This enables command loading 2. Set BS1 to “0” 3. Set DATA to “1000 0000”. This is the command for Chip Erase 4. Give XTAL1 a positive pulse. This loads the command 5. Give WR a negative pulse. This starts the Chip Erase. RDY/BSY goes low 6. Wait until RDY/BSY goes high before loading a new command
2486AA–AVR–02/2013 ATmega8(L) Programming the Flash The Flash is organized in pages, see Table 89 on page 218. When programming the Flash, the program data is latched into a page buffer. This allows one page of program data to be pro- grammed simultaneously. The following procedure describes how to program the entire Flash memory: A. Load Command “Write Flash” 1. Set XA1, XA0 to “10”. This enables command loading 2. Set BS1 to ”0” 3. Set DATA to “0001 0000”. This is the command for Write Flash 4. Give XTAL1 a positive pulse. This loads the command B. Load Address Low byte 1. Set XA1, XA0 to “00”. This enables address loading 2. Set BS1 to “0”. This selects low address 3. Set DATA = Address Low byte (0x00 - 0xFF) 4. Give XTAL1 a positive pulse. This loads the address Low byte C. Load Data Low byte 1. Set XA1, XA0 to “01”. This enables data loading 2. Set DATA = Data Low byte (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 “01”. 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 106 on page 224 for signal waveforms) F. Repeat B through E until the entire buffer is filled or until all data within the page is loaded While the lower bits in the address are mapped to words within the page, the higher bits address the pages within the FLASH. This is illustrated in Figure 105 on page 223. Note that if less than eight bits are required to address words in the page (pagesize <256), the most significant bit(s) in the address Low byte are used to address the page when performing a page write. G. Load Address High byte 1. Set XA1, XA0 to “00”. This enables address loading 2. Set BS1 to “1”. This selects high address 3. Set DATA = Address High byte (0x00 - 0xFF) 4. Give XTAL1 a positive pulse. This loads the address High byte H. Program Page 1. Set BS1 = “0” 2. Give WR a negative pulse. This starts programming of the entire page of data. RDY/BSY goes low 3. Wait until RDY/BSY goes high. (See Figure 106 on page 224 for signal waveforms)
- Set XA1, XA0 to “10”. This enables command loading
- Set DATA to “0000 0000”. This is the command for No Operation
- Give XTAL1 a positive pulse. This loads the command, and the internal write signals are
Figure 105. Addressing the Flash which is Organized in Pages
Figure 106. Programming the Flash Waveforms(1)
- G: Load Address High byte (0x00 - 0xFF)
- B: Load Address Low byte (0x00 - 0xFF)
- E: Latch data (give PAGEL a positive pulse)
- Wait until to RDY/BSY goes high before programming the next page (see Figure 107 on
Figure 107. Programming the EEPROM Waveforms
- G: Load Address High byte (0x00 - 0xFF)
- B: Load Address Low byte (0x00 - 0xFF)
- Set BS1 to “1”. The Flash word High byte can now be read at DATA
- G: Load Address High byte (0x00 - 0xFF)
- B: Load Address Low byte (0x00 - 0xFF)
- C: Load Data Low byte. Bit n = “0” programs and bit n = “1” erases the Fuse bit
- C: Load Data Low byte. Bit n = “0” programs and bit n = “1” erases the Fuse bit
- Set BS1 to “1” and BS2 to “0”. This selects high data byte
- Set BS1 to “0”. This selects low data byte
- C: Load Data Low byte. Bit n = “0” programs the Lock bit
The Lock Bits can only be cleared by executing Chip Erase.
- Set OE to “0”, BS2 to “1”, and BS1 to “1”. The status of the Fuse High bits can now be
- Set OE to “0”, BS2 to “0”, and BS1 to “1”. The status of the Lock Bits can now be read at
Figure 108. Mapping Between BS1, BS2 and the Fuse- and Lock Bits During Read
Figure 111. Parallel Programming Timing, Reading Sequence (within the same Page) with Tim- Table 95. Parallel Programming Characteristics, VCC = 5V ±10%
- t WLRH_CE is valid for the Chip Erase command
Table 95. Parallel Programming Characteristics, VCC = 5V ±10% (Continued)
programming is listed. Not all parts use the SPI pins dedicated for the internal SPI interface. Figure 112. Serial Programming and Verify(1) Program and EEPROM arrays into 0xFF. Table 96. Pin Mapping Serial Programming
2486AA–AVR–02/2013 ATmega8(L) Serial Programming Algorithm When writing serial data to the ATmega8, data is clocked on the rising edge of SCK. When reading data from the ATmega8, data is clocked on the falling edge of SCK. See Figure 113 on page 232 for timing details. To program and verify the ATmega8 in the Serial Programming mode, the following sequence is recommended (see four byte instruction formats in Table 98 on page 233): 1. Power-up sequence: Apply power between VCC and GND while RESET and SCK are set to “0”. In some sys- tems, the programmer can not guarantee that SCK is held low during Power-up. In this case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to “0” 2. Wait for at least 20ms and enable Serial Programming by sending the Programming Enable serial instruction to pin MOSI 3. The Serial Programming instructions will not wo rk if the communication is out of synchro- nization. When in sync. the se cond 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 page size is found in Table 89 on page 218. The memory page is loaded one byte at a time by supplying the 5 LSB of the address and data together with the Load Program memory Page instruction. To ensure correct loading of the page, the data Low byte must be loaded before data High byte is applied for a given address. The Program memory Page is stored by loading the Write Program memory Page instruction with the 7M SB of the address. If polling is not used, the user must wait at least t WD_FLASH before issuing the next page (see Table 97 on page 232). Note: If other commands than polling (read) are applied before any write operation (FLASH, EEPROM, Lock Bits, Fuses) is completed, it may result in incorrect programming 5. The EEPROM array is programmed one byte at a time by supplying the address and data together with th e appropriate Writ e instruction. An EEPROM me mory location is first automatically erased before new data is written. If polling is not used, the user must wait at least t WD_EEPROM before issuing the next byte (see Table 97 on page 232 ). In a chip erased device, no 0xFFs in the data file(s) need to be programmed 6. Any memory location can be verified by using the Read instruction which returns the con- tent at the selected address at serial output MISO 7. At the end of the programming session, RESET can be set high to commence normal operation 8. Power-off sequence (if needed): Set RESET to “1” Tur n VCC power off Data Polling Flash When a page is being programmed into the Flash, reading an address location within the page being programmed will give the value 0xFF. At th e time the device is ready for a new page, the programmed value will read correctly. This is used to determine when the next page can be writ- ten. Note that the entire page is written simultaneously and any address within the page can be used for polling. Data polling of the Flash will not work for the value 0xFF, so when programming this value, the user will have to wait for at least t WD_FLASH before programming the next page. As a chip-erased device contains 0xFF in all locations, programming of addresses that are meant to contain 0xFF, can be skipped. See Table 97 on page 232 for t WD_FLASH value.
Table 97 for tWD_EEPROM value. Figure 113. Serial Programming Waveforms Table 97. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Table 98. Serial Programming Instruction Set
0100 H000 0000 xxxx xxx b bbbb iiii iiii Write H (high or low) data i to
grammed, “1” = unprogrammed.
2486AA–AVR–02/2013 ATmega8(L) SPI Serial Programming Characteristics For characteristics of the SPI module, see “SPI Timing Characteristics” on page 239.
2486AA–AVR–02/2013 ATmega8(L) Electrical Characteristics – TA = -40°C to 85°C Note: Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers man u- factured on the same process technology. Min and Max values will be available after the device is characterized. DC Characteristics Absolute Maximum Ratings* 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. Voltage on any Pin except RESET DC Current TA = -40C to +85C, VCC = 2.7V to 5.5V (unless otherwise noted) Symbol Parameter Condition Min Typ Max Units VIL Input Low Voltage except XTAL1 and RESET pins VCC = 2.7V - 5.5V -0.5 0.2 V CC (1) V VIH Input High Voltage except XTAL1 and RESET pins VCC = 2.7V - 5.5V 0.6V CC (2) VCC + 0.5 VIL1 Input Low Voltage XTAL1 pin VCC = 2.7V - 5.5V -0.5 0.1V CC (1) VIH1 Input High Voltage XTAL 1 pin VCC = 2.7V - 5.5V 0.8V CC (2) VCC + 0.5 VIL2 Input Low Voltage RESET pin VCC = 2.7V - 5.5V -0.5 0.2 V CC VIH2 Input High Voltage RESET pin VCC = 2.7V - 5.5V 0.9V CC (2) VCC + 0.5 VIL3 Input Low Voltage RESET pin as I/O VCC = 2.7V - 5.5V -0.5 0.2V CC VIH3 Input High Voltage RESET pin as I/O VCC = 2.7V - 5.5V 0.6VCC (2) 0.7VCC (2) VCC + 0.5 VOL Output Low Voltage(3) (Ports B,C,D) IOL = 20mA, VCC = 5V IOL = 10mA, VCC = 3V 0.9 0.6 VOH Output High Voltage(4) (Ports B,C,D) IOH = -20mA, VCC = 5V IOH = -10mA, VCC = 3V 4.2 2.2 IIL Input Leakage Current I/O Pin Vcc = 5.5V, pin low (absolute value) 1 µA IIH Input Leakage Current I/O Pin Vcc = 5.5V, pin high (absolute value) 1 RRST Reset Pull-up Resistor 30 80 k
2486AA–AVR–02/2013 ATmega8(L) Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low 2. “Min” means the lowest value where t he pin is guaranteed to be read as high 3. Although each I/O port can sink more than the test condit ions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state conditions (non-transient), the following must be observed: PDIP , TQFP , and QFN/MLF Package: 1] The sum of all IOL, for all ports, should not exceed 300mA. 2] The sum of all IOL, for ports C0 - C5 should not exceed 100mA. 3] The sum of all IOL, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200mA. If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition 4. Although each I/O port can source more than the test cond itions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state conditions (non-transient), the following must be observed: PDIP , TQFP , and QFN/MLF Package: 1] The sum of all IOH, for all ports, should not exceed 300mA. 2] The sum of all IOH, for port C0 - C5, should not exceed 100mA. 3] The sum of all IOH, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200mA. If IOH exceeds the test condition, VOH may exceed the rela ted specification. Pins are not guaranteed to source current greater than the listed test condition 5. Minimum V CC for Power-down is 2.5V Rpu I/O Pin Pull-up Resistor 20 50 k ICC Power Supply Current Active 4MHz, VCC = 3V (ATmega8L) 35 mA Active 8MHz, VCC = 5V (ATmega8) 11 15 Idle 4MHz, VCC = 3V (ATmega8L) 12 Idle 8MHz, VCC = 5V (ATmega8) 4.5 7 Power-down mode(5) WDT enabled, VCC = 3V < 22 28 µA WDT disabled, VCC = 3V < 1 3 VACIO Analog Comparator Input Offset Voltage VCC = 5V Vin = VCC/2 40 mV IACLK Analog Comparator Input Leakage Current VCC = 5V Vin = VCC/2 -50 50 nA tACPD Analog Comparator Propagation Delay VCC = 2.7V VCC = 5.0V 750 500 ns TA = -40C to +85C, VCC = 2.7V to 5.5V (unless otherwise noted) (Continued) Symbol Parameter Condition Min Typ Max Units
Figure 114. External Clock Drive Waveforms
- The frequency will vary with package type and board layout
Table 99. External Clock Drive Table 100. External RC Oscillator, Typical Frequencies
Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 115 on page 239.
- Required only for f SCL > 100kHz
- C b = capacitance of one bus line in pF
- f CK = CPU clock frequency
Table 101. Two-wire Serial Bus Requirements
- This requirement applies to all ATmega8 Two-wire Serial Interface operation. Other devices connected to the Two-wire Serial
- The actual low period generated by the ATmega8 Two-wire Serial Interface is (1/f SCL - 2/fCK), thus fCK must be greater than
- The actual low period generated by the ATmega8 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus the low time requirement
Figure 115. Two-wire Serial Bus Timing See Figure 116 on page 240 and Figure 117 on page 240 for details. Table 102. SPI Timing Parameters
1 SCK period Master See Table 50 on
2 SCK high/low Master 50% duty cycle
4 Setup Master 10
5 Hold Master 10
7 SCK to out Master 10
8 SCK to out high Master 10
10 SCK period Slave 4 t ck
11 SCK high/low (1) Slave 2 t ck
12 Rise/Fall time Slave 1600
13 Setup Slave 10
14 Hold Slave 10
15 SCK to out Slave 15
16 SCK to SS
17 SS high to tri-state Slave 10
18 SS low to SCK Salve 2 t ck
- Maximum conversion time is 1/50kHz × 25 = 0.5ms
Table 103. ADC Characteristics
2486AA–AVR–02/2013 ATmega8(L) Electrical Characteristics – TA = -40°C to 105°C Note: Typical values contained in this data sheet are based on simulations and characterization of other AVR microcontrollers manu- factured on the same process technology. Min and Max values will be available after the device is characterized. Absolute Maximum Ratings* 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. Voltage on any Pin except RESET DC Current DC Characteristics TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted) Symbol Parameter Condition Min Typ Max Units VIL Input Low Voltage Except XTAL1 pin -0.5 0.2 V CC (1) V VIL1 Input Low Voltage XTAL1 pin, External Clock Selected -0.5 0.1 V CC (1) V VIH Input High Voltage Except XTAL1 and RESET pins 0.6 V CC (2) VCC + 0.5 V VIH1 Input High Voltage XTAL1 pin, External Clock Selected 0.8 V CC (2) VCC + 0.5 V VIH2 Input High Voltage RESET pin 0.9 V CC (2) VCC + 0.5 V VOL Output Low Voltage(3) (Ports A,B,C,D) IOL = 20 mA, VCC = 5V IOL = 10 mA, VCC = 3V 0.8 0.6 V V VOH Output High Voltage(4) (Ports A,B,C,D) IOH = -20 mA, VCC = 5V IOH = -10 mA, VCC = 3V 4.0 2.2 V V IIL Input Leakage Current I/O Pin Vcc = 5.5V, pin low (absolute value) 3µ A IIH Input Leakage Current I/O Pin Vcc = 5.5V, pin high (absolute value) 3µ A RRST Reset Pull-up Resistor 30 80 k Rpu I/O Pin Pull-up Resistor 20 50 k
2486AA–AVR–02/2013 ATmega8(L) Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low 2. “Min” means the lowest value where t he pin is guaranteed to be read as high 3. Although each I/O port can sink more than the test condit ions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state conditions (non-transient), the following must be observed: 1] The sum of all IOL, for all ports, should not exceed 400 mA. 2] The sum of all IOL, for ports C0 - C5 should not exceed 200 mA. 3] The sum of all IOL, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 100 mA. TQFP and MLF Package: 1] The sum of all IOL, for all ports, should not exceed 400 mA. 2] The sum of all IOL, for ports C0 - C5, should not exceed 200 mA. 3] The sum of all IOL, for ports C6, D0 - D4, should not exceed 300 mA. 4] The sum of all IOL, for ports B0 - B7, D5 - D7, should not exceed 300 mA. If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition. 4. Although each I/O port can source more than the test cond itions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state conditions (non-transient), the following must be observed: 1] The sum of all IOH, for all ports, should not exceed 400 mA. 2] The sum of all IOH, for port C0 - C5, should not exceed 100 mA. 3] The sum of all IOH, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 100 mA. TQFP and MLF Package: 1] The sum of all IOH, for all ports, should not exceed 400 mA. 2] The sum of all IOH, for ports C0 - C5, should not exceed 200 mA. 3] The sum of all IOH, for ports C6, D0 - D4, should not exceed 300 mA. 4] The sum of all IOH, for ports B0 - B7, D5 - D7, should not exceed 300 mA. If IOH exceeds the test condition, VOH may exceed the rela ted specification. Pins are not guaranteed to source current greater than the listed test condition. 5. Minimum V CC for Power-down is 2.5V. ICC Power Supply Current Active 4 MHz, VCC = 3V (ATmega8L) 6m A Active 8 MHz, VCC = 5V (ATmega8) 15 mA Idle 4 MHz, VCC = 3V (ATmega8L) 3m A Idle 8 MHz, VCC = 5V (ATmega8) 8m A Power-down mode(5) WDT enabled, VCC = 3V 35 µA WDT disabled, VCC = 3V 6 µA VACIO Analog Comparator Input Offset Voltage VCC = 5V Vin = VCC/2 20 mV IACLK Analog Comparator Input Leakage Current VCC = 5V Vin = VCC/2 -50 50 nA tACPD Analog Comparator Propagation Delay VCC = 2.7V VCC = 5.0V 750 500 ns DC Characteristics TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted) (Continued) Symbol Parameter Condition Min Typ Max Units
2486AA–AVR–02/2013 ATmega8(L) ATmega8 Typical Characteristics TA = -40°C to 85°C The following charts show typical behavior. T hese figures are not tested during manufacturing. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A sine wave generator with Rail-to-Rail output is used as clock source. The power consumption in Power-down mode is independent of clock selection. The current consumption is a function of several factors such as: operating voltage, operating frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient tempera- ture. The dominating factors are operating voltage and frequency. The current drawn from capacitive loaded pins may be estimated (for one pin) as: C L × VCC × f where CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O pin. The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. The difference between current consumption in Power-down mode with Watchdog Timer enabled and Power-down mode with Watchdog Timer disabled represents the differential cur- rent drawn by the Watchdog Timer. Active Supply Current Figure 118. Active Supply Current vs. Frequency (0.1MHz - 1.0MHz) 0.5 1.5 2.5 Frequency (MHz) ICC (mA) 5.5V 5.0V 4.5V 3.3V 3.0V 2.7V 4.0V
Figure 126. Idle Supply Current vs. Frequency (1MHz - 20MHz)
Figure 144. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 2.7V)
Figure 148. I/O Pin Source Current vs. Output Voltage (VCC = 2.7V)
Figure 191. Reset Pulse Width vs. VCC
2486AA–AVR–02/2013 ATmega8(L) ATmega8 Typical Characteristics TA = -40°C to 105°C The following charts show typical behavior. T hese figures are not tested during manufacturing. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A sine wave generator with Rail-to-Rail output is used as clock source. The power consumption in Power-down mode is independent of clock selection. The current consumption is a function of several factors such as: operating voltage, operating frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient tempera- ture. The dominating factors are operating voltage and frequency. The current drawn from capacitive loaded pins may be estimated (for one pin) as C L*VCC*f where CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O pin. The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. The difference between current consumption in Power-down mode with Watchdog Timer enabled and Power-down mode with Watchdog Timer disabled represents the differential cur- rent drawn by the Watchdog Timer. Active Supply Current Figure 0-1. Active Supply Current vs. VCC (Internal RC Oscillator, 8 MHz) ACTIVE SUPPLY CURRENT vs. VCC INTERNAL RC OSCILLATOR, 8 MHz 2.5 3 3.5 4 4.5 5 5.5 V CC (V) ICC (mA) 85°C 25°C -40°C 105°C
2486AA–AVR–02/2013 ATmega8(L) Current Consumption in Reset and Reset Pulsewidth Figure 0-52. Reset Pulse Width vs. VCC RESET PULSE WIDTH vs. VCC 200 400 600 800 1000 1200 1400 2.5 3 3.5 4 4.5 5 5.5 VCC (V) Pulsewidth (ns) 85°C 25°C -40°C 105°C
2486AA–AVR–02/2013 ATmega8(L) Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page 0x3F (0x5F) SREG I T H S V N Z C 11 0x3E (0x5E) SPH – – – – – SP10 SP9 SP8 13 0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 13 0x3C (0x5C) Reserved 0x3B (0x5B) GICR INT1 INT0 – – – – IVSEL IVCE 49, 67 0x3A (0x5A) GIFR INTF1 INTF0 – – – – – – 67 0x39 (0x59) TIMSK OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 72, 100, 119 0x38 (0x58) TIFR OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 –T O V 0 72, 101, 119 0x37 (0x57) SPMCR SPMIE RWWSB – RWWSRE BLBSET PGWRT PGERS SPMEN 206 0x36 (0x56) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN –T W I E 165 0x35 (0x55) MCUCR SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00 33, 66 0x34 (0x54) MCUCSR – – – – WDRF BORF EXTRF PORF 41 0x33 (0x53) TCCR0 – – – – – CS02 CS01 CS00 71 0x32 (0x52) TCNT0 Timer/Counter0 (8 Bits) 72 0x31 (0x51) OSCCAL Oscillator Calibration Register 31 0x30 (0x50) SFIOR – – – – ACME PUD PSR2 PSR10 58, 74, 120, 186 0x2F (0x4F) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 96 0x2E (0x4E) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 98 0x2D (0x4D) TCNT1H Timer/Counter1 – Counter Register High byte 99 0x2C (0x4C) TCNT1L Timer/Counter1 – Counter Register Low byte 99 0x2B (0x4B) OCR1AH Timer/Counter1 – Output Compare Register A High byte 99 0x2A (0x4A) OCR1AL Timer/Counter1 – Output Compare Register A Low byte 99 0x29 (0x49) OCR1BH Timer/Counter1 – Output Compare Register B High byte 99 0x28 (0x48) OCR1BL Timer/Counter1 – Output Compare Register B Low byte 99 0x27 (0x47) ICR1H Timer/Counter1 – Input Capture Register High byte 100 0x26 (0x46) ICR1L Timer/Counter1 – Input Capture Register Low byte 100 0x25 (0x45) TCCR2 FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20 114 0x24 (0x44) TCNT2 Timer/Counter2 (8 Bits) 116 0x23 (0x43) OCR2 Timer/Counter2 Output Compare Register 116 0x22 (0x42) ASSR – – – – AS2 TCN2UB OCR2UB TCR2UB 117 0x21 (0x41) WDTCR – – – WDCE WDE WDP2 WDP1 WDP0 43 0x20(1) (0x40)(1) UBRRH URSEL – – – UBRR[11:8] 152 UCSRC URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL 150 0x1F (0x3F) EEARH – – – – – – –E E A R 8 20 0x1E (0x3E) EEARL EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 20 0x1D (0x3D) EEDR EEPROM Data Register 20 0x1C (0x3C) EECR – – – – EERIE EEMWE EEWE EERE 20 0x1B (0x3B) Reserved 0x1A (0x3A) Reserved 0x19 (0x39) Reserved 0x18 (0x38) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 65 0x17 (0x37) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 65 0x16 (0x36) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 65 0x15 (0x35) PORTC – PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 65 0x14 (0x34) DDRC – DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 65 0x13 (0x33) PINC – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 65 0x12 (0x32) PORTD PORTD7 PORTD6 PORTD 5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 65 0x11 (0x31) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 65 0x10 (0x30) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 65 0x0F (0x2F) SPDR SPI Data Register 127 0x0E (0x2E) SPSR SPIF WCOL – – – – –S P I 2 X 126 0x0D (0x2D) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 125 0x0C (0x2C) UDR USART I/O Data Register 148 0x0B (0x2B) UCSRA RXC TXC UDRE FE DOR PE U2X MPCM 148 0x0A (0x2A) UCSRB RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 149 0x09 (0x29) UBRRL USART Baud Rate Register Low byte 152 0x08 (0x28) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 186 0x07 (0x27) ADMUX REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 199 0x06 (0x26) ADCSRA ADEN ADSC ADFR ADIF ADIE ADPS2 ADPS1 ADPS0 200 0x05 (0x25) ADCH ADC Data Register High byte 201 0x04 (0x24) ADCL ADC Data Register Low byte 201 0x03 (0x23) TWDR Two-wire Serial Interface Data Register 167 0x02 (0x22) TWAR TWA6 TWA5 TW A4 TWA3 TWA2 TW A1 TWA0 TWGCE 167
2486AA–AVR–02/2013 ATmega8(L) Notes: 1. Refer to the USART description ( “USART” on page 129) for details on how to access UBRRH and UCSRC ( “Accessing UBRRH/UCSRC Registers” on page 146) 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. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O Register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers 0x00 to 0x1F only 0x01 (0x21) TWSR TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 166 0x00 (0x20) TWBR Two-wire Serial Interface Bit Rate Register 165 Register Summary (Continued) Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
2486AA–AVR–02/2013 ATmega8(L) Instruction Set Summary Mnemonics Operands Description Operation Flags #Clocks ARITHMETIC AND LOGIC INSTRUCTIONS ADD Rd, Rr Add two Registers Rd Rd + Rr Z, C, N, V, H 1 ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z, C, N, V, H 1 ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z, C, N, V, S 2 SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z, C, N, V, H 1 SUBI Rd, K Subtract Constant from Register Rd Rd - K Z, C, N, V, H 1 SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z, C, N, V, H 1 SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z, C, N ,V, H 1 SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z, C, N, V, S 2 AND Rd, Rr Logical AND Registers Rd Rd Rr Z, N, V 1 ANDI Rd, K Logical AND Register and Constant Rd Rd K Z, N, V 1 OR Rd, Rr Logical OR Registers Rd Rd v Rr Z, N, V 1 ORI Rd, K Logical OR Register and Constant Rd Rd v K Z, N, V 1 EOR Rd, Rr Exclusive OR Registers Rd Rd Rr Z, N, V 1 COM Rd One’s Complement Rd 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 MUL Rd, Rr Multiply Unsigned R1:R0 Rd x Rr Z, C 2 MULS Rd, Rr Multiply Signed R1:R0 Rd x Rr Z, C 2 MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 Rd x Rr Z, C 2 FMUL Rd, Rr Fractional Multiply Unsigned R1:R0 (Rd x Rr) << 1 Z, C 2 FMULS Rd, Rr Fractional Multiply Signed R1:R0 (Rd x Rr) << 1 Z, C 2 FMULSU Rd, Rr Fractional Multiply Signed with Unsigned R1:R0 (Rd x Rr) << 1 Z, C 2 BRANCH INSTRUCTIONS RJMP k Relative Jump PC PC + k + 1 None 2 IJMP Indirect Jump to (Z) PC Z None 2 RCALL k Relative Subroutine Call PC PC + k + 1 None 3 ICALL Indirect Call to (Z) PC ZN o n e 3 RET Subroutine Return PC STACK None 4 RETI Interrupt Return PC STACK I 4 CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1 / 2 / 3 CP Rd,Rr Compare Rd Rr Z, N, V, C, H 1 CPC Rd,Rr Compare with Carry Rd Rr C Z, N, V, C, H 1 CPI Rd,K Compare Register with Immediate Rd K Z, N, V, C, H 1 SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1 / 2 / 3 SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1 / 2 / 3 SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1 / 2 / 3 SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1 / 2 / 3 BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC PC+k + 1 None 1 / 2 BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC PC+k + 1 None 1 / 2 BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1 / 2 BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1 / 2 BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1 / 2 BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1 / 2 BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1 / 2 BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1 / 2 BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1 / 2 BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1 / 2 BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1 / 2 BRLT k Branch if Less Than Zero, Signed if (N V= 1) then PC PC + k + 1 None 1 / 2 BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1 / 2 BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1 / 2 BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1 / 2 BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1 / 2 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
2486AA–AVR–02/2013 ATmega8(L) Mnemonics Operands Description Operation Flags #Clocks BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1 / 2 BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1 / 2 DATA TRANSFER INSTRUCTIONS MOV Rd, Rr Move Between Registers Rd Rr None 1 MOVW Rd, Rr Copy Register Word Rd+1:Rd Rr+1:Rr None 1 LDI Rd, K Load Immediate Rd KN o n e 1 LD Rd, X Load Indirect Rd (X) None 2 LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2 LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None 2 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 PN o n e 1 OUT P, Rr Out Port P Rr None 1 PUSH Rr Push Register on Stack STACK Rr None 2 POP Rd Pop Register from Stack Rd STACK None 2 BIT AND BIT-TEST INSTRUCTIONS SBI P,b Set Bit in I/O Register I/O(P,b) 1N o n e 2 CBI P,b Clear Bit in I/O Register I/O(P,b) 0N o n e 2 LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z, C, N, V 1 LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z, C, N, V 1 ROL Rd Rotate Left Through Carry Rd(0) C,Rd(n+1) Rd(n),CRd(7) Z, C, N, V 1 ROR Rd Rotate Right Through Carry Rd(7) C,Rd(n) Rd(n+1),CRd(0) Z, C, N, V 1 ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z, C, N, V 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) TN o n e 1 SEC Set Carry C 1C 1 CLC Clear Carry C 0 C 1 SEN Set Negative Flag N 1N 1 CLN Clear Negative Flag N 0 N 1 SEZ Set Zero Flag Z 1Z 1 CLZ Clear Zero Flag Z 0 Z 1 SEI Global Interrupt Enable I 1I 1 CLI Global Interrupt Disable I 0 I 1 SES Set Signed Test Flag S 1S 1 CLS Clear Signed Test Flag S 0 S 1 SEV Set Twos Complement Overflow. V 1V 1 CLV Clear Twos Complement Overflow V 0 V 1 SET Set T in SREG T 1T 1 Instruction Set Summary (Continued)
2486AA–AVR–02/2013 ATmega8(L) Mnemonics Operands Description Operation Flags #Clocks CLT Clear T in SREG T 0 T 1 SEH Set Half Carry Flag in SREG H 1H 1 CLH Clear Half Carry Flag in SREG H 0 H 1 MCU CONTROL INSTRUCTIONS NOP No Operation None 1 SLEEP Sleep (see specific descr. for Sleep function) None 1 WDR Watchdog Reset (see specific descr. for WDR/timer) None 1 Instruction Set Summary (Continued)
2486AA–AVR–02/2013 ATmega8(L)
Ordering Information
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information and minimum quantities 2. Pb-free packaging complies to the European Directive for Re striction of Hazardous Substances (RoHS directive). Also Halide free and fully Green 3. Tape & Reel 4. See characterization specification at 105 C Speed (MHz) Power Supply (V) Ordering Code (2) Package(1) Operation Range 8 2.7 - 5.5 ATmega8L-8AU ATmega8L-8AUR(3) ATmega8L-8PU ATmega8L-8MU ATmega8L-8MUR(3) 32A 32A 28P3 32M1-A 32M1-A Industrial (-40 C to 85C) 16 4.5 - 5.5 ATmega8-16AU ATmega8-16AUR(3) ATmega8-16PU ATmega8-16MU ATmega8-16MUR(3) 32A 32A 28P3 32M1-A 32M1-A 8 2.7 - 5.5 ATmega8L-8AN ATmega8L-8ANR (3) ATmega8L-8PN ATmega8L-8MN ATmega8L-8MUR(3) 32A 32A 28P3 32M1-A 32M1-A Industrial (-40 C to 105C) 16 4.5 - 5.5 ATmega8-16AN ATmega8-16ANR(3) ATmega8-16PN ATmega8-16MN ATmega8-16MUR (3) 32A 32A 28P3 32M1-A 32M1-A Package Type 32A 32-lead, Thin (1.0mm) Plastic Quad Flat Package (TQFP) 28P3 28-lead, 0.300” Wide, Plastic Dual Inline Package (PDIP) 32M1-A 32-pad, 5 × 5 × 1.0 body, Lead Pitch 0.50mm Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)
2486AA–AVR–02/2013 ATmega8(L) Packaging Information 32A TITLE DRAWING NO. REV. 32A, 32-lead, 7 x 7mm body size, 1.0mm body thickness, 0.8mm lead pitch, thin profile plastic quad flat package (TQFP) C32A 2010-10-20 PIN 1 IDENTIFIER 0°~7° PIN 1 L C A1 A2 A D e E1 E B Notes: 1. This package conforms to JEDEC reference MS-026, Variation ABA. 2. Dimensions D1 and E1 do not include mold protrusion. Allowable protrusion is 0.25mm per side. Dimensions D1 and E1 are maximum plastic body size dimensions including mold mismatch. 3. Lead coplanarity is 0.10mm maximum. A – – 1.20 A1 0.05 – 0.15 A2 0.95 1.00 1.05 D 8.75 9.00 9.25 D1 6.90 7.00 7.10 Note 2 E 8.75 9.00 9.25 E1 6.90 7.00 7.10 Note 2 B 0.30 – 0.45 C 0.09 – 0.20 L 0.45 – 0.75 e 0.80 TYP COMMON DIMENSIONS (Unit of measure = mm) SYMBOL MIN NOM MAX NOTE
2486AA–AVR–02/2013 ATmega8(L) 28P3
2325 Orchard Parkway
San Jose, CA 95131 TITLE DRAWING NO. R REV. 28P3, 28-lead (0.300"/7.62mm Wide) Plastic Dual Inline Package (PDIP) B28P3 09/28/01 PIN B REF E C L SEATING PLANE A 0º ~ 15º D e eB (4 PLACES) COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL MIN NOM MAX NOTE A – – 4.5724 A1 0.50 8 – – D 34.544 – 34.798 Note 1 E 7.620 – 8.255 E1 7.112 – 7.49 3 Note 1 B 0. 381 – 0.5 33 B1 1.14 3 – 1. 397 B2 0.762 – 1.14 3 L 3.175 – 3.429 C 0.20 3 – 0. 356 eB – – 10.160 e 2.540 TYP Note: 1. Dimen sions D and E1 do not include mold Flash or Protrusion. Mold Fl ash or Protrusion shall not exceed 0.25mm (0.010").
2486AA–AVR–02/2013 ATmega8(L) 32M1-A San Jose, CA 95131 TITLE DRAWING NO. R REV. 32M1-A, 32-pad, 5 x 5 x 1.0mm Body, Lead Pitch 0.50mm, E32M1-A 5/25/06 3.10mm Exposed P ad, Micro Lead Frame Package (MLF) COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL MIN NOM MAX NOTE D E1 E eb A 0.08 C L P P A 0. 80 0.90 1.00 A1 – 0.02 0.05 A2 – 0.65 1.00 A 3 0.20 REF b 0.1 8 0.23 0.30 D D2 2.95 3.10 3.25 4.90 5.00 5.10 4.70 4.75 4. 80 4.70 4.75 4. 80 4.90 5.00 5.10 E E2 2.95 3.10 3.25 e 0.50 B SC L 0. 30 0.40 0.50 P – – 0.60 – – 12 o Note: JEDEC Standard MO-220, Fig. 2 (Anvil Singulation), VHHD-2. TOP VIEW SIDE VIEW BOTTOM VIEW Pin 1 ID Pin #1 Notch (0.20 R) K 0.20 – – K K
2486AA–AVR–02/2013 ATmega8(L) Errata The revision letter in this section refers to the revision of the ATmega8 device. ATmega8 Rev. D to I, M First Analog Comparator conversion may be delayed Interrupts may be lost when writing the timer registers in the asynchronous timer Signature may be Erased in Serial Programming Mode CKOPT Does not Enable Internal Capacitors on XTALn/TOSCn Pins when 32KHz Oscillator is Used to Clock the Asynchronous Timer/Counter2 Reading EEPROM by using ST or STS to set EERE bit triggers unexpected interrupt request 1. First Analog Comparator conversion may be delayed If the device is powered by a slow rising V CC, the first Analog Comparator conversion will take longer than expected on some devices. Problem Fix / Workaround When the device has been powered or reset, disable then enable theAnalog Comparator before the first conversion. 2. Interrupts may be lost when writing the timer registers in the asynchronous timer The interrupt will be lost if a timer register th at is synchronized to the asynchronous timer clock is written when the asynchronous Timer/Counter register(TCNTx) is 0x00. Problem Fix / Workaround Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor 0x00 before writing to the asynchronous Timer Control Register(TCCRx), asynchronous Timer Counter Register(TCNTx), or asynchronous Output Compare Register(OCRx). 3. Signature may be Erased in Serial Programming Mode If the signature bytes are read before a chiperase command is completed, the signature may be erased causing the device ID and calibration bytes to disappear. This is critical, espe- cially, if the part is running on internal RC oscillator. Problem Fix / Workaround: Ensure that the chiperase command has exceeded before applying the next command. 4. CKOPT Does not Enable Internal Capacitors on XTALn/TOSCn Pins when 32KHz Oscillator is Used to Clock the Asynchronous Timer/Counter2 When the internal RC Oscillator is used as the main clock source, it is possible to run the Timer/Counter2 asynchronously by connecting a 32KHz Oscillator between XTAL1/TOSC1 and XTAL2/TOSC2. But when th e internal RC Oscillator is selected as the main clock source, the CKOPT Fuse does not control the internal capacitors on XTAL1/TOSC1 and XTAL2/TOSC2. As long as there are no ca pacitors connected to XTAL1/TOSC1 and XTAL2/TOSC2, safe operation of the Oscillator is not guaranteed. Problem Fix / Workaround Use external capacitors in the range of 20pF - 36pF on XTAL1/TOSC1 and XTAL2/TOSC2. This will be fixed in ATmega8 Rev. G where the CKOPT Fuse will control internal capacitors also when internal RC Oscillator is selected as main clock source. For ATmega8 Rev. G, CKOPT = 0 (programmed) will enable the internal capacitors on XTAL1 and XTAL2. Cus- tomers who want compatibility between Rev. G and older revisions, must ensure that CKOPT is unprogrammed (CKOPT = 1).
2486AA–AVR–02/2013 ATmega8(L) 5. Reading EEPROM by using ST or STS to set EERE bit triggers unexpected interrupt request. Reading EEPROM by using the ST or STS command to set th e EERE bit in the EECR reg- ister triggers an unexpected EEPROM interrupt request. Problem Fix / Workaround Always use OUT or SBI to set EERE in EECR.
2486AA–AVR–02/2013 ATmega8(L) Datasheet Revision History Please note that the referring page numbers in th is section are referred to this document. The referring revision in this section are referring to the document revision. Changes from Rev. 2486Z- 02/11 to Rev. 2486AA- 02/2013 1. Updated the datasheet according to the Atmel new Brand Style Guide. 2.Removed the reference to “On-chip debugging” from the content . 3.Added “Electrical Characteristics – TA = -40°C to 105°C” on page 242. 4.Added “ATmega8 Typical Characteristics – TA = -40°C to 105°C” on page 282. 5.Updated “Ordering Information” on page 314. Changes from Rev. 2486Y- 10/10 to Rev. 2486Z- 02/11 1. Updated the datasheet according to the Atmel new Brand Style Guide. 2. Updated “Ordering Information” on page 314 . Added Ordering Information for “Tape & Reel” devices Changes from Rev. 2486X- 06/10 to Rev. 2486Y- 10/10 1. Max Rise/Fall time in Table 102 on page 239 has been corrected from 1.6ns to 1600ns. 2. Note is added to “Performing Page Erase by SPM” on page 209. 3. Updated/corrected several short-cuts and added some new ones. 4. Updated last page according to new standard. Changes from Rev. 2486W- 02/10 to Rev. 2486X- 06/10 1. Updated “DC Characteristics” on page 235 with new V OL maximum value (0.9V and 0.6V). Changes from Rev. 2486V- 05/09 to Rev. 2486W- 02/10 1. Updated “ADC Characteristics” on page 241 with VINT maximum value (2.9V). Changes from Rev. 2486U- 08/08 to Rev. 2486V- 05/09 1. Updated “Errata” on page 318. 2. Updated the last page with Atmel’s new adresses. Changes from Rev. 2486T- 05/08 to Rev. 2486U- 08/08 1. Updated “DC Characteristics” on page 235 with ICC typical values.
2486AA–AVR–02/2013 ATmega8(L) Changes from Rev. 2486S- 08/07 to Rev. 2486T- 05/08 1. Updated Table 98 on page 233. 2. Updated “Ordering Information” on page 314. - Commercial Ordering Code removed. - No Pb-free packaging option removed. Changes from Rev. 2486R- 07/07 to Rev. 2486S- 08/07 1. Updated “Features” on page 1. 2. Added “Data Retention” on page 7. 3. Updated “Errata” on page 318. 4. Updated “Slave Mode” on page 125. Changes from Rev. 2486Q- 10/06 to Rev. 2486R- 07/07 1. Added text to Table 81 on page 211. 2. Fixed typo in “Peripheral Features” on page 1. 3. Updated Table 16 on page 42. 4. Updated Table 75 on page 199. 5. Removed redundancy and updated typo in Notes section of “DC Characteristics” on page 235. Changes from Rev. 2486P- 02/06 to Rev. 2486Q- 10/06 1. Updated “Timer/Counter Oscillator” on page 32. 2. Updated “Fast PWM Mode” on page 88. 3. Updated code example in “USART Initialization” on page 134. 4. Updated Table 37 on page 96, Table 39 on page 97, Table 42 on page 115, Table 44 on page 115, and Table 98 on page 233. 5. Updated “Errata” on page 318. Changes from Rev. 2486O-10/04 to Rev. 2486P- 02/06 1. Added “Resources” on page 7. 2. Updated “External Clock” on page 32. 3. Updated “Serial Peripheral Interface – SPI” on page 121 . 4. Updated Code Example in “USART Initialization” on page 134. 5. Updated Note in “Bit Rate Generator Unit” on page 164. 6. Updated Table 98 on page 233. 7. Updated Note in Table 103 on page 241.
2486AA–AVR–02/2013 ATmega8(L) 8. Updated “Errata” on page 318. Changes from Rev. 2486N-09/04 to Rev. 2486O-10/04 1. Removed to instances of “analog ground”. Replaced by “ground”. 2. Updated Table 7 on page 29, Table 15 on page 38, and Table 100 on page 237. 3. Updated “Calibrated Internal RC Oscillator” on page 30 with the 1MHz default value. 4. Table 89 on page 218 and Table 90 on page 218 moved to new section “Page Size” on page 218. 5. Updated descripton for bit 4 in “Store Program Memory Control Register – SPMCR” on page 206. 6. Updated “Ordering Information” on page 314. Changes from Rev. 2486M-12/03 to Rev. 2486N-09/04 1. Added note to MLF package in “Pin Configurations” on page 2. 2. Updated “Internal Voltage Reference Characteristics” on page 42 . 3. Updated “DC Characteristics” on page 235. 4. ADC4 and ADC5 support 10-bit accuracy. Document updated to reflect this. Updated features in “Analog-to-Digital Converter” on page 189. Updated “ADC Characteristics” on page 241. 5. Removed reference to “External RC Oscillator application note” from “External RC Oscillator” on page 28. Changes from Rev. 2486L-10/03 to Rev. 2486M-12/03 1. Updated “Calibrated Internal RC Oscillator” on page 30. Changes from Rev. 2486K-08/03 to Rev. 2486L-10/03 1. Removed “Preliminary” and TBDs from the datasheet. 2. Renamed ICP to ICP1 in the datasheet. 3. Removed instructions CALL and JMP from the datasheet. 4. Updated t RST in Table 15 on page 38 , VBG in Table 16 on page 42 , Table 100 on page 237 and Table 102 on page 239. 5. Replaced text “XTAL1 and XTAL2 should be left unconnected (NC)” after Table 9 in “Calibrated Internal RC Oscillator” on page 30 . Added text regarding XTAL1/XTAL2 and CKOPT Fuse in “Timer/Counter Oscillator” on page 32. 6. Updated Watchdog Timer code examples in “Timed Sequences for Changing the Configuration of the Watchdog Timer” on page 45. 7. Removed bit 4, ADHSM, from “Special Function IO Register – SFIOR” on page 58 . 8. Added note 2 to Figure 103 on page 208.
2486AA–AVR–02/2013 ATmega8(L) 9. Updated item 4 in the “Serial Programming Algorithm” on page 231. 10. Added t WD_FUSE to Table 97 on page 232 and updated Read Calibration Byte, Byte 3, in Table 98 on page 233. 11. Updated Absolute Maximum Ratings* and DC Characteristics in “Electrical Character- istics – TA = -40°C to 85°C” on page 235 . Changes from Rev. 2486J-02/03 to Rev. 2486K-08/03 1. Updated V BOT values in Table 15 on page 38. 2. Updated “ADC Characteristics” on page 241. 3. Updated “ATmega8 Typical Characteristics – TA = -40°C to 85°C” on page 244 . 4. Updated “Errata” on page 318. Changes from Rev. 2486I-12/02 to Rev. 2486J-02/03 1. Improved the description of “Asynchronous Timer Clock – clkASY” on page 26 . 2. Removed reference to the “Multipurpose Oscillator” application note and the “32kHz Crystal Oscillator” application note, which do not exist. 3. Corrected OCn waveforms in Figure 38 on page 89. 4. Various minor Timer 1 corrections. 5. Various minor TWI corrections. 6. Added note under “Filling the Temporary Buffer (Page Loading)” on page 209 about writing to the EEPROM during an SPM Page load. 7. Removed ADHSM completely. 8. Added section “EEPROM Write during Power-down Sleep Mode” on page 23 . 9. Removed XTAL1 and XTAL2 description on page 5 because they were already described as part of “Port B (PB7..PB0) XTAL1/XTAL2/TOSC1/TOSC2” on page 5 . 10. Improved the table under “SPI Timing Characteristics” on page 239 and removed the table under “SPI Serial Programming Characteristics” on page 234 . 11. Corrected PC6 in “Alternate Functions of Port C” on page 61. 12. Corrected PB6 and PB7 in “Alternate Functions of Port B” on page 58. 13. Corrected 230.4 Mbps to 230.4 kbps under “Examples of Baud Rate Setting” on page 153. 14. Added information about PWM symmetry for Timer 2 in “Phase Correct PWM Mode” on page 111. 15. Added thick lines around accessible registers in Figure 76 on page 163.
2486AA–AVR–02/2013 ATmega8(L) 16. Changed “will be ignored” to “must be written to zero” for unused Z-pointer bits under “Performing a Page Write” on page 209. 17. Added note for RSTDISBL Fuse in Table 87 on page 216. 18. Updated drawings in “Packaging Information” on page 315. Changes from Rev. 2486H-09/02 to Rev. 2486I-12/02 1. Added errata for Rev D, E, and F on page 318. Changes from Rev. 2486G-09/02 to Rev. 2486H-09/02 1. Changed the Endurance on the Flash to 10,000 Write/Erase Cycles. Changes from Rev. 2486F-07/02 to Rev. 2486G-09/02 1. Updated Table 103, “ADC Characteristics,” on page 241. Changes from Rev. 2486E-06/02 to Rev. 2486F-07/02 1. Changes in “Digital Input Enable and Sleep Modes” on page 55. 2. Addition of OCS2 in “MOSI/OC2 – Port B, Bit 3” on page 59 . 3. The following tables have been updated: Table 51, “CPOL and CPHA Functionality,” on page 127 , Table 59, “UCPOL Bit Settings,” on page 152, Table 72, “Analog Comparator Multiplexed Input(1),” on page 188 , Table 73, “ADC Conversion Time,” on page 193, Table 75, “Input Channel Selections,” on page 199 , and Table 84, “Explanation of Different Variables used in Figure 103 on page 208 and the Mapping to the Z-pointer,” on page 214. 4. Changes in “Reading the Calibration Byte” on page 227. 5. Corrected Errors in Cross References. Changes from Rev. 2486D-03/02 to Rev. 2486E-06/02 1. Updated Some Preliminary Test Limits and Characterization Data The following tables have been updated: Table 15, “Reset Characteristics,” on page 38, Table 16, “Internal Voltage Reference Char- acteristics,” on page 42, DC Characteristics on page 235, Table , “ADC Characteristics,” on page 241. 2. Changes in External Clock Frequency Added the description at the end of “External Clock” on page 32. Added period changing data in Table 99, “External Clock Drive,” on page 237. 3. Updated TWI Chapter More details regarding use of the TWI bit rate prescaler and a Table 65, “TWI Bit Rate Pres- caler,” on page 167.
2486AA–AVR–02/2013 ATmega8(L) Changes from Rev. 2486C-03/02 to Rev. 2486D-03/02 1. Updated Typical Start-up Times. The following tables has been updated: Table 5, “Start-up Times for the Crysta l Oscillator Clock Selection,” on page 28 , Table 6, “Start-up Times for the Low-frequency Crystal Oscillator Clock Selection,” on page 28 , Table 8, “Start-up Times for the External RC Oscillator Clock Selection,” on page 29 , and Table 12, “Start-up Times for the External Clock Selection,” on page 32. 2. Added “ATmega8 Typical Characteristics – TA = -40°C to 85°C” on page 244 . Changes from Rev. 2486B-12/01 to Rev. 2486C-03/02 1. Updated TWI Chapter. More details regarding use of the TWI Powe r-down operation and using the TWI as Master with low TWBRR values are added into the datasheet. Added the note at the end of the “Bit Rate Generator Unit” on page 164. Added the description at the end of “Address Match Unit” on page 164. 2. Updated Description of OSCCAL Calibration Byte. In the datasheet, it was not explained how to take advantage of the calibration bytes for 2, 4, and 8MHz Oscillator selections. This is now added in the following sections: Improved description of “Oscillator Calibration Register – OSCCAL” on page 31 and “Cali- bration Byte” on page 218. 3. Added Some Preliminary Test Li mits and Characterization Data. Removed some of the TBD’s in the following tables and pages: Table 3 on page 26, Table 15 on page 38, Table 16 on page 42, Table 17 on page 44, “TA = -40°C to +85°C, VCC = 2.7V to 5.5V (unless otherwise noted)” on page 235 , Table 99 on page 237, and Table 102 on page 239. 4. Updated Programming Figures. Figure 104 on page 219 and Figure 112 on page 230 are updated to also reflect that AV CC must be connected during Programming mode. 5. Added a Description on how to Enter Parallel Programming Mode if RESET Pin is Dis- abled or if External Oscillators are Selected. Added a note in section “Enter Programming Mode” on page 221.
2486AA–AVR–02/2013 ATmega8(L) Table of Contents Features 1 Pin Configurations 2 Overview 3 Block Diagram 3 Disclaimer 4 Pin Descriptions 5 Resources 7 Data Retention 7 About Code Examples 8 Atmel AVR CPU Core 9 Introduction 9 Architectural Overview 9 Arithmetic Logic Unit – ALU 11 Status Register 11 General Purpose Register File 12 Stack Pointer 13 Instruction Execution Timing 13 Reset and Interrupt Handling 14 AVR ATmega8 Memories 17 In-System Reprogrammable Flash Program Memory 17 SRAM Data Memory 18 Data Memory Access Times 19 EEPROM Data Memory 19 I/O Memory 24 System Clock and Clock Options 25 Clock Systems and their Distribution 25 Clock Sources 26 Crystal Oscillator 27 Low-frequency Crystal Oscillator 28 External RC Oscillator 28 Calibrated Internal RC Oscillator 30 External Clock 32 Timer/Counter Oscillator 32 Power Management and Sleep Modes 33 Idle Mode 34
2486AA–AVR–02/2013 ATmega8(L) ADC Noise Reduction Mode 34 Power-down Mode 34 Power-save Mode 34 Standby Mode 35 Minimizing Power Consumption 35 System Control and Reset 37 Internal Voltage Reference 42 Watchdog Timer 43 Timed Sequences for Changing the Configuration of the Watchdog Timer 45 Interrupts 46 Interrupt Vectors in ATmega8 46 I/O Ports 51 Introduction 51 Ports as General Digital I/O 52 Alternate Port Functions 56 Register Description for I/O Ports 65 External Interrupts 66 8-bit Timer/Counter0 69 Overview 69 Timer/Counter Clock Sources 70 Counter Unit 70 Operation 70 Timer/Counter Timing Diagrams 70 8-bit Timer/Counter Register Description 71 Timer/Counter0 and Timer/Counter1 Prescalers 73 16-bit Timer/Counter1 75 Overview 75 Accessing 16-bit Registers 77 Timer/Counter Clock Sources 80 Counter Unit 80 Input Capture Unit 81 Output Compare Units 83 Compare Match Output Unit 85 Modes of Operation 87 Timer/Counter Timing Diagrams 94 16-bit Timer/Counter Register Description 96 8-bit Timer/Counter2 with PWM and Asynchronous Operation 102 Overview 102
2486AA–AVR–02/2013 ATmega8(L) Timer/Counter Clock Sources 103 Counter Unit 104 Output Compare Unit 105 Compare Match Output Unit 107 Modes of Operation 108 Timer/Counter Timing Diagrams 112 8-bit Timer/Counter Register Description 114 Asynchronous Operation of the Timer/Counter 117 Timer/Counter Prescaler 120 Serial Peripheral Interface – SPI 121 SS Pin Functionality 125 Data Modes 127 USART 129 Overview 129 Clock Generation 130 Frame Formats 133 USART Initialization 134 Data Transmission – The USART Transmitter 136 Data Reception – The USART Receiver 138 Asynchronous Data Reception 142 Multi-processor Communication Mode 145 Accessing UBRRH/UCSRC Registers 146 USART Register Description 148 Examples of Baud Rate Setting 153 Two-wire Serial Interface 157 Features 157 Two-wire Serial Interface Bus Definition 157 Data Transfer and Frame Format 158 Multi-master Bus Systems, Arbitration and Synchronization 161 Overview of the TWI Module 163 TWI Register Description 165 Using the TWI 168 Transmission Modes 171 Multi-master Systems and Arbitration 184 Analog Comparator 186 Analog Comparator Multiplexed Input 188 Analog-to-Digital Converter 189 Features 189 Starting a Conversion 191 Prescaling and Conversion Timing 191 Changing Channel or Reference Selection 194
2486AA–AVR–02/2013 ATmega8(L) ADC Noise Canceler 195 ADC Conversion Result 199 Boot Loader Support – Read-While-Write Self-Programming 202 Boot Loader Features 202 Application and Boot Loader Flash Sections 202 Read-While-Write and No Read-While-Write Flash Sections 202 Boot Loader Lock Bits 204 Entering the Boot Loader Program 205 Addressing the Flash During Self-Programming 207 Self-Programming the Flash 208 Memory Programming 215 Program And Data Memory Lock Bits 215 Fuse Bits 216 Signature Bytes 218 Calibration Byte 218 Page Size 218 Parallel Programming Parameters, Pin Mapping, and Commands 219 Parallel Programming 221 Serial Downloading 230 Serial Programming Pin Mapping 230 Electrical Characteristics – TA = -40°C to 85°C 235 Absolute Maximum Ratings* 235 DC Characteristics 235 External Clock Drive Waveforms 237 External Clock Drive 237 Two-wire Serial Interface Characteristics 238 SPI Timing Characteristics 239 ADC Characteristics 241 Electrical Characteristics – TA = -40°C to 105°C 242 Absolute Maximum Ratings* 242 DC Characteristics TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted) 242 ATmega8 Typical Characteristics – TA = -40°C to 85°C 244 ATmega8 Typical Characteristics – TA = -40°C to 105°C 282 Active Supply Current 282 Idle Supply Current 284 Power-down Supply Current 286 Pin Pull-up 287 Pin Driver Strength 289 Pin Thresholds and Hysteresis 293
2486AA–AVR–02/2013 ATmega8(L) Bod Thresholds and Analog Comparator Offset 298 Internal Oscillator Speed 300 Current Consumption of Peripheral Units 305 Current Consumption in Reset and Reset Pulsewidth 308 Register Summary 309 Instruction Set Summary 311 Ordering Information 314 Packaging Information 315 32A 315 28P3 316 32M1-A 317 Errata 318 ATmega8 Rev. D to I, M 318 Datasheet Revision History 320 Changes from Rev. 2486Z- 02/11 to Rev. 2486AA- 02/2013 320 Changes from Rev. 2486Y- 10/10 to Rev. 2486Z- 02/11 320 Changes from Rev. 2486X- 06/10 to Rev. 2486Y- 10/10 320 Changes from Rev. 2486W- 02/10 to Rev. 2486X- 06/10 320 Changes from Rev. 2486V- 05/09 to Rev. 2486W- 02/10 320 Changes from Rev. 2486U- 08/08 to Rev. 2486V- 05/09 320 Changes from Rev. 2486T- 05/08 to Rev. 2486U- 08/08 320 Changes from Rev. 2486S- 08/07 to Rev. 2486T- 05/08 321 Changes from Rev. 2486R- 07/07 to Rev. 2486S- 08/07 321 Changes from Rev. 2486Q- 10/06 to Rev. 2486R- 07/07 321 Changes from Rev. 2486P- 02/06 to Rev. 2486Q- 10/06 321 Changes from Rev. 2486O-10/04 to Rev. 2486P- 02/06 321 Changes from Rev. 2486N-09/04 to Rev. 2486O-10/04 322 Changes from Rev. 2486M-12/03 to Rev. 2486N-09/04 322 Changes from Rev. 2486L-10/03 to Rev. 2486M-12/03 322 Changes from Rev. 2486K-08/03 to Rev. 2486L-10/03 322 Changes from Rev. 2486J-02/03 to Rev. 2486K-08/03 323 Changes from Rev. 2486I-12/02 to Rev. 2486J-02/03 323 Changes from Rev. 2486H-09/02 to Rev. 2486I-12/02 324 Changes from Rev. 2486G-09/02 to Rev. 2486H-09/02 324 Changes from Rev. 2486F-07/02 to Rev. 2486G-09/02 324 Changes from Rev. 2486E-06/02 to Rev. 2486F-07/02 324 Changes from Rev. 2486D-03/02 to Rev. 2486E-06/02 324 Changes from Rev. 2486C-03/02 to Rev. 2486D-03/02 325 Changes from Rev. 2486B-12/01 to Rev. 2486C-03/02 325
2486AA–AVR–02/2013 Atmel Corporation
1600 Technology Drive
San Jose, CA 95110 USA www.atmel.com Atmel Asia Limited Unit 01-5 & 16, 19F BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon HONG KONG Tel: (+852) 2245-6100 Fax: (+852) 2722-1369 Atmel Munich GmbH Business Campus Parkring 4 D-85748 Garching b. Munich GERMANY Fax: (+49) 89-3194621 Atmel Japan G.K. 16F Shin-Osaki Kangyo Bldg 1-6-4 Osaki, Shinagawa-ku Tokyo 141-0032 JAPAN © 2013 Atmel Corporation. All rights reserved. / Rev.: 2486AA–AVR–02/2013 Atmel ®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others. 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 THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. Table of Contents 1