ATmega48/88/168 Automotive 8-bit AVR Microcontroller with 8Kbytes In-system Programmable Flash DATASHEET Features ● High performance, low power AVR® 8-bit microcontroller ● Advanced RISC architecture ● ● ● ● ● 131 powerful instructions – most single clock cycle execution 32 × 8 general purpose working registers Fully static operation Up to 16MIPS throughput at 16MHz On-chip 2-cycle multiplier ● Non-volatile program and data memories ● 4/8/16Kbytes of in-system self-programmable flash (ATmega48/88/168) ●
● I/O and packages ● 23 programmable I/O lines ● Green/ROHS 32-lead TQFP and 32-pad QFN ● Operating voltage: ● 2.7 - 5.5V for ATmega48/88/168 ● Temperature range: ● –40°C to 125°C ● Speed grade: ● ATmega48/88/168: 0 to 8MHz at 2.7 to 5.5V, 0 - 16MHz at 4.5 to 5.5V ● Low power consumption ● Active mode: ● 4MHz, 3.0V: 1.8mA ● Power-down mode: ● 5µA at 3.
1. Pin Configurations Figure 1-1.
2. Overview The Atmel® ATmega48/88/168 is a low-power CMOS 8-bit microcontroller based on the AVR® enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the Atmel ATmega48/88/168 achieves throughputs approaching 1MIPS per MHz allowing the system designer to optimize power consumption versus processing speed. 2.1 Block Diagram Figure 2-1.
The AVR® core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the arithmetic logic unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
2.3 Comparison Between ATmega48, ATmega88, and ATmega168 The Atmel® ATmega48, ATmega88 and ATmega168 differ only in memory sizes, boot loader support, and interrupt vector sizes. Table 2-2 summarizes the different memory and interrupt vector sizes for the three devices. Table 2-2.
2.4.6 Port D (PD7..0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The port D output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, port D pins that are externally pulled low will source current if the pull-up resistors are activated. The port D pins are tri-stated when a reset condition becomes active, even if the clock is not running.
3. About Code Examples This documentation contains simple code examples that briefly show how to use various parts of the device. These code examples assume that the part specific header file is included before compilation. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details. 4. AVR CPU Core 4.
In order to maximize performance and parallelism, the AVR® uses a Harvard architecture – with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. The program memory is in-system reprogrammable flash memory.
4.4 Status Register The status register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the status register is updated after all ALU operations, as specified in the instruction set reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code.
4.5 General Purpose Register File The register file is optimized for the AVR® enhanced RISC instruction set.
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 registers 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. Figure 4-3.
4.7 Instruction Execution Timing This section describes the general access timing concepts for instruction execution. The AVR® CPU is driven by the CPU clock clkCPU, 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 Harvard architecture and the fast-access register file concept.
There are basically two types of interrupts. The first type is triggered by an event that sets the interrupt flag. For these interrupts, the program counter is vectored to the actual interrupt vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared.
5. AVR ATmega48/88/168 Memories This section describes the different memories in the Atmel® ATmega48/88/168. The AVR® architecture has two main memory spaces, the data memory and the program memory space. In addition, the Atmel ATmega48/88/168 features an EEPROM memory for data storage. All three memory spaces are linear and regular. 5.1 In-System Reprogrammable Flash Program Memory The Atmel ATmega48/88/168 contains 4/8/16K bytes on-chip in-system reprogrammable flash memory for program storage.
Figure 5-2. Program Memory Map, ATmega88 and ATmega168 Program Memory 0x0000 Application Flash Section Boot Flash Section 0x3FFF/0x7FFF 5.2 SRAM Data Memory Figure 5-3 shows how the Atmel® ATmega48/88/168 SRAM Memory is organized. The Atmel ATmega48/88/168 is a complex microcontroller with more peripheral units than can be supported within the 64 locations reserved in the opcode for the IN and OUT instructions.
5.2.1 Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 5-4. Figure 5-4. On-chip Data SRAM Access Cycles T1 T2 T3 clkCPU Address Compute Address Address valid Data Write WR Data Read RD Memory Access Instruction 5.3 Next Instruction EEPROM Data Memory The Atmel ATmega48/88/168 contains 256/512/512 bytes of data EEPROM memory.
• Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the Atmel® ATmega48/88/168 and will always read as zero. • Bits 8..0 – EEAR8..0: EEPROM Address The EEPROM address registers – EEARH and EEARL specify the EEPROM address in the 256/512/512 bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 255/511/511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed.
• Bit 2 – EEMPE: EEPROM Master Write Enable The EEMPE bit determines whether setting EEPE to one causes the EEPROM to be written. When EEMPE is set, setting EEPE within four clock cycles will write data to the EEPROM at the selected address If EEMPE is zero, setting EEPE will have no effect. When EEMPE has been written to one by software, hardware clears the bit to zero after four clock cycles. See the description of the EEPE bit for an EEPROM write procedure.
The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash Boot Loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish.
The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions.
5.4 I/O Memory The I/O space definition of the Atmel® ATmega48/88/168 is shown in Section “” on page 285. All Atmel 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. I/O registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions.
6. System Clock and Clock Options 6.1 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 Section 7. “Power Management and Sleep Modes” on page 33. The clock systems are detailed below. Figure 6-1.
6.1.4 Asynchronous Timer Clock – clkASY The asynchronous timer clock allows the asynchronous Timer/Counter to be clocked directly from an external clock or an external 32kHz 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 – clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce noise generated by digital circuitry.
Main purpose of the delay is to keep the AVR® in reset until it is supplied with minimum VCC. The delay will not monitor the actual voltage and it will be required to select a delay longer than the VCC rise time. If this is not possible, an internal or external brown-out detection circuit should be used. A BOD circuit will ensure sufficient VCC before it releases the reset, and the time-out delay can be disabled.
The CKSEL0 fuse together with the SUT1..0 fuses select the start-up times as shown in Table 6-4. Table 6-4. Start-up Times for the Low Power Crystal Oscillator Clock Selection Oscillator Source / Power Conditions Start-up Time from Powerdown and Power-save Additional Delay from Reset (VCC = 5.0V) CKSEL0 SUT1..0 Ceramic resonator, fast rising power 258CK 14CK + 4.
Figure 6-3. Crystal Oscillator Connections C2 XTAL2 C1 XTAL1 GND Table 6-6. Start-up Times for the Full Swing Crystal Oscillator Clock Selection Oscillator Source / Power Conditions Start-up Time from Powerdown and Power-save Additional Delay from Reset (VCC = 5.0V) CKSEL0 SUT1..0 Ceramic resonator, fast rising power 258CK 14CK + 4.
6.5 Low Frequency Crystal Oscillator The device can utilize a 32.768kHz watch crystal as clock source by a dedicated low frequency crystal Oscillator. The crystal should be connected as shown in Figure 6-2 on page 25. When this oscillator is selected, start-up times are determined by the SUT fuses and CKSEL0 as shown in Table 6-7. Table 6-7.
6.6.1 Oscillator Calibration Register – OSCCAL Bit Read/Write 7 6 5 4 3 2 1 0 CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 R/W R/W R/W R/W R/W R/W R/W R/W Initial Value OSCCAL Device Specific Calibration Value • Bits 7..0 – CAL7..0: Oscillator Calibration Value The oscillator calibration register is used to trim the calibrated internal RC oscillator to remove process variations from the oscillator frequency.
6.8 External Clock The device can utilize a external clock source as shown in Figure 6-4. To run the device on an external clock, the CKSEL fuses must be programmed as shown in Table 6-12. Table 6-12. Full Swing Crystal Oscillator operating modes(2) Frequency Range(1) (MHz) Notes: 1. 2. CKSEL3..0 Recommended Range for Capacitors C1 and C2 (pF) 0 - 100 0000 The frequency ranges are preliminary values. Actual values are TBD.
6.10 Timer/Counter Oscillator The device can operate its Timer/Counter2 from an external 32.768kHz watch crystal or a external clock source. The Timer/Counter oscillator pins (TOSC1 and TOSC2) are shared with XTAL1 and XTAL2. This means that the Timer/Counter oscillator can only be used when an internal RC oscillator is selected as system clock source. See Figure 6-2 on page 25 for crystal connection. Applying an external clock source to TOSC1 requires EXTCLK in the ASSR register written to logic one.
The CKDIV8 fuse determines the initial value of the CLKPS bits. If CKDIV8 is unprogrammed, the CLKPS bits will be reset to “0000”. If CKDIV8 is programmed, CLKPS bits are reset to “0011”, giving a division factor of 8 at start up. This feature should be used if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. Note that any value can be written to the CLKPS bits regardless of the CKDIV8 fuse setting.
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 consumption 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.
7.2 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. This sleep mode basically halts clkCPU and clkFLASH, while allowing the other clocks to run.
7.6 Standby Mode When the SM2..0 bits are 110 and an external crystal/resonator clock option is selected, the SLEEP instruction makes the MCU enter standby mode. This mode is identical to power-down with the exception that the oscillator is kept running. From standby mode, the device wakes up in six clock cycles. Active Clock Domains and Wake-up Sources in the Different Sleep Modes.
• Bit 5 - PRTIM0: Power Reduction Timer/Counter0 Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0 is enabled, operation will continue like before the shutdown. • Bit 4 - Res: Reserved bit This bit is reserved in Atmel® ATmega48/88/168 and will always read as zero. • Bit 3 - PRTIM1: Power Reduction Timer/Counter1 Writing a logic one to this bit shuts down the Timer/Counter1 module.
7.8.4 Internal Voltage Reference The internal voltage reference will be enabled when needed by the brown-out detection, the analog comparator or the ADC. If these modules are disabled as described in the sections above, the internal voltage reference will be disabled and it will not be consuming power. When turned on again, the user must allow the reference to start up before the output is used. If the reference is kept on in sleep mode, the output can be used immediately. Refer to Section 8.
8. System Control and Reset 8.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 – absolute jump – instruction to the reset handling routine. For the ATmega48 and ATmega88, the instruction placed at the reset vector must be an RJMP – relative jump – instruction to the reset handling routine.
Figure 8-1. Reset Logic DATA BUS Power-on Reset Circuit BODLEVEL [2 to 0] Brown-out Reset Circuit WDRF BORF Pull-up Resistor Reset Circuit S RESET SPIKE FILTER COUNTER RESET R Watchdog Timer RSTDISBL Q INTERNAL RESET VCC EXTRF PORF MCU Status Register (MCUSR) Watchdog Oscillator Clock Generator CK Delay Counters TIMEOUT CKSEL[3:0] SUT[1:0] 8.3 Power-on Reset A power-on reset (POR) pulse is generated by an on-chip detection circuit.
Figure 8-2. MCU Start-up, RESET Tied to VCC V CCRR V CC VPORMAX VPORMIN RESET VRST tTOUT TIME-OUT INTERNAL RESET Figure 8-3. MCU Start-up, RESET Extended Externally V DD V RST RESET tTOUT TIME-OUT INTERNAL RESET Table 8-1. Power On Reset Specifications Parameter Symbol Power-on reset threshold voltage (rising) (1) Power-on reset threshold voltage (falling) VPOT Min Typ Max Unit 1.1 1.4 1.7 V 0.8 1.3 1.6 V 0.4 V VCC max.
8.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 on page 40) will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the reset threshold voltage – VRST – on its positive edge, the delay counter starts the MCU after the time-out period – tTOUT – has expired.
When the BOD is enabled, and VCC decreases to a value below the trigger level (VBOT- in Figure 8-5), the brown-out reset is immediately activated. When VCC increases above the trigger level (VBOT+ in Figure 8-5), the delay counter starts the MCU after the time-out period tTOUT has expired. The BOD circuit will only detect a drop in VCC if the voltage stays below the trigger level for longer than tBOD given in Table 8-1 on page 40. Figure 8-5.
8.7 MCU Status Register – MCUSR The MCU status register provides information on which reset source caused an MCU reset. Bit 7 6 5 4 3 2 1 0 – – Read/Write R R – – WDRF BORF EXTRF PORF R R R/W R/W R/W R/W Initial Value 0 0 0 0 MCUSR See Bit Description • Bit 7..4: Res: Reserved Bits These bits are unused bits in the Atmel® ATmega48/88/168, and will always read as zero. • Bit 3 – WDRF: Watchdog System Reset Flag This bit is set if a watchdog system reset occurs.
8.9 Watchdog Timer Atmel® 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 Possible hardware fuse watchdog always on (WDTON) for fail-safe mode Figure 8-7.
The following code example shows one assembly and one C function for turning off the watchdog timer. The example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the execution of these functions.
The following code example shows one assembly and one C function for changing the time-out value of the watchdog timer. Assembly Code Example(1) WDT_Prescaler_Change: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Start timed sequence lds r16, WDTCSR ori r16, (1<
If WDE is set, the watchdog timer is in interrupt and system reset mode. The first time-out in the watchdog timer will set WDIF. Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the watchdog goes to system reset mode). This is useful for keeping the watchdog timer security while using the interrupt. To stay in interrupt and system reset mode, WDIE must be set after each interrupt.
9. Interrupts This section describes the specifics of the interrupt handling as performed in Atmel® ATmega48/88/168. For a general explanation of the AVR® interrupt handling, refer to Section 4.8 “Reset and Interrupt Handling” on page 13. The interrupt vectors in Atmel ATmega48, Atmel ATmega88 and Atmel ATmega168 are generally the same, with the following differences: ● Each interrupt vector occupies two instruction words in ATmega168, and one instruction word in ATmega48 and ATmega88. ● 9.
The most typical and general program setup for the reset and interrupt vector addresses in Atmel® ATmega48 is: Address Labels Code Comments 0x000 rjmp RESET ; Reset Handler 0x001 rjmp EXT_INT0 ; IRQ0 Handler 0x002 rjmp EXT_INT1 ; IRQ1 Handler 0x003 rjmp PCINT0 ; PCINT0 Handler 0x004 rjmp PCINT1 ; PCINT1 Handler 0x005 rjmp PCINT2 ; PCINT2 Handler 0x006 rjmp WDT ; Watchdog Timer Handler 0x007 rjmp TIM2_COMPA ; Timer2 Compare A Handler 0x008 rjmp TIM2_COMPB ; Timer2 Compare B Handler 0x009 rjmp TIM2_OVF ; Time
Table 9-2. Reset and Interrupt Vectors in ATmega88 (Continued) Vector No.
The most typical and general program setup for the reset and interrupt vector addresses in Atmel® ATmega88 is: Address Labels Code Comments 0x000 rjmp RESET ; Reset Handler 0x001 rjmp EXT_INT0 ; IRQ0 Handler 0x002 rjmp EXT_INT1 ; IRQ1 Handler 0x003 rjmp PCINT0 ; PCINT0 Handler 0x004 rjmp PCINT1 ; PCINT1 Handler 0x005 rjmp PCINT2 ; PCINT2 Handler 0x006 rjmp WDT ; Watchdog Timer Handler 0x007 rjmp TIM2_COMPA ; Timer2 Compare A Handler 0X008 rjmp TIM2_COMPB ; Timer2 Compare B Handler 0x009 rjmp TIM2_OVF ; Time
When the BOOTRST fuse is programmed and the boot section size set to 2Kbytes, the most typical and general program setup for the reset and interrupt vector addresses in Atmel® ATmega88 is: Address Labels Code Comments .org 0x001 0x001 rjmp EXT_INT0 ; IRQ0 Handler 0x002 rjmp EXT_INT1 ; IRQ1 Handler ... ... ... ; 0x019 rjmp SPM_RDY ; Store Program Memory Ready Handler ; .
Table 9-4. Reset and Interrupt Vectors in ATmega168 (Continued) VectorNo.
The most typical and general program setup for the reset and interrupt vector addresses in Atmel® ATmega168 is: Address Labels Code Comments 0x0000 jmp RESET ; Reset Handler 0x0002 jmp EXT_INT0 ; IRQ0 Handler 0x0004 jmp EXT_INT1 ; IRQ1 Handler 0x0006 jmp PCINT0 ; PCINT0 Handler 0x0008 jmp PCINT1 ; PCINT1 Handler 0x000A jmp PCINT2 ; PCINT2 Handler 0x000C jmp WDT ; Watchdog Timer Handler 0x000E jmp TIM2_COMPA ; Timer2 Compare A Handler 0x0010 jmp TIM2_COMPB ; Timer2 Compare B Handler 0x0012 jmp TIM2_OVF ; Tim
When the BOOTRST fuse is programmed and the boot section size set to 2Kbytes, the most typical and general program setup for the reset and interrupt vector addresses in Atmel® ATmega168 is: Address Labels Code Comments .org 0x0002 0x0002 jmp EXT_INT0 ; IRQ0 Handler 0x0004 jmp EXT_INT1 ; IRQ1 Handler ... ... ... ; 0x0032 jmp SPM_RDY ; Store Program Memory Ready Handler ; .
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE is set, and they remain disabled until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the status register is unaffected by the automatic disabling.
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 changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input).
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 functional description of one I/Oport pin, here generically called Pxn. Figure 10-2. General Digital I/O(1) PUD Q D DDxn Q CLR RESET WDx RDx D 0 PORTxn Q CLR RESET SLEEP DATA BUS 1 Q Pxn WRx WPx RRx Synchronizer RPx D Q D Q PINxn L Q Q CLKI/O PUD: SLEEP: CLKI/O: Note: 1.
10.2.2 Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port. 10.2.3 Switching Between Input and Output When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 10-4. The out instruction sets the “SYNC LATCH” signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is 1 system clock period. Figure 10-4.
10.2.5 Digital Input Enable and Sleep Modes As shown in Figure 10-2 on page 58, the digital input signal can be clamped to ground at the input of the schmitt trigger. The signal denoted SLEEP in the figure, is set by the MCU sleep controller in power-down mode, power-save mode, and standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2. SLEEP is overridden for port pins enabled as external interrupt pins.
10.3 Alternate Port Functions Most port pins have alternate functions in addition to being general digital I/Os. Figure 10-5 shows how the port pin control signals from the simplified Figure 10-2 on page 58 can be overridden by alternate functions. The overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the AVR® microcontroller family. Figure 10-5.
Table 10-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 10-5 on page 62 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 Description PUOE Pull-up override enable If this signal is set, the pull-up enable is controlled by the PUOV signal.
10.3.2 Alternate Functions of Port B The port B pins with alternate functions are shown in Table 10-3. Table 10-3.
• SCK/PCINT5 – Port B, Bit 5 SCK: master clock output, slave clock input pin for SPI channel. When the SPI is enabled as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit. PCINT5: pin change interrupt source 5. The PB5 pin can serve as an external interrupt source.
Table 10-4 and Table 10-5 relate the alternate functions of port B to the overriding signals shown in Figure 10-5 on page 62. SPI MSTR INPUT and SPI SLAVE OUTPUT constitute the MISO signal, while MOSI is divided into SPI MSTR OUTPUT and SPI SLAVE INPUT. Table 10-4. Overriding Signals for Alternate Functions in PB7..
10.3.3 Alternate Functions of Port C The port C pins with alternate functions are shown in Table 10-6. Table 10-6.
• ADC2/PCINT10 – Port C, Bit 2 PC2 can also be used as ADC input channel 2. Note that ADC input channel 2 uses analog power. PCINT10: pin change interrupt source 10. The PC2 pin can serve as an external interrupt source. • ADC1/PCINT9 – Port C, Bit 1 PC1 can also be used as ADC input channel 1. Note that ADC input channel 1 uses analog power. PCINT9: pin change interrupt source 9. The PC1 pin can serve as an external interrupt source.
10.3.4 Alternate Functions of Port D The port D pins with alternate functions are shown in Table 10-9. Table 10-9.
• XCK/T0/PCINT20 – Port D, Bit 4 XCK, USART external clock. T0, Timer/Counter0 counter source. PCINT20: pin change interrupt source 20. The PD4 pin can serve as an external interrupt source. • INT1/OC2B/PCINT19 – Port D, Bit 3 INT1, external interrupt source 1: The PD3 pin can serve as an external interrupt source. OC2B, output compare match output: The PD3 pin can serve as an external output for the Timer/Counter0 compare match B.
Table 10-11. Overriding Signals for Alternate Functions in PD3..PD0 10.
10.4.5 The Port C Data Direction Register – DDRC Bit 7 6 5 4 3 2 1 0 – DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 Read/Write R R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 DDRC 10.4.6 The Port C Input Pins Address – PINC Bit 7 6 5 4 3 2 1 0 – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 Read/Write R R R R R R R R Initial Value 0 N/A N/A N/A N/A N/A N/A N/A PINC 10.4.
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. The pin change interrupt PCI1 will trigger if any enabled PCINT14..8 pin toggles.
• Bit 1, 0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0 The external interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt mask are set. The level and edges on the external INT0 pin that activate the interrupt are defined in Table 11-2. The value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt.
• Bit 1 – INTF1: External Interrupt Flag 1 When an edge or logic change on the INT1 pin triggers an interrupt request, INTF1 becomes set (one). If the I-bit in SREG and the INT1 bit in EIMSK are set (one), the MCU will jump to the corresponding interrupt vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared when INT1 is configured as a level interrupt.
• Bit 1 - PCIF1: Pin Change Interrupt Flag 1 When a logic change on any PCINT14..8 pin triggers an interrupt request, PCIF1 becomes set (one). If the I-bit in SREG and the PCIE1 bit in PCICR are set (one), the MCU will jump to the corresponding interrupt vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. • Bit 0 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT7..
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 management) and wave generation.
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 compare 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. The definitions in the following table are also used extensively throughout the document.
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). clkTn Timer/Counter clock, referred to as clkT0 in the following. top Signalize that TCNT0 has reached maximum value. bottom Signalize that TCNT0 has reached minimum value (zero). Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0).
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 double buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare Registers to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
Figure 12-4. Compare Match Output Unit, Schematic COMnx1 COMnx0 FOCn Waveform Generator D Q 1 OCnx Pin OCnx 0 DATA BUS D Q PORT D Q DDR clkI/O The general I/O port function is overridden by the output compare (OC0x) from the waveform generator if either of the COM0x1:0 bits are set. However, the OC0x pin direction (input or output) is still controlled by the data direction register (DDR) for the port pin.
12.6.1 Normal Mode The simplest mode of operation is the normal mode (WGM02:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter overflow flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero.
12.6.3 Fast PWM Mode The fast pulse width modulation or fast PWM mode (WGM02:0 = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7. In non-inverting compare output mode, the output compare (OC0x) is cleared on the compare match between TCNT0 and OCR0x, and set at BOTTOM.
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0x to toggle its logical level on each compare match (COM0x1:0 = 1). The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the output compare unit is enabled in the fast PWM mode. 12.6.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A0 bits to 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 88).
Figure 12-9 shows the same timing data, but with the prescaler enabled. Figure 12-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O/8) TCNTn MAX - 1 MAX 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.
12.8 8-bit Timer/Counter Register Description 12.8.1 Timer/Counter Control Register A – TCCR0A Bit 7 6 5 4 3 2 1 0 COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 Read/Write R/W R/W R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR0A • Bits 7:6 – COM0A1:0: Compare Match Output A Mode These bits control the output compare pin (OC0A) behavior.
Bits 5:4 – COM0B1:0: Compare Match Output B Mode These bits control the output compare pin (OC0B) behavior. If one or both of the COM0B1:0 bits are set, the OC0B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the data direction register (DDR) bit corresponding to the OC0B pin must be set in order to enable the output driver. When OC0B is connected to the pin, the function of the COM0B1:0 bits depends on the WGM02:0 bit setting.
Table 12-8. Waveform Generation Mode Bit Description Timer/Counter Mode of Operation TOP Update of OCRx at TOV Flag Set on(1)(2) 0 Normal 0xFF Immediate MAX 0 1 PWM, phase correct 0xFF TOP BOTTOM 0 1 0 CTC OCRA Immediate MAX 0 1 1 Fast PWM 0xFF TOP MAX 4 1 0 0 Reserved – – – 5 1 0 1 PWM, phase correct OCRA TOP BOTTOM 6 1 1 0 Reserved – – – 1 1 Fast PWM OCRA TOP TOP 1. 1 MAX 2.
Table 12-9. Clock Select Bit Description CS02 CS01 CS00 Description 0 0 0 No clock source (Timer/Counter stopped) 0 0 1 clkI/O/(no prescaling) 0 1 0 clkI/O/8 (from prescaler) 0 1 1 clkI/O/64 (from prescaler) 1 0 0 clkI/O/256 (from prescaler) 1 0 1 clkI/O/1024 (from prescaler) 1 1 0 External clock source on T0 pin. Clock on falling edge. 1 1 1 External clock source on T0 pin. Clock on rising edge.
12.8.6 Timer/Counter Interrupt Mask Register – TIMSK0 Bit 7 6 5 4 3 2 1 0 – – – Read/Write R R R – – OCIE0B OCIE0A TOIE0 R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIMSK0 • Bits 7..3 – Res: Reserved Bits These bits are reserved bits in the Atmel® ATmega48/88/168 and will always read as zero.
13. Timer/Counter0 and Timer/Counter1 Prescalers Timer/Counter1 and Timer/Counter0 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description below applies to both Timer/Counter1 and Timer/Counter0. 13.1 Internal Clock Source The Timer/Counter can be clocked directly by the system clock (by setting the CSn2:0 = 1). This provides the fastest operation, with a maximum Timer/Counter clock frequency equal to system clock frequency (fCLK_I/O).
Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. The external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (nyquist sampling theorem).
14. 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) ● ● ● ● ● ● ● ● ● ● 14.
Figure 14-1. 16-bit Timer/Counter Block Diagram(1) TOVn (Int. Req.) Count Clear Direction Clock Select Control Logic clkTn TOP BOTTOM = = Edge Detector Tn (from Prescaler) Timer/Counter TCNTn 0 OCnA (Int. Req.) Waveform Generation = OCnA DATA BUS OCRnA Fixed TOP Value OCnB (Int. Req.) Waveform Generation = OCnB (From Analog Comparator Output) OCRnB ICFn (Int. Req.) Edge Detector ICRn TCCRnA Note: 1.
The double buffered output compare registers (OCR1A/B) are compared with the Timer/Counter value at all time. The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the output compare pin (OC1A/B). See Section 14.6 “Output Compare Units” on page 102. 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 following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCR1A/B and ICR1 registers. Note that when using “C”, the compiler handles the 16-bit access. Assembly Code Examples(1) ... ; 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(1) unsigned int i; ...
The following code examples show how to do an atomic read of the TCNT1 register contents. Reading any of the OCR1A/B or ICR1 registers can be done by using the same principle.
The following code examples show how to do an atomic write of the TCNT1 register contents. Writing any of the OCR1A/B or ICR1 registers can be done by using the same principle.
14.4 Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 14-2 shows a block diagram of the counter and its surroundings. Figure 14-2. Counter Unit Block Diagram DATA BUS (8-bit) TOVn (Int. Req.
14.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. The external signal indicating an event, or multiple events, can be applied via the ICP1 pin or alternatively, via the analog-comparator unit. The time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. Alternatively the time-stamps can be used for creating a log of the events.
14.5.1 Input Capture Trigger Source The main trigger source for the input capture unit is the input capture pin (ICP1). Timer/Counter1 can alternatively use the analog comparator output as trigger source for the Input Capture unit. The Analog Comparator is selected as trigger source by setting the analog comparator input capture (ACIC) bit in the analog comparator control and status register (ACSR). Be aware that changing trigger source can trigger a capture.
Figure 14-4 shows a block diagram of the output compare unit. The small “n” in the register and bit names indicates the device number (n = 1 for Timer/Counter 1), and the “x” indicates output compare unit (A/B). The elements of the block diagram that are not directly a part of the output compare unit are gray shaded. Figure 14-4. Output Compare Unit, Block Diagram DATA BUS (8-bit) TEMP (8-bit) OCRnxH Buf. (8-bit) OCRnxL Buf.
14.6.2 Compare Match Blocking by TCNT1 Write All CPU writes to the TCNT1 register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled. 14.6.
The general I/O port function is overridden by the output compare (OC1x) from the waveform generator if either of the COM1x1:0 bits are set. However, the OC1x pin direction (input or output) is still controlled by the data direction register (DDR) for the port pin. The data direction register bit for the OC1x pin (DDR_OC1x) must be set as output before the OC1x value is visible on the pin. The port override function is generally independent of the waveform generation mode, but there are some exceptions.
Figure 14-6. CTC Mode, Timing Diagram OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) TCNTn OCnA (Toggle) Period (COMnA1:0 = 1) 1 2 3 4 An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 flag according to the register used to define the TOP value. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
In fast PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 = 14), or the value in OCR1A (WGM13:0 = 15). The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 14-7. The figure shows fast PWM mode when OCR1A or ICR1 is used to define TOP.
The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ---------------------------------N ⋅ ( 1 + TOP ) The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the output will be a narrow spike for each TOP+1 timer clock cycle.
Figure 14-8. Phase Correct PWM Mode, Timing Diagram OCRnx/ TOP Update and OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) TOVn Interrupt Flag Set (Interrupt on Bottom) TCNTn OCnx (COMnx1:0 = 2) OCnx (COMnx1:0 = 3) Period 1 2 3 4 The Timer/Counter overflow flag (TOV1) is set each time the counter reaches BOTTOM.
14.8.5 Phase and Frequency Correct PWM Mode The phase and frequency correct pulse width modulation, or phase and frequency correct PWM mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequency correct PWM waveform generation option. The phase and frequency correct PWM mode is, like the phase correct PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM.
When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of all of the compare registers. If the TOP value is lower than any of the compare registers, a compare match will never occur between the TCNT1 and the OCR1x. As Figure 14-9 on page 110 shows the output generated is, in contrast to the phase correct mode, symmetrical in all periods. Since the OCR1x registers are updated at BOTTOM, the length of the rising and the falling slopes will always be equal.
Figure 14-11 shows the same timing data, but with the prescaler enabled. Figure 14-11.Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O/8) OCRnx - 1 TCNTn OCRnx OCRnx OCRnx + 1 OCRnx + 2 OCRnx Value OCFnx Figure 14-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.
Figure 14-13 shows the same timing data, but with the prescaler enabled. Figure 14-13.Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O/8) TCNTn (CTC and FPWM) TOP - 1 TOP BOTTOM BOTTOM + 1 TCNTn (PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2 TOVn (FPWM) and ICFn (if used as TOP) OCRnx (Update at TOP) Old OCRnx Value New OCRnx Value 14.10 16-bit Timer/Counter Register Description 14.10.
Table 14-3 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the fast PWM mode. Table 14-3. Compare Output Mode, Fast PWM(1) COM1A1/COM1B1 COM1A0/COM1B0 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 WGM13:0 = 14 or 15: Toggle OC1A on compare match, OC1B disconnected (normal port operation). For all other WGM1 settings, normal port operation, OC1A/OC1B disconnected. 1 0 Clear OC1A/OC1B on compare match, set OC1A/OC1B at TOP Note: 1.
Table 14-5. Waveform Generation Mode Bit Description(1) (Continued) Mode WGM13 WGM12 (CTC1) WGM11 (PWM11) 9 1 0 0 1 10 1 0 1 11 1 0 12 1 13 1 14 1 15 Note: 1.
Table 14-6. Clock Select Bit Description CS12 CS11 CS10 Description 0 0 0 No clock source (Timer/Counter stopped). 0 0 1 clkI/O/1 (no prescaling) 0 1 0 clkI/O/8 (from prescaler) 0 1 1 clkI/O/64 (from prescaler) 1 0 0 clkI/O/256 (from prescaler) 1 0 1 clkI/O/1024 (from prescaler) 1 1 0 External clock source on T1 pin. Clock on falling edge. 1 1 1 External clock source on T1 pin. Clock on rising edge.
14.10.5 Output Compare Register 1 A – OCR1AH and OCR1AL Bit 7 6 5 4 3 2 1 0 OCR1A[15:8] OCR1AH OCR1A[7:0] OCR1AL Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 2 1 0 14.10.
• Bit 2 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1 output compare B match interrupt is enabled. The corresponding interrupt vector (see Section 9. “Interrupts” on page 48) is executed when the OCF1B flag, located in TIFR1, is set.
15. 8-bit Timer/Counter2 with PWM and Asynchronous Operation Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module.
15.1.1 Registers The Timer/Counter (TCNT2) and output compare register (OCR2A and OCR2B) are 8-bit registers. 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). TIFR2 and TIMSK2 are not shown in the figure. The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from the TOSC1/2 pins, as detailed later in this section.
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). clkTn Timer/Counter clock, referred to as clkT2 in the following. top Signalizes that TCNT2 has reached maximum value. bottom Signalizes that TCNT2 has reached minimum value (zero). Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT2).
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. The double buffering synchronizes the update of the OCR2x compare register to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
Figure 15-4. Compare Match Output Unit, Schematic COMnx1 COMnx0 FOCn Waveform Generator D Q 1 OCnx Pin OCnx 0 DATA BUS D Q PORT D Q DDR clkI/O The general I/O port function is overridden by the output compare (OC2x) from the waveform generator if either of the COM2x1:0 bits are set. However, the OC2x pin direction (input or output) is still controlled by the data direction register (DDR) for the port pin.
15.6.1 Normal Mode The simplest mode of operation is the normal mode (WGM22:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter overflow flag (TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero.
15.6.3 Fast PWM Mode The fast pulse width modulation or fast PWM mode (WGM22:0 = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7. In non-inverting compare output mode, the output compare (OC2x) is cleared on the compare match between TCNT2 and OCR2x, and set at BOTTOM.
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC2x to toggle its logical level on each compare match (COM2x1:0 = 1). The waveform generated will have a maximum frequency of foc2 = fclk_I/O/2 when OCR2A is set to zero. This feature 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.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin. Setting the COM2x1:0 bits to two will produce a non-inverted PWM. An inverted PWM 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 129). The actual OC2x value will only be visible on the port pin if the data direction for the port pin is set as output.
Figure 15-9 shows the same timing data, but with the prescaler enabled. Figure 15-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O/8) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 15-10 shows the setting of OCF2A in all modes except CTC mode. Figure 15-10.
15.8 8-bit Timer/Counter Register Description 15.8.1 Timer/Counter Control Register A – TCCR2A Bit 7 6 5 4 3 2 1 0 COM2A1 COM2A0 COM2B1 COM2B0 – – WGM21 WGM20 Read/Write R/W R/W R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR2A • Bits 7:6 – COM2A1:0: Compare Match Output A Mode These bits control the output compare pin (OC2A) behavior.
• Bits 5:4 – COM2B1:0: Compare Match Output B Mode These bits control the output compare pin (OC2B) behavior. If one or both of the COM2B1:0 bits are set, the OC2B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the data direction register (DDR) bit corresponding to the OC2B pin must be set in order to enable the output driver. When OC2B is connected to the pin, the function of the COM2B1:0 bits depends on the WGM22:0 bit setting.
Table 15-8. Waveform Generation Mode Bit Description Timer/Counter Mode of Operation TOP Update of OCRx at TOV Flag Set on(1)(2) 0 Normal 0xFF Immediate MAX 0 1 PWM, phase correct 0xFF TOP BOTTOM 0 1 0 CTC OCRA Immediate MAX 0 1 1 Fast PWM 0xFF TOP MAX 4 1 0 0 Reserved – – – 5 1 0 1 PWM, phase correct OCRA TOP BOTTOM 6 1 1 0 Reserved – – – 1 1 Fast PWM OCRA TOP TOP Mode WGM2 WGM1 WGM0 0 0 0 1 0 2 3 7 Notes: 1. 1 MAX = 0xFF 2.
Table 15-9. Clock Select Bit Description CS22 CS21 CS20 Description 0 0 0 No clock source (Timer/Counter stopped).
15.8.6 Timer/Counter2 Interrupt Mask Register – TIMSK2 Bit 7 6 5 4 3 2 1 0 – – – Read/Write R R R – – OCIE2B OCIE2A TOIE2 R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIMSK2 • 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.
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. ● ● b. Select clock source by setting AS2 as appropriate. c. Write new values to TCNT2, OCR2x, and TCCR2x. d.
● Reading of the TCNT2 register shortly after wake-up from power-save may give an incorrect result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2 must be done through a register synchronized to the internal I/O clock domain. Synchronization takes place for every rising TOSC1 edge. When waking up from power-save mode, and the I/O clock (clkI/O) again becomes active, TCNT2 will read as the previous value (before entering sleep) until the next rising TOSC1 edge.
• Bit 0 – TCR2BUB: Timer/Counter Control Register2 Update Busy When Timer/Counter2 operates asynchronously and TCCR2B is written, this bit becomes set. When TCCR2B has been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that TCCR2B is ready to be updated with a new value.
15.10.1 General Timer/Counter Control Register – GTCCR Bit 7 6 5 4 3 2 1 0 TSM – – – – – PSRASY PSRSYN C Read/Write R/W R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 GTCCR • Bit 1 – PSRASY: Prescaler Reset Timer/Counter2 When this bit is one, the Timer/Counter2 prescaler will be reset. This bit is normally cleared immediately by hardware.
16. Serial Peripheral Interface – SPI The serial peripheral interface (SPI) allows high-speed synchronous data transfer between the Atmel® ATmega48/88/168 and peripheral devices or between several AVR® devices.
The interconnection between master and slave CPUs with SPI is shown in Figure 16-2. The system consists of two shift registers, and a master clock generator. The SPI master initiates the communication cycle when pulling low the slave select SS pin of the desired slave. 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.
The following code examples show how to initialize the SPI as a master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actual data direction register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. E.g. if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB.
The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception.
16.1.2 Master Mode When the SPI is configured as a master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI slave. If SS is configured as an input, it must be held high to ensure master SPI operation.
• Bit 2 – CPHA: Clock Phase The settings of the clock phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK. Refer to Figure 16-3 on page 145 and Figure 16-4 on page 145 for an example. The CPOL functionality is summarized below: Table 16-3. CPHA Functionality CPHA Leading Edge Trailing Edge 0 Sample Setup 1 Setup Sample • Bits 1, 0 – SPR1, SPR0: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a master.
• Bit 5..1 – Res: Reserved Bits These bits are reserved bits in the Atmel® ATmega48/88/168 and will always read as zero. • Bit 0 – SPI2X: Double SPI Speed Bit When this bit is written logic one the SPI speed (SCK frequency) will be doubled when the SPI is in master mode (see Table 16-4 on page 143). This means that the minimum SCK period will be two CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at fosc/4 or lower.
Figure 16-3. SPI Transfer Format with CPHA = 0 SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) MSB LSB first (DORD =1) LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB Figure 16-4.
17. USART0 The universal synchronous and asynchronous serial receiver and transmitter (USART) is a highly flexible serial communication device.
Overview A simplified block diagram of the USART Transmitter is shown in Figure 17-1. CPU accessible I/O Registers and I/O pins are shown in bold. Figure 17-1. USART Block Diagram(1) Clock Generator UBRRn [H:L] OSC Baud Rate Generator Sync Logic Pin Control XCKn Transmitter TX Control UDRn (Transmit) DATA BUS 17.1 Parity Generator 1.
17.2 Clock Generation The clock generation logic generates the base clock for the transmitter and receiver. The USART supports four modes of clock operation: normal asynchronous, double speed asynchronous, master synchronous and slave synchronous mode. The UMSELn bit in USART control and status register C (UCSRnC) selects between asynchronous and synchronous operation. Double speed (asynchronous mode only) is controlled by the U2Xn found in the UCSRnA register.
Table 17-1 contains equations for calculating the baud rate (in bits per second) and for calculating the UBRRn value for each mode of operation using an internally generated clock source. Table 17-1.
Figure 17-3. Synchronous Mode XCKn Timing UCPOL = 1 XCK RxD/ TxD Sample UCPOL = 0 XCK RxD/ TxD Sample The UCPOLn bit UCRSC selects which XCKn clock edge is used for data sampling and which is used for data change. As Figure 17-3 shows, when UCPOLn is zero the data will be changed at rising XCKn edge and sampled at falling XCKn edge. If UCPOLn is set, the data will be changed at falling XCKn edge and sampled at rising XCKn edge. 17.
17.3.1 Parity Bit Calculation The parity bit is calculated by doing an exclusive-or of all the data bits. If odd parity is used, the result of the exclusive or is inverted.
More advanced initialization routines can be made that include frame format as parameters, disable interrupts and so on. However, many applications use a fixed setting of the baud and control registers, and for these types of applications the initialization code can be placed directly in the main routine, or be combined with initialization code for other I/O modules. 17.
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 UCSRnB before the low byte of the character is written to UDRn. The following code examples show a transmit function that handles 9-bit characters. For the assembly code, the data to be sent is assumed to be stored in registers R17:R16.
The TXCn flag is useful in half-duplex communication interfaces (like the RS-485 standard), where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. When the transmit compete interrupt enable (TXCIEn) bit in UCSRnB is set, the USART transmit complete interrupt will be executed when the TXCn flag becomes set (provided that global interrupts are enabled).
The function simply waits for data to be present in the receive buffer by checking the RXCn flag, before reading the buffer and returning the value. 17.6.2 Receiving Frames with 9 Data Bits If 9-bit characters are used (UCSZn=7) the ninth bit must be read from the RXB8n bit in UCSRnB before reading the low bits from the UDRn. This rule applies to the FEn, DORn and UPEn status flags as well. Read status from UCSRnA, then data from UDRn.
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). If the receiver is disabled (RXENn = 0), the receive buffer will be flushed and consequently the RXCn bit will become zero.
17.6.7 Flushing the Receive Buffer The receiver buffer FIFO will be flushed when the receiver is disabled, i.e., the buffer will be emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal operation, due to for instance an error condition, read the UDRn I/O location until the RXCn flag is cleared. The following code example shows how to flush the receive buffer.
17.7.2 Asynchronous Data Recovery When the receiver clock is synchronized to the start bit, the data recovery can begin. The data recovery unit uses a state machine that has 16 states for each bit in normal mode and eight states for each bit in double speed mode. Figure 17-6 shows the sampling of the data bits and the parity bit. Each of the samples is given a number that is equal to the state of the recovery unit. Figure 17-6.
17.7.3 Asynchronous Operational Range The operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. If the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see Table 17-2) base frequency, the Receiver will not be able to synchronize the frames to the start bit.
tolerance. The second source for the error is more controllable. The baud rate generator can not always do an exact division of the system frequency to get the baud rate wanted. In this case an UBRRn value that gives an acceptable low error can be used if possible. 17.8 Multi-processor Communication Mode Setting the multi-processor communication mode (MPCMn) bit in UCSRnA enables a filtering function of incoming frames received by the USART receiver.
17.9 USART Register Description 17.9.1 USART I/O Data Register n– UDRn Bit 7 6 5 4 3 2 1 0 RXB[7:0] UDRn (Read) TXB[7:0] UDRn (Write) Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 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 register (TXB) will be the destination for data written to the UDRn register location.
• Bit 3 – DORn: Data OverRun This bit is set if a data overrun condition is detected. A data overrun occurs when the receive buffer is full (two characters), it is a new character waiting in the receive shift register, and a new start bit is detected. This bit is valid until the receive buffer (UDRn) is read. Always set this bit to zero when writing to UCSRnA.
• Bit 2 – UCSZn2: Character Size n The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (character size) in a frame the receiver and transmitter use. • Bit 1 – RXB8n: Receive Data Bit 8 n RXB8n is the ninth data bit of the received character when operating with serial frames with nine data bits. Must be read before reading the low bits from UDRn.
• Bit 3 – USBSn: Stop Bit Select This bit selects the number of stop bits to be inserted by the transmitter. The receiver ignores this setting. Table 17-6. USBS Bit Settings USBSn Stop Bit(s) 0 1-bit 1 2-bit • Bit 2:1 – UCSZn1:0: Character Size The UCSZn1:0 bits combined with the UCSZn2 bit in UCSRnB sets the number of data bits (character size) in a frame the receiver and transmitter use. Table 17-7.
• Bit 15:12 – Reserved Bits These bits are reserved for future use. For compatibility with future devices, these bit must be written to zero when UBRRnH is written. • Bit 11:0 – UBRR11:0: USART Baud Rate Register This is a 12-bit register which contains the USART baud rate. The UBRRnH contains the four most significant bits, and the UBRRnL contains the eight least significant bits of the USART baud rate. Ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed.
Table 17-10. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 3.6864MHz fosc = 4.0000MHz fosc = 7.3728MHz Baud Rate (bps) UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 23 0.0% 47 0.0% 25 0.2% 51 0.2% 47 0.0% 95 0.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 –0.8% 31 0.
Table 17-12. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 16.0000MHz fosc = 18.4320MHz fosc = 20.0000MHz Baud Rate (bps) UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error 2400 416 –0.1% 832 0.0% 479 0.0% 959 0.0% 520 0.0% 1041 0.0% 4800 207 0.2% 416 –0.1% 239 0.0% 479 0.0% 259 0.2% 520 0.0% 9600 103 0.2% 207 0.2% 119 0.0% 239 0.0% 129 0.2% 259 0.2% 14.4k 68 0.6% 138 –0.1% 79 0.
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 following features: ● Full duplex, three-wire synchronous data transfer ● ● ● ● ● ● ● 18.
18.3 SPI Data Modes and Timing There are four combinations of XCKn (SCK) phase and polarity with respect to serial data, which are determined by control bits UCPHAn and UCPOLn. The data transfer timing diagrams are shown in Figure 18-1. Data bits are shifted out and latched in on opposite edges of the XCKn signal, ensuring sufficient time for data signals to stabilize. The UCPOLn and UCPHAn functionality is summarized in Table 18-2.
18.4.1 USART MSPIM Initialization The USART in MSPIM mode has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting master mode of operation (by setting DDR_XCKn to one), setting frame format and enabling the transmitter and the receiver. Only the transmitter can operate independently.
18.5 Data Transfer Using the USART in MSPI mode requires the transmitter to be enabled, i.e. the TXENn bit in the UCSRnB register is set to one. When the transmitter is enabled, the normal port operation of the TxDn pin is overridden and given the function as the transmitter's serial output. Enabling the receiver is optional and is done by setting the RXENn bit in the UCSRnB register to one.
18.5.1 Transmitter and Receiver Flags and Interrupts The RXCn, TXCn, and UDREn flags and corresponding interrupts in USART in MSPIM mode are identical in function to the normal USART operation. However, the receiver error status flags (FE, DOR, and PE) are not in use and is always read as zero. 18.5.2 Disabling the Transmitter or Receiver The disabling of the transmitter or receiver in USART in MSPIM mode is identical in function to the normal USART operation. 18.
• Bit 6 - TXCIEn: TX Complete Interrupt Enable Writing this bit to one enables interrupt on the TXCn flag. A USART transmit complete interrupt will be generated only if the TXCIEn bit is written to one, the global interrupt flag in SREG is written to one and the TXCn bit in UCSRnA is set. • Bit 5 - UDRIE: USART Data Register Empty Interrupt Enable Writing this bit to one enables interrupt on the UDREn flag.
• Bit 1 - UCPHAn: Clock Phase The UCPHAn bit setting determine if data is sampled on the leasing edge (first) or tailing (last) edge of XCKn. Refer to the SPI data modes and timing section page 4 for details. • 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. 18.6.
19. 2-wire Serial Interface 19.1 Features ● ● ● ● ● ● ● ● ● ● 19.
19.2.2 Electrical Interconnection As depicted in Figure 19-1 on page 175, both bus lines are connected to the positive supply voltage through pull-up resistors. The bus drivers of all TWI-compliant devices are open-drain or open-collector. This implements a wired-AND function which is essential to the operation of the interface. A low level on a TWI bus line is generated when one or more TWI devices output a zero.
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. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed. When a slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle.
Figure 19-5. Data Packet Format Data MSB Data LSB ACK Aggregate SDA SDA from Transmitter SDA from Receiver SCL from Master 1 2 7 SLA + R/W 8 9 STOP, REPEATED START or next Data Byte Data Byte 19.3.5 Combining Address and Data Packets into a Transmission A transmission basically consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition. An empty message, consisting of a START followed by a STOP condition, is illegal.
The wired-ANDing of the bus lines is used to solve both these problems. The serial clocks from all masters will be wired-ANDed, yielding a combined clock with a high period equal to the one from the master with the shortest high period. The low period of the combined clock is equal to the low period of the master with the longest low period.
Note that arbitration is not allowed between: ● A REPEATED START condition and a data bit. ● ● A STOP condition and a data bit. A REPEATED START and a STOP condition. It is the user software’s responsibility to ensure that these illegal arbitration conditions never occur. This implies that in multi-master systems, all data transfers must use the same composition of SLA+R/W and data packets.
19.5.2 Bit Rate Generator Unit This unit controls the period of SCL when operating in a master mode. The SCL period is controlled by settings in the TWI bit rate register (TWBR) and the prescaler bits in the TWI status register (TWSR). Slave operation does not depend on bit rate or prescaler settings, but the CPU clock frequency in the slave must be at least 16 times higher than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period.
The TWINT flag is set in the following situations: ● After the TWI has transmitted a START/REPEATED START condition. ● ● ● ● ● ● ● 19.6 After the TWI has transmitted SLA+R/W. After the TWI has transmitted an address byte. After the TWI has lost arbitration. After the TWI has been addressed by own slave address or general call. After the TWI has received a data byte. After a STOP or REPEATED START has been received while still addressed as a slave.
By writing the TWEA bit to zero, the device can be virtually disconnected from the 2-wire serial bus temporarily. Address recognition can then be resumed by writing the TWEA bit to one again. • Bit 5 – TWSTA: TWI START Condition Bit The application writes the TWSTA bit to one when it desires to become a master on the 2-wire serial bus. The TWI hardware checks if the bus is available, and generates a START condition on the bus if it is free.
Table 19-2. TWI Bit Rate Prescaler TWPS1 TWPS0 Prescaler Value 0 0 1 0 1 4 1 0 16 1 1 64 To calculate bit rates, see Section 19.5.2 “Bit Rate Generator Unit” on page 181. The value of TWPS1..0 is used in the equation. 19.6.4 TWI Data Register – TWDR Bit 7 6 5 4 3 2 1 0 TWD7 TWD6 TWD5 TWD4 TWD3 TWD2 TWD1 TWD0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 TWDR In transmit mode, TWDR contains the next byte to be transmitted.
19.6.6 TWI (Slave) Address Mask Register – TWAMR Bit 7 6 5 Read/Write R/W R/W R/W Initial Value 0 0 0 4 3 2 1 0 R/W R/W R/W R/W R 0 0 0 0 0 TWAM[6:0] – TWAMR • Bits 7..1 – TWAM: TWI Address Mask The TWAMR can be loaded with a 7-bit salve address mask. Each of the bits in TWAMR can mask (disable) the corresponding address bits in the TWI address register (TWAR).
Application Action Figure 19-11. Interfacing the Application to the TWI in a Typical Transmission 1. Application writes to TWCR to initiate transmission of START TWI Hardware Action TWI bus 186 3. Check TWSR to see if START was sent. Application loads SLA + W into TWDR, and loads appropriate control signals into TWCR, makin sure that TWINT is written to one, and TWSTA is written to zero. START 2. TWINT set. Status code indicates START condition sent SLA + W 5.
7. The application software should now examine the value of TWSR, to make sure that the data packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on.
Table 19-3. Code Example (Continued) No. 6 7 Assembly Code Example C Example Comments wait3: in sbrs rjmp r16,TWCR r16,TWINT wait3 while (!(TWCR & (1<
Figure 19-12. Data Transfer in Master Transmitter Mode VCC Device 1 Device 2 Master Transmitter Slave Receiver Device 3 ........ Device n R1 R2 SDA SCL A START condition is sent by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE value 1 X 1 0 X 1 0 X TWEN must be set to enable the 2-wire serial interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT flag.
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 without losing control of the bus. Table 19-4.
Figure 19-13.
19.8.2 Master Receiver Mode In the master receiver mode, a number of data bytes are received from a slave transmitter (slave see Figure 19-14). In order to enter a master mode, a START condition must be transmitted. The format of the following address packet determines whether master transmitter or master receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered.
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 without losing control over the bus. Table 19-5.
Figure 19-15.
To initiate the slave receiver mode, TWAR and TWCR must be initialized as follows: TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device’s Own Slave Address value 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.
Table 19-6.
Table 19-6.
19.8.4 Slave Transmitter Mode In the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see Figure 19-18). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 19-18. Data Transfer in Slave Transmitter Mode VCC Device 1 Device 2 Slave Transmitter Master Receiver Device 3 ........
Table 19-7.
Figure 19-19. Formats and States in the Slave Transmitter Mode Reception of the own slave address and one or more data bytes S SLA R A DATA A $A8 Arbitration lost as master and addressed as slave DATA $B8 A P or S $C0 A $B0 Last data byte transmitted.
19.8.6 Combining Several TWI Modes In some cases, several TWI modes must be combined in order to complete the desired action. Consider for example reading data from a serial EEPROM. Typically, such a transfer involves the following steps: 1. The transfer must be initiated. 2. The EEPROM must be instructed what location should be read. 3. The reading must be performed. 4. The transfer must be finished. Note that data is transmitted both from master to slave and vice versa.
Several different scenarios may arise during arbitration, as described below: ● Two or more masters are performing identical communication with the same slave. In this case, neither the slave nor any of the masters will know about the bus contention. ● Two or more masters are accessing the same slave with different data or direction bit. In this case, arbitration will occur, either in the READ/WRITE bit or in the data bits.
20. Analog Comparator The analog comparator compares the input values on the positive pin AIN0 and negative pin AIN1. When the voltage on the positive pin AIN0 is higher than the voltage on the negative pin AIN1, the analog comparator output, ACO, is set. The comparator’s output can be set to trigger the Timer/Counter1 input capture function. In addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator.
20.2 Analog Comparator Control and Status Register – ACSR Bit 7 6 5 4 3 2 1 0 ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 Read/Write R/W R/W R R/W R/W R/W R/W R/W Initial Value 0 0 N/A 0 0 0 0 0 ACSR • Bit 7 – ACD: Analog Comparator Disable When this bit is written logic one, the power to the analog comparator is switched off. This bit can be set at any time to turn off the analog comparator. This will reduce power consumption in Active and idle mode.
20.3 Analog Comparator Multiplexed Input It is possible to select any of the ADC7..0 pins to replace the negative input to the analog comparator. The ADC multiplexer is used to select this input, and consequently, the ADC must be switched off to utilize this feature. If the analog comparator multiplexer enable bit (ACME in ADCSRB) is set and the ADC is switched off (ADEN in ADCSRA is zero), MUX2..0 in ADMUX select the input pin to replace the negative input to the analog comparator, as shown in Table 20-2.
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 15kSPS at maximum resolution 6 multiplexed single ended input channels 2 additional multiplexed single ended input channels (TQFP and QFN package only) Optional left adjustment for ADC result readout 0 - VCC ADC input voltage range Selectable 1.
Figure 21-1. Analog to Digital Converter Block Schematic Operation ADC Conversion Complete IRQ ADC[9:0] ADPS0 ADPS1 ADPS2 0 ADC Data Register (ADCH/ADCL) Channel Selection Prescaler Conversion Logic Sample and Hold Comparator 10-Bit DAC AREF ADIF ADFR ADSC ADEN MUX0 MUX1 MUX2 MUX3 REFS0 ADLAR REFS1 MUX Decoder Internal 1.
The ADC generates a 10-bit result which is presented in the ADC data registers, ADCH and ADCL. By default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the ADLAR bit in ADMUX. If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then ADCH, to ensure that the content of the data registers belongs to the same conversion.
Prescaling and Conversion Timing Figure 21-3. ADC Prescaler ADEN START Reset 7-Bit ADC Prescaler CK/128 CK/64 CK/32 CK/16 CK/8 CK/4 CK CK/2 21.3 ADPS0 ADPS1 ADPS2 ADC Clock Source By default, the successive approximation circuitry requires an input clock frequency between 50kHz and 200kHz to get maximum resolution. If a lower resolution than 10 bits is needed, the input clock frequency to the ADC can be higher than 200kHz to get a higher sample rate.
Figure 21-4. ADC Timing Diagram, First Conversion (Single Conversion Mode) Next Conversion First Conversion Cycle Number 1 2 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3 ADC Clock ADEN ADSC ADIF ADCH Sign and MSB of Result ADCL LSB of Result MUX and REFS Update Figure 21-5.
Figure 21-6. ADC Timing Diagram, Auto Triggered Conversion Next Conversion One Conversion Cycle Number 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 ADC Clock Trigger Source ADATE ADIF ADCH Sign and MSB of Result ADCL LSB of Result Sample and Hold Prescaler Reset Prescaler Reset Conversion Complete MUX and REFS Update Figure 21-7.
21.4 Changing Channel or Reference Selection The MUXn and REFS1:0 bits in the ADMUX register are single buffered through a temporary register to which the CPU has random access. This ensures that the channels and reference selection only takes place at a safe point during the conversion. The channel and reference selection is continuously updated until a conversion is started. Once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the ADC.
21.5 ADC Noise Canceler The ADC features a noise canceler that enables conversion during sleep mode to reduce noise induced from the CPU core and other I/O peripherals. The noise canceler can be used with ADC noise reduction and idle mode. To make use of this feature, the following procedure should be used: a. Make sure that the ADC is enabled and is not busy converting. Single conversion mode must be selected and the ADC conversion complete interrupt must be enabled. b.
21.5.2 Analog Noise Canceling Techniques Digital circuitry inside and outside the device generates EMI which might affect the accuracy of analog measurements. If conversion accuracy is critical, the noise level can be reduced by applying the following techniques: a. Keep analog signal paths as short as possible. Make sure analog tracks run over the analog ground plane, and keep them well away from high-speed switching digital tracks. b.
21.5.3 ADC Accuracy Definitions An n-bit single-ended ADC converts a voltage linearly between GND and VREF in 2n steps (LSBs). The lowest code is read as 0, and the highest code is read as 2n-1. Several parameters describe the deviation from the ideal behavior: ● Offset: The deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 LSB). Ideal value: 0 LSB. Figure 21-10.
● Integral non-linearity (INL): After adjusting for offset and gain error, the INL is the maximum deviation of an actual transition compared to an ideal transition for any code. Ideal value: 0 LSB. Figure 21-12. Integral Non-linearity (INL) INL Output Code Ideal ADC Actual ADC VREF 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.
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: V IN ⋅ 1024 ADC = ------------------------V REF where VIN is the voltage on the selected input pin and VREF the selected voltage reference (see Table 21-2 and Table 21-3 on page 218). 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. 21.6.
Table 21-3. Input Channel Selections MUX3..0 Single Ended Input 0000 ADC0 0001 ADC1 0010 ADC2 0011 ADC3 0100 ADC4 0101 ADC5 0110 ADC6 0111 ADC7 1000 (reserved) 1001 (reserved) 1010 (reserved) 1011 (reserved) 1100 (reserved) 1101 (reserved) 1110 1.1V (VBG) 1111 0V (GND) 21.6.
• Bit 3 – ADIE: ADC Interrupt Enable When this bit is written to one and the I-bit in SREG is set, the ADC conversion complete interrupt is activated. • Bits 2:0 – ADPS2:0: ADC Prescaler Select Bits These bits determine the division factor between the system clock frequency and the input clock to the ADC. Table 21-4. ADC Prescaler Selections ADPS2 ADPS1 ADPS0 Division Factor 0 0 0 2 0 0 1 2 0 1 0 4 0 1 1 8 1 0 0 16 1 0 1 32 1 1 0 64 1 1 1 128 21.6.
21.6.4 ADC Control and Status Register B – ADCSRB Bit 7 6 5 4 3 2 1 0 – ACME – Read/Write R R/W R – – ADTS2 ADTS1 ADTS0 R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 ADCSRB • Bit 7, 5:3 – Res: Reserved Bits These bits are reserved for future use. To ensure compatibility with future devices, these bist must be written to zero when ADCSRB is written.
22. debugWIRE On-chip Debug System 22.1 Features ● ● ● ● ● ● ● ● ● ● 22.
22.4 Software Break Points debugWIRE supports program memory break points by the AVR® break instruction. Setting a break point in AVR Studio® will insert a BREAK instruction in the program memory. The instruction replaced by the BREAK instruction will be stored. When program execution is continued, the stored instruction will be executed before continuing from the program memory. A break can be inserted manually by putting the BREAK instruction in the program.
23. Self-Programming the Flash, ATmega48 In Atmel® ATmega48, there is no read-while-write support, and no separate boot loader section. The SPM instruction can be executed from the entire flash. 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 associated protocol to read code and write (program) that code into the program memory.
23.4 Addressing the Flash During Self-Programming The Z-pointer is used to address the SPM commands. Bit 15 14 13 12 11 10 9 8 ZH (R31) Z15 Z14 Z13 Z12 Z11 Z10 Z9 Z8 ZL (R30) Z7 Z6 Z5 Z4 Z3 Z2 Z1 Z0 7 6 5 4 3 2 1 0 Since the flash is organized in pages (see Table 25-12 on page 247), the program counter can be treated as having two different sections.
23.4.1 Store Program Memory Control and Status Register – SPMCSR The store program memory control and status register contains the control bits needed to control the program memory operations.
23.4.2 EEPROM Write Prevents Writing to SPMCSR Note that an EEPROM write operation will block all software programming to flash. Reading the fuses and lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEPE) in the EECR register and verifies that the bit is cleared before writing to the SPMCSR register. 23.4.3 Reading the Fuse and Lock Bits from Software It is possible to read both the fuse and lock bits from software.
Flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. Keep the AVR® RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal brown-out detector (BOD) if the operating voltage matches the detection level. If not, an external low VCC reset protection circuit can be used.
; subi sbci ldi rcall execute Page Write ZL, low(PAGESIZEB) ;restore pointer ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256 spmcrval, (1<
24. Boot Loader Support – Read-While-Write Self-Programming, ATmega88 and ATmega168 In Atmel® ATmega88 and Atmel 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-resident boot loader program.
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 software 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.
Figure 24-1. Read-While-Write versus No Read-While-Write Read While Write (RWW) Section Z-pointer Addresses NRWW Section Z-pointer Addresses RWW Section No Read While Write (NRWW) Section CPU is Halted During the Operation Code located in NRWW Section can be Read During the Operation Figure 24-2.
24.4 Boot Loader Lock Bits If no boot loader capability is needed, the entire flash is available for application code. The boot loader has two separate sets of boot lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection. The user can select: ● To protect the entire flash from a software update by the MCU. ● ● ● To protect only the boot loader flash section from a software update by the MCU.
24.5 “Entering the Boot Loader Program Entering the boot loader takes place by a jump or call from the application program. This may be initiated by a trigger such as a command received via USART, or SPI interface. Alternatively, the boot reset fuse can be programmed so that the reset vector is pointing to the boot flash start address after a reset. In this case, the boot loader is started after a reset. After the application code is loaded, the program can start executing the application code.
• Bit 2 – PGWRT: Page Write If this bit is written to one at the same time as SELFPRGEN, the next SPM instruction within four clock cycles executes page write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a page write, or if no SPM instruction is executed within four clock cycles.
Figure 24-3. Addressing the Flash During SPM(1) BIT 15 ZPCMSB ZPAGEMSB Z-REGISTER 1 0 0 PCMSB PROGRAM COUNTER PAGEMSB PCPAGE PAGE ADDRESS WITHIN THE FLASH PCWORD WORD ADDRESS WITHIN PAGE Program Memory Page Page Instructions Word PCWORD [PAGEMSB:0] 00 01 02 PAGEEND Note: 24.7 1. The different variables used in Figure 24-3 are listed in Table 24-8 on page 240. Self-Programming the Flash The program memory is updated in a page by page fashion.
24.7.2 Filling the Temporary Buffer (Page Loading) To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write “00000001” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The content of PCWORD in the Z-register is used to address the data in the temporary buffer. The temporary buffer will auto-erase after a page write operation or by writing the RWWSRE bit in SPMCSR. It is also erased after a system reset.
24.7.8 EEPROM Write Prevents Writing to SPMCSR Note that an EEPROM write operation will block all software programming to flash. Reading the fuses and lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEPE) in the EECR register and verifies that the bit is cleared before writing to the SPMCSR register. 24.7.9 Reading the Fuse and Lock Bits from Software It is possible to read both the fuse and lock bits from software.
Flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. If there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal brown-out detector (BOD) if the operating voltage matches the detection level.
; subi sbci ldi call execute Page Write ZL, low(PAGESIZEB) ;restore pointer ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256 spmcrval, (1<
24.7.13 ATmega88 Boot Loader Parameters In Table 24-6 through Table 24-8, the parameters used in the description of the self programming are given. Table 24-6.
24.7.14 ATmega168 Boot Loader Parameters In Table 24-9 through Table 24-11, the parameters used in the description of the self programming are given. Table 24-9.
25. Memory Programming 25.1 Program And Data Memory Lock Bits The Atmel® ATmega88/168 provides six lock bits which can be left unprogrammed (“1”) or can be programmed (“0”) to obtain the additional features listed in Table 25-2. The lock bits can only be erased to “1” with the chip erase command.The Atmel ATmega48 has no separate boot loader section. The SPM instruction is enabled for the whole flash if the SELFPRGEN fuse is programmed (“0”), otherwise it is disabled. Table 25-1.
Table 25-3. Lock Bit Protection Modes(1)(2). Only ATmega88/168. BLB0 Mode BLB02 BLB01 1 1 1 No restrictions for SPM or LPM accessing the application section. 2 1 0 SPM is not allowed to write to the application section. 3 0 0 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.
Table 25-5. Extended Fuse Byte for ATmega88/168 Extended Fuse Byte Bit No Description Default Value – 7 – 1 – 6 – 1 – 5 – 1 – 4 – 1 Note: – 3 – 1 BOOTSZ1 2 Select boot size (see Table 113 for details) 0 (programmed)(1) BOOTSZ0 1 Select boot size (see Table 113 for details) 0 (programmed)(1) BOOTRST 0 Select reset vector 1 (unprogrammed) 1. The default value of BOOTSZ1..0 results in maximum boot size. See Table 25-8 on page 246 for details. Table 25-6.
25.2.1 Latching of Fuses The fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. This does not apply to the EESAVE fuse which will take effect once it is programmed. The fuses are also latched on power-up in normal mode. 25.3 Signature Bytes All Atmel® microcontrollers have a three-byte signature code which identifies the device.
Figure 25-1. Parallel Programming + 4.5V to 5.5V RDY/BSY PD1 OE PD2 WR PD3 BS1 PD4 XA0 PD5 XA1 PD6 PAGEL PD7 VCC + 4.5V to 5.5V AVCC +12V PC[1:0]:PB[5:0] DATA RESET PC2 BS2 XTAL1 GND Table 25-8.
Table 25-11. Command Byte Bit Coding Command Byte Command Executed 1000 0000 Chip erase 0100 0000 Write fuse bits 0010 0000 Write lock bits 0001 0000 Write flash 0001 0001 Write EEPROM 0000 1000 Read signature bytes and calibration byte 0000 0100 Read fuse and lock bits 0000 0010 Read flash 0000 0011 Read EEPROM Table 25-12. No. of Words in a Page and No. of Pages in the Flash Device Flash Size Page Size PCWORD No.
25.7.2 Considerations for Efficient Programming The loaded command and address are retained in the device during programming. For efficient programming, the following should be considered. ● The command needs only be loaded once when writing or reading multiple memory locations. ● Skip writing the data value 0xFF, that is the contents of the entire EEPROM (unless the EESAVE fuse is programmed) and flash after a chip erase.
F. Repeat B through E until the entire buffer is filled or until all data within the page is loaded. While the lower bits in the address are mapped to words within the page, the higher bits address the pages within the FLASH. This is illustrated in Figure 25-2. Note that if less than eight bits are required to address words in the page (page size < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. G. Load address high byte 1.
Figure 25-3. Programming the Flash Waveforms(1) F DATA A B C D E B C D E G 0x10 ADDR. LOW DATA LOW DATA HIGH XX ADDR. LOW DATA LOW DATA HIGH XX ADDR. HIGH H XX XA1 XA0 BS1 XTAL1 WR RDY/BSY RESET +12V OE PAGEL BS2 Note: 1. “XX” is don’t care. The letters refer to the programming description above. 25.7.5 Programming the EEPROM The EEPROM is organized in pages, see Table 25-13 on page 247. When programming the EEPROM, the program data is latched into a page buffer.
Figure 25-4. Programming the EEPROM Waveforms K A DATA 0x11 G B ADDR. HIGH ADDR. LOW C E B C E DATA XX ADDR. LOW DATA XX L XA1 XA0 BS1 XTAL1 WR RDY/BSY RESET +12V OE PAGEL BS2 25.7.6 Reading the Flash The algorithm for reading the Flash memory is as follows (refer to Section 25.7.4 “Programming the Flash” on page 248 for details on command and address loading): 1. A: Load command “0000 0010”. 2. G: Load address high byte (0x00 - 0xFF). 3. B: Load address low byte (0x00 - 0xFF). 4.
25.7.9 Programming the Fuse High Bits The algorithm for programming the use high bits is as follows (refer to Section 25.7.4 “Programming the Flash” on page 248 for details on command and data loading): 1. A: Load command “0100 0000”. 2. C: Load data low byte. Bit n = “0” programs and bit n = “1” erases the fuse bit. 3. Set BS1 to “1” and BS2 to “0”. This selects high data byte. 4. Give WR a negative pulse and wait for RDY/BSY to go high. 5. Set BS1 to “0”. This selects low data byte. 25.7.
25.7.12 Reading the Fuse and Lock Bits The algorithm for reading the fuse and lock bits is as follows (refer to Section 25.7.4 “Programming the Flash” on page 248 for details on command loading): 1. A: Load command “0000 0100”. 2. Set OE to “0”, BS2 to “0” and BS1 to “0”. The status of the fuse low bits can now be read at DATA (“0” means programmed). 3. Set OE to “0”, BS2 to “1” and BS1 to “1”. The status of the fuse high bits can now be read at DATA (“0” means programmed). 4.
25.7.15 Parallel Programming Characteristics Figure 25-7. Parallel Programming Timing, Including some General Timing Requirements tXLWL XTAL1 tXHXL tDVXH tXLDX Data and Control (DATA, XA0/1, BS1, BS2) tBVPH tPLBX tBVWL tWLBX tPHPL PAGEL tWLWH WR tPLWL tWLRL RDY/BSY tWLRH Figure 25-8.
Figure 25-9. Parallel Programming Timing, Reading Sequence (within the Same Page) with Timing Requirements(1) Load Address (Low Byte) Read Data (Low Byte) Read Data (High Byte) Load Address (Low Byte) tXLOL XTAL1 tBVDV BS1 tOLDV OE tOHDZ DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte) XA0 XA1 Note: 1. Table 25-15. The timing requirements shown in Figure 25-7 on page 254 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading operation.
25.8 Serial Downloading Both the flash and EEPROM memory arrays can be programmed using the serial SPI bus while RESET is pulled to GND. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the programming enable instruction needs to be executed first before program/erase operations can be executed. NOTE, in Table 25-14 on page 247, the pin mapping for SPI programming is listed. Not all parts use the SPI pins dedicated for the internal SPI interface.
4. The flash is programmed one page at a time. The memory page is loaded one byte at a time by supplying the 6 LSB of the address and data together with the load program memory page instruction. To ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. The program memory page is stored by loading the write program memory page instruction with the 8MSB of the address.
Table 25-17. Serial Programming Instruction Set Instruction Format Instruction Byte 1 Byte 2 Byte 3 Byte4 Programming enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx Enable serial programming after RESET goes low. Chip erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx Chip erase EEPROM and flash. Read program memory 0010 H000 000a aaaa bbbb bbbb Read H (high or low) data o from oooo oooo program memory at word address a:b.
Table 25-17. Serial Programming Instruction Set (Continued) Instruction Format Instruction Byte 1 Byte 2 Byte 3 Byte4 Operation Read extended fuse bits 0101 0000 0000 1000 xxxx xxxx Read extended fuse bits. “0” = programmed, “1” = unprogrammed. oooo oooo See Table 25-4 on page 243 for details. Read calibration byte 0011 1000 000x xxxx 0000 0000 oooo oooo Read calibration byte If o = “1”, a programming operation is still busy.
26. Electrical Characteristics 26.1 A Absolute Maximum Ratings* Stresses beyond those listed under “Absolute Maximum Ratings” may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.
26.2 DC Characteristics (Continued) TA = –40°C to +125°C, VCC = 2.7V to 5.5V (unless otherwise noted) Symbol Min.(5) VCC = 2.7V - 5.5V VIH VCC = 2.7V - 5.5V Input high voltage, RESET VCC = 2.7V - 5.5V pin Parameter Condition Input high voltage, except XTAL1 and RESET pins Input high voltage, XTAL1 pin Max.(5) Unit 0.6VCC(2) VCC + 0.5 V VIH1 0.7VCC(2) VCC + 0.5 V VIH2 0.9VCC(2) VCC + 0.5 V 0.8 0.5 V Typ.
26.2 DC Characteristics (Continued) TA = –40°C to +125°C, VCC = 2.7V to 5.5V (unless otherwise noted) Parameter Typ. Max.(5) Unit Active 4MHz, VCC = 3V (ATmega48/88/168L) 1.8 3.0 mA Active 8MHz, VCC = 5V (ATmega48/88/168) 6.0 10 mA Active 15MHz, VCC = 5V (ATmega48/88/168) 10.0 16 mA Idle 4MHz, VCC = 3V (ATmega48/88/168V) 0.4 1 mA 1.4 2.4 mA 2.8 4 mA WDT enabled, VCC = 3V 8 30 µA WDT enabled, VCC = 5V 12.6 50 µA WDT disabled, VCC = 3V 5 24 µA WDT disabled, VCC = 5V 6.
26.3 External Clock Drive Waveforms Figure 26-1. External Clock Drive Waveforms tCHCX tCLCH tCHCX tCHCL VIH1 VIL1 tCLCX tCLCL 26.4 External Clock Drive Table 26-1. External Clock Drive VCC=2.7 to 5.5V Min. Max. 1/tCLCL 0 8 tCLCL 125 62.5 ns High time tCHCX 50 25 ns Low time tCLCX 50 25 ns Rise time tCLCH 1.6 0.5 µs Fall time tCHCL 1.6 0.5 µs Change in period from one clock cycle to the next DtCLCL 2 2 % 26.
26.6 LIN Re-synchronization Algorithm 26.7 Synchronization Algorithm The possibility to change the value of OSCCAL during the oscillator operation allows for in-situ calibration of the slave node to entering Master frames. The principle of operation is to measure the TBit during the SYNCH byte and to change the calibration value of OSCCAL to recover from local frequency drifts due to local voltage or temperature deviation.
26.8.1 RC Oscillator Precision for LIN Slave implementation For LIN slave devices, the precision of the RC oscillator before and after re-synchronization are described in the Table 26-2. Table 26-2. Oscillator Tolerance Before and After Re-Synchronization Algorithm (2.7V < VCC < 5.
27. 2-wire Serial Interface Characteristics Table 27-1 describes the requirements for devices connected to the 2-wire serial bus. The Atmel® ATmega48/88/168 2-wire serial interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 27-1. Table 27-1.
Table 27-1. 2-wire Serial Bus Requirements (Continued) Parameter Condition Min Max Unit 4.0 – µs 0.6 – µs 4.7 – µs fSCL > 100kHz 1.3 In Atmel ATmega48/88/168, this parameter is characterized and not 100% tested. – µs fSCL ≤ 100kHz Setup time for STOP condition 1. tSU;STO fSCL > 100kHz fSCL ≤ 100kHz Bus free time between a STOP and START condition Notes: Symbol 2. Required only for fSCL > 100kHz. 3. Cb = capacitance of one bus line in pF. tBUF 4. fCK = CPU clock frequency 5.
27.1 SPI Timing Characteristics See Figure 27-2 and Figure 27-3 for details. Table 27-2. SPI Timing Parameters No. Description Mode 1 SCK period Master See Table 16-4 2 SCK high/low Master 50% duty cycle 3 Rise/fall time Master 3.6 4 Setup Master 10 5 Hold Master 10 6 Out to SCK Master 0.
Figure 27-3. SPI Interface Timing Requirements (Slave Mode) SS 16 10 9 SCK (CPOL = 0) 11 11 SCK (CPOL = 1) 13 MOSI (Data Input) 14 12 ... MSB LSB 17 15 MISO (Data Output) 27.2 ... MSB LSB X ADC Characteristics Table 27-3. ADC Characteristics Parameter Condition Symbol Min Resolution Typ Max 10 Unit Bits VREF = 4V, VCC = 4V, ADC clock = 200kHz 2 3.5 LSB VREF = 4V, VCC = 4V, ADC clock = 200kHz noise reduction mode 2 3.
28. ATmega48/88/168 Typical Characteristics 28.1 Active Supply Current Figure 28-1. Active Supply Current versus Frequency (1 to 20MHz) 20 18 16 5.5V 14 ICC (mA) 5.0V 12 4.5V 10 8 3.3V 3.0V 2.7V 6 4 2 0 0 2 4 6 8 10 12 14 16 18 20 Frequency (MHz) Figure 28-2. Idle Supply Current versus Frequency (1 to 20MHz) 6 4 ICC (mA) 5.5V 5.0V 4.5V 2 3.3V 3.0V 2.
28.1.1 Power-Down Supply Current Figure 28-3. Power-Down Supply Current versus VCC (Watchdog Timer Disabled) 8 7 6 125 ICC (µA) 5 85 4 25 3 -40 2 1 0 0 3.5 4 4.5 5 5.5 VCC (V) Figure 28-4. Power-Down Supply Current versus VCC (Watchdog Timer Enabled) 8 7 6 125 ICC (µA) 5 85 25 4 -40 3 2 1 0 2.5 3 3.5 4 4.5 5 5.
28.1.2 Pin Pull-up Figure 28-5. I/O Pin Pull-up Resistor Current versus Input Voltage (VCC = 5V) 160 125 140 -40 120 IOP (µA) 100 80 60 40 20 0 0 1 2 3 4 5 6 VOP (V) Figure 28-6. Output Low Voltage versus Output Low Current (VCC = 5V) 0.8 0.7 125°C 0.6 85°C VOL (V) 0.5 25°C 0.4 -40°C 0.3 0.2 0.
Figure 28-7. Output Low Voltage versus Output Low Current (VCC = 3V) 1.2 125°C 1 85°C IOL (mA) 0.8 25°C 0.6 -40°C 0.4 0.2 0 0 2 4 6 8 10 12 14 16 18 20 VOL (V) Figure 28-8. Output High Voltage versus Output High Current (VCC = 5V) 5.2 5 VOH (V) 4.8 4.6 -40°C 25°C 85°C 125°C 4.4 4.
Figure 28-9. Output High Voltage versus Output High Current (VCC = 3V) 3.5 3 Current (V) 2.5 -40°C 25°C 85°C 125°C 2 1.5 1 0.5 0 0 2 4 6 8 10 12 14 16 18 20 IOH (mA) Figure 28-10.
28.1.3 Pin Driver Strength Figure 28-11. Output Low Voltage versus Output Low Current (VCC = 5.0V) 0.8 0.7 125°C 0.6 85°C VOL (V) 0.5 25°C 0.4 -40°C 0.3 0.2 0.1 0 0 2 4 6 8 10 12 14 16 18 20 IOL (mA) Figure 28-12. Output Low Voltage versus Output Low Current (VCC = 3.0V) 1.2 125°C 1 85°C IOL (mA) 0.8 25°C 0.6 -40°C 0.4 0.
Figure 28-13. Output High Voltage versus Output High Current (VCC = 5.0V) 5.2 5 VOH (V) 4.8 4.6 -40°C 25°C 85°C 125°C 4.4 4.2 4 0 2 4 6 8 10 12 14 16 18 20 IOH (mA) Figure 28-14. Output High Voltage versus Output High Current (VCC = 3.0V) 3.5 3 Current (V) 2.5 -40°C 25°C 85°C 125°C 2 1.5 1 0.
28.1.4 Pin Thresholds and Hysteresis Figure 28-15. I/O Pin Input Threshold versus VCC (VIH, I/O Pin Read as ‘1 3.5 3 IIH (V) 2.5 125 85 2 25 -40 1.5 1 2 2.5 3 3.5 4 4.5 5 5.5 VCC (V) Figure 28-16. I/O Pin Input Threshold versus VCC (VIL, I/O Pin Read as ‘0’) 3 125°C -40°C 2.5 VIL (V) 2 1.5 1 0.5 0 2 2.5 3 3.5 4 4.5 5 5.
Figure 28-17. Reset Input Threshold Voltage versus VCC (VIH, Reset Pin Read as ‘1’) 4 3.5 Threshold (V) 3 -40°C 25°C 85°C 125°C 2.5 2 1.5 1 0.5 0 2 2.5 3 3.5 4 4.5 5 5.5 VCC (V) Figure 28-18. Reset Input Threshold Voltage versus VCC (VIL, Reset Pin Read as ‘0’) 2.5 125°C 85°C 25°C -40°C Threshold (V) 2 1.5 1 0.5 0 2 2.5 3 3.5 4 VCC (V) 278 ATmega48/88/168 Automotive [DATASHEET] 7530K–AVR–07/14 4.5 5 5.
28.1.5 Internal Oscillator Speed Figure 28-19. Watchdog Oscillator Frequency versus VCC 130 FRC (kHz) 128 126 -40°C 124 25°C 122 120 85°C 125°C 118 116 114 112 110 2.5 3 3.5 4 4.5 5 5.5 VCC (V) Figure 28-20. Calibrated 8MHz RC Oscillator Frequency versus Temperature 8.4 8.3 FRC (MHz) 8.2 5.0V 8.1 2.7V 8 7.9 7.8 7.7 7.
Figure 28-21. Calibrated 8MHz RC Oscillator Frequency versus VCC 8.4 FRC (MHz) 8.2 8 125°C 85°C 25°C 7.8 -40°C 7.6 7.4 7.2 7 2.5 3 3.5 4 4.5 5 5.5 VCC (V) Figure 28-22.
Figure 28-23. Calibrated 8MHz RC Oscillator Frequency versus OSCCAL Value (for ATmega88-15AZ only) 14 125°C 85°C 25°C -40°C 12 FRC (MHz) 10 8 6 4 2 0 16 32 48 64 80 96 112 128 144 160 176 192 208 65 75 85 224 240 OSCCAL (X1) 28.1.6 BOD Thresholds and Analog Comparator Offset Figure 28-24. BOD Threshold versus Temperature (BODLEVEL is 4.0V) 4.6 4.5 Threshold (V) Rising VCC 4.4 4.3 Falling VCC 4.2 4.
Figure 28-25. BOD Threshold versus Temperature (BODLEVEL is 2.7V) 3 2.9 Threshold (V) Rising VCC 2.8 2.7 Falling VCC 2.6 2.5 2.4 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120 Temperature (°C) Figure 28-26. Bandgap Voltage versus VCC 1.1 Bandgap Voltage (V) 1.095 1.09 85°C 25°C 125°C 1.085 1.08 -40°C 1.075 2.5 3 3.5 4 VCC (V) 282 ATmega48/88/168 Automotive [DATASHEET] 7530K–AVR–07/14 4.5 5 5.
28.1.7 Peripheral Units Figure 28-27. Analog to Digital Converter GAIN versus VCC 0 -0.2 Error (LSB) -0.4 -0.6 4V IDLE -0.8 4V STD -1 -1.2 -1.4 -1.6 -50 0 50 100 150 Temperature (°C) Figure 28-28. Analog to Digital Converter OFFSET versus VCC 2.5 Error (LSB) 2 1.5 4V IDLE 4V STD 1 0.
Figure 28-29. Analog to Digital Converter DNL versus VCC 0.4 0.35 Error (LSB) 0.3 0.25 4V IDLE 0.2 4V STD 0.15 0.1 0.05 0 -50 0 50 100 150 Temperature (°C) Figure 28-30. Analog to Digital Converter INL versus VCC 0.7 0.6 Error (LSB) 0.5 0.4 4V IDLE 4V STD 0.3 0.2 0.
29.
29.
29.
29.
29.
29.
29.
30.
30.
30.
30. Instruction Set Summary (Continued) Mnemonics Operands Description Operation Flags #Clocks ST Z, Rr Store indirect (Z) ← Rr None 2 ST Z+, Rr Store indirect and post-inc. (Z) ← Rr, Z ← Z + 1 None 2 ST -Z, Rr Store ndirect and pre-dec.
31. Ordering Information 31.1 ATmega48 Speed (MHz) Power Supply Ordering Code Package(1) Operation Range 16(2) 2.7 - 5.5 ATmega48-15AT ATmega48-15AT1 ATmega48-15AZ MA –40°C to +85°C –40°C to +105°C –40°C to +125°C 16(2) 2.7 - 5.5 ATmega48-15MT ATmega48-15MT1 ATmega48-15MZ PN –40°C to 85°C –40°C to +105°C –40°C to 125°C Notes: 31.2 1. Green and ROHS packaging 2. See Figure 26-2 on page 263. 3.
32. Packaging Information 32.1 MA Drawings not scaled A A2 A1 D1 32 1 E1 e L 0°~7° Top View C Side View D COMMON DIMENSIONS (Unit of Measure = mm) Symbol MIN NOM A MAX A1 0.05 A2 0.95 1.00 1.05 D/E 8.75 9.00 9.25 D1/E1 6.90 7.00 7.10 C 0.09 0.20 L 0.45 0.75 b 0.30 0.45 E b Bottom View NOTE 1.20 0.15 e 0.80 TYP. n 32 2 Notes: 1. This drawing is for general information only. Refer to JEDEC Drawing MS-026, Variation ABA. 2.
32.2 PN Drawings not scaled A A3 D A1 N 1 0.30 Dia. Typ. Laser Marking E Seating Plane C 0.080 C Top View L Side View D2 COMMON DIMENSIONS b (Unit of Measure = mm) Option A Pin 1# Chamfer (C 0.30) E2 Option B PIN1 ID 1 Pin 1# Notch (C 0.20 R) See Options A, B e Symbol MIN NOM MAX A 0.80 0.85 0.90 A1 A3 0.00 NOTE 0.05 0.20 REF D/E 5.00 BSC D2/E2 3.00 3.10 3.20 L 0.30 0.40 0.50 b 0.18 0.25 0.30 e 0.50 BSC n 32 2 Bottom View Notes: 1.
33. Errata ATmega48 The revision letter in this section refers to the revision of the Atmel® ATmega48 device. 33.1 Rev. E ● Interrupts may be lost when writing the timer registers in the asynchronous timer 1. Interrupts may be lost when writing the timer registers in the asynchronous timer If one of the timer registers which is synchronized to the asynchronous Timer2 clock is written in the cycle before an overflow interrupt occurs, the interrupt may be lost.
34. Errata ATmega88 The revision letter in this section refers to the revision of the ATmega88 device. 34.1 Rev. G ● Interrupts may be lost when writing the timer registers in the asynchronous timer 1. Interrupts may be lost when writing the timer registers in the asynchronous timer If one of the timer registers which is synchronized to the asynchronous Timer2 clock is written in the cycle before an overflow interrupt occurs, the interrupt may be lost.
35. Errata ATmega168 The revision letter in this section refers to the revision of the ATmega168 device. 35.1 Rev. F ● Interrupts may be lost when writing the timer registers in the asynchronous timer 1. Interrupts may be lost when writing the timer registers in the asynchronous timer If one of the timer registers which is synchronized to the asynchronous Timer2 clock is written in the cycle before an overflow interrupt occurs, the interrupt may be lost.
36. Revision History Please note that the following page numbers referred to in this section refer to the specific revision mentioned, not to this document. Revision No. History 7530K-AVR-07/14 • Put datasheet in the latest template 7530J-AVR-03/12 • Package updated 7530I-AVR-02/10 • Package updated 7530H-AVR-02/09 • Update Section 7.7.1 “Power Reduction Register - PRR” on page 35 7530G-AVR-10/07 • Update to errata section • Modification to POR. Table 8-1 on page 40.
37. Table of Contents Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1. Pin Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.1 2. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.1 2.2 2.3 2.4 3. 4. Introduction . . . . . . . . . . . . . . . .
8. Minimizing Power Consumption. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 9. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Timer/Counter Clock Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Counter Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.8 Modes of Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 14.9 Timer/Counter Timing Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 14.10 16-bit Timer/Counter Register Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 15. 8-bit Timer/Counter2 with PWM and Asynchronous Operation . . . . . . . . . . . . . . . . . 119 15.1 15.2 15.
21. Analog-to-Digital Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 21.1 21.2 21.3 21.4 21.5 21.6 22. Program And Data Memory Lock Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fuse Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Signature Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
28. ATmega48/88/168 Typical Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 28.1 Active Supply Current . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 29. Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 30. Instruction Set Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XXXXXX Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com © 2014 Atmel Corporation. / Rev.: Rev.: 7530K–AVR–07/14 Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, AVR®, AVR Studio®, and others are registered trademarks or trademarks of Atmel Corporation in U.S. and other countries. Other terms and product names may be trademarks of others.