ATMEGA328P-20PU Atmel, ATMEGA328P-20PU Datasheet

ATMEGA328P-20PU
Specifications of ATMEGA328P-20PU
Related parts for ATMEGA328P-20PU
ATMEGA328P-20PU Summary of contents
Page 1
Features • High Performance, Low Power AVR • Advanced RISC Architecture – 131 Powerful Instructions – Most Single Clock Cycle Execution – General Purpose Working Registers – Fully Static Operation – MIPS Throughput at ...
Page 2
Pin Configurations Figure 1-1. Pinout ATmega48P/88P/168P TQFP Top View (PCINT19/OC2B/INT1) PD3 1 (PCINT20/XCK/T0) PD4 2 GND 3 VCC 4 GND 5 VCC 6 (PCINT6/XTAL1/TOSC1) PB6 7 (PCINT7/XTAL2/TOSC2) PB7 8 28 MLF Top View (PCINT19/OC2B/INT1) PD3 1 (PCINT20/XCK/T0) PD4 2 ...
Page 3
Pin Descriptions 1.1.1 VCC Digital supply voltage. 1.1.2 GND Ground. 1.1.3 Port B (PB7:0) XTAL1/XTAL2/TOSC1/TOSC2 Port 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive ...
Page 4
The various special features of Port D are elaborated in 85. 1.1 the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally CC connected to V through a low-pass filter. Note ...
Page 5
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 ...
Page 6
... Application Flash section is updated, providing true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel ATmega48P/88P/168P is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. ...
Page 7
... Resources A comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr. Note: 4. Data Retention Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C. ...
Page 8
AVR CPU Core 6.1 Overview This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control ...
Page 9
ALU operation, two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File – in one clock cycle. Six of the 32 registers can be used as three ...
Page 10
Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and ...
Page 11
General Purpose Register File The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: • One 8-bit output ...
Page 12
The X-register, Y-register, and Z-register The registers R26..R31 have some added functions to their general purpose usage. These reg- isters are 16-bit address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and ...
Page 13
SPH and SPL – Stack Pointer High and Stack Pointer Low Register Bit 0x3E (0x5E) 0x3D (0x5D) Read/Write Initial Value 6.6 Instruction Execution Timing This section describes the general access timing concepts for instruction execution. The AVR CPU is ...
Page 14
Reset and Interrupt Handling The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a separate program vector in the program memory space. All interrupts are assigned individual enable bits which must be ...
Page 15
Assembly Code Example in r16, SREG cli sbi EECR, EEMPE sbi EECR, EEPE out SREG, r16 C Code Example char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ _CLI(); EECR |= (1<<EEMPE); ...
Page 16
AVR Memories 7.1 Overview This section describes the different memories in the ATmega48P/88P/168P. The AVR architec- ture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega48P/88P/168P features an EEPROM Memory for ...
Page 17
Figure 7-1. Figure 7-2. 8025K–AVR–10/09 Program Memory Map, ATmega48P Program Memory Application Flash Section Program Memory Map, ATmega88P and ATmega168P Program Memory Application Flash Section Boot Flash Section ATmega48P/88P/168P 0x0000 0x7FF 0x0000 0x0FFF/0x1FFF 17 ...
Page 18
SRAM Data Memory Figure 7-3 The ATmega48P/88P/168P 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. For the Extended I/O space from ...
Page 19
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 clk Figure 7-4. 7.4 EEPROM Data Memory The ATmega48P/88P/168P contains 256/512/512 bytes of data ...
Page 20
Preventing EEPROM Corruption During periods of low V too low for the CPU and the EEPROM to operate properly. These issues are the same as for board level systems using EEPROM, and the same design solutions should be applied. ...
Page 21
Register Description 7.6.1 EEARH and EEARL – The EEPROM Address Register Bit 0x22 (0x42) 0x21 (0x41) Read/Write Initial Value • Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the ATmega48P/88P/168P and will always read as ...
Page 22
EEPMn will be ignored. During reset, the EEPMn bits will be reset to 0b00 unless the EEPROM is busy programming. Table 7-1. EEPM1 • Bit 3 – EERIE: EEPROM Ready Interrupt ...
Page 23
When the write access time has elapsed, the EEPE bit is cleared by hardware. The user soft- ware can poll this bit and wait for a zero before writing the next byte. When EEPE has been set, the CPU is ...
Page 24
Assembly Code Example EEPROM_write: C Code Example void EEPROM_write(unsigned int uiAddress, unsigned char ucData 8025K–AVR–10/09 ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out ...
Page 25
The next code examples show assembly and C functions for reading the EEPROM. The exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. Assembly Code Example EEPROM_read: C Code Example unsigned ...
Page 26
System Clock and Clock Options 8.1 Clock Systems and their Distribution Figure 8-1 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 ...
Page 27
Asynchronous Timer Clock – clk The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clocked directly from an external clock or an external 32 kHz clock crystal. The dedicated clock domain allows using this Timer/Counter as a real-time ...
Page 28
Table 8-2. Typ Time-out (V Main purpose of the delay is to keep the AVR in reset until it is supplied with minimum V delay will not monitor the actual voltage ...
Page 29
Figure 8-2. The Low Power Oscillator can operate in three different modes, each optimized for a specific fre- quency range. The operating mode is selected by the fuses CKSEL3..1 as shown in on page Table 8-3. Frequency Range Notes: The ...
Page 30
Table 8-4. Oscillator Source / Power Conditions Crystal Oscillator, BOD enabled Crystal Oscillator, fast rising power Crystal Oscillator, slowly rising power Notes: 8.4 Full Swing Crystal Oscillator Pins XTAL1 and XTAL2 are input and output, respectively inverting amplifier ...
Page 31
Figure 8-3. Table 8-6. Oscillator Source / Power Conditions Ceramic resonator, fast rising power Ceramic resonator, slowly rising power Ceramic resonator, BOD enabled Ceramic resonator, fast rising power Ceramic resonator, slowly rising power Crystal Oscillator, BOD enabled Crystal Oscillator, fast ...
Page 32
Low Frequency Crystal Oscillator The Low-frequency Crystal Oscillator is optimized for use with a 32.768 kHz watch crystal. When selecting crystals, load capasitance and crystal’s Equivalent Series Resistance, ESR must be taken into consideration. Both values are specified by ...
Page 33
Table 8-10. CKSEL3..0 0100 0101 Note: 8.6 Calibrated Internal RC Oscillator By default, the Internal RC Oscillator provides an approximate 8.0 MHz clock. Though voltage and temperature dependent, this clock can be very accurately calibrated by the user. See 28-1 ...
Page 34
Internal Oscillator The 128 kHz internal Oscillator is a low power Oscillator providing a clock of 128 kHz. The fre- quency is nominal at 3V and 25°C. This clock may be select as the system clock by ...
Page 35
When this clock source is selected, start-up times are determined by the SUT Fuses as shown in Table 8-16. Table 8-16. Power Conditions BOD enabled Fast rising power Slowly rising power When applying an external clock required to ...
Page 36
CPU and all synchronous peripherals. clk divided by a factor as shown in When switching between prescaler settings, the System Clock Prescaler ensures that no glitches occurs in the clock system. It also ensures that no intermediate ...
Page 37
Register Description 8.12.1 OSCCAL – Oscillator Calibration Register Bit (0x66) Read/Write Initial 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 ...
Page 38
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 ...
Page 39
Power Management and Sleep Modes Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consump- tion to the application’s ...
Page 40
BOD Disable When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses, the BOD is actively monitoring the power supply voltage during a sleep period. To save power possible to disable the BOD by software for some ...
Page 41
Power-down Mode When the SM2..0 bits are written to 010, the SLEEP instruction makes the MCU enter Power- down mode. In this mode, the external Oscillator is stopped, while the external interrupts, the 2- wire Serial Interface address watch, ...
Page 42
Power Reduction Register The Power Reduction Register (PRR), see vides a method to stop the clock to individual peripherals to reduce power consumption. The current state of the peripheral is frozen and the I/O registers can not be read ...
Page 43
Watchdog Timer If the Watchdog Timer is not needed in the application, the module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes and hence always consume power. In the ...
Page 44
Register Description 9.11.1 SMCR – Sleep Mode Control Register The Sleep Mode Control Register contains control bits for power management. Bit 0x33 (0x53) Read/Write Initial Value • Bits 7..4 Res: Reserved Bits These bits are unused bits in the ...
Page 45
Then, to set the BODS bit, BODS must be set to one and BODSE must be set to zero within four clock cycles. The BODS bit is active three clock cycles after it is set. A ...
Page 46
System Control and Reset 10.1 Resetting the AVR During reset, all I/O Registers are set to their initial values, and the program starts execution from the Reset Vector. For the ATmega168P, the instruction placed at the Reset Vector must ...
Page 47
Figure 10-1. Reset Logic BODLEVEL [2..0] RSTDISBL 10.3 Power-on Reset A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level is defined below the detection level. The POR circuit can be used ...
Page 48
Figure 10-3. MCU Start-up, RESET Extended Externally TIME-OUT INTERNAL 10.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 reset, even if the clock is ...
Page 49
Figure 10-5. Brown-out Reset During Operation 10.6 Watchdog System Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the ...
Page 50
ADC is used. To reduce power consumption in Power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering Power-down mode. 10.8 Watchdog Timer 10.8.1 Features • Clocked from separate On-chip ...
Page 51
To further ensure program security, altera- tions to the Watchdog set-up must follow timed sequences. The sequence for clearing WDE and changing time-out configuration is as follows the ...
Page 52
Assembly Code Example WDT_off: C Code Example void WDT_off(void Note: Note: If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. ...
Page 53
The following code example shows one assembly and one C function for changing the time-out value of the Watchdog Timer. Assembly Code Example WDT_Prescaler_Change: C Code Example void WDT_Prescaler_Change(void Note: Note: The Watchdog Timer should be reset before ...
Page 54
Register Description 10.9.1 MCUSR – MCU Status Register The MCU Status Register provides information on which reset source caused an MCU reset. Bit 0x35 (0x55) Read/Write Initial Value • Bit 7..4: Res: Reserved Bits These bits are unused bits ...
Page 55
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. This ...
Page 56
Table 10-2. WDP3 8025K–AVR–10/09 Watchdog Timer Prescale Select (Continued) Number of WDT Oscillator WDP2 WDP1 WDP0 512K (524288) cycles 1024K (1048576) cycles ...
Page 57
Interrupts ...
Page 58
Table 11-1. Reset and Interrupt Vectors in ATmega48P (Continued) Vector No. Program Address 24 0x017 25 0x018 26 0x019 The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega48P is: Address Labels Code 0x000 ...
Page 59
Interrupt Vectors in ATmega88P Table 11-2. Reset and Interrupt Vectors in ATmega88P Program (2) Vector No. Address (1) 1 0x000 2 0x001 3 0x002 4 0x003 5 0x004 6 0x005 7 0x006 8 0x007 9 0x008 10 0x009 11 ...
Page 60
Table 11-3. BOOTRST Note: The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega88P is: Address Labels Code 0x000 0x001 0x002 0x003 0x004 0x005 0x006 0x007 0X008 0x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F ...
Page 61
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and ...
Page 62
Interrupt Vectors in ATmega168P Table 11-4. Reset and Interrupt Vectors in ATmega168P Program (2) VectorNo. Address (1) 1 0x0000 2 0x0002 3 0x0004 4 0x0006 5 0x0008 6 0x000A 7 0x000C 8 0x000E 9 ...
Page 63
Table 11-5 on page 63 tions of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case ...
Page 64
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general ...
Page 65
Address Labels Code ; .org 0x1C00 0x1C00 0x1C02 0x1C04 ... 0x1C32 ; 0x1C33 0x1C34 0x1C35 0x1C36 0x1C37 0x1C38 11.4 Register Description 11.4.1 Moving Interrupts Between Application and Boot Space, ATmega88P and ATmega168P The MCU Control Register controls the placement of ...
Page 66
Bit 0 – IVCE: Interrupt Vector Change Enable The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is ...
Page 67
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 ...
Page 68
Register Description 12.2.1 EICRA – External Interrupt Control Register A The External Interrupt Control Register A contains control bits for interrupt sense control. Bit (0x69) Read/Write Initial Value • Bit 7..4 – Res: Reserved Bits These bits are unused ...
Page 69
EIMSK – External Interrupt Mask Register Bit 0x1D (0x3D) Read/Write Initial Value • Bit 7..2 – Res: Reserved Bits These bits are unused bits in the ATmega48P/88P/168P, and will always read as zero. • Bit 1 – INT1: External ...
Page 70
PCICR – Pin Change Interrupt Control Register Bit (0x68) Read/Write Initial Value • Bit 7..3 - Res: Reserved Bits These bits are unused bits in the ATmega48P/88P/168P, and will always read as zero. • Bit 2 - PCIE2: Pin ...
Page 71
Bit 0 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT7..0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in SREG and the PCIE0 bit in PCICR are set (one), ...
Page 72
I/O-Ports 13.1 Overview 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 ...
Page 73
Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital I/O. 13.2 Ports as General Digital I/O The ports are bi-directional I/O ports ...
Page 74
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin ...
Page 75
Figure 13-3. Synchronization when Reading an Externally Applied Pin value INSTRUCTIONS Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the ...
Page 76
Assembly Code Example C Code Example unsigned char i; Note: 13.2.5 Digital Input Enable and Sleep Modes As shown in Schmitt Trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down mode, Power-save ...
Page 77
Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin enable ...
Page 78
Table 13-2 ure 13-5 on page 77 generated internally in the modules having the alternate function. Table 13-2. Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO The following subsections shortly describe the alternate functions for ...
Page 79
Alternate Functions of Port B The Port B pins with alternate functions are shown in Table 13-3. Port Pin PB7 PB6 PB5 PB4 PB3 PB2 PB1 PB0 The alternate pin configuration is as follows: • XTAL2/TOSC2/PCINT7 – Port B, ...
Page 80
AS2 bit in ASSR is set (one) to enable asynchronous clocking of Timer/Counter2, pin PB6 is dis- connected from the port, and becomes the input of the inverting Oscillator amplifier. In this mode, a crystal Oscillator is connected to this ...
Page 81
The OC1A pin is also the output pin for the PWM mode timer function. PCINT1: Pin Change Interrupt source 1. The PB1 pin can serve as an external interrupt source. • ICP1/CLKO/PCINT0 – Port B, ...
Page 82
Table 13-5. Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO 13.3.2 Alternate Functions of Port C The Port C pins with alternate functions are shown in Table 13-6. Port Pin 8025K–AVR–10/09 Overriding Signals for Alternate Functions ...
Page 83
The alternate pin configuration is as follows: • RESET/PCINT14 – Port C, Bit 6 RESET, Reset pin: When the RSTDISBL Fuse is programmed, this pin functions as a normal I/O pin, and the part will have to rely on Power-on ...
Page 84
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 ...
Page 85
Table 13-8. Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO 13.3.3 Alternate Functions of Port D The Port D pins with alternate functions are shown in Table 13-9. Port Pin 8025K–AVR–10/09 Overriding Signals for Alternate Functions ...
Page 86
The alternate pin configuration is as follows: • AIN1/OC2B/PCINT23 – Port D, Bit 7 AIN1, Analog Comparator Negative Input. Configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with ...
Page 87
INT0/PCINT18 – Port D, Bit 2 INT0, External Interrupt source 0: The PD2 pin can serve as an external interrupt source. PCINT18: Pin Change Interrupt source 18. The PD2 pin can serve as an external interrupt source. • TXD/PCINT17 ...
Page 88
Table 13-11. Overriding Signals for Alternate Functions in PD3..PD0 Signal Name PUOE PUO DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO 8025K–AVR–10/09 PD3/OC2B/INT1/ PD2/INT0/ PCINT19 PCINT18 OC2B ENABLE 0 OC2B 0 INT1 ...
Page 89
Register Description 13.4.1 MCUCR – MCU Control Register Bit 0x35 (0x55) Read/Write Initial Value • Bit 4 – PUD: Pull-up Disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the ...
Page 90
PORTD – The Port D Data Register Bit 0x0B (0x2B) Read/Write Initial Value 13.4.9 DDRD – The Port D Data Direction Register Bit 0x0A (0x2A) Read/Write Initial Value 13.4.10 PIND – The Port D Input Pins Address Bit 0x09 ...
Page 91
Timer/Counter0 with PWM 14.1 Features • Two Independent Output Compare Units • Double Buffered Output Compare Registers • Clear Timer on Compare Match (Auto Reload) • Glitch Free, Phase Correct Pulse Width Modulator (PWM) • Variable PWM Period ...
Page 92
Figure 14-1. 8-bit Timer/Counter Block Diagram 14.2.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 ...
Page 93
The Timer/Counter can be clocked internally, via the prescaler external clock source on the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The ...
Page 94
The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the Timer/Counter Control Register (TCCR0A) and the WGM02 bit located in the Timer/Counter Control Register B (TCCR0B). There are close connections between how the ...
Page 95
The OCR0x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is dis- abled the CPU will access the OCR0x ...
Page 96
Figure 14-4. Compare Match Output Unit, Schematic 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 out- put) ...
Page 97
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 ...
Page 98
The waveform generated will have a maximum frequency when OCR0A is set to zero (0x00). The waveform frequency is defined by the following clk_I/O equation: The N variable represents the ...
Page 99
In fast 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 and an inverted PWM output can be generated by setting the COM0x1:0 to ...
Page 100
Figure 14-7. Phase Correct PWM Mode, Timing Diagram TCNTn OCnx OCnx Period The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches ...
Page 101
BOTTOM the OCnx value at MAX must correspond to the result of an up- counting Compare Match. • The timer starts counting from a value higher than the one in OCRnx, and for that reason misses the Compare ...
Page 102
Figure 14-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (f clk clk (clk TCNTn OCRnx OCFnx Figure 14-11 PWM mode where OCR0A is TOP. Figure 14-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Pres- clk clk ...
Page 103
Register Description 14.9.1 TCCR0A – Timer/Counter Control Register A Bit 0x24 (0x44) Read/Write Initial Value • Bits 7:6 – COM0A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC0A) behavior. If one or both of ...
Page 104
Table 14-4 rect PWM mode. Table 14-4. COM0A1 Note: • 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 ...
Page 105
Table 14-7 rect PWM mode. Table 14-7. COM0B1 Note: • Bits 3, 2 – Res: Reserved Bits These bits are reserved bits in the ATmega48P/88P/168P and will always read as zero. • Bits 1:0 – WGM01:0: ...
Page 106
TCCR0B – Timer/Counter Control Register B Bit 0x25 (0x45) Read/Write Initial Value • Bit 7 – FOC0A: Force Output Compare A The FOC0A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility ...
Page 107
Table 14-9. CS02 external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature ...
Page 108
TIMSK0 – Timer/Counter Interrupt Mask Register Bit (0x6E) Read/Write Initial Value • Bits 7..3 – Res: Reserved Bits These bits are reserved bits in the ATmega48P/88P/168P and will always read as zero. • Bit 2 – OCIE0B: Timer/Counter Output ...
Page 109
Bit 0 – TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one ...
Page 110
Timer/Counter1 with PWM 15.1 Features • True 16-bit Design (i.e., Allows 16-bit PWM) • Two independent Output Compare Units • Double Buffered Output Compare Registers • One Input Capture Unit • Input Capture Noise Canceler • Clear Timer ...
Page 111
Figure 15-1. 16-bit Timer/Counter Block Diagram Note: 15.2.1 Registers The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Regis- ter (ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16- bit registers. These procedures are ...
Page 112
Compare Units” on page Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request. The Input Capture Register can capture the Timer/Counter value at a given external (edge trig- gered) event on either the Input Capture ...
Page 113
Assembly Code Examples C Code Examples Note: The assembly code example returns the TCNT1 value in the r17:r16 register pair important to notice that accessing 16-bit registers are atomic operations interrupt occurs between the two instructions ...
Page 114
Assembly Code Example TIM16_ReadTCNT1: C Code Example unsigned int TIM16_ReadTCNT1( void ) { } Note: The assembly code example returns the TCNT1 value in the r17:r16 register pair. The following code examples show how atomic write of ...
Page 115
Assembly Code Example TIM16_WriteTCNT1: C Code Example void TIM16_WriteTCNT1( unsigned int Note: The assembly code example requires that the r17:r16 register pair contains the value to be writ- ten to TCNT1. 15.3.1 Reusing the Temporary High ...
Page 116
Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 15-2 Figure 15-2. Counter Unit Block Diagram Signal description (internal signals): Count Direction Clear clk TOP BOTTOM The 16-bit counter is mapped ...
Page 117
The Timer/Counter Overflow Flag (TOV1) is set according to the mode of operation selected by the WGM13:0 bits. TOV1 can be used for generating a CPU interrupt. 15.6 Input Capture Unit The Timer/Counter incorporates an Input Capture unit that can ...
Page 118
TOP value can be written to the ICR1 Register. When writing the ICR1 Register the high byte must be written to the ICR1H I/O location before the low byte is written ...
Page 119
I/O bit location). For measuring frequency only, the clearing of the ICF1 Flag is not required (if an interrupt handler is used). 15.7 Output Compare Units The 16-bit comparator continuously compares ...
Page 120
PWM pulses, thereby making the out- put glitch-free. The OCR1x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR1x Buffer ...
Page 121
Compare Match Output Unit The Compare Output mode (COM1x1:0) bits have two functions. The Waveform Generator uses the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next compare match. Secondly the COM1x1:0 bits control the OC1x ...
Page 122
PWM refer to page 132. A change of the COM1x1:0 bits state will have effect at the first compare match after the bits are written. ...
Page 123
Figure 15-6. CTC Mode, Timing Diagram TCNTn OCnA (Toggle) Period An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag according to the register used to define ...
Page 124
The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the max- imum resolution is 16-bit ...
Page 125
When the OCR1A I/O location is written the value written will be put into the OCR1A Buffer Register. The OCR1A Compare Register will then be updated with the value in the Buffer Register at the next ...
Page 126
OCR1A set to MAX). The PWM resolu- tion in bits can be calculated by using the following equation: In phase correct PWM mode the counter is incremented until the counter value ...
Page 127
TOP value, while the length of the rising slope is determined by the new TOP value. When these two values differ the two slopes of the period ...
Page 128
OCR1A set to MAX). The PWM resolution in bits can be calculated using the following equation: In phase and frequency correct PWM mode the counter is incremented until the counter value matches either ...
Page 129
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively ...
Page 130
Figure 15-11. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (f Figure 15-12 frequency correct PWM mode the OCR1x Register is updated at BOTTOM. The timing diagrams will be the same, but TOP should be replaced by BOTTOM, TOP-1 by ...
Page 131
Figure 15-13 Figure 15-13. Timer/Counter Timing Diagram, with Prescaler (f and ICF n 15.11 Register Description 15.11.1 TCCR1A – Timer/Counter1 Control Register A Bit (0x80) Read/Write Initial Value • Bit 7:6 – COM1A1:0: Compare Output Mode for Channel A • ...
Page 132
Table 15-2 PWM mode. Table 15-2. COM1A1/COM1B1 Note: Table 15-3 correct or the phase and frequency correct, PWM mode. Table 15-3. COM1A1/COM1B1 Note: • Bit 1:0 – WGM11:0: Waveform Generation Mode Combined with the WGM13:2 bits found in the TCCR1B ...
Page 133
Table 15-4. Waveform Generation Mode Bit Description WGM12 WGM11 Mode WGM13 (CTC1) (PWM11 ...
Page 134
When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequently the Input Cap- ture function is disabled. • Bit 5 – Reserved ...
Page 135
TCNT1H and TCNT1L – Timer/Counter1 Bit (0x85) (0x84) Read/Write Initial Value The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To ensure ...
Page 136
ICR1H and ICR1L – Input Capture Register 1 Bit (0x87) (0x86) Read/Write Initial Value The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin (or optionally on the Analog Comparator ...
Page 137
TIFR1 – Timer/Counter1 Interrupt Flag Register Bit 0x16 (0x36) Read/Write Initial Value • Bit 7, 6 – Res: Reserved Bits These bits are unused bits in the ATmega48P/88P/168P, and will always read as zero. • Bit 5 – ICF1: ...
Page 138
Timer/Counter0 and Timer/Counter1 Prescalers ”8-bit Timer/Counter0 with PWM” on page 91 110 share the same prescaler module, but the Timer/Counters can have different prescaler set- tings. The description below applies to both Timer/Counter1 and Timer/Counter0. 16.1 Internal Clock Source ...
Page 139
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least one system clock cycle, otherwise risk that a false Timer/Counter clock pulse is generated. Each half period of the ...
Page 140
Register Description 16.4.1 GTCCR – General Timer/Counter Control Register Bit 0x23 (0x43) Read/Write Initial Value • Bit 7 – TSM: Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the value ...
Page 141
Timer/Counter2 with PWM and Asynchronous Operation 17.1 Features • Single Channel Counter • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) • Frequency Generator • 10-bit Clock Prescaler • Overflow and ...
Page 142
Registers The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit reg- isters. Interrupt request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR2). All interrupts are individually masked with the Timer ...
Page 143
Figure 17-2. Counter Unit Block Diagram Signal description (internal signals): count direction clear clk top bottom Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk selected by the Clock Select ...
Page 144
Figure 17-3. Output Compare Unit, Block Diagram The OCR2x Register is double buffered when using any of the Pulse Width Modulation (PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. ...
Page 145
The setup of the OC2x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC2x value is to use the Force Output Com- pare (FOC2x) strobe bit in ...
Page 146
Compare Output Mode and Waveform Generation The Waveform Generator uses the COM2x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM2x1 tells the Waveform Generator that no action on the OC2x Register ...
Page 147
Figure 17-5. CTC Mode, Timing Diagram TCNTn OCnx (Toggle) Period An interrupt can be generated each time the counter value reaches the TOP value by using the OCF2A Flag. If the interrupt is enabled, the interrupt handler routine can be ...
Page 148
In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in togram for ...
Page 149
OC2A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 17.7.4 Phase Correct PWM Mode ...
Page 150
COM2x1:0 to three. TOP is defined as 0xFF when WGM2 and OCR2A when MGM2 (See value will only be visible on the port pin if the data direction for ...
Page 151
Figure 17-9. Timer/Counter Timing Diagram, with Prescaler (f clk clk (clk TCNTn TOVn Figure 17-10 Figure 17-10. Timer/Counter Timing Diagram, Setting of OCF2A, with Prescaler (f clk clk (clk TCNTn OCRnx OCFnx Figure 17-11 Figure 17-11. Timer/Counter Timing Diagram, Clear ...
Page 152
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 ...
Page 153
Description of wake up from Power-save or ADC Noise Reduction mode when the timer is clocked asynchronously: When the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, ...
Page 154
When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port C. A crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock source for Timer/Counter2. The Oscillator is optimized for ...
Page 155
Register Description 17.11.1 TCCR2A – Timer/Counter Control Register A Bit (0xB0) Read/Write Initial Value • Bits 7:6 – COM2A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC2A) behavior. If one or both of the ...
Page 156
Table 17-4 rect PWM mode. Table 17-4. COM2A1 Note: • 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 ...
Page 157
Note: Table 17-7 rect PWM mode. Table 17-7. COM2B1 Note: • Bits 3, 2 – Res: Reserved Bits These bits are reserved bits in the ATmega48P/88P/168P and will always read as zero. • Bits 1:0 – ...
Page 158
TCCR2B – Timer/Counter Control Register B Bit (0xB1) Read/Write Initial Value • Bit 7 – FOC2A: Force Output Compare A The FOC2A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with ...
Page 159
Table 17-9. CS22 external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature ...
Page 160
TIMSK2 – Timer/Counter2 Interrupt Mask Register Bit (0x70) Read/Write Initial Value • Bit 2 – OCIE2B: Timer/Counter2 Output Compare Match B Interrupt Enable When the OCIE2B bit is written to one and the I-bit in the Status Register is ...
Page 161
ASSR – Asynchronous Status Register Bit (0xB6) Read/Write Initial Value • Bit 7 – RES: Reserved bit This bit is reserved and will always read as zero. • Bit 6 – EXCLK: Enable External Clock Input When EXCLK is ...
Page 162
The mechanisms for reading TCNT2, OCR2A, OCR2B, TCCR2A and TCCR2B are different. When reading TCNT2, the actual timer value is read. When reading OCR2A, OCR2B, TCCR2A and TCCR2B the value in the temporary storage register is read. 17.11.9 GTCCR – ...
Page 163
SPI – Serial Peripheral Interface 18.1 Features • Full-duplex, Three-wire Synchronous Data Transfer • Master or Slave Operation • LSB First or MSB First Data Transfer • Seven Programmable Bit Rates • End of Transmission Interrupt Flag • Write ...
Page 164
The interconnection between Master and Slave CPUs with SPI is shown in 164. 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 ...
Page 165
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to ”Alternate Port Functions” on page Table 18-1. Pin MOSI MISO SCK SS Note: The following code examples show how to ...
Page 166
Assembly Code Example SPI_MasterInit: SPI_MasterTransmit: Wait_Transmit: C Code Example void SPI_MasterInit(void void SPI_MasterTransmit(char cData Note: 8025K–AVR–10/09 (1) ; Set MOSI and SCK output, all others input ldi r17,(1<<DD_MOSI)|(1<<DD_SCK) out DDR_SPI,r17 ; Enable SPI, Master, set clock ...
Page 167
The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example SPI_SlaveInit: SPI_SlaveReceive: C Code Example void SPI_SlaveInit(void char SPI_SlaveReceive(void Note: 8025K–AVR–10/09 (1) ; ...
Page 168
SS Pin Functionality 18.3.1 Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so ...
Page 169
Figure 18-3. SPI Transfer Format with CPHA = 0 Figure 18-4. SPI Transfer Format with CPHA = 1 8025K–AVR–10/09 SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 ...
Page 170
Register Description 18.5.1 SPCR – SPI Control Register Bit 0x2C (0x4C) Read/Write Initial Value • Bit 7 – SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is ...
Page 171
Bits 1, 0 – SPR1, SPR0: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have no effect on the Slave. The relationship between ...
Page 172
SPDR – SPI Data Register Bit 0x2E (0x4E) Read/Write Initial Value The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. ...
Page 173
USART0 19.1 Features • Full Duplex Operation (Independent Serial Receive and Transmit Registers) • Asynchronous or Synchronous Operation • Master or Slave Clocked Synchronous Operation • High Resolution Baud Rate Generator • Supports Serial Frames with ...
Page 174
Figure 19-1. USART Block Diagram Note: 19.3 Clock Generation The Clock Generation logic generates the base clock for the Transmitter and Receiver. The USART supports four modes of clock operation: Normal asynchronous, Double Speed asyn- chronous, Master synchronous and Slave ...
Page 175
Figure 19-2 Figure 19-2. Clock Generation Logic, Block Diagram Signal description: txclk rxclk xcki operation. xcko fosc 19.3.1 Internal Clock Generation – The Baud Rate Generator Internal clock generation is used for the asynchronous and the synchronous master modes of ...
Page 176
Table 19-1 ing the UBRRn value for each mode of operation using an internally generated clock source. Table 19-1. Operating Mode Asynchronous Normal mode (U2Xn = 0) Asynchronous Double Speed mode (U2Xn = 1) Synchronous Master mode Note: BAUD f ...
Page 177
External Clock External clocking is used by the synchronous slave modes of operation. The description in this section refers to External clock input from the XCKn pin is sampled by a synchronization register to minimize the chance of meta-stability. ...
Page 178
A frame starts with the start bit followed by the least significant data bit. Then the next data bits total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit is inserted ...
Page 179
USART Initialization The USART has to be initialized before any communication can take place. The initialization pro- cess normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. ...
Page 180
For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 Registers. Assembly Code Example USART_Init: C Code Example #define FOSC 1843200 // Clock Speed #define BAUD 9600 #define MYUBRR FOSC/16/BAUD-1 void main( void ) ...
Page 181
XCKn pin will be overridden and used as transmission clock. 19.6.1 Sending Frames with Data Bit A data transmission is initiated by loading the transmit buffer with the data ...
Page 182
For the assembly code, the data to be sent is assumed to be stored in registers R17:R16. Assembly Code Example USART_Transmit: C Code Example void USART_Transmit( unsigned int data ) { } ...
Page 183
UDRn in order to clear UDREn or disable the Data Register Empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. The Transmit Complete (TXCn) Flag bit is set one when the entire frame in the Transmit ...
Page 184
UDRn will be masked to zero. The USART has to be initialized before the function can be used. Assembly Code Example USART_Receive: C Code Example unsigned char USART_Receive( void ) { } Note: ...
Page 185
Assembly Code Example USART_Receive: USART_ReceiveNoError: C Code Example unsigned int USART_Receive( void ) { } Note: The receive function example reads all the I/O Registers into the Register File before any com- putation is done. This gives an optimal receive ...
Page 186
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 buf- fer. This flag is one when unread ...
Page 187
The UPEn bit is set if the next character that can be read from the receive buffer had a Parity Error when received and the Parity Checking was enabled at that point (UPMn1 = 1). This bit is valid until ...
Page 188
Figure 19-5. Start Bit Sampling When the clock recovery logic detects a high (idle) to low (start) transition on the RxDn line, the start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in the ...
Page 189
Figure 19-7. Stop Bit Sampling and Next Start Bit Sampling The same majority voting is done to the stop bit as done for the other bits in the frame. If the stop bit is registered to have a logic 0 ...
Page 190
Table 19-2. # (Data+Parity Bit) Table 19-3. # (Data+Parity Bit) The recommendations of the maximum receiver baud rate error was made under the assump- tion that the Receiver and Transmitter equally divides the maximum total error. There are two possible ...
Page 191
When the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. When the frame type bit ...
Page 192
Register Description 19.10.1 UDRn – USART I/O Data Register n Bit Read/Write Initial Value The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address referred to as USART Data Register or UDRn. ...
Page 193
Data Register Empty interrupt (see description of the UDRIEn bit). UDREn is set after a reset to indicate that the Transmitter is ready. • Bit 4 – FEn: Frame Error This bit is set if the next character in the ...
Page 194
Bit 5 – UDRIEn: USART Data Register Empty Interrupt Enable n Writing this bit to one enables interrupt on the UDREn Flag. A Data Register Empty interrupt will be generated only if the UDRIEn bit is written to one, ...
Page 195
Bits 5:4 – UPMn1:0: Parity Mode These bits enable and set type of parity generation and check. If enabled, the Transmitter will automatically generate and send the parity of the transmitted data bits within each frame. The Receiver will ...
Page 196
Table 19-8. UCPOLn 0 1 19.10.5 UBRRnL and UBRRnH – USART Baud Rate Registers Bit Read/Write Initial Value • Bit 15:12 – Reserved Bits These bits are reserved for future use. For compatibility with future devices, these bit must be ...
Page 197
Table 19-9. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies f = 1.0000 MHz osc Baud U2Xn = 0 Rate (bps) UBRRn Error UBRRn 2400 25 0.2% 51 4800 12 0.2% 25 9600 6 -7.0% 12 14.4k 3 8.5% ...
Page 198
Table 19-10. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued 3.6864 MHz osc Baud U2Xn = 0 U2Xn = 1 Rate (bps) UBRRn Error UBRRn 2400 95 0.0% 191 4800 47 0.0% 95 9600 23 0.0% ...
Page 199
Table 19-11. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued 8.0000 MHz osc Baud U2Xn = 0 U2Xn = 1 Rate (bps) UBRRn Error UBRRn 2400 207 0.2% 416 4800 103 0.2% 207 9600 51 0.2% ...
Page 200
Table 19-12. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued 16.0000 MHz osc Baud U2Xn = 0 U2Xn = 1 Rate (bps) UBRRn Error UBRRn 2400 416 -0.1% 832 4800 207 0.2% 416 9600 103 0.2% ...