Atmel ATmega48/V Preliminary
Atmel ATmega48/V Preliminary

Atmel ATmega48/V Preliminary

8-bit microcontroller with 8k bytes in-system programmable flash
Table of Contents

Advertisement

Quick Links

Features

High Performance, Low Power AVR
Advanced RISC Architecture
– 131 Powerful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 20 MIPS Throughput at 20 MHz
– On-chip 2-cycle Multiplier
Non-volatile Program and Data Memories
– 4/8/16K Bytes of In-System Self-Programmable Flash (ATmega48/88/168)
Endurance: 10,000 Write/Erase Cycles
– Optional Boot Code Section with Independent Lock Bits
In-System Programming by On-chip Boot Program
True Read-While-Write Operation
– 256/512/512 Bytes EEPROM (ATmega48/88/168)
Endurance: 100,000 Write/Erase Cycles
– 512/1K/1K Byte Internal SRAM (ATmega48/88/168)
– Programming Lock for Software Security
Peripheral Features
– Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode
– One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture
Mode
– Real Time Counter with Separate Oscillator
– Six PWM Channels
– 8-channel 10-bit ADC in TQFP and QFN/MLF package
– 6-channel 10-bit ADC in PDIP Package
– Programmable Serial USART
– Master/Slave SPI Serial Interface
– Byte-oriented 2-wire Serial Interface
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
– Interrupt and Wake-up on Pin Change
Special Microcontroller Features
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated Oscillator
– External and Internal Interrupt Sources
– Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, and
Standby
I/O and Packages
– 23 Programmable I/O Lines
– 28-pin PDIP, 32-lead TQFP and 32-pad QFN/MLF
Operating Voltage:
– 1.8 - 5.5V for ATmega48V/88V/168V
– 2.7 - 5.5V for ATmega48/88/168
Temperature Range:
°
°
– -40
C to 85
C
Speed Grade:
– ATmega48V/88V/168V: 0 - 4 MHz @ 1.8 - 5.5V, 0 - 10 MHz @ 2.7 - 5.5V
– ATmega48/88/168: 0 - 10 MHz @ 2.7 - 5.5V, 0 - 20 MHz @ 4.5 - 5.5V
®
8-Bit Microcontroller
8-bit
Microcontroller
with 8K Bytes
In-System
Programmable
Flash
ATmega48/V
ATmega88/V
ATmega168/V
Preliminary
Rev. 2545E–AVR–02/05

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the ATmega48/V and is the answer not in the manual?

Questions and answers

Summary of Contents for Atmel ATmega48/V

  • Page 1: Features

    Peripheral Features – Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode – One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode ATmega48/V – Real Time Counter with Separate Oscillator ATmega88/V – Six PWM Channels – 8-channel 10-bit ADC in TQFP and QFN/MLF package ATmega168/V –...
  • Page 2: Pin Configurations

    • Low Power Consumption – Active Mode: 1 MHz, 1.8V: 240µA 32 kHz, 1.8V: 15µA (including Oscillator) – Power-down Mode: 0.1µA at 1.8V 1. Pin Configurations Figure 1-1. Pinout ATmega48/88/168 PDIP (PCINT14/RESET) PC6 PC5 (ADC5/SCL/PCINT13) (PCINT16/RXD) PD0 PC4 (ADC4/SDA/PCINT12) (PCINT17/TXD) PD1 PC3 (ADC3/PCINT11) (PCINT18/INT0) PD2 PC2 (ADC2/PCINT10)
  • Page 3: Disclaimer

    ATmega48/88/168 Disclaimer Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers manufactured on the same process technology. Min and Max values will be available after the device is characterized. 2. Overview The ATmega48/88/168 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture.
  • Page 4: Comparison Between Atmega48, Atmega88, And Atmega168

    Application Flash section is updated, providing true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel ATmega48/88/168 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications.
  • Page 5: Pin Descriptions

    ATmega48/88/168 In ATmega48, there is no Read-While-Write support and no separate Boot Loader Section. The SPM instruction can execute from the entire Flash. Pin Descriptions 2.3.1 Digital supply voltage. 2.3.2 Ground. 2.3.3 Port B (PB7..0) 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.
  • Page 6: About Code Examples

    resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not running. The various special features of Port D are elaborated in ”Alternate Functions of Port D” on page 2.3.7 is the supply voltage pin for the A/D Converter, PC3..0, and ADC7..6.
  • Page 7: Avr Cpu Core

    ATmega48/88/168 4. AVR CPU Core Introduction This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. Architectural Overview Figure 4-1.
  • Page 8: Alu - Arithmetic Logic Unit

    The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typ- ical ALU operation, two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File –...
  • Page 9: Status Register

    ATmega48/88/168 Status Register The Status Register contains information about the result of the most recently executed arith- metic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference.
  • Page 10: General Purpose Register File

    • Bit 0 – C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set Description” for detailed information. General Purpose Register File The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: •...
  • Page 11: Stack Pointer

    ATmega48/88/168 4.5.1 The X-register, Y-register, and Z-register The registers R26..R31 have some added functions to their general purpose usage. These reg- isters are 16-bit address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as described in Figure 4-3.
  • Page 12: Instruction Execution Timing

    Instruction Execution Timing This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the CPU clock clk , directly generated from the selected clock source for the chip. No internal clock division is used. Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Har- vard architecture and the fast-access Register File concept.
  • Page 13 ATmega48/88/168 priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request 0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR). Refer to ”Interrupts”...
  • Page 14 Assembly Code Example in r16, SREG ; store SREG value ; disable interrupts during timed sequence sbi EECR, EEMPE ; start EEPROM write sbi EECR, EEPE out SREG, r16 ; restore SREG value (I-bit) C Code Example char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ _CLI();...
  • Page 15: Avr Atmega48/88/168 Memories

    ATmega48/88/168 5. AVR ATmega48/88/168 Memories This section describes the different memories in the ATmega48/88/168. The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega48/88/168 features an EEPROM Memory for data storage. All three memory spaces are linear and regular.
  • Page 16 Figure 5-1. Program Memory Map, ATmega48 Program Memory 0x0000 Application Flash Section 0x7FF Figure 5-2. Program Memory Map, ATmega88 and ATmega168 Program Memory 0x0000 Application Flash Section Boot Flash Section 0x0FFF/0x1FFF ATmega48/88/168 2545E–AVR–02/05...
  • Page 17: Sram Data Memory

    ATmega48/88/168 SRAM Data Memory Figure 5-3 shows how the ATmega48/88/168 SRAM Memory is organized. The ATmega48/88/168 is a complex microcontroller with more peripheral units than can be sup- ported within the 64 locations reserved in the Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instruc- tions can be used.
  • Page 18: Eeprom Data Memory

    Figure 5-4. On-chip Data SRAM Access Cycles Address Address valid Compute Address Data Data Memory Access Instruction Next Instruction EEPROM Data Memory The ATmega48/88/168 contains 256/512/512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.
  • Page 19 ATmega48/88/168 5.3.2 The EEPROM Address Register – EEARH and EEARL – – – – – – – EEAR8 EEARH EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL Read/Write Initial Value • Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the ATmega48/88/168 and will always read as zero. •...
  • Page 20 is set, any write to EEPMn will be ignored. During reset, the EEPMn bits will be reset to 0b00 unless the EEPROM is busy programming. Table 5-1. EEPROM Mode Bits Programming EEPM1 EEPM0 Time Operation 3.4 ms Erase and Write in one operation (Atomic Operation) 1.8 ms Erase Only 1.8 ms...
  • Page 21 ATmega48/88/168 When the write access time has elapsed, the EEPE bit is cleared by hardware. The user soft- ware can poll this bit and wait for a zero before writing the next byte. When EEPE has been set, the CPU is halted for two cycles before the next instruction is executed. •...
  • Page 22 Assembly Code Example EEPROM_write: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to Data Register out EEDR,r16 ; Write logical one to EEMPE sbi EECR,EEMPE ;...
  • Page 23 ATmega48/88/168 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. Assembly Code Example EEPROM_read: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_read ;...
  • Page 24: I/O Memory

    I/O Memory The I/O space definition of the ATmega48/88/168 is shown in ”Register Summary” on page 334. All ATmega48/88/168 I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed by the LD/LDS/LDD and ST/STS/STD instructions, transferring data between the 32 general purpose working registers and the I/O space.
  • Page 25: System Clock And Clock Options

    ATmega48/88/168 6. System Clock and Clock Options Clock Systems and their Distribution Figure 6-1 presents the principal clock systems in the AVR and their distribution. All of the clocks need not be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in ”Power Manage- ment and Sleep Modes”...
  • Page 26: Clock Sources

    6.1.4 Asynchronous Timer Clock – clk The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clocked directly from an external clock or an external 32 kHz clock crystal. The dedicated clock domain allows using this Timer/Counter as a real-time counter even when the device is in sleep mode. 6.1.5 ADC Clock –...
  • Page 27: Low Power Crystal Oscillator

    ATmega48/88/168 dependent as shown in ”ATmega48/88/168 Typical Characteristics – Preliminary Data” on page 307. Table 6-2. Number of Watchdog Oscillator Cycles Typ Time-out (V = 5.0V) Typ Time-out (V = 3.0V) Number of Cycles 0 ms 0 ms 4.1 ms 4.3 ms 4K (4,096) 65 ms...
  • Page 28 Figure 6-2. Crystal Oscillator Connections XTAL2 XTAL1 The Low Power Oscillator can operate in three different modes, each optimized for a specific fre- quency range. The operating mode is selected by the fuses CKSEL3..1 as shown in Table 6-3 on page Table 6-3.
  • Page 29: Full Swing Crystal Oscillator

    ATmega48/88/168 Table 6-4. Start-up Times for the Low Power Crystal Oscillator Clock Selection (Continued) Start-up Time from Additional Delay Oscillator Source / Power-down and from Reset Power Conditions Power-save = 5.0V) CKSEL0 SUT1..0 Crystal Oscillator, BOD 16K CK 14CK enabled Crystal Oscillator, fast 16K CK 14CK + 4.1 ms...
  • Page 30 Figure 6-3. Crystal Oscillator Connections XTAL2 XTAL1 Table 6-6. Start-up Times for the Full Swing Crystal Oscillator Clock Selection Start-up Time from Additional Delay Oscillator Source / Power-down and from Reset Power Conditions Power-save = 5.0V) CKSEL0 SUT1..0 Ceramic resonator, fast 258 CK 14CK + 4.1 ms rising power...
  • Page 31: Low Frequency Crystal Oscillator

    ATmega48/88/168 Low Frequency Crystal Oscillator The device can utilize a 32.768 kHz watch crystal as clock source by a dedicated Low Fre- quency Crystal Oscillator. The crystal should be connected as shown in Figure 6-2. When this Oscillator is selected, start-up times are determined by the SUT Fuses and CKSEL0 as shown in Table 6-7.
  • Page 32 When this Oscillator is selected, start-up times are determined by the SUT Fuses as shown in Table 6-9 on page Table 6-9. Start-up times for the internal calibrated RC Oscillator clock selection Start-up Time from Power- Additional Delay from Power Conditions down and Power-save Reset (V = 5.0V)
  • Page 33: Khz Internal Oscillator

    ATmega48/88/168 128 kHz Internal Oscillator The 128 kHz internal Oscillator is a low power Oscillator providing a clock of 128 kHz. The fre- quency is nominal at 3V and 25°C. This clock may be select as the system clock by programming the CKSEL Fuses to “11”...
  • Page 34: Clock Output Buffer

    Table 6-13. Start-up Times for the External Clock Selection Start-up Time from Power- Additional Delay from Power Conditions down and Power-save Reset (V = 5.0V) SUT1..0 BOD enabled 6 CK 14CK Fast rising power 6 CK 14CK + 4.1 ms Slowly rising power 6 CK 14CK + 65 ms...
  • Page 35 ATmega48/88/168 frequency of the undivided clock, which may be faster than the CPU's clock frequency. Hence, it is not possible to determine the state of the prescaler - even if it were readable, and the exact time it takes to switch from one clock division to the other cannot be exactly predicted. From the time the CLKPS values are written, it takes between T1 + T2 and T1 + 2 * T2 before the new clock frequency is active.
  • Page 36 Table 6-14. Clock Prescaler Select CLKPS3 CLKPS2 CLKPS1 CLKPS0 Clock Division Factor Reserved Reserved Reserved Reserved Reserved Reserved Reserved ATmega48/88/168 2545E–AVR–02/05...
  • Page 37: Power Management And Sleep Modes

    ATmega48/88/168 7. Power Management and Sleep Modes Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consump- tion to the application’s requirements. To enter any of the five sleep modes, the SE bit in SMCR must be written to logic one and a SLEEP instruction must be executed.
  • Page 38: Idle Mode

    purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up. Idle Mode When the SM2..0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing the SPI, USART, Analog Comparator, ADC, 2-wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system to continue operating.
  • Page 39: Standby Mode

    ATmega48/88/168 If Timer/Counter2 is enabled, it will keep running during sleep. The device can wake up from either Timer Overflow or Output Compare event from Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in TIMSK2, and the Global Interrupt Enable bit in SREG is set.
  • Page 40 7.6.1 Power Reduction Register - PRR PRTWI PRTIM2 PRTIM0 – PRTIM1 PRSPI PRUSART0 PRADC Read/Write Initial Value • Bit 7 - PRTWI: Power Reduction TWI Writing a logic one to this bit shuts down the TWI by stopping the clock to the module. When waking up the TWI again, the TWI should be re initialized to ensure proper operation.
  • Page 41: Minimizing Power Consumption

    ATmega48/88/168 Minimizing Power Consumption There are several possibilities to consider when trying to minimize the power consumption in an AVR controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possible of the device’s functions are operat- ing.
  • Page 42 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 68 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 /2, the input buffer will use excessive power.
  • Page 43: System Control And Reset

    ATmega48/88/168 8. System Control and Reset 8.0.1 Resetting the AVR During reset, all I/O Registers are set to their initial values, and the program starts execution from the Reset Vector. For the ATmega168, the instruction placed at the Reset Vector must be a JMP –...
  • Page 44 Figure 8-1. Reset Logic DATA BUS MCU Status Register (MCUSR) Power-on Reset Circuit Brown-out BODLEVEL [2..0] Reset Circuit Pull-up Resistor SPIKE FILTER RSTDISBL Watchdog Oscillator Delay Counters Clock Generator TIMEOUT CKSEL[3:0] SUT[1:0] Table 8-1. Reset Characteristics Symbol Parameter Units Power-on Reset Threshold Voltage (rising) Power-on Reset Threshold Voltage (falling) RESET Pin Threshold Voltage 0.2 V...
  • Page 45 ATmega48/88/168 Figure 8-2. MCU Start-up, RESET Tied to V RESET TOUT TIME-OUT INTERNAL RESET Figure 8-3. MCU Start-up, RESET Extended Externally RESET TOUT TIME-OUT INTERNAL RESET 8.0.4 External Reset An External Reset is generated by a low level on the RESET pin. Reset pulses longer than the minimum pulse width (see Table 8-1) will generate a reset, even if the clock is not running.
  • Page 46 8.0.5 Brown-out Detection ATmega48/88/168 has an On-chip Brown-out Detection (BOD) circuit for monitoring the V level during operation by comparing it to a fixed trigger level. The trigger level for the BOD can be selected by the BODLEVEL Fuses. The trigger level has a hysteresis to ensure spike free Brown-out Detection.
  • Page 47 ATmega48/88/168 Figure 8-5. Brown-out Reset During Operation BOT+ BOT- RESET TIME-OUT TOUT INTERNAL RESET 8.0.6 Watchdog System Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period t .
  • Page 48: Internal Voltage Reference

    • Bit 1 – EXTRF: External Reset Flag This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. • Bit 0 – PORF: Power-on Reset Flag This bit is set if a Power-on Reset occurs.
  • Page 49: Watchdog Timer

    ATmega48/88/168 Watchdog Timer ATmega48/88/168 has an Enhanced Watchdog Timer (WDT). The main features are: • Clocked from separate On-chip Oscillator • 3 Operating modes – Interrupt – System Reset – Interrupt and System Reset • Selectable Time-out period from 16ms to 8s •...
  • Page 50 1. In the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit. 2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as desired, but with the WDCE bit cleared.
  • Page 51 ATmega48/88/168 Note: If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of time-out resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialisation routine, even if the Watchdog is not in use.
  • Page 52 8.2.1 Watchdog Timer Control Register - WDTCSR WDIF WDIE WDP3 WDCE WDP2 WDP1 WDP0 WDTCSR Read/Write Initial Value • Bit 7 - WDIF: Watchdog Interrupt Flag This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is config- ured for interrupt.
  • Page 53 ATmega48/88/168 • Bit 5, 2..0 - WDP3..0: Watchdog Timer Prescaler 3, 2, 1 and 0 The WDP3..0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is run- ning. The different prescaling values and their corresponding time-out periods are shown in Table 8-6 on page Table 8-6.
  • Page 54: Interrupts

    9. Interrupts This section describes the specifics of the interrupt handling as performed in ATmega48/88/168. For a general explanation of the AVR interrupt handling, refer to ”Reset and Interrupt Handling” on page The interrupt vectors in ATmega48, ATmega88 and ATmega168 are generally the same, with the following differences: •...
  • Page 55 ATmega48/88/168 Table 9-1. Reset and Interrupt Vectors in ATmega48 (Continued) Vector No. Program Address Source Interrupt Definition 0x017 ANALOG COMP Analog Comparator 0x018 2-wire Serial Interface 0x019 SPM READY Store Program Memory Ready The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega48 is: Address Labels Code Comments...
  • Page 56: Interrupt Vectors In Atmega88

    Interrupt Vectors in ATmega88 Table 9-2. Reset and Interrupt Vectors in ATmega88 Program Vector No. Address Source Interrupt Definition 0x000 RESET External Pin, Power-on Reset, Brown-out Reset and Watchdog System Reset 0x001 INT0 External Interrupt Request 0 0x002 INT1 External Interrupt Request 1 0x003 PCINT0 Pin Change Interrupt Request 0...
  • Page 57 ATmega48/88/168 Table 9-3. Reset and Interrupt Vectors Placement in ATmega88 BOOTRST IVSEL Reset Address Interrupt Vectors Start Address 0x000 0x001 0x000 Boot Reset Address + 0x001 Boot Reset Address 0x001 Boot Reset Address Boot Reset Address + 0x001 Note: 1. The Boot Reset Address is shown in Table 24-6 on page 276.
  • Page 58 When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega88 is: Address Labels Code Comments 0x000...
  • Page 59: Interrupt Vectors In Atmega168

    ATmega48/88/168 0xC1B SPH,r16 ; Set Stack Pointer to top of RAM 0xC1C r16,low(RAMEND) 0xC1D SPL,r16 0xC1E ; Enable interrupts 0xC1F <instr> Interrupt Vectors in ATmega168 Table 9-4. Reset and Interrupt Vectors in ATmega168 Program VectorNo. Address Source Interrupt Definition 0x0000 RESET External Pin, Power-on Reset, Brown-out Reset and Watchdog System Reset 0x0002...
  • Page 60 2. When the IVSEL bit in MCUCR is set, Interrupt Vectors will be moved to the start of the Boot Flash Section. The address of each Interrupt Vector will then be the address in this table added to the start address of the Boot Flash Section. Table 9-5 shows reset and Interrupt Vectors placement for the various combinations of BOOTRST and IVSEL settings.
  • Page 61 ATmega48/88/168 0x0033RESET: r16, high(RAMEND); Main program start 0x0034 SPH,r16 ; Set Stack Pointer to top of RAM 0x0035 r16, low(RAMEND) 0x0036 SPL,r16 0x0037 ; Enable interrupts 0x0038 <instr> When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega168 is: Address Labels Code...
  • Page 62 Address Labels Code Comments .org 0x1C00 0x1C00 RESET ; Reset handler 0x1C02 EXT_INT0 ; IRQ0 Handler 0x1C04 EXT_INT1 ; IRQ1 Handler 0x1C32 SPM_RDY ; Store Program Memory Ready Handler 0x1C33 RESET: ldi r16,high(RAMEND); Main program start 0x1C34 SPH,r16 ; Set Stack Pointer to top of RAM 0x1C35 r16,low(RAMEND) 0x1C36...
  • Page 63 ATmega48/88/168 • 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.
  • Page 64: O-Ports

    10. I/O-Ports 10.1 Introduction All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when chang- ing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input).
  • Page 65: Ports As General Digital I/O

    ATmega48/88/168 Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital I/O. 10.2 Ports as General Digital I/O The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a func- tional description of one I/O-port pin, here generically called Pxn.
  • Page 66 If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). 10.2.2 Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn.
  • Page 67 ATmega48/88/168 Figure 10-3. Synchronization when Reading an Externally Applied Pin value SYSTEM CLK INSTRUCTIONS in r17, PINx SYNC LATCH PINxn 0x00 0xFF pd, max pd, min Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the “SYNC LATCH”...
  • Page 68 Assembly Code Example ; Define pull-ups and set outputs high ; Define directions for port pins r16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0) r17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0) PORTB,r16 DDRB,r17 ; Insert nop for synchronization ; Read port pins r16,PINB C Code Example unsigned char i; /* Define pull-ups and set outputs high */ /* Define directions for port pins */ PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0);...
  • Page 69: Alternate Port Functions

    ATmega48/88/168 ing inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset.
  • Page 70 Table 10-2 summarizes the function of the overriding signals. The pin and port indexes from Fig- ure 10-5 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function. Table 10-2. Generic Description of Overriding Signals for Alternate Functions Signal Name Full Name...
  • Page 71 ATmega48/88/168 10.3.1 MCU Control Register – MCUCR – – – – – IVSEL IVCE MCUCR Read/Write Initial Value • Bit 4 – PUD: Pull-up Disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01).
  • Page 72 becomes the inverting output of the Oscillator amplifier. In this mode, a crystal Oscillator is con- nected to this pin, and the pin cannot be used as an I/O pin. PCINT7: Pin Change Interrupt source 7. The PB7 pin can serve as an external interrupt source. If PB7 is used as a clock pin, DDB7, PORTB7 and PINB7 will all read 0.
  • Page 73 ATmega48/88/168 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.
  • Page 74 Table 10-4. Overriding Signals for Alternate Functions in PB7..PB4 Signal PB7/XTAL2/ PB6/XTAL1/ PB5/SCK/ PB4/MISO/ Name TOSC2/PCINT7 TOSC1/PCINT6 PCINT5 PCINT4 INTRC • EXTCK+ PUOE INTRC + AS2 SPE • MSTR SPE • MSTR PUOV PORTB5 • PUD PORTB4 • PUD INTRC • EXTCK+ DDOE INTRC + AS2 SPE •...
  • Page 75 ATmega48/88/168 10.3.3 Alternate Functions of Port C The Port C pins with alternate functions are shown in Table 10-6. Table 10-6. Port C Pins Alternate Functions Port Pin Alternate Function RESET (Reset pin) PCINT14 (Pin Change Interrupt 14) ADC5 (ADC Input Channel 5) SCL (2-wire Serial Bus Clock Line) PCINT13 (Pin Change Interrupt 13) ADC4 (ADC Input Channel 4)
  • Page 76 the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew- rate limitation. PC4 can also be used as ADC input Channel 4.
  • Page 77 ATmega48/88/168 Table 10-7 Table 10-8 relate the alternate functions of Port C to the overriding signals shown in Figure 10-5 on page Table 10-7. Overriding Signals for Alternate Functions in PC6..PC4 Signal Name PC6/RESET/PCINT14 PC5/SCL/ADC5/PCINT13 PC4/SDA/ADC4/PCINT12 PUOE RSTDISBL TWEN TWEN PUOV PORTC5 •...
  • Page 78 10.3.4 Alternate Functions of Port D The Port D pins with alternate functions are shown in Table 10-9. Table 10-9. Port D Pins Alternate Functions Port Pin Alternate Function AIN1 (Analog Comparator Negative Input) PCINT23 (Pin Change Interrupt 23) AIN0 (Analog Comparator Positive Input) OC0A (Timer/Counter0 Output Compare Match A Output) PCINT22 (Pin Change Interrupt 22) T1 (Timer/Counter 1 External Counter Input)
  • Page 79 ATmega48/88/168 • T1/OC0B/PCINT21 – Port D, Bit 5 T1, Timer/Counter1 counter source. OC0B, Output Compare Match output: The PD5 pin can serve as an external output for the Timer/Counter0 Compare Match B. The PD5 pin has to be configured as an output (DDD5 set (one)) to serve this function.
  • Page 80 Table 10-10. Overriding Signals for Alternate Functions PD7..PD4 Signal PD7/AIN1 PD6/AIN0/ PD5/T1/OC0B/ PD4/XCK/ Name /PCINT23 OC0A/PCINT22 PCINT21 T0/PCINT20 PUOE DDOE DDOV PVOE OC0A ENABLE OC0B ENABLE UMSEL PVOV OC0A OC0B XCK OUTPUT DIEOE PCINT23 • PCIE2 PCINT22 • PCIE2 PCINT21 • PCIE2 PCINT20 •...
  • Page 81: Register Description For I/O Ports

    ATmega48/88/168 10.4 Register Description for I/O Ports 10.4.1 The Port B Data Register – PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 PORTB Read/Write Initial Value 10.4.2 The Port B Data Direction Register – DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1...
  • Page 82 10.4.9 The Port D Input Pins Address – PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 PIND Read/Write Initial Value ATmega48/88/168 2545E–AVR–02/05...
  • Page 83: External Interrupts

    ATmega48/88/168 11. External Interrupts The External Interrupts are triggered by the INT0 and INT1 pins or any of the PCINT23..0 pins. Observe that, if enabled, the interrupts will trigger even if the INT0 and INT1 or PCINT23..0 pins are configured as outputs. This feature provides a way of generating a software interrupt. The pin change interrupt PCI2 will trigger if any enabled PCINT23..16 pin toggles.
  • Page 84 11.1.1 External Interrupt Control Register A – EICRA The External Interrupt Control Register A contains control bits for interrupt sense control. – – – – ISC11 ISC10 ISC01 ISC00 EICRA Read/Write Initial Value • Bit 7..4 – Res: Reserved Bits These bits are unused bits in the ATmega48/88/168, and will always read as zero.
  • Page 85 ATmega48/88/168 11.1.2 External Interrupt Mask Register – EIMSK – – – – – – INT1 INT0 EIMSK Read/Write Initial Value • Bit 7..2 – Res: Reserved Bits These bits are unused bits in the ATmega48/88/168, and will always read as zero. •...
  • Page 86 11.1.4 Pin Change Interrupt Control Register - PCICR – – – – – PCIE2 PCIE1 PCIE0 PCICR Read/Write Initial Value • Bit 7..3 - Res: Reserved Bits These bits are unused bits in the ATmega48/88/168, and will always read as zero. •...
  • Page 87 ATmega48/88/168 • Bit 0 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT7..0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in SREG and the PCIE0 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector.
  • Page 88: 12 8-Bit Timer/Counter0 With Pwm

    12. 8-bit Timer/Counter0 with PWM Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and with PWM support. It allows accurate program execution timing (event man- agement) and wave generation. The main features are: • Two Independent Output Compare Units •...
  • Page 89: Timer/Counter Clock Sources

    ATmega48/88/168 12.1.1 Definitions Many register and bit references in this section are written in general form. A lower case “n” replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Com- pare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing Timer/Counter0 counter value and so on.
  • Page 90: Output Compare Unit

    Figure 12-2. Counter Unit Block Diagram TOVn (Int.Req.) DATA BUS Clock Select count Edge Detector clear TCNTn Control Logic direction ( From Prescaler ) bottom Signal description (internal signals): count Increment or decrement TCNT0 by 1. direction Select between increment and decrement. clear Clear TCNT0 (set all bits to zero).
  • Page 91 ATmega48/88/168 Figure 12-3. Output Compare Unit, Block Diagram DATA BUS OCRnx TCNTn (8-bit Comparator ) OCFnx (Int.Req.) bottom Waveform Generator OCnx FOCn WGMn1:0 COMnx1:0 The OCR0x Registers are double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the dou- ble buffering is disabled.
  • Page 92: Compare Match Output Unit

    The setup of the OC0x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC0x value is to use the Force Output Com- pare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even when changing between Waveform Generation modes.
  • Page 93: Modes Of Operation

    ATmega48/88/168 non-PWM modes refer to Table 12-2 on page 99. For fast PWM mode, refer to Table 12-3 on page 99, and for phase correct PWM refer to Table 12-4 on page 100. A change of the COM0x1:0 bits state will have effect at the first compare match after the bits are written.
  • Page 94 Figure 12-5. CTC Mode, Timing Diagram OCnx Interrupt Flag Set TCNTn (COMnx1:0 = 1) (Toggle) Period An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
  • Page 95 ATmega48/88/168 PWM mode is shown in Figure 12-6. The TCNT0 value is in the timing diagram shown as a his- togram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0x and TCNT0.
  • Page 96 feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Out- put Compare unit is enabled in the fast PWM mode. 12.6.4 Phase Correct PWM Mode The phase correct PWM mode (WGM02:0 = 1 or 5) provides a high resolution phase correct PWM waveform generation option.
  • Page 97: Timer/Counter Timing Diagrams

    ATmega48/88/168 one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (see Table 12-7 on page 101). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC0x Register at the compare match between OCR0x and TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at compare match between OCR0x and TCNT0 when the counter decrements.
  • Page 98 Figure 12-9. Timer/Counter Timing Diagram, with Prescaler (f clk_I/O (clk TCNTn MAX - 1 BOTTOM BOTTOM + 1 TOVn Figure 12-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC mode and PWM mode, where OCR0A is TOP. Figure 12-10.
  • Page 99: Bit Timer/Counter Register Description

    ATmega48/88/168 12.8 8-bit Timer/Counter Register Description 12.8.1 Timer/Counter Control Register A – TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 TCCR0A Read/Write Initial Value • Bits 7:6 – COM0A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC0A) behavior. If one or both of the COM0A1:0 bits are set, the OC0A output overrides the normal port functionality of the I/O pin it is connected to.
  • Page 100 Table 12-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase cor- rect PWM mode. Table 12-4. Compare Output Mode, Phase Correct PWM Mode COM0A1 COM0A0 Description Normal port operation, OC0A disconnected. WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match.
  • Page 101 ATmega48/88/168 Table 12-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase cor- rect PWM mode. Table 12-7. Compare Output Mode, Phase Correct PWM Mode COM0B1 COM0B0 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match when up-counting. Set OC0B on Compare Match when down-counting.
  • Page 102 12.8.2 Timer/Counter Control Register B – TCCR0B FOC0A FOC0B – – WGM02 CS02 CS01 CS00 TCCR0B Read/Write Initial Value • Bit 7 – FOC0A: Force Output Compare A The FOC0A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode.
  • Page 103 ATmega48/88/168 Table 12-9. Clock Select Bit Description CS02 CS01 CS00 Description No clock source (Timer/Counter stopped) /(No prescaling) /8 (From prescaler) /64 (From prescaler) /256 (From prescaler) /1024 (From prescaler) External clock source on T0 pin. Clock on falling edge. External clock source on T0 pin.
  • Page 104 12.8.6 Timer/Counter Interrupt Mask Register – TIMSK0 – – – – – OCIE0B OCIE0A TOIE0 TIMSK0 Read/Write Initial Value • Bits 7..3 – Res: Reserved Bits These bits are reserved bits in the ATmega48/88/168 and will always read as zero. •...
  • Page 105 ATmega48/88/168 • Bit 0 – TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed.
  • Page 106: 16-Bit Timer/Counter1 With Pwm

    13. 16-bit Timer/Counter1 with PWM The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are: • True 16-bit Design (i.e., Allows 16-bit PWM) • Two independent Output Compare Units •...
  • Page 107 ATmega48/88/168 Figure 13-1. 16-bit Timer/Counter Block Diagram Count TOVn (Int.Req.) Clear Control Logic Clock Select Direction Edge Detector BOTTOM ( From Prescaler ) Timer/Counter TCNTn OCnA (Int.Req.) Waveform OCnA Generation OCRnA OCnB Fixed (Int.Req.) Values Waveform OCnB Generation OCRnB ( From Analog Comparator Ouput ) ICFn (Int.Req.) Edge...
  • Page 108: Accessing 16-Bit Registers

    Section “13.6” on page 115.. The compare match event will also set the Compare Match Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request. The Input Capture Register can capture the Timer/Counter value at a given external (edge trig- gered) event on either the Input Capture pin (ICP1) or on the Analog Comparator pins (See Section “20.”...
  • Page 109 ATmega48/88/168 Assembly Code Examples ; Set TCNT1 to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNT1H,r17 out TCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H C Code Examples unsigned int i; /* Set TCNT1 to 0x01FF */ TCNT1 = 0x1FF; /* Read TCNT1 into i */ i = TCNT1;...
  • Page 110 Assembly Code Example TIM16_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 C Code Example unsigned int TIM16_ReadTCNT1( void ) unsigned char sreg; unsigned int i;...
  • Page 111: Timer/Counter Clock Sources

    ATmega48/88/168 Assembly Code Example TIM16_WriteTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts ; Set TCNT1 to r17:r16 out TCNT1H,r17 out TCNT1L,r16 ; Restore global interrupt flag out SREG,r18 C Code Example void TIM16_WriteTCNT1( unsigned int i ) unsigned char sreg;...
  • Page 112: Counter Unit

    13.4 Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 13-2 shows a block diagram of the counter and its surroundings. Figure 13-2. Counter Unit Block Diagram DATA BUS (8-bit) TOVn (Int.Req.) TEMP (8-bit) Clock Select Count...
  • Page 113: Input Capture Unit

    ATmega48/88/168 The Timer/Counter Overflow Flag (TOV1) is set according to the mode of operation selected by the WGM13:0 bits. TOV1 can be used for generating a CPU interrupt. 13.5 Input Capture Unit The Timer/Counter incorporates an Input Capture unit that can capture external events and give them a time-stamp indicating time of occurrence.
  • Page 114 tion mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1 Register. When writing the ICR1 Register the high byte must be written to the ICR1H I/O location before the low byte is written to ICR1L. For more information on how to access the 16-bit registers refer to ”Accessing 16-bit Registers”...
  • Page 115: Output Compare Units

    ATmega48/88/168 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). 13.6 Output Compare Units The 16-bit comparator continuously compares TCNT1 with the Output Compare Register (OCR1x).
  • Page 116 prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the out- put glitch-free. The OCR1x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR1x Buffer Register, and if double buffering is dis- abled the CPU will access the OCR1x directly.
  • Page 117: Compare Match Output Unit

    ATmega48/88/168 13.7 Compare Match Output Unit The Compare Output mode (COM1x1:0) bits have two functions. The Waveform Generator uses the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next compare match. Secondly the COM1x1:0 bits control the OC1x pin output source. Figure 13-5 shows a simplified schematic of the logic affected by the COM1x1:0 bit setting.
  • Page 118: Modes Of Operation

    non-PWM modes refer to Table 13-1 on page 128. For fast PWM mode refer to Table 13-2 on page 128, and for phase correct and phase and frequency correct PWM refer to Table 13-3 on page 129. A change of the COM1x1:0 bits state will have effect at the first compare match after the bits are written.
  • Page 119 ATmega48/88/168 Figure 13-6. CTC Mode, Timing Diagram OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) TCNTn OCnA (COMnA1:0 = 1) (Toggle) Period An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag according to the register used to define the TOP value.
  • Page 120 The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the max- imum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated by using the following equation: ---------------------------------- - 2 ( )
  • Page 121 ATmega48/88/168 to be written anytime. When the OCR1A I/O location is written the value written will be put into the OCR1A Buffer Register. The OCR1A Compare Register will then be updated with the value in the Buffer Register at the next timer clock cycle the TCNT1 matches TOP. The update is done at the same timer clock cycle as the TCNT1 is cleared and the TOV1 Flag is set.
  • Page 122 0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolu- tion in bits can be calculated by using the following equation: ---------------------------------- - 2 ( ) PCPWM 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).
  • Page 123 ATmega48/88/168 implies that the length of the falling slope is determined by the previous TOP value, while the length of the rising slope is determined by the new TOP value. When these two values differ the two slopes of the period will differ in length. The difference in length gives the unsymmetrical result on the output.
  • Page 124 the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated using the following equation: ---------------------------------- - 2 ( ) PFCPWM 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).
  • Page 125: Timer/Counter Timing Diagrams

    ATmega48/88/168 Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively changed by changing the TOP value, using the OCR1A as TOP is clearly a better choice due to its double buffer feature.
  • Page 126 Figure 13-11. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (f clk_I/O (clk TCNTn OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2 OCRnx OCRnx Value OCFnx Figure 13-12 shows the count sequence close to TOP in various modes. When using phase and frequency correct PWM mode the OCR1x Register is updated at BOTTOM.
  • Page 127 ATmega48/88/168 Figure 13-13. Timer/Counter Timing Diagram, with Prescaler (f clk_I/O (clk TCNTn TOP - 1 BOTTOM BOTTOM + 1 (CTC and FPWM) TCNTn TOP - 1 TOP - 1 TOP - 2 (PC and PFC PWM) TOVn (FPWM) and ICF n (if used as TOP) OCRnx...
  • Page 128: 6-Bit Timer/Counter Register Description

    13.10 16-bit Timer/Counter Register Description 13.10.1 Timer/Counter1 Control Register A – TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 TCCR1A Read/Write Initial Value • 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.
  • Page 129 ATmega48/88/168 Table 13-3 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase correct or the phase and frequency correct, PWM mode. Table 13-3. Compare Output Mode, Phase Correct and Phase and Frequency Correct COM1A1/COM1B1 COM1A0/COM1B0 Description Normal port operation, OC1A/OC1B disconnected.
  • Page 130 Table 13-4. Waveform Generation Mode Bit Description WGM12 WGM11 WGM10 Timer/Counter Mode of Update of TOV1 Flag Mode WGM13 (CTC1) (PWM11) (PWM10) Operation OCR1 Set on Normal 0xFFFF Immediate PWM, Phase Correct, 8-bit 0x00FF BOTTOM PWM, Phase Correct, 9-bit 0x01FF BOTTOM PWM, Phase Correct, 10-bit 0x03FF...
  • Page 131 ATmega48/88/168 When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequently the Input Cap- ture function is disabled. • Bit 5 – Reserved Bit This bit is reserved for future use.
  • Page 132 A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear Timer on Compare match (CTC) mode using OCR1A as TOP. The FOC1A/FOC1B bits are always read as zero. 13.10.4 Timer/Counter1 – TCNT1H and TCNT1L TCNT1[15:8] TCNT1H TCNT1[7:0]...
  • Page 133 ATmega48/88/168 13.10.7 Input Capture Register 1 – ICR1H and ICR1L ICR1[15:8] ICR1H ICR1[7:0] ICR1L Read/Write Initial Value The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin (or optionally on the Analog Comparator output for Timer/Counter1). The Input Capture can be used for defining the counter TOP value.
  • Page 134 13.10.9 Timer/Counter1 Interrupt Flag Register – TIFR1 – – ICF1 – – OCF1B OCF1A TOV1 TIFR1 Read/Write Initial Value • Bit 7, 6 – Res: Reserved Bits These bits are unused bits in the ATmega48/88/168, and will always read as zero. •...
  • Page 135: Timer/Counter0 And Timer/Counter1 Prescalers

    ATmega48/88/168 14. Timer/Counter0 and Timer/Counter1 Prescalers ”8-bit Timer/Counter0 with PWM” on page 88 ”16-bit Timer/Counter1 with PWM” on page share the same prescaler module, but the Timer/Counters can have different prescaler set- tings. The description below applies to both Timer/Counter1 and Timer/Counter0. 14.0.1 Internal Clock Source The Timer/Counter can be clocked directly by the system clock (by setting the CSn2:0 = 1).
  • Page 136 Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated. Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling.
  • Page 137 ATmega48/88/168 14.0.4 General Timer/Counter Control Register – GTCCR – – – – – PSRASY PSRSYNC GTCCR Read/Write Initial Value • Bit 7 – TSM: Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the value that is written to the PSRASY and PSRSYNC bits is kept, hence keeping the correspond- ing prescaler reset signals asserted.
  • Page 138: 15 8-Bit Timer/Counter2 With Pwm And Asynchronous Operation

    15. 8-bit Timer/Counter2 with PWM and Asynchronous Operation Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. The main features are: • Single Channel Counter • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) •...
  • Page 139: Timer/Counter Clock Sources

    ATmega48/88/168 15.1.1 Registers The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit reg- isters. Interrupt request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK2).
  • Page 140: Output Compare Unit

    Figure 15-2. Counter Unit Block Diagram TOVn DATA BUS (Int.Req.) TOSC1 count clear Oscillator TCNTn Control Logic Prescaler direction TOSC2 bottom Signal description (internal signals): count Increment or decrement TCNT2 by 1. direction Selects between increment and decrement. clear Clear TCNT2 (set all bits to zero). Timer/Counter clock, referred to as clk in the following.
  • Page 141 ATmega48/88/168 Figure 15-3. Output Compare Unit, Block Diagram DATA BUS OCRnx TCNTn (8-bit Comparator ) OCFnx (Int.Req.) bottom Waveform Generator OCnx FOCn WGMn1:0 COMnX1:0 The OCR2x Register is double buffered when using any of the Pulse Width Modulation (PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled.
  • Page 142: Compare Match Output Unit

    The setup of the OC2x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC2x value is to use the Force Output Com- pare (FOC2x) strobe bit in Normal mode. The OC2x Register keeps its value even when changing between Waveform Generation modes.
  • Page 143: Modes Of Operation

    ATmega48/88/168 15.5.1 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM2x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM2x1:0 = 0 tells the Waveform Generator that no action on the OC2x Register is to be performed on the next compare match. For compare output actions in the non-PWM modes refer to Table 15-5 on page 150.
  • Page 144 Figure 15-5. CTC Mode, Timing Diagram OCnx Interrupt Flag Set TCNTn OCnx (COMnx1:0 = 1) (Toggle) Period An interrupt can be generated each time the counter value reaches the TOP value by using the OCF2A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
  • Page 145 ATmega48/88/168 In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 15-6.
  • Page 146 generated will have a maximum frequency of f /2 when OCR2A is set to zero. This fea- clk_I/O ture is similar to the OC2A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 15.6.4 Phase Correct PWM Mode The phase correct PWM mode (WGM22:0 = 1 or 5) provides a high resolution phase correct...
  • Page 147: Timer/Counter Timing Diagrams

    ATmega48/88/168 output can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7 (See Table 15-4 on page 150). The actual OC2x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC2x Register at the compare match between OCR2x and TCNT2 when the counter increments, and setting (or clearing) the OC2x Register at compare match between OCR2x and TCNT2 when the counter decrements.
  • Page 148 Figure 15-9. Timer/Counter Timing Diagram, with Prescaler (f clk_I/O (clk TCNTn MAX - 1 BOTTOM BOTTOM + 1 TOVn Figure 15-10 shows the setting of OCF2A in all modes except CTC mode. Figure 15-10. Timer/Counter Timing Diagram, Setting of OCF2A, with Prescaler (f clk_I/O (clk TCNTn...
  • Page 149: Bit Timer/Counter Register Description

    ATmega48/88/168 15.8 8-bit Timer/Counter Register Description 15.8.1 Timer/Counter Control Register A – TCCR2A COM2A1 COM2A0 COM2B1 COM2B0 – – WGM21 WGM20 TCCR2A Read/Write Initial Value • Bits 7:6 – COM2A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC2A) behavior. If one or both of the COM2A1:0 bits are set, the OC2A output overrides the normal port functionality of the I/O pin it is connected to.
  • Page 150 Table 15-4 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to phase cor- rect PWM mode. Table 15-4. Compare Output Mode, Phase Correct PWM Mode COM2A1 COM2A0 Description Normal port operation, OC2A disconnected. WGM22 = 0: Normal Port Operation, OC2A Disconnected. WGM22 = 1: Toggle OC2A on Compare Match.
  • Page 151 ATmega48/88/168 Table 15-7 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to phase cor- rect PWM mode. Table 15-7. Compare Output Mode, Phase Correct PWM Mode COM2B1 COM2B0 Description Normal port operation, OC2B disconnected. Reserved Clear OC2B on Compare Match when up-counting. Set OC2B on Compare Match when down-counting.
  • Page 152 15.8.2 Timer/Counter Control Register B – TCCR2B FOC2A FOC2B – – WGM22 CS22 CS21 CS20 TCCR2B Read/Write Initial Value • Bit 7 – FOC2A: Force Output Compare A The FOC2A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR2B is written when operating in PWM mode.
  • Page 153 ATmega48/88/168 Table 15-9. Clock Select Bit Description CS22 CS21 CS20 Description No clock source (Timer/Counter stopped). /(No prescaling) /8 (From prescaler) /32 (From prescaler) /64 (From prescaler) /128 (From prescaler) /256 (From prescaler) /1024 (From prescaler) If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output.
  • Page 154 15.8.6 Timer/Counter2 Interrupt Mask Register – TIMSK2 – – – – – OCIE2B OCIE2A TOIE2 TIMSK2 Read/Write Initial Value • Bit 2 – OCIE2B: Timer/Counter2 Output Compare Match B Interrupt Enable When the OCIE2B bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare Match B interrupt is enabled.
  • Page 155: Asynchronous Operation Of The Timer/Counter

    ATmega48/88/168 15.9 Asynchronous operation of the Timer/Counter 15.9.1 Asynchronous Operation of Timer/Counter2 When Timer/Counter2 operates asynchronously, some considerations must be taken. • Warning: When switching between asynchronous and synchronous clocking of Timer/Counter2, the Timer Registers TCNT2, OCR2x, and TCCR2x might be corrupted. A safe procedure for switching clock source is: a.
  • Page 156 • Description of wake up from Power-save or ADC Noise Reduction mode when the timer is clocked asynchronously: When the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value.
  • Page 157 ATmega48/88/168 • Bit 3 – OCR2AUB: Output Compare Register2 Update Busy When Timer/Counter2 operates asynchronously and OCR2A is written, this bit becomes set. When OCR2A has been updated from the temporary storage register, this bit is cleared by hard- ware. A logical zero in this bit indicates that OCR2A is ready to be updated with a new value. •...
  • Page 158: Timer/Counter Prescaler

    15.10 Timer/Counter Prescaler Figure 15-12. Prescaler for Timer/Counter2 10-BIT T/C PRESCALER Clear TOSC1 PSRASY CS20 CS21 CS22 TIMER/COUNTER2 CLOCK SOURCE The clock source for Timer/Counter2 is named clk . clk is by default connected to the main system I/O clock clk .
  • Page 159: Serial Peripheral Interface - Spi

    ATmega48/88/168 16. Serial Peripheral Interface – SPI The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega48/88/168 and peripheral devices or between several AVR devices. The ATmega48/88/168 SPI includes the following features: • Full-duplex, Three-wire Synchronous Data Transfer •...
  • Page 160 communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and Slave prepare the data to be sent in their respective shift Registers, and the Master generates the required clock pulses on the SCK line to interchange data. Data is always shifted from Mas- ter to Slave on the Master Out –...
  • Page 161 ATmega48/88/168 (Note:) Table 16-1. SPI Pin Overrides Direction, Master SPI Direction, Slave SPI MOSI User Defined Input MISO Input User Defined User Defined Input User Defined Input Note: ”Alternate Functions of Port B” on page 71 for a detailed description of how to define the direction of the user defined SPI pins.
  • Page 162 Assembly Code Example SPI_MasterInit: ; Set MOSI and SCK output, all others input r17,(1<<DD_MOSI)|(1<<DD_SCK) DDR_SPI,r17 ; Enable SPI, Master, set clock rate fck/16 r17,(1<<SPE)|(1<<MSTR)|(1<<SPR0) SPCR,r17 SPI_MasterTransmit: ; Start transmission of data (r16) SPDR,r16 Wait_Transmit: ; Wait for transmission complete sbis SPSR,SPIF rjmp Wait_Transmit C Code Example void SPI_MasterInit(void)
  • Page 163 ATmega48/88/168 The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example SPI_SlaveInit: ; Set MISO output, all others input r17,(1<<DD_MISO) DDR_SPI,r17 ; Enable SPI r17,(1<<SPE) SPCR,r17 SPI_SlaveReceive: ;...
  • Page 164: Ss Pin Functionality

    16.1 SS Pin Functionality 16.1.1 Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs.
  • Page 165 ATmega48/88/168 • 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. •...
  • Page 166: Data Modes

    16.1.4 SPI Status Register – SPSR SPIF WCOL – – – – – SPI2X SPSR Read/Write Initial Value • Bit 7 – SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled.
  • Page 167 ATmega48/88/168 Table 16-5. CPOL Functionality Leading Edge Trailing eDge SPI Mode CPOL=0, CPHA=0 Sample (Rising) Setup (Falling) CPOL=0, CPHA=1 Setup (Rising) Sample (Falling) CPOL=1, CPHA=0 Sample (Falling) Setup (Rising) CPOL=1, CPHA=1 Setup (Falling) Sample (Rising) Figure 16-3. SPI Transfer Format with CPHA = 0 SCK (CPOL = 0) mode 0 SCK (CPOL = 1)
  • Page 168: Usart0

    17. USART0 The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a highly flexible serial communication device. The main features are: • Full Duplex Operation (Independent Serial Receive and Transmit Registers) • Asynchronous or Synchronous Operation • Master or Slave Clocked Synchronous Operation •...
  • Page 169: Clock Generation

    ATmega48/88/168 Figure 17-1. USART Block Diagram Clock Generator UBRRn [H:L] BAUD RATE GENERATOR SYNC LOGIC XCKn CONTROL Transmitter UDRn(Transmit) CONTROL PARITY GENERATOR TRANSMIT SHIFT REGISTER TxDn CONTROL Receiver CLOCK RECOVERY CONTROL DATA RECEIVE SHIFT REGISTER RxDn RECOVERY CONTROL PARITY UDRn (Receive) CHECKER UCSRnA UCSRnB...
  • Page 170 Figure 17-2. Clock Generation Logic, Block Diagram UBRRn U2Xn foscn UBRRn+1 Prescaling Down-Counter txclk DDR_XCKn Sync Edge Register Detector xcki UMSELn XCKn xcko DDR_XCKn UCPOLn rxclk Signal description: txclk Transmitter clock (Internal Signal). rxclk Receiver base clock (Internal Signal). xcki Input from XCK pin (internal Signal).
  • Page 171 ATmega48/88/168 Table 17-1 contains equations for calculating the baud rate (in bits per second) and for calculat- ing the UBRRn value for each mode of operation using an internally generated clock source. Table 17-1. Equations for Calculating Baud Rate Register Setting Equation for Calculating Baud Equation for Calculating Operating Mode...
  • Page 172: Frame Formats

    17.2.3 External Clock External clocking is used by the synchronous slave modes of operation. The description in this section refers to Figure 17-2 for details. External clock input from the XCKn pin is sampled by a synchronization register to minimize the chance of meta-stability.
  • Page 173 ATmega48/88/168 A frame starts with the start bit followed by the least significant data bit. Then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state.
  • Page 174: Usart Initialization

    17.4 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.
  • Page 175 ATmega48/88/168 For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 Registers. Assembly Code Example USART_Init: ; Set baud rate UBRRnH, r17 UBRRnL, r16 ; Enable receiver and transmitter r16, (1<<RXENn)|(1<<TXENn) UCSRnB,r16 ; Set frame format: 8data, 2stop bit r16, (1<<USBSn)|(3<<UCSZn0) UCSRnC,r16 C Code Example...
  • Page 176: Data Transmission - The Usart Transmitter

    17.5 Data Transmission – The USART Transmitter The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRnB Register. When the Transmitter is enabled, the normal port operation of the TxDn pin is overrid- den by the USART and given the function as the Transmitter’s serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions.
  • Page 177 ATmega48/88/168 17.5.2 Sending Frames with 9 Data Bit If 9-bit characters are used (UCSZn = 7), the ninth bit must be written to the TXB8 bit in UCS- RnB before the low byte of the character is written to UDRn. The following code examples show a transmit function that handles 9-bit characters.
  • Page 178: Data Reception - The Usart Receiver

    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 UCSRnA Register. When the Data Register Empty Interrupt Enable (UDRIEn) bit in UCSRnB is written to one, the USART Data Register Empty Interrupt will be executed as long as UDREn is set (provided that global interrupts are enabled).
  • Page 179 ATmega48/88/168 The following code example shows a simple USART receive function based on polling of the Receive Complete (RXCn) Flag. When using frames with less than eight bits the most significant bits of the data read from the UDRn will be masked to zero. The USART has to be initialized before the function can be used.
  • Page 180 Assembly Code Example USART_Receive: ; Wait for data to be received sbis UCSRnA, RXCn rjmp USART_Receive ; Get status and 9th bit, then data from buffer r18, UCSRnA r17, UCSRnB r16, UDRn ; If error, return -1 andi r18,(1<<FEn)|(1<<DORn)|(1<<UPEn) breq USART_ReceiveNoError r17, HIGH(-1) r16, LOW(-1) USART_ReceiveNoError:...
  • Page 181 ATmega48/88/168 17.6.3 Receive Compete Flag and Interrupt The USART Receiver has one flag that indicates the Receiver state. The Receive Complete (RXCn) Flag indicates if there are unread data present in the receive buffer. This flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data).
  • Page 182: Asynchronous Data Reception

    The UPEn 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 (UPMn1 = 1). This bit is valid until the receive buffer (UDRn) is read. 17.6.6 Disabling the Receiver In contrast to the Transmitter, disabling of the Receiver will be immediate.
  • Page 183 ATmega48/88/168 Figure 17-5. Start Bit Sampling IDLE START BIT 0 Sample (U2X = 0) Sample (U2X = 1) When the clock recovery logic detects a high (idle) to low (start) transition on the RxDn line, the start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in the figure.
  • Page 184 Figure 17-7. Stop Bit Sampling and Next Start Bit Sampling STOP 1 Sample (U2X = 0) Sample (U2X = 1) The same majority voting is done to the stop bit as done for the other bits in the frame. If the stop bit is registered to have a logic 0 value, the Frame Error (FEn) Flag will be set.
  • Page 185: Multi-Processor Communication Mode

    ATmega48/88/168 Table 17-2. Recommended Maximum Receiver Baud Rate Error for Normal Speed Mode (U2Xn = 0) Recommended Max # (Data+Parity Bit) Max Total Error (%) Receiver Error (%) slow fast 93.20 106.67 +6.67/-6.8 ± 3.0 94.12 105.79 +5.79/-5.88 ± 2.5 94.81 105.11 +5.11/-5.19...
  • Page 186 nine data bits, then the ninth bit (RXB8n) is used for identifying address and data frames. When the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. When the frame type bit is zero the frame is a data frame. The Multi-processor Communication mode enables several slave MCUs to receive data from a master MCU.
  • Page 187: Usart Register Description

    ATmega48/88/168 17.9 USART Register Description 17.9.1 USART I/O Data Register n– UDRn RXB[7:0] UDRn (Read) TXB[7:0] UDRn (Write) Read/Write Initial Value 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 UDRn. The Transmit Data Buffer Reg- ister (TXB) will be the destination for data written to the UDRn Register location.
  • Page 188 UDREn is set after a reset to indicate that the Transmitter is ready. • Bit 4 – FEn: Frame Error This bit is set if the next character in the receive buffer had a Frame Error when received. I.e., when the first stop bit of the next character in the receive buffer is zero. This bit is valid until the receive buffer (UDRn) is read.
  • Page 189 ATmega48/88/168 • Bit 5 – UDRIEn: USART Data Register Empty Interrupt Enable n Writing this bit to one enables interrupt on the UDREn Flag. A Data Register Empty interrupt will be generated only if the UDRIEn bit is written to one, the Global Interrupt Flag in SREG is written to one and the UDREn bit in UCSRnA is set.
  • Page 190 • Bits 5:4 – UPMn1:0: Parity Mode These bits enable and set type of parity generation and check. If enabled, the Transmitter will automatically generate and send the parity of the transmitted data bits within each frame. The Receiver will generate a parity value for the incoming data and compare it to the UPMn setting. If a mismatch is detected, the UPEn Flag in UCSRnA will be set.
  • Page 191: Examples Of Baud Rate Setting

    ATmega48/88/168 Table 17-8. UCPOLn Bit Settings Transmitted Data Changed (Output of Received Data Sampled (Input on RxDn UCPOLn TxDn Pin) Pin) Rising XCKn Edge Falling XCKn Edge Falling XCKn Edge Rising XCKn Edge 17.9.5 USART Baud Rate Registers – UBRRnL and UBRRnH –...
  • Page 192 Table 17-9. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies = 1.0000 MHz = 1.8432 MHz = 2.0000 MHz U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 Baud Rate UBRR UBRR UBRR...
  • Page 193 ATmega48/88/168 Table 17-10. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) = 3.6864 MHz = 4.0000 MHz = 7.3728 MHz U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 Baud Rate UBRR...
  • Page 194 Table 17-11. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) 11.0592 = 8.0000 MHz = 14.7456 MHz U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 Baud Rate UBRR UBRR UBRR UBRR...
  • Page 195 ATmega48/88/168 Table 17-12. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) = 16.0000 MHz = 18.4320 MHz = 20.0000 MHz U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 U2Xn = 0 U2Xn = 1 Baud Rate UBRR...
  • Page 196: Usart In Spi Mode

    18. USART in SPI Mode The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) can be set to a master SPI compliant mode of operation. The Master SPI Mode (MSPIM) has the follow- ing features: • Full Duplex, Three-wire Synchronous Data Transfer •...
  • Page 197: Spi Data Modes And Timing

    ATmega48/88/168 Table 18-1. Equations for Calculating Baud Rate Register Setting Equation for Calculating Baud Equation for Calculating UBRRn Operating Mode Rate Value Synchronous Master ------------------- - 1 BAUD -------------------------------------- - UBRRn – mode 2 UBRRn 2BAUD Note: 1. The baud rate is defined to be the transfer rate in bit per second (bps) BAUD Baud rate (in bits per second, bps) System Oscillator clock frequency...
  • Page 198: Frame Formats

    18.4 Frame Formats A serial frame for the MSPIM is defined to be one character of 8 data bits. The USART in MSPIM mode has two valid frame formats: • 8-bit data with MSB first • 8-bit data with LSB first A frame starts with the least or most significant data bit.
  • Page 199: Data Transfer

    ATmega48/88/168 baud rate is given as a function parameter. For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. Assembly Code Example USART_Init: clr r18 out UBRRnH,r18 out UBRRnL,r18 ; Setting the XCKn port pin as output, enables master mode. sbi XCKn_DDR, XCKn ;...
  • Page 200 After initialization the USART is ready for doing data transfers. A data transfer is initiated by writ- ing to the UDRn I/O location. This is the case for both sending and receiving data since the transmitter controls the transfer clock. The data written to UDRn is moved from the transmit buffer to the shift register when the shift register is ready to send a new frame.
  • Page 201: Usart Mspim Register Description

    ATmega48/88/168 Assembly Code Example USART_MSPIM_Transfer: ; Wait for empty transmit buffer sbis UCSRnA, UDREn rjmp USART_MSPIM_Transfer ; Put data (r16) into buffer, sends the data out UDRn,r16 ; Wait for data to be received USART_MSPIM_Wait_RXCn: sbis UCSRnA, RXCn rjmp USART_MSPIM_Wait_RXCn ;...
  • Page 202 RXCn TXCn UDREn UCSRnA Read/Write Initial Value • Bit 7 - RXCn: USART Receive Complete This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXCn bit will become zero.
  • Page 203 ATmega48/88/168 Writing this bit to one enables the USART Receiver in MSPIM mode. The Receiver will override normal port operation for the RxDn pin when enabled. Disabling the Receiver will flush the receive buffer. Only enabling the receiver in MSPI mode (i.e. setting RXENn=1 and TXENn=0) has no meaning since it is the transmitter that controls the transfer clock and since only master mode is supported.
  • Page 204: Avr Usart Mspim Vs. Avr Spi

    • Bit 0 - UCPOLn: Clock Polarity The UCPOLn bit sets the polarity of the XCKn clock. The combination of the UCPOLn and UCPHAn bit settings determine the timing of the data transfer. Refer to the SPI Data Modes and Timing section page 4 for details.
  • Page 205: 19 2-Wire Serial Interface

    ATmega48/88/168 19. 2-wire Serial Interface 19.1 Features • Simple Yet Powerful and Flexible Communication Interface, only two Bus Lines Needed • Both Master and Slave Operation Supported • Device can Operate as Transmitter or Receiver • 7-bit Address Space Allows up to 128 Different Slave Addresses •...
  • Page 206: Data Transfer And Frame Format

    The PRTWI bit in ”Power Reduction Register - PRR” on page 40 must be written to zero to enable the 2-wire Serial Interface. 19.2.2 Electrical Interconnection As depicted in Figure 19-1, both bus lines are connected to the positive supply voltage through pull-up resistors.
  • Page 207 ATmega48/88/168 depicted below, START and STOP conditions are signalled by changing the level of the SDA line when the SCL line is high. Figure 19-3. START, REPEATED START and STOP conditions START STOP START REPEATED START STOP 19.3.3 Address Packet Format All address packets transmitted on the TWI bus are 9 bits long, consisting of 7 address bits, one READ/WRITE control bit and an acknowledge bit.
  • Page 208 19.3.4 Data Packet Format All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the Master generates the clock and the START and STOP conditions, while the Receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signalled by the Receiver pulling the SDA line low during the ninth SCL cycle.
  • Page 209: Multi-Master Bus Systems, Arbitration And Synchronization

    ATmega48/88/168 19.4 Multi-master Bus Systems, Arbitration and Synchronization The TWI protocol allows bus systems with several masters. Special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more masters initiate a transmission at the same time. Two problems arise in multi-master systems: •...
  • Page 210 bits. If several masters are trying to address the same Slave, arbitration will continue into the data packet. Figure 19-8. Arbitration Between Two Masters START Master A Loses Arbitration, SDA SDA from Master A SDA from Master B SDA Line Synchronized SCL Line Note that arbitration is not allowed between:...
  • Page 211: Overview Of The Twi Module

    ATmega48/88/168 19.5 Overview of the TWI Module The TWI module is comprised of several submodules, as shown in Figure 19-9. All registers drawn in a thick line are accessible through the AVR data bus. Figure 19-9. Overview of the TWI Module Spike Spike Slew-rate...
  • Page 212 that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period. The SCL frequency is generated according to the following equation: CPU Clock frequency SCL frequency ---------------------------------------------------------------------------------------- - ⋅ 2(TWBR) PrescalerValue • TWBR = Value of the TWI Bit Rate Register. •...
  • Page 213: Twi Register Description

    ATmega48/88/168 able. As long as the TWINT Flag is set, the SCL line is held low. This allows the application software to complete its tasks before allowing the TWI transmission to continue. The TWINT Flag is set in the following situations: •...
  • Page 214 • 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.
  • Page 215 ATmega48/88/168 19.6.3 TWI Status Register – TWSR TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 TWSR Read/Write Initial Value • Bits 7..3 – TWS: TWI Status These 5 bits reflect the status of the TWI logic and the 2-wire Serial Bus. The different status codes are described later in this section.
  • Page 216 • Bits 7..0 – TWD: TWI Data Register These eight bits constitute the next data byte to be transmitted, or the latest data byte received on the 2-wire Serial Bus. 19.6.5 TWI (Slave) Address Register – TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1...
  • Page 217: Using The Twi

    ATmega48/88/168 Figure 19-10. TWI Address Match Logic, Block Diagram TWAR0 Address Match Address Bit 0 TWAMR0 Address Bit Comparator 0 Address Bit Comparator 6..1 • Bit 0 – Res: Reserved Bit This bit is an unused bit in the ATmega48/88/168, and will always read as zero. 19.7 Using the TWI The AVR TWI is byte-oriented and interrupt based.
  • Page 218 Figure 19-11. Interfacing the Application to the TWI in a Typical Transmission 3. Check TWSR to see if START was 5. Check TWSR to see if SLA+W was 1. Application 7. Check TWSR to see if data was sent sent. Application loads SLA+W into sent and ACK received.
  • Page 219 ATmega48/88/168 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.
  • Page 220 Assembly Code Example C Example Comments r16, TWCR = (1<<TWINT)|(1<<TWSTA)| (1<<TWINT)|(1<<TWSTA)| (1<<TWEN) Send START condition (1<<TWEN) TWCR, r16 wait1: while (!(TWCR & (1<<TWINT))) Wait for TWINT Flag set. This r16,TWCR indicates that the START sbrs r16,TWINT condition has been transmitted rjmp wait1 r16,TWSR if ((TWSR &...
  • Page 221: Transmission Modes

    ATmega48/88/168 19.8 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.
  • Page 222 Figure 19-12. Data Transfer in Master Transmitter Mode Device 1 Device 2 Device 3 ..Device n MASTER SLAVE TRANSMITTER RECEIVER A START condition is sent by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN –...
  • Page 223 ATmega48/88/168 After a repeated START condition (state 0x10) the 2-wire Serial Interface can access the same Slave again, or a new Slave without transmitting a STOP condition. Repeated START enables the Master to switch between Slaves, Master Transmitter mode and Master Receiver mode with- out losing control of the bus.
  • Page 224 Figure 19-13. Formats and States in the Master Transmitter Mode Successfull DATA transmission to a slave receiver Next transfer started with a repeated start condition Not acknowledge received after the slave address Not acknowledge received after a data byte Arbitration lost in slave Other master Other master A or A...
  • Page 225 ATmega48/88/168 Figure 19-14. Data Transfer in Master Receiver Mode Device 1 Device 2 ..Device 3 Device n MASTER SLAVE RECEIVER TRANSMITTER A START condition is sent by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN –...
  • Page 226 the Master to switch between Slaves, Master Transmitter mode and Master Receiver mode with- out losing control over the bus. Table 19-4. Status codes for Master Receiver Mode Status Code Application Software Response (TWSR) Status of the 2-wire Serial Bus To TWCR Prescaler Bits and 2-wire Serial Interface...
  • Page 227 ATmega48/88/168 Figure 19-15. Formats and States in the Master Receiver Mode Successfull DATA DATA reception from a slave receiver Next transfer started with a repeated start condition Not acknowledge received after the slave address Arbitration lost in slave Other master Other master A or A address or data byte...
  • Page 228 The upper 7 bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address. TWCR TWINT TWEA...
  • Page 229 ATmega48/88/168 Table 19-5. Status Codes for Slave Receiver Mode Status Code Application Software Response (TWSR) Status of the 2-wire Serial Bus To TWCR Prescaler Bits and 2-wire Serial Interface Hard- To/from TWDR TWIN are 0 ware Next Action Taken by TWI Hardware 0x60 Own SLA+W has been received;...
  • Page 230 Figure 19-17. Formats and States in the Slave Receiver Mode Reception of the own DATA DATA P or S slave address and one or more data bytes. All are acknowledged Last data byte received P or S is not acknowledged Arbitration lost as master and addressed as slave Reception of the general call...
  • Page 231 ATmega48/88/168 value Device’s Own Slave Address The upper seven bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
  • Page 232 Table 19-6. Status Codes for Slave Transmitter Mode Status Code Application Software Response (TWSR) Status of the 2-wire Serial Bus To TWCR Prescaler and 2-wire Serial Interface Hard- To/from TWDR TWIN Bits ware Next Action Taken by TWI Hardware are 0 0xA8 Own SLA+R has been received;...
  • Page 233 ATmega48/88/168 Figure 19-19. Formats and States in the Slave Transmitter Mode Reception of the own DATA DATA P or S slave address and one or more data bytes Arbitration lost as master and addressed as slave Last data byte transmitted. All 1's P or S Switched to not addressed...
  • Page 234: Multi-Master Systems And Arbitration

    Note that data is transmitted both from Master to Slave and vice versa. The Master must instruct the Slave what location it wants to read, requiring the use of the MT mode. Subsequently, data must be read from the Slave, implying the use of the MR mode. Thus, the transfer direction must be changed.
  • Page 235: Analog Comparator

    ATmega48/88/168 • Two or more masters are accessing different slaves. In this case, arbitration will occur in the SLA bits. Masters trying to output a one on SDA while another Master outputs a zero will lose the arbitration. Masters losing arbitration in SLA will switch to Slave mode to check if they are being addressed by the winning Master.
  • Page 236 Figure 20-1. Analog Comparator Block Diagram BANDGAP REFERENCE ACBG ACME ADEN ADC MULTIPLEXER OUTPUT Notes: 1. See Table 20-2 on page 238. 2. Refer to Figure 1-1 on page 2 Table 10-9 on page 78 for Analog Comparator pin placement. 20.0.1 ADC Control and Status Register B –...
  • Page 237: Analog Comparator Multiplexed Input

    ATmega48/88/168 • Bit 5 – ACO: Analog Comparator Output The output of the Analog Comparator is synchronized and then directly connected to ACO. The synchronization introduces a delay of 1 - 2 clock cycles. • Bit 4 – ACI: Analog Comparator Interrupt Flag This bit is set by hardware when a comparator output event triggers the interrupt mode defined by ACIS1 and ACIS0.
  • Page 238 20-2. If ACME is cleared or ADEN is set, AIN1 is applied to the negative input to the Analog Comparator. Table 20-2. Analog Comparator Multiplexed Input ACME ADEN MUX2..0 Analog Comparator Negative Input AIN1 AIN1 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7...
  • Page 239: Analog-To-Digital Converter

    ATmega48/88/168 21. Analog-to-Digital Converter 21.1 Features • 10-bit Resolution • 0.5 LSB Integral Non-linearity • ± 2 LSB Absolute Accuracy • 13 - 260 µs Conversion Time • Up to 15 kSPS at Maximum Resolution • 6 Multiplexed Single Ended Input Channels •...
  • Page 240 Figure 21-1. Analog to Digital Converter Block Schematic Operation ADC CONVERSION COMPLETE IRQ 8-BIT DATA BUS ADC MULTIPLEXER ADC CTRL. & STATUS ADC DATA REGISTER SELECT (ADMUX) REGISTER (ADCSRA) (ADCH/ADCL) MUX DECODER PRESCALER CONVERSION LOGIC AVCC INTERNAL 1.1V REFERENCE SAMPLE & HOLD COMPARATOR AREF 10-BIT DAC...
  • Page 241: Starting A Conversion

    ATmega48/88/168 read, neither register is updated and the result from the conversion is lost. When ADCH is read, ADC access to the ADCH and ADCL Registers is re-enabled. The ADC has its own interrupt which can be triggered when a conversion completes. When ADC access to the Data Registers is prohibited between reading of ADCH and ADCL, the interrupt will trigger even if the result is lost.
  • Page 242: Prescaling And Conversion Timing

    If Auto Triggering is enabled, single conversions can be started by writing ADSC in ADCSRA to one. ADSC can also be used to determine if a conversion is in progress. The ADSC bit will be read as one during a conversion, independently of how the conversion was started. 21.3 Prescaling and Conversion Timing Figure 21-3.
  • Page 243 ATmega48/88/168 Figure 21-4. ADC Timing Diagram, First Conversion (Single Conversion Mode) Next First Conversion Conversion Cycle Number ADC Clock ADEN ADSC ADIF Sign and MSB of Result ADCH LSB of Result ADCL MUX and REFS Conversion MUX and REFS Sample & Hold Update Complete Update...
  • Page 244: Changing Channel Or Reference Selection

    Figure 21-7. ADC Timing Diagram, Free Running Conversion One Conversion Next Conversion Cycle Number ADC Clock ADSC ADIF ADCH Sign and MSB of Result ADCL LSB of Result Sample & Hold Conversion MUX and REFS Complete Update Table 21-1. ADC Conversion Time Sample &...
  • Page 245: Adc Noise Canceler

    ATmega48/88/168 21.4.1 ADC Input Channels When changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: In Single Conversion mode, always select the channel before starting the conversion. The chan- nel selection may be changed one ADC clock cycle after writing one to ADSC. However, the simplest method is to wait for the conversion to complete before changing the channel selection.
  • Page 246 21.5.1 Analog Input Circuitry The analog input circuitry for single ended channels is illustrated in Figure 21-8. An analog source applied to ADCn is subjected to the pin capacitance and input leakage of that pin, regard- less of whether that channel is selected as input for the ADC. When the channel is selected, the source must drive the S/H capacitor through the series resistance (combined resistance in the input path).
  • Page 247 ATmega48/88/168 and ADC5) will only affect the conversion on ADC4 and ADC5 and not the other ADC channels. Figure 21-9. ADC Power Connections PC1 (ADC1) PC0 (ADC0) ADC7 AREF ADC6 AVCC 21.5.3 ADC Accuracy Definitions An n-bit single-ended ADC converts a voltage linearly between GND and V in 2 steps (LSBs).
  • Page 248 Figure 21-10. Offset Error Output Code Ideal ADC Actual ADC Offset Error Input Voltage • Gain error: After adjusting for offset, the gain error is found as the deviation of the last transition (0x3FE to 0x3FF) compared to the ideal transition (at 1.5 LSB below maximum). Ideal value: 0 Figure 21-11.
  • Page 249 ATmega48/88/168 Figure 21-12. Integral Non-linearity (INL) Output Code Ideal ADC Actual ADC Input Voltage • Differential Non-linearity (DNL): The maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 LSB). Ideal value: 0 LSB. Figure 21-13.
  • Page 250: Adc Conversion Result

    21.6 ADC Conversion Result After the conversion is complete (ADIF is high), the conversion result can be found in the ADC Result Registers (ADCL, ADCH). For single ended conversion, the result is ⋅ 1024 -------------------------- where V is the voltage on the selected input pin and V the selected voltage reference (see Table 21-2 on page 250 Table 21-3 on page...
  • Page 251 ATmega48/88/168 The value of these bits selects which analog inputs are connected to the ADC. See Table 21-3 for details. If these bits are changed during a conversion, the change will not go in effect until this conversion is complete (ADIF in ADCSRA is set). Table 21-3.
  • Page 252 • Bit 5 – ADATE: ADC Auto Trigger Enable When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a con- version on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB.
  • Page 253 ATmega48/88/168 21.6.3 The ADC Data Register – ADCL and ADCH 21.6.3.1 ADLAR = 0 – – – – – – ADC9 ADC8 ADCH ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 ADCL Read/Write Initial Value 21.6.3.2 ADLAR = 1 ADC9 ADC8 ADC7 ADC6...
  • Page 254 trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching to Free Running mode (ADTS[2:0]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set Table 21-5. ADC Auto Trigger Source Selections ADTS2 ADTS1 ADTS0...
  • Page 255: Debugwire On-Chip Debug System

    ATmega48/88/168 22. debugWIRE On-chip Debug System 22.1 Features • Complete Program Flow Control • Emulates All On-chip Functions, Both Digital and Analog, except RESET Pin • Real-time Operation • Symbolic Debugging Support (Both at C and Assembler Source Level, or for Other HLLs) •...
  • Page 256: Software Break Points

    When designing a system where debugWIRE will be used, the following observations must be made for correct operation: • Pull-up resistors on the dW/(RESET) line must not be smaller than 10kΩ. The pull-up resistor is not required for debugWIRE functionality. •...
  • Page 257 ATmega48/88/168 The device provides a Self-Programming mechanism for downloading and uploading program code by the MCU itself. The Self-Programming can use any available data interface and associ- ated protocol to read code and write (program) that code into the Program memory. The Program memory is updated in a page by page fashion.
  • Page 258: Addressing The Flash During Self-Programming

    23.0.3 Performing a Page Write To execute Page Write, set up the address in the Z-pointer, write “00000101” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer must be written to zero during this operation.
  • Page 259 ATmega48/88/168 23.1.1 Store Program Memory Control and Status Register – SPMCSR The Store Program Memory Control and Status Register contains the control bits needed to con- trol the Program memory operations. SPMIE RWWSB – RWWSRE BLBSET PGWRT PGERS SELFPRGEN SPMCSR Read/Write Initial Value •...
  • Page 260 • Bit 0 – SELFPRGEN: Self Programming 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.
  • Page 261 ATmega48/88/168 shown below. See Table 25-5 on page 282 for detailed description and mapping of the Extended Fuse byte. FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0 Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are unprogrammed, will be read as one.
  • Page 262 ;-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 ;...
  • Page 263 ATmega48/88/168 ; return to RWW section ; verify that RWW section is safe to read Return: temp1, SPMCSR sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet ; re-enable the RWW section spmcrval, (1<<RWWSRE) | (1<<SELFPRGEN) rcallDo_spm rjmp Return Do_spm:...
  • Page 264: Boot Loader Support - Read-While-Write Self-Programming, Atmega88 And Atmega168

    24. Boot Loader Support – Read-While-Write Self-Programming, ATmega88 and ATmega168 In ATmega88 and ATmega168, 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 application software updates controlled by the MCU using a Flash-resi- dent Boot Loader program.
  • Page 265: Read-While-Write And No Read-While-Write Flash Sections

    ATmega48/88/168 24.3 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-While-Write (RWW) section and the No Read-While- Write (NRWW) section.
  • Page 266 Figure 24-1. Read-While-Write vs. No Read-While-Write Read-While-Write (RWW) Section Z-pointer Addresses NRWW Section Z-pointer Addresses RWW No Read-While-Write (NRWW) Section Section CPU is Halted During the Operation Code Located in NRWW Section Can be Read During the Operation ATmega48/88/168 2545E–AVR–02/05...
  • Page 267: Boot Loader Lock Bits

    ATmega48/88/168 Figure 24-2. Memory Sections Program Memory Program Memory BOOTSZ = '11' BOOTSZ = '10' 0x0000 0x0000 Application Flash Section Application Flash Section End RWW End RWW Start NRWW Start NRWW Application Flash Section Application Flash Section End Application End Application Start Boot Loader Boot Loader Flash Section Start Boot Loader...
  • Page 268: Entering The Boot Loader Program

    Table 24-2. Boot Lock Bit0 Protection Modes (Application Section) BLB0 Mode BLB02 BLB01 Protection No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section.
  • Page 269 ATmega48/88/168 Note: 1. “1” means unprogrammed, “0” means programmed 24.5.1 Store Program Memory Control and Status Register – SPMCSR The Store Program Memory Control and Status Register contains the control bits needed to con- trol the Boot Loader operations. SPMIE RWWSB –...
  • Page 270: Addressing The Flash During Self-Programming

    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 SELFPRGEN, the next SPM instruction within four clock cycles executes Page Erase.
  • Page 271: Self-Programming The Flash

    ATmega48/88/168 Figure 24-3. Addressing the Flash During SPM ZPCMSB ZPAGEMSB Z - REGISTER PCMSB PAGEMSB PROGRAM PCPAGE PCWORD COUNTER PAGE ADDRESS WORD ADDRESS WITHIN THE FLASH WITHIN A PAGE PROGRAM MEMORY PAGE PCWORD[PAGEMSB:0]: PAGE INSTRUCTION WORD PAGEEND Note: 1. The different variables used in Figure 24-3 are listed in Table 24-8 on page...
  • Page 272 24.7.1 Performing Page Erase by SPM To execute Page Erase, set up the address in the Z-pointer, write “X0000011” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 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 273 ATmega48/88/168 the RWWSB by writing the RWWSRE. See ”Simple Assembly Code Example for a Boot Loader” on page 275 for an example. 24.7.7 Setting the Boot Loader Lock Bits by SPM To set the Boot Loader Lock bits, write the desired data to R0, write “X0001001” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR.
  • Page 274 shown below. Refer to Table 25-6 on page 282 for detailed description and mapping of the Fuse High byte. FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0 When reading the Extended Fuse byte, load 0x0002 in the Z-pointer. When an LPM instruction is executed within three cycles after the BLBSET and SELFPRGEN bits are set in the SPMCSR, the value of the Extended Fuse byte (EFB) will be loaded in the destination register as shown below.
  • Page 275 ATmega48/88/168 24.7.12 Simple Assembly Code Example for a Boot Loader ;-the routine writes one page of data from RAM to Flash ; the first data location in RAM is pointed to by the Y pointer ; the first data location in Flash is pointed to by the Z-pointer ;-error handling is not included ;-the routine must be placed inside the Boot space ;...
  • Page 276 ; return to RWW section ; verify that RWW section is safe to read Return: temp1, SPMCSR sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet ; re-enable the RWW section spmcrval, (1<<RWWSRE) | (1<<SELFPRGEN) call Do_spm rjmp Return Do_spm:...
  • Page 277 ATmega48/88/168 Note: The different BOOTSZ Fuse configurations are shown in Figure 24-2. Table 24-7. Read-While-Write Limit, ATmega88 Section Pages Address Read-While-Write section (RWW) 0x000 - 0xBFF No Read-While-Write section (NRWW) 0xC00 - 0xFFF For details about these two section, see ”NRWW –...
  • Page 278 24.7.14 ATmega168 Boot Loader Parameters Table 24-9 through Table 24-11, the parameters used in the description of the self program- ming are given. Table 24-9. Boot Size Configuration, ATmega168 Boot Reset Boot Address Application Loader (Start Boot Boot Flash Flash Application Loader BOOTSZ1...
  • Page 279 ATmega48/88/168 Table 24-11. Explanation of Different Variables used in Figure 24-3 and the Mapping to the Z- pointer, ATmega168 Corresponding Variable Z-value Description Most significant bit in the Program Counter. (The PCMSB Program Counter is 12 bits PC[11:0]) Most significant bit which is used to address the words within one page (64 words in a page PAGEMSB requires 6 bits PC [5:0])
  • Page 280: Memory Programming

    25. Memory Programming 25.1 Program And Data Memory Lock Bits The ATmega88/168 provides six Lock bits which can be left unprogrammed (“1”) or can be pro- grammed (“0”) to obtain the additional features listed in Table 25-2. The Lock bits can only be erased to “1”...
  • Page 281: Fuse Bits

    ATmega48/88/168 (1)(2) Table 25-3. Lock Bit Protection Modes . Only ATmega88/168. BLB0 Mode BLB02 BLB01 No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section.
  • Page 282 Table 25-5. Extended Fuse Byte for mega88/168 Extended Fuse Byte Bit No Description Default Value – – – – – – – – – – Select Boot Size BOOTSZ1 0 (programmed) (see Table 113 for details) Select Boot Size BOOTSZ0 0 (programmed) (see Table 113 for details) BOOTRST...
  • Page 283: Signature Bytes

    25.3 Signature Bytes All Atmel microcontrollers have a three-byte signature code which identifies the device. This code can be read in both serial and parallel mode, also when the device is locked. The three bytes reside in a separate address space.
  • Page 284: Calibration Byte

    25.4 Calibration Byte The ATmega48/88/168 has a byte calibration value for the internal RC Oscillator. This byte resides in the high byte of address 0x000 in the signature address space. During reset, this byte is automatically written into the OSCCAL Register to ensure correct frequency of the calibrated RC Oscillator.
  • Page 285 ATmega48/88/168 Figure 25-1. Parallel Programming +4.5 - 5.5V RDY/BSY +4.5 - 5.5V AVCC PC[1:0]:PB[5:0] DATA PAGEL +12 V RESET XTAL1 Note: - 0.3V < AV < V + 0.3V, however, AV should always be within 4.5 - 5.5V Table 25-10. Pin Name Mapping Signal Name in Programming Mode Pin Name...
  • Page 286: Parallel Programming

    Table 25-12. XA1 and XA0 Coding Action when XTAL1 is Pulsed Load Flash or EEPROM Address (High or low address byte determined by BS1). Load Data (High or Low data byte for Flash determined by BS1). Load Command No Action, Idle Table 25-13.
  • Page 287 ATmega48/88/168 4. Keep the Prog_enable pins unchanged for at least 10µs after the High-voltage has been applied to ensure the Prog_enable Signature has been latched. 5. Wait until V actually reaches 4.5 -5.5V before giving any parallel programming commands. 6. Exit Programming mode by power the device down or by bringing RESET pin to 0V. 25.7.2 Considerations for Efficient Programming The loaded command and address are retained in the device during programming.
  • Page 288 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.
  • Page 289 ATmega48/88/168 Figure 25-2. Addressing the Flash Which is Organized in Pages PCMSB PAGEMSB PROGRAM PCPAGE PCWORD COUNTER PAGE ADDRESS WORD ADDRESS WITHIN THE FLASH WITHIN A PAGE PROGRAM MEMORY PAGE PCWORD[PAGEMSB:0]: PAGE INSTRUCTION WORD PAGEEND Note: 1. PCPAGE and PCWORD are listed in Table 25-8 on page 284.
  • Page 290 5. E: Latch data (give PAGEL a positive pulse). K: Repeat 3 through 5 until the entire buffer is filled. L: Program EEPROM page 1. Set BS1 to “0”. 2. Give WR a negative pulse. This starts programming of the EEPROM page. RDY/BSY goes low.
  • Page 291 ATmega48/88/168 25.7.8 Programming the Fuse Low Bits The algorithm for programming the Fuse Low bits is as follows (refer to ”Programming the Flash” on page 287 for details on Command and Data loading): 1. A: Load Command “0100 0000”. 2. C: Load Data Low Byte. Bit n = “0” programs and bit n = “1” erases the Fuse bit. 3.
  • Page 292 1. A: Load Command “0010 0000”. 2. C: Load Data Low Byte. Bit n = “0” programs the Lock bit. If LB mode 3 is programmed (LB1 and LB2 is programmed), it is not possible to program the Boot Lock bits by any External Programming mode.
  • Page 293 ATmega48/88/168 25.7.14 Reading the Calibration Byte The algorithm for reading the Calibration byte is as follows (refer to ”Programming the Flash” on page 287 for details on Command and Address loading): 1. A: Load Command “0000 1000”. 2. B: Load Address Low Byte, 0x00. 3.
  • Page 294 Figure 25-9. Parallel Programming Timing, Reading Sequence (within the Same Page) with Timing Requirements LOAD ADDRESS READ DATA READ DATA LOAD ADDRESS (LOW BYTE) (LOW BYTE) (HIGH BYTE) (LOW BYTE) XLOL XTAL1 BVDV OLDV OHDZ DATA (High Byte) ADDR1 (Low Byte) DATA ADDR0 (Low Byte) DATA (Low Byte)
  • Page 295: Serial Downloading

    ATmega48/88/168 Table 25-14. Parallel Programming Characteristics, V = 5V ± 10% (Continued) Symbol Parameter Units BS1 Valid to DATA valid BVDV OE Low to DATA Valid OLDV OE High to DATA Tri-stated OHDZ Notes: 1. t is valid for the Write Flash, Write EEPROM, Write Fuse bits and Write Lock bits WLRH commands.
  • Page 296: Serial Programming Pin Mapping

    25.9 Serial Programming Pin Mapping Table 25-15. Pin Mapping Serial Programming Symbol Pins Description MOSI Serial Data in MISO Serial Data out Serial Clock 25.9.1 Serial Programming Algorithm When writing serial data to the ATmega48/88/168, data is clocked on the rising edge of SCK. When reading data from the ATmega48/88/168, data is clocked on the falling edge of SCK.
  • Page 297 ATmega48/88/168 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.
  • Page 298 Table 25-17. Serial Programming Instruction Set (Continued) Instruction Format Instruction Byte 1 Byte 2 Byte 3 Byte4 Operation Load data i to EEPROM memory page 1100 0001 0000 0000 0000 00bb iiii iiii Load EEPROM Memory buffer. After data is loaded, program Page (page access) EEPROM page.
  • Page 299: Electrical Characteristics

    ATmega48/88/168 26. Electrical Characteristics 26.1 Absolute Maximum Ratings* *NOTICE: Stresses beyond those listed under “Absolute Operating Temperature........-55°C to +125°C Maximum Ratings” may cause permanent dam- age to the device. This is a stress rating only and Storage Temperature ........-65°C to +150°C functional operation of the device at these or Voltage on any Pin except RESET other conditions beyond those indicated in the...
  • Page 300 = -40°C to 85°C, V = 1.8V to 5.5V (unless otherwise noted) (Continued) Symbol Parameter Condition Min. Typ. Max. Units Reset Pull-up Resistor kΩ I/O Pin Pull-up Resistor kΩ Active 1MHz, V = 2V 0.55 (ATmega48/88/168V) Active 4MHz, V = 3V (ATmega48/88/168L) Active 8MHz, V = 5V...
  • Page 301: External Clock Drive Waveforms

    ATmega48/88/168 If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition. 5. All DC Characteristics contained in this datasheet are based on simulation and characterization of other AVR microcontrol- lers manufactured in the same process technology.
  • Page 302: Wire Serial Interface Characteristics

    Figure 26-2. Maximum Frequency vs. V , ATmega48V/88V/168V 10 MHz Safe Operating Area 4 MHz 1.8V 2.7V 5.5V Figure 26-3. Maximum Frequency vs. V , ATmega48/88/168 20 MHz 10 MHz Safe Operating Area 2.7V 4.5V 5.5V 26.6 2-wire Serial Interface Characteristics Table 26-2 describes the requirements for devices connected to the 2-wire Serial Bus.
  • Page 303 ATmega48/88/168 Table 26-2. 2-wire Serial Bus Requirements (Continued) Symbol Parameter Condition Units Capacitance for each I/O Pin – SCL Clock Frequency > max(16f , 250kHz) ≤ 100 kHz – 0,4V 1000ns Ω ---------------- - --------------------------- - Value of Pull-up resistor –...
  • Page 304: Spi Timing Characteristics

    Figure 26-4. 2-wire Serial Bus Timing HIGH SU;STA HD;STA HD;DAT SU;DAT SU;STO 26.7 SPI Timing Characteristics Figure 26-5 Figure 26-6 for details. Table 26-3. SPI Timing Parameters Description Mode SCK period Master Table 16-4 SCK high/low Master 50% duty cycle Rise/Fall time Master Setup...
  • Page 305 ATmega48/88/168 Figure 26-5. SPI Interface Timing Requirements (Master Mode) (CPOL = 0) (CPOL = 1) MISO (Data Input) MOSI (Data Output) Figure 26-6. SPI Interface Timing Requirements (Slave Mode) (CPOL = 0) (CPOL = 1) MOSI (Data Input) MISO (Data Output) 2545E–AVR–02/05...
  • Page 306: Adc Characteristics - Preliminary Data

    26.8 ADC Characteristics – Preliminary Data Table 26-4. ADC Characteristics Symbol Parameter Condition Units Resolution Bits = 4V, V = 4V, ADC clock = 200 kHz = 4V, V = 4V, ADC clock = 1 MHz Absolute accuracy (Including = 4V, V = 4V, INL, DNL, quantization error, ADC clock = 200 kHz...
  • Page 307: Atmega48/88/168 Typical Characteristics - Preliminary Data

    ATmega48/88/168 27. ATmega48/88/168 Typical Characteristics – Preliminary Data The following charts show typical behavior. These figures are not tested during manufacturing. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A square wave generator with rail-to-rail output is used as clock source.
  • Page 308 Figure 27-2. Active Supply Current vs. Frequency (1 - 24 MHz) ACTIVE SUPPLY CURRENT vs. FREQUENCY 1 - 24 MHz 5.5V 5.0V 4.5V 4.0V 3.3V 2.7V 1.8V Frequency (MHz) Figure 27-3. Active Supply Current vs. V (Internal RC Oscillator, 128 kHz) ACTIVE SUPPLY CURRENT vs.
  • Page 309 ATmega48/88/168 Figure 27-4. Active Supply Current vs. V (Internal RC Oscillator, 1 MHz) ACTIVE SUPPLY CURRENT vs. V INTERNAL RC OSCILLATOR, 1 MHz 25 °C -40 °C 85 °C Figure 27-5. Active Supply Current vs. V (Internal RC Oscillator, 8 MHz) ACTIVE SUPPLY CURRENT vs.
  • Page 310: Idle Supply Current

    Figure 27-6. Active Supply Current vs. V (32 kHz External Oscillator) ACTIVE SUPPLY CURRENT vs. V 32 kHz EXTERNAL OSCILLATOR 25 °C 27.2 Idle Supply Current Figure 27-7. Idle Supply Current vs. Frequency (0.1 - 1.0 MHz) IDLE SUPPLY CURRENT vs. FREQUENCY 0.1 - 1.0 MHz 0.18 5.5 V...
  • Page 311 ATmega48/88/168 Figure 27-8. Idle Supply Current vs. Frequency (1 - 24 MHz) IDLE SUPPLY CURRENT vs. FREQUENCY 1 - 24 MHz 5.5V 5.0V 4.5V 4.0V 3.3V 2.7V 1.8V Frequency (MHz) Figure 27-9. Idle Supply Current vs. V (Internal RC Oscillator, 128 kHz) IDLE SUPPLY CURRENT vs.
  • Page 312 Figure 27-10. Idle Supply Current vs. V (Internal RC Oscillator, 1 MHz) IDLE SUPPLY CURRENT vs. V INTERNAL RC OSCILLATOR, 1 MHz 0.35 85 °C 25 °C -40 °C 0.25 0.15 0.05 Figure 27-11. Idle Supply Current vs. V (Internal RC Oscillator, 8 MHz) IDLE SUPPLY CURRENT vs.
  • Page 313: Supply Current Of I/O Modules

    ATmega48/88/168 Figure 27-12. Idle Supply Current vs. V (32 kHz External Oscillator) IDLE SUPPLY CURRENT vs. V 32 kHz EXTERNAL OSCILLATOR 25 °C 27.3 Supply Current of I/O modules The tables and formulas below can be used to calculate the additional current consumption for the different I/O modules in Active and Idle mode.
  • Page 314 Table 27-2. Additional Current Consumption (percentage) in Active and Idle mode Additional Current consumption compared to Active with external Additional Current consumption clock compared to Idle with external clock PRR bit (see Figure 27-1 Figure 27-2) (see Figure 27-7 Figure 27-8) PRUSART0 3.3%...
  • Page 315: Power-Down Supply Current

    ATmega48/88/168 27.4 Power-Down Supply Current Figure 27-13. Power-Down Supply Current vs. V (Watchdog Timer Disabled) POWER-DOWN SUPPLY CURRENT vs. V WATCHDOG TIMER DISABLED 85 °C 25 °C -40 °C Figure 27-14. Power-Down Supply Current vs. V (Watchdog Timer Enabled) POWER-DOWN SUPPLY CURRENT vs. V WATCHDOG TIMER ENABLED 85 °C -40 °C...
  • Page 316: Power-Save Supply Current

    27.5 Power-Save Supply Current Figure 27-15. Power-Save Supply Current vs. V (Watchdog Timer Disabled) POWER-SAVE SUPPLY CURRENT vs. V WATCHDOG TIMER DISABLED 25 °C 27.6 Standby Supply Current Figure 27-16. Standby Supply Current vs. V (Low Power Crystal Oscillator) STANDBY SUPPLY CURRENT vs. V Low Power Crystal Oscillator 6 MHz Xtal 6 MHz Res.
  • Page 317: Pin Pull-Up

    ATmega48/88/168 Figure 27-17. Standby Supply Current vs. V (Full Swing Crystal Oscillator) STANDBY SUPPLY CURRENT vs. V Full Swing Crystal Oscillator 16 MHz Xtal 12 MHz Xtal 6 MHz Xtal (ckopt) 4 MHz Xtal (ckopt) 2 MHz Xtal (ckopt) 27.7 Pin Pull-up Figure 27-18.
  • Page 318 Figure 27-19. I/O Pin Pull-Up Resistor Current vs. Input Voltage (V = 2.7V) I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE = 2.7V 25 °C 85 °C -40 °C Figure 27-20. Reset Pull-Up Resistor Current vs. Reset Pin Voltage (V = 5V) RESET PULL-UP RESISTOR CURRENT vs.
  • Page 319: Pin Driver Strength

    ATmega48/88/168 Figure 27-21. Reset Pull-Up Resistor Current vs. Reset Pin Voltage (V = 2.7V) RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE = 2.7V 25 °C -40 °C 85 °C RESET 27.8 Pin Driver Strength Figure 27-22. I/O Pin Source Current vs. Output Voltage (V = 5V) I/O PIN SOURCE CURRENT vs.
  • Page 320 Figure 27-23. I/O Pin Source Current vs. Output Voltage (V = 2.7V) I/O PIN SOURCE CURRENT vs. OUTPUT VOLTAGE = 2.7V -40 °C 25 °C 85 °C Figure 27-24. I/O Pin Source Current vs. Output Voltage (V = 1.8V) I/O PIN SOURCE CURRENT vs. OUTPUT VOLTAGE = 1.8V 25 °C -40 °C 85 °C...
  • Page 321 ATmega48/88/168 Figure 27-25. I/O Pin Sink Current vs. Output Voltage (V = 5V) I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE = 5V 25 °C 85 °C Figure 27-26. I/O Pin Sink Current vs. Output Voltage (V = 2.7V) I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE = 2.7V -40 °C 25 °C...
  • Page 322: Pin Thresholds And Hysteresis

    Figure 27-27. I/O Pin Sink Current vs. Output Voltage (V = 1.8V) I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE = 1.8V -40 °C 25 °C 85 °C 27.9 Pin Thresholds and Hysteresis Figure 27-28. I/O Pin Input Threshold Voltage vs. V (VIH, I/O Pin Read As '1') I/O PIN INPUT THRESHOLD VOLTAGE vs.
  • Page 323 ATmega48/88/168 Figure 27-29. I/O Pin Input Threshold Voltage vs. V (VIL, I/O Pin Read As '0') I/O PIN INPUT THRESHOLD VOLTAGE vs. V VIL, IO PIN READ AS '0' 85 °C -40 °C 25 °C Figure 27-30. Reset Input Threshold Voltage vs. V (VIH, Reset Pin Read As '1') RESET INPUT THRESHOLD VOLTAGE vs.
  • Page 324 Figure 27-31. Reset Input Threshold Voltage vs. V (VIL, Reset Pin Read As '0') RESET INPUT THRESHOLD VOLTAGE vs. V VIL, IO PIN READ AS '0' -40 °C 85 °C 25 °C Figure 27-32. Reset Input Pin Hysteresis vs. V RESET PIN INPUT HYSTERESIS vs.
  • Page 325: Bod Thresholds And Analog Comparator Offset

    ATmega48/88/168 27.10 BOD Thresholds and Analog Comparator Offset Figure 27-33. BOD Thresholds vs. Temperature (BODLEVEL Is 4.0V) BOD THRESHOLDS vs. TEMPERATURE BODLEVEL IS 4.0V 4.45 Rising Vcc 4.35 Falling Vcc 4.25 Temperature (C) Figure 27-34. BOD Thresholds vs. Temperature (BODLEVEL Is 2.7V) BOD THRESHOLDS vs.
  • Page 326 Figure 27-35. BOD Thresholds vs. Temperature (BODLEVEL Is 1.8V) BOD THRESHOLDS vs. TEMPERATURE BODLEVEL IS 1.8V 1.86 1.84 Rising Vcc 1.82 Falling Vcc 1.78 1.76 Temperature (C) Figure 27-36. Bandgap Voltage vs. V BANDGAP VOLTAGE vs. V 1.095 -40 C 1.09 85 C 1.085...
  • Page 327 ATmega48/88/168 Figure 27-37. Analog Comparator Offset Voltage vs. Common Mode Voltage (V =5V) ANALOG COMPARATOR OFFSET VOLTAGE vs. COMMON MODE VOLTAGE 0.009 0.008 85 C 0.007 -40 C 0.006 0.005 0.004 0.003 0.002 0.001 Common Mode Voltage (V) Figure 27-38. Analog Comparator Offset Voltage vs. Common Mode Voltage (V =2.7V) ANALOG COMPARATOR OFFSET VOLTAGE vs.
  • Page 328: Internal Oscillator Speed

    27.11 Internal Oscillator Speed Figure 27-39. Watchdog Oscillator Frequency vs. V WATCHDOG OSCILLATOR FREQUENCY vs. V -40 °C 25 °C 85 °C Figure 27-40. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature CALIBRATED 8 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE 5.0 V 2.7 V 1.8 V...
  • Page 329 ATmega48/88/168 Figure 27-41. Calibrated 8 MHz RC Oscillator Frequency vs. V CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. V 85 ˚C 25 ˚C -40 ˚C Figure 27-42. Calibrated 8 MHz RC Oscillator Frequency vs. Osccal Value CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE 85 °C 25 °C -40 °C...
  • Page 330: Current Consumption Of Peripheral Units

    27.12 Current Consumption of Peripheral Units Figure 27-43. Brownout Detector Current vs. V BROWNOUT DETECTOR CURRENT vs. V -40 ˚C 25 ˚C 85 ˚C Figure 27-44. ADC Current vs. V (ADC at 50 kHz) AREF vs. V ADC AT 50 KHz -40 °C 25 °C 85 °C...
  • Page 331 ATmega48/88/168 Figure 27-45. Aref Current vs. V (ADC at 1 MHz) AREF vs. V ADC AT 1 MHz 85 ˚C 25 ˚C -40 ˚C Figure 27-46. Analog Comparator Current vs. V ANALOG COMPARATOR CURRENT vs. V -40 ˚C 25 ˚C 85 ˚C 2545E–AVR–02/05...
  • Page 332: Current Consumption In Reset And Reset Pulse Width

    Figure 27-47. Programming Current vs. V PROGRAMMING CURRENT vs. V -40 ˚C 25 ˚C 85 ˚C 27.13 Current Consumption in Reset and Reset Pulse width Figure 27-48. Reset Supply Current vs. V (0.1 - 1.0 MHz, Excluding Current through the Reset Pull-up) RESET SUPPLY CURRENT vs.
  • Page 333 ATmega48/88/168 Figure 27-49. Reset Supply Current vs. V (1 - 24 MHz, Excluding Current through the Reset Pull-up) RESET SUPPLY CURRENT vs. V 1 - 24 MHz, EXCLUDING CURRENT THROUGH THE RESET PULL-UP 5.5V 5.0V 4.5V 4.0V 3.3V 2.7V 1.8V Frequency (MHz) Figure 27-50.
  • Page 334: Register Summary

    28. Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page (0xFF) Reserved – – – – – – – – (0xFE) Reserved – – – – – – –...
  • Page 335 ATmega48/88/168 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page (0xBF) Reserved – – – – – – – – (0xBE) Reserved – – – – – – – – (0xBD) TWAMR TWAM6...
  • Page 336 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page (0x7D) Reserved – – – – – – – – (0x7C) ADMUX REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 (0x7B) ADCSRB –...
  • Page 337 ATmega48/88/168 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page 0x1B (0x3B) PCIFR – – – – – PCIF2 PCIF1 PCIF0 0x1A (0x3A) Reserved – – – – – – –...
  • Page 338: Instruction Set Summary

    29. Instruction Set Summary Mnemonics Operands Description Operation Flags #Clocks ARITHMETIC AND LOGIC INSTRUCTIONS Rd ← Rd + Rr Rd, Rr Add two Registers Z,C,N,V,H Rd ← Rd + Rr + C Rd, Rr Add with Carry two Registers Z,C,N,V,H Rdh:Rdl ←...
  • Page 339 ATmega48/88/168 Mnemonics Operands Description Operation Flags #Clocks if ( I = 1) then PC ← PC + k + 1 BRIE Branch if Interrupt Enabled None if ( I = 0) then PC ← PC + k + 1 BRID Branch if Interrupt Disabled None BIT AND BIT-TEST INSTRUCTIONS...
  • Page 340 Mnemonics Operands Description Operation Flags #Clocks Rd ← STACK Pop Register from Stack None MCU CONTROL INSTRUCTIONS No Operation None SLEEP Sleep (see specific descr. for Sleep function) None Watchdog Reset (see specific descr. for WDR/timer) None BREAK Break For On-chip Debug Only None Note: 1.
  • Page 341: Ordering Information

    32M1-A Note: 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 alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS direc- tive).Also Halide free and fully Green.
  • Page 342: Atmega88

    32M1-A Note: 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 alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS direc- tive).Also Halide free and fully Green.
  • Page 343: Atmega168

    32M1-A Note: 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 alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS direc- tive).Also Halide free and fully Green.
  • Page 344: Packaging Information

    31. Packaging Information 31.1 PIN 1 PIN 1 IDENTIFIER 0˚~7˚ COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL NOTE – – 1.20 0.05 – 0.15 0.95 1.00 1.05 8.75 9.00 9.25 6.90 7.00 7.10 Note 2 8.75 9.00 9.25 Notes: 1.
  • Page 345 ATmega48/88/168 31.2 28P3 SEATING PLANE (4 PLACES) COMMON DIMENSIONS (Unit of Measure = mm) 0º ~ 15º NOTE SYMBOL – – 4.5724 0.508 – – 34.544 – 34.798 Note 1 7.620 – 8.255 7.112 – 7.493 Note 1 0.381 – 0.533 1.143 –...
  • Page 346: M1-A

    31.3 32M1-A Pin 1 ID SIDE VIEW TOP VIEW COMMON DIMENSIONS 0.08 C (Unit of Measure = mm) SYMBOL NOTE 0.80 0.90 1.00 – 0.02 0.05 – 0.65 1.00 Pin #1 Notch (0.20 R) 0.20 REF 0.18 0.23 0.30 5.00 BSC 4.75 BSC 2.95 3.10...
  • Page 347: Errata

    ATmega48/88/168 32. Errata 32.1 Errata ATmega48 The revision letter in this section refers to the revision of the ATmega48 device. 32.1.1 Rev A • Wrong values read after Erase Only operation • Watchdog Timer Interrupt disabled • Start-up time with Crystal Oscillator is higher than expected •...
  • Page 348: Errata Atmega88

    The Asynchronous oscillator does not stop when entering power down mode. This leads to higher power consumption than expected. Problem fix / Workaround Manually disable the asynchronous timer before entering power down. 32.2 Errata ATmega88 The revision letter in this section refers to the revision of the ATmega88 device. 32.2.1 Rev.
  • Page 349: Errata Atmega168

    ATmega48/88/168 32.3 Errata ATmega168 The revision letter in this section refers to the revision of the ATmega168 device. 32.3.1 Rev A • Wrong values read after Erase Only operation • Part may hang in reset 1. Wrong values read after Erase Only operation At supply voltages below 2.7 V, an EEPROM location that is erased by the Erase Only operation may read as programmed (0x00).
  • Page 350: Datasheet Revision History

    33. Datasheet Revision History Please note that the referring page numbers in this section are referred to this document. The referring revision in this section are referring to the document revision. 33.1 Rev. 2545E-02/05 MLF-package alternative changed to “ Quad Flat No-Lead/Micro Lead Frame Package QFN/MLF”.
  • Page 351: Rev. 2545B-01/04

    ATmega48/88/168 33.4 Rev. 2545B-01/04 Added PDIP to “I/O and Packages”, updated “Speed Grade” and Power Consumption Estimates in 33.”Features” on page Updated ”Stack Pointer” on page 11 with RAMEND as recommended Stack Pointer value. Added section ”Power Reduction Register” on page 39 and a note regarding the use of the PRR bits to 2-wire, Timer/Counters, USART, Analog Comparator and ADC sections.
  • Page 352 ATmega48/88/168 2545E–AVR–02/05...
  • Page 353: Table Of Contents

    Table of Contents Features ..................... 1 Pin Configurations ................... 2 1.1Disclaimer ........................3 Overview ....................3 2.1Block Diagram ......................3 2.2Comparison Between ATmega48, ATmega88, and ATmega168 ......4 2.3Pin Descriptions ......................5 About Code Examples ................6 AVR CPU Core ..................7 4.1Introduction ........................7 4.2Architectural Overview ....................7 4.3ALU –...
  • Page 354 6.10Timer/Counter Oscillator ..................34 6.11System Clock Prescaler ..................34 Power Management and Sleep Modes ..........37 7.1Idle Mode .........................38 7.2ADC Noise Reduction Mode ...................38 7.3Power-down Mode ....................38 7.4Power-save Mode ....................38 7.5Standby Mode ......................39 7.6Power Reduction Register ..................39 7.7Minimizing Power Consumption ................41 System Control and Reset ..............43 8.1Internal Voltage Reference ..................48 8.2Watchdog Timer ......................49 Interrupts ....................
  • Page 355 13.1Overview ......................106 13.2Accessing 16-bit Registers ..................108 13.3Timer/Counter Clock Sources ................111 13.4Counter Unit ......................112 13.5Input Capture Unit ....................113 13.6Output Compare Units ..................115 13.7Compare Match Output Unit ................117 13.8Modes of Operation .....................118 13.9Timer/Counter Timing Diagrams .................125 13.1016-bit Timer/Counter Register Description ............128 14 Timer/Counter0 and Timer/Counter1 Prescalers ......135 15 8-bit Timer/Counter2 with PWM and Asynchronous Operation ..
  • Page 356 17.10Examples of Baud Rate Setting ................191 18 USART in SPI Mode ................196 18.1Overview ......................196 18.2Clock Generation ....................196 18.3SPI Data Modes and Timing ................197 18.4Frame Formats ....................198 18.5Data Transfer ......................199 18.6USART MSPIM Register Description ..............201 18.7AVR USART MSPIM vs. AVR SPI ..............204 19 2-wire Serial Interface ................
  • Page 357 22.6debugWIRE Related Register in I/O Memory ............256 23 Self-Programming the Flash, ATmega48 ........... 256 23.1Addressing the Flash During Self-Programming ..........258 24 Boot Loader Support – Read-While-Write Self-Programming, ATmega88 and ATmega168 264 24.1Boot Loader Features ..................264 24.2Application and Boot Loader Flash Sections ............264 24.3Read-While-Write and No Read-While-Write Flash Sections ......265 24.4Boot Loader Lock Bits ..................267 24.5Entering the Boot Loader Program ..............268...
  • Page 358 27.4Power-Down Supply Current ................315 27.5Power-Save Supply Current ................316 27.6Standby Supply Current ..................316 27.7Pin Pull-up ......................317 27.8Pin Driver Strength ....................319 27.9Pin Thresholds and Hysteresis ................322 27.10BOD Thresholds and Analog Comparator Offset ..........325 27.11Internal Oscillator Speed ...................328 27.12Current Consumption of Peripheral Units ............330 27.13Current Consumption in Reset and Reset Pulse width ........332 28 Register Summary ................
  • Page 359 Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL’S TERMS AND CONDI- TIONS OF SALE LOCATED ON ATMEL’S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY...

Table of Contents