ATmega328P Automotive Atmel Corporation, ATmega328P Automotive Datasheet
ATmega328P Automotive
Specifications of ATmega328P Automotive
Related parts for ATmega328P Automotive
ATmega328P Automotive 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 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 VCC ...
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 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 that PC6..4 use digital supply voltage, V 1.1.8 AREF AREF is ...
Page 5
Overview The ATmega328P 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 ATmega328P achieves throughputs approaching 1 MIPS per MHz allowing the system designer to ...
Page 6
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 ...
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 ...
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
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation typ- ical ALU operation, two operands are output from the Register ...
Page 10
Status Register The Status Register contains information about the result of the most recently executed arithme- tic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is ...
Page 11
Bit 0 – C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set Description” for detailed information. 6.4 General Purpose Register File The Register File is optimized for the ...
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 ATmega328P. The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega328P features an EEPROM Memory for data ...
Page 17
Figure 7-1. 7.3 SRAM Data Memory Figure 7-2 The ATmega328P is a complex microcontroller with more peripheral units than can be sup- ported within the 64 locations reserved in the Opcode for the IN and OUT instructions. For the Extended ...
Page 18
Figure 7-2. 7.3.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 clk Figure 7-3. 7.4 EEPROM Data Memory The ATmega328P contains 1K byte ...
Page 19
EEPROM Read/Write Access The EEPROM Access Registers are accessible in the I/O space. The write access time for the EEPROM is given in lets the user software detect when the next byte can be written. If the user code ...
Page 20
Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI instructions will only operate on the specified bit, and can therefore be used on registers containing ...
Page 21
EECR – The EEPROM Control Register Bit 0x1F (0x3F) Read/Write Initial Value • Bits 7..6 – Res: Reserved Bits These bits are reserved bits in the ATmega328P and will always read as zero. • Bits 5, 4 – EEPM1 ...
Page 22
Write a logical one to the EEMPE bit while writing a zero to EEPE in EECR. 6. Within four clock cycles after setting EEMPE, write a logical one to EEPE. The EEPROM can not be programmed during a CPU ...
Page 23
Assembly Code Example EEPROM_write: C Code Example void EEPROM_write(unsigned int uiAddress, unsigned char ucData 7810A–AVR–11/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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 on page 307 See “System Clock ...
Page 33
When this clock source is selected, start-up times are determined by the SUT Fuses as shown in Table 8-13. Table 8-13. Power Conditions BOD enabled Fast rising power Slowly rising power Note: 8.8 External Clock To drive the device from ...
Page 34
When applying an external clock required to avoid sudden changes in the applied clock fre- quency to ensure stable operation of the MCU. A variation in frequency of more than 2% from one clock cycle to the next ...
Page 35
To avoid unintentional changes of clock frequency, a special write procedure must befollowed to change the CLKPS bits: 1. Write the Clock Prescaler Change Enable (CLKPCE) bit to one and all other bitsin CLKPR to zero. 2. Within four cycles, ...
Page 36
Bits 3..0 – CLKPS3..0: Clock Prescaler Select Bits These bits define the division factor between the selected clock source and the internal system clock. These bits can be written run-time to vary the clock frequency to ...
Page 37
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 38
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 39
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, and the ...
Page 40
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 41
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 ...
Page 42
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 43
The BODS bit is active three clock cycles after it is set. A sleep instruction must be executed while BODS is active in order to turn off the BOD for the actual sleep mode. The BODS bit is automatically cleared ...
Page 44
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 ATmega328P, the instruction placed at the Reset Vector must ...
Page 45
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 46
Figure 10-2. MCU Start-up, RESET Tied to V RESET TIME-OUT INTERNAL RESET Figure 10-3. . MCU Start-up, RESET Extended Externally RESET TIME-OUT INTERNAL RESET Table 10-1. Symbol V POT V PORMAX V PORMIN V CCRR Note: ATmega328P [Preliminary ...
Page 47
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 not running. Shorter pulses are not guaranteed to generate ...
Page 48
Watchdog System Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period t page 49 Figure ...
Page 49
Watchdog Timer 10.8.1 Features • 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 ...
Page 50
The sequence for clearing WDE and changing time-out configuration is as follows the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of ...
Page 51
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 52
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 53
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 54
Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hard- ware (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 ...
Page 55
Table 10-3. WDP3 7810A–AVR–11/09 ATmega328P [Preliminary] Watchdog Timer Prescale Select Number of WDT Oscillator WDP2 WDP1 WDP0 ...
Page 56
Interrupts This section describes the specifics of the interrupt handling as performed in ATmega328P. For a general explanation of the AVR interrupt handling, refer to page 14. • Each Interrupt Vector occupies two instruction words in ATmega328P. • In ...
Page 57
Table 11-2 on page 57 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 58
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program ...
Page 59
Register Description 11.2.1 Moving Interrupts Between Application and Boot Space, ATmega88P, ATmega168P and ATmega328P The MCU Control Register controls the placement of the Interrupt Vector table. 11.2.2 MCUCR – ...
Page 60
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as ...
Page 61
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 62
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 63
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 ATmega328P, and will always read as zero. • Bit 1 – INT1: External ...
Page 64
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 ATmega328P, and will always read as zero. • Bit 2 - PCIE2: Pin ...
Page 65
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 66
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 67
Ports as General Digital I/O The ports are bi-directional I/O ports with optional internal pull-ups. tional description of one I/O-port pin, here generically called Pxn. Figure 13-2. General Digital I/O Note: 13.2.1 Configuring the Pin Each port pin consists ...
Page 68
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. 13.2.3 Switching Between ...
Page 69
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 70
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 71
Unconnected Pins If some pins are unused recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, float- ing inputs ...
Page 72
Figure 13-5. Alternate Port Functions Pxn PUOExn: PUOVxn: DDOExn: DDOVxn: PVOExn: PVOVxn: DIEOExn: Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE DIEOVxn: Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE SLEEP: PTOExn: Note: ATmega328P [Preliminary] 72 (1) PUOExn PUOVxn 1 0 DDOExn DDOVxn 1 0 PVOExn ...
Page 73
Table 13-2 ure 13-5 on page 72 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 74
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 75
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 76
OC1A/PCINT1 – Port B, Bit 1 OC1A, Output Compare Match output: The PB1 pin can serve as an external output for the Timer/Counter1 Compare Match A. The PB1 pin has to be configured as an output (DDB1 set (one)) ...
Page 77
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 7810A–AVR–11/09 Overriding Signals for Alternate Functions ...
Page 78
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 an input pin, and the part will have to rely on Power-on Reset ...
Page 79
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 80
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 ATmega328P [Preliminary] 80 Overriding Signals for ...
Page 81
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 82
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 83
Table 13-11. Overriding Signals for Alternate Functions in PD3..PD0 Signal Name PUOE PUO DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO 7810A–AVR–11/09 ATmega328P [Preliminary] PD3/OC2B/INT1/ PD2/INT0/ PCINT19 PCINT18 OC2B ENABLE 0 OC2B ...
Page 84
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 85
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 86
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 87
Definitions Many register and bit references in this section are written in general form. A lower case “n” replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Com- pare Unit, in this case ...
Page 88
Figure 14-2. Counter Unit Block Diagram Signal description (internal signals): count direction clear clk top bottom Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk selected by the Clock Select ...
Page 89
Figure 14-3. Output Compare Unit, Block Diagram The OCR0x Registers are double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the dou- ble buffering is ...
Page 90
The setup of the OC0x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC0x value is to use the Force Output Com- pare (FOC0x) strobe bits in ...
Page 91
Compare Output Mode and Waveform Generation The Waveform Generator uses the COM0x1:0 bits differently in Normal, CTC, and PWM modes. For all modes, setting the COM0x1 tells the Waveform Generator that no action on the OC0x Register ...
Page 92
Figure 14-5. CTC Mode, Timing Diagram TCNTn OCn (Toggle) Period An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be ...
Page 93
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 94
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by set- ting OC0x to toggle its logical level on each compare match (COM0x1:0 = 1). The waveform generated will have a maximum frequency of ...
Page 95
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 ...
Page 96
Figure 14-9 Figure 14-9. Timer/Counter Timing Diagram, with Prescaler (f clk clk (clk TCNTn TOVn Figure 14-10 mode and PWM mode, where OCR0A is TOP. Figure 14-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (f clk clk (clk TCNTn ...
Page 97
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 98
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 99
Table 14-7 rect PWM mode. Table 14-7. COM0B1 Note: • Bits 3, 2 – Res: Reserved Bits These bits are reserved bits in the ATmega328P and will always read as zero. • Bits 1:0 – WGM01:0: ...
Page 100
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 101
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 102
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 ATmega328P and will always read as zero. • Bit 2 – OCIE0B: Timer/Counter Output ...
Page 103
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 104
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 105
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 described ...
Page 106
The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Coun- ter 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 ...
Page 107
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 108
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 109
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 110
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 111
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 112
The ICR1 Register can only be written when using a Waveform Generation mode that utilizes the ICR1 Register for defining the counter’s TOP value. In these cases the Waveform Genera- tion mode (WGM13:0) bits must be set before the TOP ...
Page 113
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after each capture. Changing the edge sensing must be done as early as possible after the ICR1 Register has been read. After a change of the ...
Page 114
The OCR1x Register is double buffered when using any of the twelve 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 ...
Page 115
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 116
Compare Output Mode and Waveform Generation The Waveform Generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM1x1 tells the Waveform Generator that no action on the OC1x Register ...
Page 117
The timing diagram for the CTC mode is shown in increases until a compare match occurs with either OCR1A or ICR1, and then counter (TCNT1) is cleared. Figure 15-6. CTC Mode, Timing Diagram TCNTn OCnA (Toggle) Period An interrupt can ...
Page 118
Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM13 14, or 15) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM options by its ...
Page 119
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 ...
Page 120
Phase Correct PWM Mode The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13 10, or 11) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is, ...
Page 121
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is set accord- ingly at the same timer clock cycle ...
Page 122
Phase and Frequency Correct PWM Mode The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM mode (WGM13 provides a high resolution phase and frequency correct PWM wave- form generation option. ...
Page 123
Figure 15-9. Phase and Frequency Correct PWM Mode, Timing Diagram TCNTn OCnx OCnx Period The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x Registers are updated with the double buffer value (at BOTTOM). ...
Page 124
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 phase correct PWM mode. If the OCR1x is set ...
Page 125
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 BOTTOM+1 and so on. The same renaming applies for modes that ...
Page 126
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 • Bit 5:4 – COM1B1:0: Compare Output Mode for Channel B The COM1A1:0 and ...
Page 127
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 Register, these bits control the counting sequence of ...
Page 128
Table 15-4. Waveform Generation Mode Bit Description WGM12 Mode WGM13 (CTC1) (PWM11 ...
Page 129
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 130
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 131
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 132
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 ATmega328P, and will always read as zero. • Bit 5 – ICF1: ...
Page 133
Timer/Counter0 and Timer/Counter1 Prescalers “8-bit Timer/Counter0 with PWM” on page 86 104 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 134
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 135
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 136
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 137
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 138
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 139
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 140
Using the Output Compare Unit Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT2 when using the Output Compare channel, independently of whether ...
Page 141
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 out- put) is still controlled by the Data Direction ...
Page 142
Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the ...
Page 143
Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM22 provides a high fre- quency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. ...
Page 144
The PWM frequency for the output can be calculated by the following equation: The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). The extreme values for the OCR2A Register represent special cases when generating ...
Page 145
Figure 17-7. Phase Correct PWM Mode, Timing Diagram TCNTn OCnx OCnx Period The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches ...
Page 146
OCR2A changes its value from MAX, like in OCn pin value is the same as the result of a down-counting compare match. To ensure symmetry around BOTTOM the OCn value at MAX must correspond to the result of an ...
Page 147
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 Timer on Compare Match mode, with Pres- clk clk (clk TCNTn (CTC) OCRnx OCFnx 17.9 ...
Page 148
Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode before the changes are effective. This is particularly important if any of the Output Compare2 interrupt is used to wake up the device, since the ...
Page 149
During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous timer takes 3 processor cycles plus one timer cycle. The timer is therefore advanced by at least one before the processor can read the timer value causing the ...
Page 150
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 151
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 152
Table 17-7 rect PWM mode. Table 17-7. COM2B1 Note: • Bits 3, 2 – Res: Reserved Bits These bits are reserved bits in the ATmega328P and will always read as zero. • Bits 1:0 – WGM21:0: ...
Page 153
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 154
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 155
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 156
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 157
If a write is performed to any of the five Timer/Counter2 Registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur. The mechanisms for reading TCNT2, OCR2A, OCR2B, TCCR2A ...
Page 158
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 159
The interconnection between Master and Slave CPUs with SPI is shown in 159. 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 160
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 161
Assembly Code Example SPI_MasterInit: SPI_MasterTransmit: Wait_Transmit: C Code Example void SPI_MasterInit(void void SPI_MasterTransmit(char cData Note: 7810A–AVR–11/09 (1) ; Set MOSI and SCK output, all others input r17,(1<<DD_MOSI)|(1<<DD_SCK) ldi out DDR_SPI,r17 ; Enable SPI, Master, set clock ...
Page 162
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: ATmega328P [Preliminary] 162 ...
Page 163
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 164
Figure 18-3. SPI Transfer Format with CPHA = 0 Figure 18-4. SPI Transfer Format with CPHA = 1 18.5 Register Description 18.5.1 SPCR – SPI Control Register Bit 0x2C (0x4C) Read/Write Initial Value • Bit 7 – SPIE: SPI Interrupt ...
Page 165
Bit 5 – DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted ...
Page 166
SPSR – SPI Status Register Bit 0x2D (0x4D) Read/Write Initial Value • Bit 7 – SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is ...
Page 167
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 168
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 169
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 170
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 171
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 172
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 173
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 174
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 ) { ... ... } void USART_Init( unsigned int ubrr Note: More advanced initialization routines can ...
Page 175
Data Transmission – The USART Transmitter The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRnB Register. When the Transmitter is enabled, the normal port operation of the TxDn pin is overrid- den by ...
Page 176
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 ...
Page 177
When the Data Register Empty Interrupt Enable (UDRIEn) bit in UCSRnB is written to one, the USART Data Register Empty Interrupt will be executed as long as UDREn is set (provided that global interrupts are enabled). UDREn is cleared by ...
Page 178
The following code example shows a simple USART receive function based on polling of the Receive Complete (RXCn) Flag. When using frames with less than eight bits the most significant bits of the data read from the UDRn will be ...
Page 179
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 180
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 181
Parity Checker The Parity Checker is active when the high USART Parity mode (UPMn1) bit is set. Type of Par- ity Check to be performed (odd or even) is selected by the UPMn0 bit. When enabled, the Parity Checker ...
Page 182
Asynchronous Data Reception The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames ...
Page 183
Figure 19-6. Sampling of Data and Parity Bit The decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. ...
Page 184
The following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate slow Table 19-2 on page 184 that can be tolerated. Note that Normal ...
Page 185
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 sources for the receivers baud ...
Page 186
Using MPCMn For an MCU to act as a master MCU, it can use a 9-bit character frame format (UCSZn = 7). The ninth bit (TXB8n) must be set when an address frame (TXB8n = 1) or cleared when ...
Page 187
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 188
Bit 5 – UDREn: USART Data Register Empty The UDREn Flag indicates if the transmit buffer (UDRn) is ready to receive new data. If UDREn is one, the buffer is empty, and therefore ready to be written. The UDREn ...
Page 189
Bit 6 – TXCIEn: TX Complete Interrupt Enable n 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 ...
Page 190
Table 19-4. UMSELn1 Note: • 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 ...
Page 191
Table 19-7. UCSZn2 • Bit 0 – UCPOLn: Clock Polarity This bit is used for synchronous mode only. Write this bit to zero when asynchronous mode is used. The UCPOLn bit sets the relationship between data output change and data ...
Page 192
Examples of Baud Rate Setting For standard crystal and resonator frequencies, the most commonly used baud rates for asyn- chronous operation can be generated by using the UBRRn settings in values which yield an actual baud rate differing less ...
Page 193
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 194
Table 19-11. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued 8.0000 MHz osc Baud U2Xn = 0 Rate (bps) UBRRn Error UBRRn 2400 207 0.2% 416 4800 103 0.2% 207 9600 51 0.2% 103 14.4k 34 ...
Page 195
Table 19-12. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies Baud Rate (bps) 2400 4800 9600 14.4k 19.2k 28.8k 38.4k 57.6k 76.8k 115.2k 230.4k 250k 0.5M 1M (1) Max. 1. 7810A–AVR–11/09 (Continued) U2Xn = 0 UBRRn 416 207 103 ...
Page 196
USART in SPI Mode 20.1 Features • Full Duplex, Three-wire Synchronous Data Transfer • Master Operation • Supports all four SPI Modes of Operation (Mode and 3) • LSB First or MSB First Data Transfer (Configurable ...
Page 197
Note: BAUD f UBRRn 20.4 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 ...
Page 198
The UDORDn bit in UCSRnC sets the frame format used by the USART in MSPIM mode. The Receiver and Transmitter use the same setting. Note that changing the setting of any of these bits will corrupt all ongoing communication for ...
Page 199
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 void USART_Init( unsigned int baud ) { } ...
Page 200
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 ...