Features • High Performance, Low Power AVR 8-Bit Microcontroller • Advanced RISC Architecture • • • • • • • • – 131 Powerful Instructions – Most Single Clock Cycle Execution – 32 x 8 General Purpose Working Registers – Fully Static Operation – Up to 16 MIPS Throughput at 16 MHz – On-chip 2-cycle Multiplier High Endurance Non-volatile Memory Segments – 32K Bytes of In-System Self-Programmable Flash program memory – 1K Bytes EEPROM – 2K Bytes Internal SRAM – Write/Erase Cycles: 10,000 Flash/100,000 EEP
1. Pin Configurations Figure 1-1.
Atmel ATmega328P [Preliminary] 1.1 1.1.1 Pin Descriptions VCC Digital supply voltage. 1.1.2 GND Ground. 1.1.3 Port B (PB7:0) XTAL1/XTAL2/TOSC1/TOSC2 Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated.
1.1.7 AVCC AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6..4 use digital supply voltage, VCC. 1.1.8 AREF AREF is the analog reference pin for the A/D Converter. 1.1.9 1.2 ADC7:6 (TQFP and QFN/MLF Package Only) In the TQFP and QFN/MLF package, ADC7:6 serve as analog inputs to the A/D converter.
Atmel ATmega328P [Preliminary] 2. 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 optimize power consumption versus processing speed. Block Diagram Block Diagram GND Figure 2-1. VCC 2.
The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
Atmel ATmega328P [Preliminary] 3. Resources A comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr. Note: 1. 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. 5. About Code Examples This documentation contains simple code examples that briefly show how to use various parts of the device.
6. 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 peripherals, and handle interrupts. Figure 6-1.
Atmel ATmega328P [Preliminary] The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical 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.
6.3 Status Register The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code.
Atmel ATmega328P [Preliminary] • 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 AVR Enhanced RISC instruction set.
6.4.1 The X-register, Y-register, and Z-register The registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as described in Figure 6-3. Figure 6-3.
Atmel ATmega328P [Preliminary] 6.5.
6.7 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 written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt.
Atmel ATmega328P [Preliminary] Assembly Code Example in r16, SREG cli ; store SREG value ; disable interrupts during timed sequence sbi EECR, EEMPE ; start EEPROM write sbi EECR, EEPE out SREG, r16 ; restore SREG value (I-bit) C Code Example char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ _CLI(); EECR |= (1<
7. 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 storage. All three memory spaces are linear and regular. 7.2 In-System Reprogrammable Flash Program Memory The ATmega328P contains 32K bytes On-chip In-System Reprogrammable Flash memory for program storage.
Atmel ATmega328P [Preliminary] Figure 7-1. Program Memory Map ATmega328P Program Memory 0x0000 Application Flash Section Boot Flash Section 0x3FFF 7.3 SRAM Data Memory Figure 7-2 shows how the ATmega328P SRAM Memory is organized. The ATmega328P 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.
Figure 7-2. Data Memory Map Data Memory 0x0000 - 0x001F 0x0020 - 0x005F 0x0060 - 0x00FF 0x0100 32 Registers 64 I/O Registers 160 Ext I/O Reg. Internal SRAM (2048 x 8) 0x08FF 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 clkCPU cycles as described in Figure 7-3. Figure 7-3.
Atmel ATmega328P [Preliminary] 7.4.1 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 Table 7-2. A self-timing function, however, lets the user software detect when the next byte can be written. If the user code contains instructions that write the EEPROM, some precautions must be taken. In heavily filtered power supplies, VCC is likely to rise or fall slowly on power-up/down.
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 such Status Flags. The CBI and SBI instructions work with registers 0x00 to 0x1F only. The I/O and peripherals control registers are explained in later sections. 7.5.1 7.6 7.6.1 General Purpose I/O Registers The ATmega328P contains three General Purpose I/O Registers.
Atmel ATmega328P [Preliminary] 7.6.3 EECR – The EEPROM Control Register Bit 7 6 5 4 3 2 1 0 0x1F (0x3F) – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 0 0 X X 0 0 X 0 EECR • Bits 7..6 – Res: Reserved Bits These bits are reserved bits in the ATmega328P and will always read as zero.
5. 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 write to the Flash memory. The software must check that the Flash programming is completed before initiating a new EEPROM write. Step 2 is only relevant if the software contains a Boot Loader allowing the CPU to program the Flash. If the Flash is never being updated by the CPU, step 2 can be omitted.
Atmel ATmega328P [Preliminary] Assembly Code Example EEPROM_write: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to Data Register out EEDR,r16 ; Write logical one to EEMPE sbi EECR,EEMPE ; Start eeprom write by setting EEPE sbi EECR,EEPE ret C Code Example void EEPROM_write(unsigned int uiAddress, unsigned char ucData) { /* Wait for completion of previous write */ while(EECR & (1<
The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions.
Atmel ATmega328P [Preliminary] 8. System Clock and Clock Options 8.1 Clock Systems and their Distribution Figure 8-1 presents the principal clock systems in the AVR and their distribution. All of the clocks need not be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in “Power Management and Sleep Modes” on page 37. The clock systems are detailed below. Figure 8-1.
8.1.4 Asynchronous Timer Clock – clkASY The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clocked directly from an external clock or an external 32 kHz clock crystal. The dedicated clock domain allows using this Timer/Counter as a real-time counter even when the device is in sleep mode. 8.1.5 ADC Clock – clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce noise generated by digital circuitry.
Atmel ATmega328P [Preliminary] selectable delays are shown in Table 8-2. The frequency of the Watchdog Oscillator is voltage dependent as shown in “Typical Characteristics” on page 315. Table 8-2. Number of Watchdog Oscillator Cycles Typ Time-out (VCC = 5.0V) Typ Time-out (VCC = 3.0V) Number of Cycles 0 ms 0 ms 0 4.1 ms 4.3 ms 512 65 ms 69 ms 8K (8,192) Main purpose of the delay is to keep the AVR in reset until it is supplied with minimum VCC.
Figure 8-2. Crystal Oscillator Connections C2 XTAL2 (TOSC2) C1 XTAL1 (TOSC1) GND The Low Power Oscillator can operate in three different modes, each optimized for a specific frequency range. The operating mode is selected by the fuses CKSEL3..1 as shown in Table 8-3 on page 28. Table 8-3. Low Power Crystal Oscillator Operating Modes(2) Frequency Range (MHz) Recommended Range for Capacitors C1 and C2 (pF) CKSEL3..1 0.4 - 0.9 – 100(1) 0.9 - 3.0 12 - 22 101 3.0 - 8.0 12 - 22 110 8.0 - 16.
Atmel ATmega328P [Preliminary] Table 8-4. Start-up Times for the Low Power Crystal Oscillator Clock Selection (Continued) Start-up Time from Power-down and Power-save Additional Delay from Reset (VCC = 5.0V) CKSEL0 SUT1..0 Crystal Oscillator, BOD enabled 16K CK 14CK 1 01 Crystal Oscillator, fast rising power 16K CK 14CK + 4.1 ms 1 10 Crystal Oscillator, slowly rising power 16K CK 14CK + 65 ms 1 11 Oscillator Source / Power Conditions Notes: 8.4 1.
Figure 8-3. Crystal Oscillator Connections C2 XTAL2 (TOSC2) C1 XTAL1 (TOSC1) GND Table 8-6. Start-up Times for the Full Swing Crystal Oscillator Clock Selection Start-up Time from Power-down and Power-save Additional Delay from Reset (VCC = 5.0V) CKSEL0 SUT1..0 Ceramic resonator, fast rising power 258 CK 14CK + 4.
Atmel ATmega328P [Preliminary] 8.5 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 the crystal vendor. ATmega328P oscillator is optimized for very low power consumption, and thus when selecting crystals, see Table 8-7 on page 31 for maximum ESR recommendations on 6.5 pF, 9.
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 Table 28-1 on page 307 for more details. The device is shipped with the CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 34 for more details. This clock may be selected as the system clock by programming the CKSEL Fuses as shown in Table 8-10.
Atmel ATmega328P [Preliminary] When this clock source is selected, start-up times are determined by the SUT Fuses as shown in Table 8-13. Table 8-13. Start-up Times for the 128 kHz Internal Oscillator Start-up Time from Power-down and Power-save Additional Delay from Reset SUT1..0 BOD enabled 6 CK 14CK(1) 00 Fast rising power 6 CK 14CK + 4 ms 01 Slowly rising power 6 CK 14CK + 64 ms 10 Power Conditions Reserved Note: 8.8 11 1.
When applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable operation of the MCU. A variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. If changes of more than 2% is required, ensure that the MCU is kept in Reset during the changes. Note that the System Clock Prescaler can be used to implement run-time changes of the internal clock frequency while still ensuring stable operation.
Atmel ATmega328P [Preliminary] 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, write the desired value to CLKPS while writing a zero to CLKPCE. Interrupts must be disabled when changing prescaler setting to make sure the write procedure is not interrupted. 8.12 8.12.
• Bits 3..0 – CLKPS3..0: Clock Prescaler Select Bits 3 - 0 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 suit the application requirements. As the divider divides the master clock input to the MCU, the speed of all synchronous peripherals is reduced when a division factor is used. The division factors are given in Table 8-16 on page 36.
Atmel ATmega328P [Preliminary] 9. Power Management and Sleep Modes Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to the application’s requirements. When enabled, the Brown-out Detector (BOD) actively monitors the power supply voltage during the sleep periods. To further save power, it is possible to disable the BOD in some sleep modes.
9.2 BOD Disable When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses, Table 27-7 on page 289, the BOD is actively monitoring the power supply voltage during a sleep period. To save power, it is possible to disable the BOD by software for some of the sleep modes, see Table 9-1 on page 39. The sleep mode power consumption will then be at the same level as when BOD is globally disabled by fuses. If BOD is disabled in software, the BOD function is turned off immediately after entering the sleep mode.
Atmel ATmega328P [Preliminary] 9.5 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 Watchdog continue operating (if enabled).
9.9 Power Reduction Register The Power Reduction Register (PRR), see “PRR – Power Reduction Register” on page 43, provides 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 or written. Resources used by the peripheral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock.
Atmel ATmega328P [Preliminary] 9.10.4 Internal Voltage Reference The Internal Voltage Reference will be enabled when needed by the Brown-out Detection, the Analog Comparator or the ADC. If these modules are disabled as described in the sections above, the internal voltage reference will be disabled and it will not be consuming power. When turned on again, the user must allow the reference to start up before the output is used. If the reference is kept on in sleep mode, the output can be used immediately.
9.11 9.11.1 Register Description SMCR – Sleep Mode Control Register The Sleep Mode Control Register contains control bits for power management. Bit 7 6 5 4 3 2 1 0 0x33 (0x53) – – – – SM2 SM1 SM0 SE Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 SMCR • Bits 7..4 Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero. • Bits 3..1 – SM2..
Atmel ATmega328P [Preliminary] 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 after three clock cycles. • Bit 5 – BODSE: BOD Sleep Enable BODSE enables setting of BODS control bit, as explained in BODS bit description. BOD disable is controlled by a timed sequence. 9.11.
10. 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 be an RJMP – Relative Jump – instruction to the reset handling routine. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations.
Atmel ATmega328P [Preliminary] Figure 10-1. Reset Logic DATA BUS PORF BORF EXTRF WDRF MCU Status Register (MCUSR) Power-on Reset Circuit Brown-out Reset Circuit BODLEVEL [2..0] Pull-up Resistor SPIKE FILTER RSTDISBL Watchdog Oscillator Clock Generator CK Delay Counters TIMEOUT CKSEL[3:0] SUT[1:0] 10.3 Power-on Reset A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level is defined in “System and Reset Characteristics” on page 308.
Figure 10-2. MCU Start-up, RESET Tied to VCC VPOT VCC VRST RESET tTOUT TIME-OUT INTERNAL RESET Figure 10-3. . MCU Start-up, RESET Extended Externally VPOT VCC VRST RESET tTOUT TIME-OUT INTERNAL RESET Table 10-1. Symbol Power On Reset Specifications Parameter Min Power-on Reset Threshold Voltage (rising) VPOT Max 1.4 () 1.0 1.3 Units V 1.6 V 0.4 V VPORMAX VCC Max. start voltage to ensure internal Power-on Reset signal VPORMIN VCC Min.
Atmel ATmega328P [Preliminary] 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 “System and Reset Characteristics” on page 308) will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage – VRST – on its positive edge, the delay counter starts the MCU after the Time-out period – tTOUT – has expired.
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 Time-out period tTOUT. Refer to page 49 for details on operation of the Watchdog Timer. Figure 10-6. Watchdog System Reset During Operation CC CK 10.7 Internal Voltage Reference ATmega328P features an internal bandgap reference.
Atmel ATmega328P [Preliminary] 10.8 10.8.1 Watchdog Timer 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 (WDTON) for fail-safe mode 10.8.2 Overview ATmega328P has an Enhanced Watchdog Timer (WDT). The WDT is a timer counting cycles of a separate on-chip 128 kHz oscillator.
The sequence for clearing WDE and changing time-out configuration is as follows: 1. In the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit. 2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as desired, but with the WDCE bit cleared. This must be done in one operation.
Atmel ATmega328P [Preliminary] Assembly Code Example(1) WDT_off: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Clear WDRF in MCUSR in r16, MCUSR andi r16, (0xff & (0<
The following code example shows one assembly and one C function for changing the time-out value of the Watchdog Timer. Assembly Code Example(1) WDT_Prescaler_Change: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Start timed sequence lds r16, WDTCSR r16, (1<
Atmel ATmega328P [Preliminary] 10.9 10.9.1 Register Description MCUSR – MCU Status Register The MCU Status Register provides information on which reset source caused an MCU reset. Bit 7 6 5 4 3 2 1 0 0x35 (0x55) – – – – WDRF BORF EXTRF PORF Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 MCUSR See Bit Description • Bit 7..4: Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero.
Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the Watchdog goes to System Reset Mode). This is useful for keeping the Watchdog Timer security while using the interrupt. To stay in Interrupt and System Reset Mode, WDIE must be set after each interrupt. This should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the Watchdog System Reset mode.
Atmel ATmega328P [Preliminary] Table 10-3. Watchdog Timer Prescale Select WDP3 WDP2 WDP1 WDP0 Number of WDT Oscillator Cycles Typical Time-out at VCC = 5.0V 0 0 0 0 2K (2048) cycles 16 ms 0 0 0 1 4K (4096) cycles 32 ms 0 0 1 0 8K (8192) cycles 64 ms 0 0 1 1 16K (16384) cycles 0.125 s 0 1 0 0 32K (32768) cycles 0.25 s 0 1 0 1 64K (65536) cycles 0.5 s 0 1 1 0 128K (131072) cycles 1.0 s 0 1 1 1 256K (262144) cycles 2.
11. 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 “Reset and Interrupt Handling” on page 14. • Each Interrupt Vector occupies two instruction words in ATmega328P. • In ATmega328P, the Reset Vector is affected by the BOOTRST fuse, and the Interrupt Vector start address is affected by the IVSEL bit in MCUCR. 11.1 Interrupt Vectors in ATmega328P Table 11-1. Vector No.
Atmel ATmega328P [Preliminary] Table 11-2 on page 57 shows reset and Interrupt Vectors placement for the various combinations 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 if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. Table 11-2.
0x0035 ldi r16, low(RAMEND) 0x0036 out SPL,r16 0x0037 sei 0x0038 ... ; Enable interrupts ... ... xxx ...
Atmel ATmega328P [Preliminary] 0x3C04 jmp EXT_INT1 ; IRQ1 Handler ... ... ... ; 0x3C32 jmp SPM_RDY ; Store Program Memory Ready Handler ; 11.2 0x3C33 RESET: ldi r16,high(RAMEND); Main program start 0x3C34 out SPH,r16 0x3C35 ldi r16,low(RAMEND) 0x3C36 0x3C37 out sei SPL,r16 0x3C38 ; Set Stack Pointer to top of RAM ; Enable interrupts xxx Register Description 11.2.
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the IVSEL description above. See Code Example below.
Atmel ATmega328P [Preliminary] 12. External Interrupts The External Interrupts are triggered by the INT0 and INT1 pins or any of the PCINT23..0 pins. Observe that, if enabled, the interrupts will trigger even if the INT0 and INT1 or PCINT23..0 pins are configured as outputs. This feature provides a way of generating a software interrupt. The pin change interrupt PCI2 will trigger if any enabled PCINT23..16 pin toggles. The pin change interrupt PCI1 will trigger if any enabled PCINT14..8 pin toggles.
12.2 12.2.1 Register Description EICRA – External Interrupt Control Register A The External Interrupt Control Register A contains control bits for interrupt sense control. Bit 7 6 5 4 3 2 1 0 (0x69) – – – – ISC11 ISC10 ISC01 ISC00 Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 EICRA • Bit 7..4 – Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero.
Atmel ATmega328P [Preliminary] 12.2.2 EIMSK – External Interrupt Mask Register Bit 7 6 5 4 3 2 1 0 0x1D (0x3D) – – – – – – INT1 INT0 Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 EIMSK • Bit 7..2 – Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero.
12.2.4 PCICR – Pin Change Interrupt Control Register Bit 7 6 5 4 3 2 1 0 (0x68) – – – – – PCIE2 PCIE1 PCIE0 Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 PCICR • Bit 7..3 - Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero. • Bit 2 - PCIE2: Pin Change Interrupt Enable 2 When the PCIE2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 2 is enabled.
Atmel ATmega328P [Preliminary] • Bit 0 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT7..0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in SREG and the PCIE0 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. 12.2.
13. 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 the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input).
Atmel ATmega328P [Preliminary] 13.2 Ports as General Digital I/O The ports are bi-directional I/O ports with optional internal pull-ups. Figure 13-2 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 13-2. General Digital I/O(1) PUD Q D DDxn Q CLR WDx RESET DATA BUS RDx 1 Q Pxn D 0 PORTxn Q CLR RESET SLEEP RRx SYNCHRONIZER D Q L Q D WRx WPx RPx Q PINxn Q clk I/O PUD: SLEEP: clkI/O: Note: 13.2.
13.2.2 Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port. 13.2.3 Switching Between Input and Output When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur.
Atmel ATmega328P [Preliminary] Figure 13-3. Synchronization when Reading an Externally Applied Pin value SYSTEM CLK INSTRUCTIONS XXX XXX in r17, PINx SYNC LATCH PINxn r17 0x00 0xFF t pd, max t pd, min Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock goes low.
Assembly Code Example(1) ... ; Define pull-ups and set outputs high ; Define directions for port pins ldi r16,(1<
Atmel ATmega328P [Preliminary] 13.2.6 Unconnected Pins If some pins are unused, it is 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, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up.
Figure 13-5.
Atmel ATmega328P [Preliminary] Table 13-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 13-5 on page 72 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function. Table 13-2. Generic Description of Overriding Signals for Alternate Functions Signal Name Full Name Description PUOE Pull-up Override Enable If this signal is set, the pull-up enable is controlled by the PUOV signal.
13.3.1 Alternate Functions of Port B The Port B pins with alternate functions are shown in Table 13-3. Table 13-3.
Atmel ATmega328P [Preliminary] AS2 bit in ASSR is set (one) to enable asynchronous clocking of Timer/Counter2, pin PB6 is disconnected from the port, and becomes the input of the inverting Oscillator amplifier. In this mode, a crystal Oscillator is connected to this pin, and the pin can not be used as an I/O pin. PCINT6: Pin Change Interrupt source 6. The PB6 pin can serve as an external interrupt source. If PB6 is used as a clock pin, DDB6, PORTB6 and PINB6 will all read 0.
• 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)) to serve this function. 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.
Atmel ATmega328P [Preliminary] Table 13-5. 13.3.2 Overriding Signals for Alternate Functions in PB3..
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 and Brown-out Reset as its reset sources. When the RSTDISBL Fuse is unprogrammed, the reset circuitry is connected to the pin, and the pin can not be used as an input pin. If PC6 is used as a reset pin, DDC6, PORTC6 and PINC6 will all read 0. PCINT14: Pin Change Interrupt source 14.
Atmel ATmega328P [Preliminary] • ADC1/PCINT9 – Port C, Bit 1 PC1 can also be used as ADC input Channel 1. Note that ADC input channel 1 uses analog power. PCINT9: Pin Change Interrupt source 9. The PC1 pin can serve as an external interrupt source. • ADC0/PCINT8 – Port C, Bit 0 PC0 can also be used as ADC input Channel 0. Note that ADC input channel 0 uses analog power. PCINT8: Pin Change Interrupt source 8. The PC0 pin can serve as an external interrupt source.
Table 13-8. 13.3.
Atmel ATmega328P [Preliminary] 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 the function of the Analog Comparator. PCINT23: Pin Change Interrupt source 23. The PD7 pin can serve as an external interrupt source. • AIN0/OC0A/PCINT22 – Port D, Bit 6 AIN0, Analog Comparator Positive Input.
• 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 – Port D, Bit 1 TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1. PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
Atmel ATmega328P [Preliminary] Table 13-11. Overriding Signals for Alternate Functions in PD3..
13.4 13.4.1 Register Description MCUCR – MCU Control Register Bit 7 6 5 4 3 2 1 0 0x35 (0x55) – BODS BODSE PUD – – IVSEL IVCE Read/Write R R R R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 MCUCR • Bit 4 – PUD: Pull-up Disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01).
Atmel ATmega328P [Preliminary] 13.4.8 PORTD – The Port D Data Register Bit 13.4.9 7 6 5 4 3 2 1 0 0x0B (0x2B) PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 DDRD – The Port D Data Direction Register Bit 13.4.
14. 8-bit Timer/Counter0 with PWM 14.1 Features • • • • • • • 14.2 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 Frequency Generator Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B) Overview Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and with PWM support.
Atmel ATmega328P [Preliminary] 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 Compare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing Timer/Counter0 counter value and so on.
Figure 14-2. Counter Unit Block Diagram TOVn (Int.Req.) DATA BUS Clock Select count clear TCNTn Control Logic clkTn Edge Detector Tn direction ( From Prescaler ) bottom top Signal description (internal signals): count Increment or decrement TCNT0 by 1. direction Select between increment and decrement. clear Clear TCNT0 (set all bits to zero). clkTn Timer/Counter clock, referred to as clkT0 in the following. top Signalize that TCNT0 has reached maximum value.
Atmel ATmega328P [Preliminary] Figure 14-3. Output Compare Unit, Block Diagram DATA BUS OCRnx TCNTn = (8-bit Comparator ) OCFnx (Int.Req.) top bottom Waveform Generator OCnx FOCn WGMn1:0 COMnx1:0 The OCR0x Registers are double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled.
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 Compare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even when changing between Waveform Generation modes. Be aware that the COM0x1:0 bits are not double buffered together with the compare value. Changing the COM0x1:0 bits will take effect immediately. 14.
Atmel ATmega328P [Preliminary] 14.6.1 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:0 = 0 tells the Waveform Generator that no action on the OC0x Register is to be performed on the next compare match. For compare output actions in the non-PWM modes refer to Table 14-2 on page 97. For fast PWM mode, refer to Table 14-3 on page 97, and for phase correct PWM refer to Table 14-4 on page 98.
Figure 14-5. CTC Mode, Timing Diagram OCnx Interrupt Flag Set TCNTn OCn (Toggle) Period (COMnx1:0 = 1) 1 2 3 4 An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
Atmel ATmega328P [Preliminary] In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 14-6. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWM outputs.
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0x to toggle its logical level on each compare match (COM0x1:0 = 1). The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 14.7.
Atmel ATmega328P [Preliminary] In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A0 bits to one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (see Table 14-7 on page 99).
Figure 14-9 shows the same timing data, but with the prescaler enabled. Figure 14-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O /8) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 14-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC mode and PWM mode, where OCR0A is TOP. Figure 14-10.
Atmel ATmega328P [Preliminary] 14.9 14.9.1 Register Description TCCR0A – Timer/Counter Control Register A Bit 7 6 5 4 3 2 1 0 0x24 (0x44) COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 Read/Write R/W R/W R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR0A • Bits 7:6 – COM0A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC0A) behavior.
Table 14-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode. Table 14-4. Compare Output Mode, Phase Correct PWM Mode(1) COM0A1 COM0A0 0 0 Normal port operation, OC0A disconnected. 0 1 WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. 1 0 Clear OC0A on Compare Match when up-counting. Set OC0A on Compare Match when down-counting. 1 1 Set OC0A on Compare Match when up-counting.
Atmel ATmega328P [Preliminary] Table 14-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode. Table 14-7. Compare Output Mode, Phase Correct PWM Mode(1) COM0B1 COM0B0 0 0 Normal port operation, OC0B disconnected. 0 1 Reserved 1 0 Clear OC0B on Compare Match when up-counting. Set OC0B on Compare Match when down-counting. 1 1 Set OC0B on Compare Match when up-counting. Clear OC0B on Compare Match when down-counting. Note: Description 1.
14.9.2 TCCR0B – Timer/Counter Control Register B Bit 7 6 5 4 3 2 1 0 0x25 (0x45) FOC0A FOC0B – – WGM02 CS02 CS01 CS00 Read/Write W W R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR0B • Bit 7 – FOC0A: Force Output Compare A The FOC0A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode.
Atmel ATmega328P [Preliminary] Table 14-9. Clock Select Bit Description CS02 CS01 CS00 Description 0 0 0 No clock source (Timer/Counter stopped) 0 0 1 clkI/O/(No prescaling) 0 1 0 clkI/O/8 (From prescaler) 0 1 1 clkI/O/64 (From prescaler) 1 0 0 clkI/O/256 (From prescaler) 1 0 1 clkI/O/1024 (From prescaler) 1 1 0 External clock source on T0 pin. Clock on falling edge. 1 1 1 External clock source on T0 pin. Clock on rising edge.
14.9.6 TIMSK0 – Timer/Counter Interrupt Mask Register Bit 7 6 5 4 3 2 1 0 (0x6E) – – – – – OCIE0B OCIE0A TOIE0 Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIMSK0 • Bits 7..3 – Res: Reserved Bits These bits are reserved bits in the ATmega328P and will always read as zero.
Atmel ATmega328P [Preliminary] • Bit 0 – TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed. The setting of this flag is dependent of the WGM02:0 bit setting.
15. 16-bit Timer/Counter1 with PWM 15.1 Features • • • • • • • • • • • 15.2 True 16-bit Design (i.e.
Atmel ATmega328P [Preliminary] Figure 15-1. 16-bit Timer/Counter Block Diagram(1) Count Clear Direction TOVn (Int.Req.) Control Logic clkTn Clock Select Edge Detector TOP Tn BOTTOM ( From Prescaler ) Timer/Counter TCNTn = =0 OCnA (Int.Req.) Waveform Generation = OCnA DATA BUS OCRnA OCnB (Int.Req.) Fixed TOP Values Waveform Generation = OCRnB OCnB ( From Analog Comparator Ouput ) ICFn (Int.Req.) Edge Detector ICRn Noise Canceler ICPn TCCRnA Note: 15.2.1 TCCRnB 1.
The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Counter value at all time. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pin (OC1A/B). See “Output Compare Units” on page 113. The compare match event will also set the Compare Match Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request.
Atmel ATmega328P [Preliminary] Assembly Code Examples(1) ... ; Set TCNT1 to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNT1H,r17 out TCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ... C Code Examples(1) unsigned int i; ... /* Set TCNT1 to 0x01FF */ TCNT1 = 0x1FF; /* Read TCNT1 into i */ i = TCNT1; ... Note: 1. See ”About Code Examples” on page 7.
Assembly Code Example(1) TIM16_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 ret C Code Example(1) unsigned int TIM16_ReadTCNT1( void ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNT1 into i */ i = TCNT1; /* Restore global interrupt flag */ SREG = sreg; return i; } Note: 1.
Atmel ATmega328P [Preliminary] Assembly Code Example(1) TIM16_WriteTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Set TCNT1 to r17:r16 out TCNT1H,r17 out TCNT1L,r16 ; Restore global interrupt flag out SREG,r18 ret C Code Example(1) void TIM16_WriteTCNT1( unsigned int i ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNT1 to i */ TCNT1 = i; /* Restore global interrupt flag */ SREG = sreg; } Note: 1.
15.5 Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 15-2 shows a block diagram of the counter and its surroundings. Figure 15-2. Counter Unit Block Diagram DATA BUS (8-bit) TOVn (Int.Req.
Atmel ATmega328P [Preliminary] 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 capture external events and give them a time-stamp indicating time of occurrence. The external signal indicating an event, or multiple events, can be applied via the ICP1 pin or alternatively, via the analog-comparator unit.
The 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 Generation mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1 Register. When writing the ICR1 Register the high byte must be written to the ICR1H I/O location before the low byte is written to ICR1L. For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers” on page 106.
Atmel ATmega328P [Preliminary] Measurement of an external signal’s duty cycle requires that the trigger edge is changed after each capture. Changing the edge sensing must be done as early as possible after the ICR1 Register has been read. After a change of the edge, the Input Capture Flag (ICF1) must be cleared by software (writing a logical one to the I/O bit location). For measuring frequency only, the clearing of the ICF1 Flag is not required (if an interrupt handler is used). 15.
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 of the OCR1x Compare Register to either TOP or BOTTOM of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
Atmel ATmega328P [Preliminary] 15.8 Compare Match Output Unit The Compare Output mode (COM1x1:0) bits have two functions. The Waveform Generator uses the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next compare match. Secondly the COM1x1:0 bits control the OC1x pin output source. Figure 15-5 shows a simplified schematic of the logic affected by the COM1x1:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold.
15.8.1 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting the COM1x1:0 = 0 tells the Waveform Generator that no action on the OC1x Register is to be performed on the next compare match. For compare output actions in the non-PWM modes refer to Table 15-1 on page 126.
Atmel ATmega328P [Preliminary] The timing diagram for the CTC mode is shown in Figure 15-6. The counter value (TCNT1) increases until a compare match occurs with either OCR1A or ICR1, and then counter (TCNT1) is cleared. Figure 15-6.
15.9.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM13:0 = 5, 6, 7, 14, or 15) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x, and set at BOTTOM.
Atmel ATmega328P [Preliminary] When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x. Note that when using fixed TOP values the unused bits are masked to zero when any of the OCR1x Registers are written.
15.9.4 Phase Correct PWM Mode The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is, like the phase and frequency correct PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM.
Atmel ATmega328P [Preliminary] 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 accordingly at the same timer clock cycle as the OCR1x Registers are updated with the double buffer value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the counter reaches the TOP or BOTTOM value.
15.9.5 Phase and Frequency Correct PWM Mode The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequency correct PWM waveform generation option. The phase and frequency correct PWM mode is, like the phase correct PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM.
Atmel ATmega328P [Preliminary] Figure 15-9. Phase and Frequency Correct PWM Mode, Timing Diagram OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) OCRnx/TOP Updateand TOVn Interrupt Flag Set (Interrupt on Bottom) TCNTn OCnx (COMnx1:0 = 2) OCnx (COMnx1:0 = 3) Period 1 2 3 4 The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x Registers are updated with the double buffer value (at BOTTOM).
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 equal to BOTTOM the output will be continuously low and if set equal to TOP the output will be set to high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
Atmel ATmega328P [Preliminary] Figure 15-12 shows the count sequence close to TOP in various modes. When using phase and frequency correct PWM mode the OCR1x Register is updated at BOTTOM. 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 set the TOV1 Flag at BOTTOM. Figure 15-12.
15.11 Register Description 15.11.1 TCCR1A – Timer/Counter1 Control Register A Bit 7 6 5 4 3 2 1 0 COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 Read/Write R/W R/W R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 (0x80) TCCR1A • Bit 7:6 – COM1A1:0: Compare Output Mode for Channel A • Bit 5:4 – COM1B1:0: Compare Output Mode for Channel B The COM1A1:0 and COM1B1:0 control the Output Compare pins (OC1A and OC1B respectively) behavior.
Atmel ATmega328P [Preliminary] Table 15-3 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase correct or the phase and frequency correct, PWM mode. Table 15-3. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM(1) COM1A1/COM1B1 COM1A0/COM1B0 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 WGM13:0 = 9 or 11: Toggle OC1A on Compare Match, OC1B disconnected (normal port operation).
Waveform Generation Mode Bit Description(1) Table 15-4.
Atmel ATmega328P [Preliminary] 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 Capture function is disabled. • Bit 5 – Reserved Bit This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be written to zero when TCCR1B is written. • Bit 4:3 – WGM13:2: Waveform Generation Mode See TCCR1A Register description.
15.11.4 TCNT1H and TCNT1L – Timer/Counter1 Bit 7 6 5 4 3 (0x85) TCNT1[15:8] (0x84) TCNT1[7:0] 2 1 0 TCNT1H TCNT1L Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The 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.
Atmel ATmega328P [Preliminary] 15.11.7 ICR1H and ICR1L – Input Capture Register 1 Bit 7 6 5 4 3 (0x87) ICR1[15:8] (0x86) ICR1[7:0] 2 1 0 ICR1H ICR1L Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin (or optionally on the Analog Comparator output for Timer/Counter1). The Input Capture can be used for defining the counter TOP value.
15.11.9 TIFR1 – Timer/Counter1 Interrupt Flag Register Bit 7 6 5 4 3 2 1 0 0x16 (0x36) – – ICF1 – – OCF1B OCF1A TOV1 Read/Write R R R/W R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIFR1 • Bit 7, 6 – Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero. • Bit 5 – ICF1: Timer/Counter1, Input Capture Flag This flag is set when a capture event occurs on the ICP1 pin.
Atmel ATmega328P [Preliminary] 16. Timer/Counter0 and Timer/Counter1 Prescalers “8-bit Timer/Counter0 with PWM” on page 86 and “16-bit Timer/Counter1 with PWM” on page 104 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description below applies to both Timer/Counter1 and Timer/Counter0. 16.1 Internal Clock Source The Timer/Counter can be clocked directly by the system clock (by setting the CSn2:0 = 1).
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated. Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. The external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle.
Atmel ATmega328P [Preliminary] 16.4 16.4.1 Register Description GTCCR – General Timer/Counter Control Register Bit 7 6 5 4 3 2 1 0 0x23 (0x43) TSM – – – – – PSRASY PSRSYNC Read/Write R/W R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 GTCCR • Bit 7 – TSM: Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode.
17. 8-bit Timer/Counter2 with PWM and Asynchronous Operation 17.1 Features • • • • • • • 17.2 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 Compare Match Interrupt Sources (TOV2, OCF2A and OCF2B) Allows Clocking from External 32 kHz Watch Crystal Independent of the I/O Clock Overview Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module.
Atmel ATmega328P [Preliminary] 17.2.1 Registers The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit registers. Interrupt request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK2). TIFR2 and TIMSK2 are not shown in the figure.
Figure 17-2. Counter Unit Block Diagram TOVn (Int.Req.) DATA BUS TOSC1 count TCNTn clear clk Tn Control Logic Prescaler T/C Oscillator direction bottom TOSC2 top clkI/O Signal description (internal signals): count Increment or decrement TCNT2 by 1. direction Selects between increment and decrement. clear Clear TCNT2 (set all bits to zero). clkTn Timer/Counter clock, referred to as clkT2 in the following. top Signalizes that TCNT2 has reached maximum value.
Atmel ATmega328P [Preliminary] Figure 17-3. Output Compare Unit, Block Diagram DATA BUS OCRnx TCNTn = (8-bit Comparator ) OCFnx (Int.Req.) top bottom Waveform Generator OCnx FOCn WGMn1:0 COMnX1:0 The OCR2x Register is double buffered when using any of the Pulse Width Modulation (PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled.
17.5.3 Using the Output Compare Unit Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT2 when using the Output Compare channel, independently of whether the Timer/Counter is running or not. If the value written to TCNT2 equals the OCR2x value, the compare match will be missed, resulting in incorrect waveform generation. Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is downcounting.
Atmel ATmega328P [Preliminary] The general I/O port function is overridden by the Output Compare (OC2x) from the Waveform Generator if either of the COM2x1:0 bits are set. However, the OC2x pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register bit for the OC2x pin (DDR_OC2x) must be set as output before the OC2x value is visible on the pin. The port override function is independent of the Waveform Generation mode.
17.7.2 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 counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution. This mode allows greater control of the compare match output frequency. It also simplifies the operation of counting external events.
Atmel ATmega328P [Preliminary] 17.7.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM22:0 = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7.
The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ----------------N ⋅ 256 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 a PWM waveform output in the fast PWM mode. If the OCR2A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle.
Atmel ATmega328P [Preliminary] Figure 17-7. Phase Correct PWM Mode, Timing Diagram OCnx Interrupt Flag Set OCRnx Update TOVn Interrupt Flag Set TCNTn OCnx (COMnx1:0 = 2) OCnx (COMnx1:0 = 3) Period 1 2 3 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 the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin.
• OCR2A changes its value from MAX, like in Figure 17-7. When the OCR2A value is MAX the 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 up-counting Compare Match. • The timer starts counting from a value higher than the one in OCR2A, and for that reason misses the Compare Match and hence the OCn change that would have happened on the way up. 17.
Atmel ATmega328P [Preliminary] Figure 17-10. Timer/Counter Timing Diagram, Setting of OCF2A, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O /8) TCNTn OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2 OCRnx Value OCRnx OCFnx Figure 17-11 shows the setting of OCF2A and the clearing of TCNT2 in CTC mode. Figure 17-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O /8) TCNTn (CTC) TOP - 1 OCRnx TOP BOTTOM BOTTOM + 1 TOP OCFnx 17.
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 Output Compare function is disabled during writing to OCR2x or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode before the corresponding OCR2xUB bit returns to zero, the device will never receive a compare match interrupt, and the MCU will not wake up.
Atmel ATmega328P [Preliminary] 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 setting of the Interrupt Flag. The Output Compare pin is changed on the timer clock and is not synchronized to the processor clock. 17.10 Timer/Counter Prescaler Figure 17-12.
17.11 Register Description 17.11.1 TCCR2A – Timer/Counter Control Register A Bit 7 6 5 4 3 2 1 0 COM2A1 COM2A0 COM2B1 COM2B0 – – WGM21 WGM20 Read/Write R/W R/W R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 (0xB0) TCCR2A • Bits 7:6 – COM2A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC2A) behavior. If one or both of the COM2A1:0 bits are set, the OC2A output overrides the normal port functionality of the I/O pin it is connected to.
Atmel ATmega328P [Preliminary] Table 17-4 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to phase correct PWM mode. Table 17-4. Compare Output Mode, Phase Correct PWM Mode(1) COM2A1 COM2A0 0 0 Normal port operation, OC2A disconnected. 0 1 WGM22 = 0: Normal Port Operation, OC2A Disconnected. WGM22 = 1: Toggle OC2A on Compare Match. 1 0 Clear OC2A on Compare Match when up-counting. Set OC2A on Compare Match when down-counting. 1 1 Set OC2A on Compare Match when up-counting.
Table 17-7 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to phase correct PWM mode. Compare Output Mode, Phase Correct PWM Mode(1) Table 17-7. COM2B1 COM2B0 0 0 Normal port operation, OC2B disconnected. 0 1 Reserved 1 0 Clear OC2B on Compare Match when up-counting. Set OC2B on Compare Match when down-counting. 1 1 Set OC2B on Compare Match when up-counting. Clear OC2B on Compare Match when down-counting. Note: Description 1.
Atmel ATmega328P [Preliminary] 17.11.2 TCCR2B – Timer/Counter Control Register B Bit 7 6 5 4 3 2 1 0 FOC2A FOC2B – – WGM22 CS22 CS21 CS20 Read/Write W W R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 (0xB1) TCCR2B • Bit 7 – FOC2A: Force Output Compare A The FOC2A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR2B is written when operating in PWM mode.
Table 17-9. Clock Select Bit Description CS22 CS21 CS20 Description 0 0 0 No clock source (Timer/Counter stopped).
Atmel ATmega328P [Preliminary] 17.11.6 TIMSK2 – Timer/Counter2 Interrupt Mask Register Bit 7 6 5 4 3 2 1 0 (0x70) – – – – – OCIE2B OCIE2A TOIE2 Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TIMSK2 • Bit 2 – OCIE2B: Timer/Counter2 Output Compare Match B Interrupt Enable When the OCIE2B bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare Match B interrupt is enabled.
17.11.8 ASSR – Asynchronous Status Register Bit 7 6 5 4 3 2 1 0 (0xB6) – EXCLK AS2 TCN2UB OCR2AUB OCR2BUB TCR2AUB TCR2BUB Read/Write R R/W R/W R R R R R Initial Value 0 0 0 0 0 0 0 0 ASSR • Bit 7 – RES: Reserved bit This bit is reserved and will always read as zero.
Atmel ATmega328P [Preliminary] 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 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.
18. SPI – Serial Peripheral Interface 18.1 Features • • • • • • • • 18.
Atmel ATmega328P [Preliminary] The interconnection between Master and Slave CPUs with SPI is shown in Figure 18-2 on page 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 of the desired Slave. Master and Slave prepare the data to be sent in their respective shift Registers, and the Master generates the required clock pulses on the SCK line to interchange data.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 18-1 on page 160. For more details on automatic port overrides, refer to “Alternate Port Functions” on page 71. Table 18-1.
Atmel ATmega328P [Preliminary] Assembly Code Example(1) SPI_MasterInit: ; Set MOSI and SCK output, all others input ldi r17,(1<
The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception.
Atmel ATmega328P [Preliminary] 18.3 18.3.1 SS Pin Functionality Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high.
Figure 18-3. SPI Transfer Format with CPHA = 0 SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) MSB LSB first (DORD = 1) LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB Figure 18-4. SPI Transfer Format with CPHA = 1 SCK (CPOL = 0) mode 1 SCK (CPOL = 1) mode 3 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) LSB first (DORD = 1) 18.5 18.5.
Atmel ATmega328P [Preliminary] • Bit 5 – DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted first. • Bit 4 – MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set.
18.5.2 SPSR – SPI Status Register Bit 7 6 5 4 3 2 1 0 SPIF WCOL – – – – – SPI2X Read/Write R R R R R R R R/W Initial Value 0 0 0 0 0 0 0 0 0x2D (0x4D) SPSR • Bit 7 – SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag.
Atmel ATmega328P [Preliminary] 19. USART0 19.1 Features • • • • • • • • • • • • 19.
Figure 19-1. USART Block Diagram(1) Clock Generator UBRRn [H:L] OSC BAUD RATE GENERATOR SYNC LOGIC PIN CONTROL XCKn Transmitter TX CONTROL DATA BUS UDRn(Transmit) PARITY GENERATOR 19.3 TxDn Receiver CLOCK RECOVERY RX CONTROL RECEIVE SHIFT REGISTER DATA RECOVERY PIN CONTROL UDRn (Receive) PARITY CHECKER UCSRnA Note: PIN CONTROL TRANSMIT SHIFT REGISTER UCSRnB RxDn UCSRnC 1. Refer to Figure 1-1 on page 2 and Table 13-9 on page 80 for USART0 pin placement.
Atmel ATmega328P [Preliminary] Figure 19-2 shows a block diagram of the clock generation logic. Figure 19-2. Clock Generation Logic, Block Diagram UBRRn U2Xn foscn Prescaling Down-Counter UBRRn+1 /2 /4 /2 0 1 0 OSC DDR_XCKn xcki XCKn Pin Sync Register Edge Detector 0 UCPOLn txclk UMSELn 1 xcko DDR_XCKn 1 1 0 rxclk Signal description: txclk Transmitter clock (Internal Signal). rxclk Receiver base clock (Internal Signal). xcki operation. 19.3.1 Input from XCK pin (internal Signal).
Table 19-1 contains equations for calculating the baud rate (in bits per second) and for calculating the UBRRn value for each mode of operation using an internally generated clock source. Table 19-1.
Atmel ATmega328P [Preliminary] 19.3.3 External Clock External clocking is used by the synchronous slave modes of operation. The description in this section refers to Figure 19-2 for details. External clock input from the XCKn pin is sampled by a synchronization register to minimize the chance of meta-stability. The output from the synchronization register must then pass through an edge detector before it can be used by the Transmitter and Receiver.
A frame starts with the start bit followed by the least significant data bit. Then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. Figure 19-4 illustrates the possible combinations of the frame formats. Bits inside brackets are optional.
Atmel ATmega328P [Preliminary] 19.5 USART Initialization The USART has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. For interrupt driven USART operation, the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the initialization.
Assembly Code Example(1) USART_Init: ; Set baud rate out UBRRnH, r17 out UBRRnL, r16 ; Enable receiver and transmitter ldi r16, (1<
Atmel ATmega328P [Preliminary] 19.6 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 overridden by the USART and given the function as the Transmitter’s serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions.
19.6.2 Sending Frames with 9 Data Bit If 9-bit characters are used (UCSZn = 7), the ninth bit must be written to the TXB8 bit in UCSRnB before the low byte of the character is written to UDRn. The following code examples show a transmit function that handles 9-bit characters. For the assembly code, the data to be sent is assumed to be stored in registers R17:R16.
Atmel ATmega328P [Preliminary] 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 writing UDRn.
The following code example shows a simple USART receive function based on polling of the Receive Complete (RXCn) Flag. When using frames with less than eight bits the most significant bits of the data read from the UDRn will be masked to zero. The USART has to be initialized before the function can be used.
Atmel ATmega328P [Preliminary] Assembly Code Example(1) USART_Receive: ; Wait for data to be received sbis UCSRnA, RXCn rjmp USART_Receive ; Get status and 9th bit, then data from buffer in r18, UCSRnA in r17, UCSRnB in r16, UDRn ; If error, return -1 andi r18,(1<
19.7.3 Receive Compete Flag and Interrupt The USART Receiver has one flag that indicates the Receiver state. The Receive Complete (RXCn) Flag indicates if there are unread data present in the receive buffer. This flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled (RXENn = 0), the receive buffer will be flushed and consequently the RXCn bit will become zero.
Atmel ATmega328P [Preliminary] 19.7.5 Parity Checker The Parity Checker is active when the high USART Parity mode (UPMn1) bit is set. Type of Parity Check to be performed (odd or even) is selected by the UPMn0 bit. When enabled, the Parity Checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. The result of the check is stored in the receive buffer together with the received data and stop bits.
19.8 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 at the RxDn pin. The data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the Receiver.
Atmel ATmega328P [Preliminary] Figure 19-6. Sampling of Data and Parity Bit RxD BIT n Sample (U2X = 0) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 Sample (U2X = 1) 1 2 3 4 5 6 7 8 1 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. The center samples are emphasized on the figure by having the sample number inside boxes.
The following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. ( D + 2 )S R fast = ----------------------------------( D + 1 )S + S M ( D + 1 )S R slow = ------------------------------------------S – 1 + D ⋅ S + SF D Sum of character size and parity size (D = 5 to 10 bit) S Samples per bit. S = 16 for Normal Speed mode and S = 8 for Double Speed mode. SF First sample number used for majority voting.
Atmel ATmega328P [Preliminary] Table 19-3. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode (U2Xn = 1) D # (Data+Parity Bit) Rslow (%) Rfast (%) Max Total Error (%) Recommended Max Receiver Error (%) 5 94.12 105.66 +5.66/-5.88 ± 2.5 6 94.92 104.92 +4.92/-5.08 ± 2.0 7 95.52 104,35 +4.35/-4.48 ± 1.5 8 96.00 103.90 +3.90/-4.00 ± 1.5 9 96.39 103.53 +3.53/-3.61 ± 1.5 10 96.70 103.23 +3.23/-3.30 ± 1.
19.9.1 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 a data frame (TXB = 0) is being transmitted. The slave MCUs must in this case be set to use a 9-bit character frame format. The following procedure should be used to exchange data in Multi-processor Communication mode: 1. All Slave MCUs are in Multi-processor Communication mode (MPCMn in UCSRnA is set). 2.
Atmel ATmega328P [Preliminary] 19.10 Register Description 19.10.1 UDRn – USART I/O Data Register n Bit 7 6 5 4 3 2 1 0 RXB[7:0] UDRn (Read) TXB[7:0] UDRn (Write) Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address referred to as USART Data Register or UDRn.
• 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 Flag can generate a 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 receive buffer had a Frame Error when received. I.e.
Atmel ATmega328P [Preliminary] • 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 Interrupt Flag in SREG is written to one and the TXCn bit in UCSRnA is set. • Bit 5 – UDRIEn: USART Data Register Empty Interrupt Enable n Writing this bit to one enables interrupt on the UDREn Flag.
Table 19-4. Note: UMSELn Bits Settings UMSELn1 UMSELn0 Mode 0 0 Asynchronous USART 0 1 Synchronous USART 1 0 (Reserved) 1 1 Master SPI (MSPIM)(1) 1. See “USART in SPI Mode” on page 196 for full description of the Master SPI Mode (MSPIM) operation • 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.
Atmel ATmega328P [Preliminary] Table 19-7. UCSZn Bits Settings UCSZn2 UCSZn1 UCSZn0 Character Size 0 0 0 5-bit 0 0 1 6-bit 0 1 0 7-bit 0 1 1 8-bit 1 0 0 Reserved 1 0 1 Reserved 1 1 0 Reserved 1 1 1 9-bit • 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 input sample, and the synchronous clock (XCKn). Table 19-8.
19.11 Examples of Baud Rate Setting For standard crystal and resonator frequencies, the most commonly used baud rates for asynchronous operation can be generated by using the UBRRn settings in Table 19-9. UBRRn values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the table.
Atmel ATmega328P [Preliminary] Table 19-10. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 3.6864 MHz Baud Rate (bps) U2Xn = 0 fosc = 4.0000 MHz U2Xn = 1 U2Xn = 0 fosc = 7.3728 MHz U2Xn = 1 U2Xn = 0 U2Xn = 1 UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 23 0.0% 47 0.0% 25 0.
Table 19-11. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 11.0592 MHz fosc = 8.0000 MHz fosc = 14.7456 MHz Baud Rate (bps) UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error UBRRn Error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.
Atmel ATmega328P [Preliminary] Table 19-12. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 16.0000 MHz U2Xn = 0 Baud Rate (bps) UBRRn U2Xn = 1 Error UBRRn Error 2400 416 -0.1% 832 0.0% 4800 207 0.2% 416 -0.1% 9600 103 0.2% 207 0.2% 14.4k 68 0.6% 138 -0.1% 19.2k 51 0.2% 103 0.2% 28.8k 34 -0.8% 68 0.6% 38.4k 25 0.2% 51 0.2% 57.6k 16 2.1% 34 -0.8% 76.8k 12 0.2% 25 0.2% 115.2k 8 -3.5% 16 2.1% 230.4k 3 8.5% 8 -3.
20. USART in SPI Mode 20.1 Features • • • • • • • • 20.
Atmel ATmega328P [Preliminary] Note: 20.4 1. The baud rate is defined to be the transfer rate in bit per second (bps) BAUD Baud rate (in bits per second, bps) fOSC System Oscillator clock frequency UBRRn Contents of the UBRRnH and UBRRnL Registers, (0-4095) SPI Data Modes and Timing There are four combinations of XCKn (SCK) phase and polarity with respect to serial data, which are determined by control bits UCPHAn and UCPOLn. The data transfer timing diagrams are shown in Figure 20-1.
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 both the Receiver and Transmitter. 16-bit data transfer can be achieved by writing two data bytes to UDRn. A UART transmit complete interrupt will then signal that the 16-bit value has been shifted out. 20.5.
Atmel ATmega328P [Preliminary] baud rate is given as a function parameter. For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. Assembly Code Example(1) USART_Init: clr r18 out UBRRnH,r18 out UBRRnL,r18 ; Setting the XCKn port pin as output, enables master mode. sbi XCKn_DDR, XCKn ; Set MSPI mode of operation and SPI data mode 0. ldi r18, (1<
20.6 Data Transfer Using the USART in MSPI mode requires the Transmitter to be enabled, i.e. the TXENn bit in the UCSRnB register is set to one. When the Transmitter is enabled, the normal port operation of the TxDn pin is overridden and given the function as the Transmitter's serial output. Enabling the receiver is optional and is done by setting the RXENn bit in the UCSRnB register to one.
Atmel ATmega328P [Preliminary] Assembly Code Example(1) USART_MSPIM_Transfer: ; Wait for empty transmit buffer sbis UCSRnA, UDREn rjmp USART_MSPIM_Transfer ; Put data (r16) into buffer, sends the data out UDRn,r16 ; Wait for data to be received USART_MSPIM_Wait_RXCn: sbis UCSRnA, RXCn rjmp USART_MSPIM_Wait_RXCn ; Get and return received data from buffer in r16, UDRn ret C Code Example(1) unsigned char USART_Receive( void ) { /* Wait for empty transmit buffer */ while ( !( UCSRnA & (1<
20.7 AVR USART MSPIM vs. AVR SPI The USART in MSPIM mode is fully compatible with the AVR SPI regarding: • Master mode timing diagram. • The UCPOLn bit functionality is identical to the SPI CPOL bit. • The UCPHAn bit functionality is identical to the SPI CPHA bit. • The UDORDn bit functionality is identical to the SPI DORD bit. However, since the USART in MSPIM mode reuses the USART resources, the use of the USART in MSPIM mode is somewhat different compared to the SPI.
Atmel ATmega328P [Preliminary] 20.8 Register Description The following section describes the registers used for SPI operation using the USART. 20.8.1 UDRn – USART MSPIM I/O Data Register The function and bit description of the USART data register (UDRn) in MSPI mode is identical to normal USART operation. See “UDRn – USART I/O Data Register n” on page 187. 20.8.
• Bit 6 - TXCIEn: TX Complete Interrupt Enable Writing this bit to one enables interrupt on the TXCn Flag. A USART Transmit Complete interrupt will be generated only if the TXCIEn bit is written to one, the Global Interrupt Flag in SREG is written to one and the TXCn bit in UCSRnA is set. • Bit 5 - UDRIE: USART Data Register Empty Interrupt Enable Writing this bit to one enables interrupt on the UDREn Flag.
Atmel ATmega328P [Preliminary] Table 20-4. UMSELn Bits Settings UMSELn1 UMSELn0 Mode 0 0 Asynchronous USART 0 1 Synchronous USART 1 0 Reserved 1 1 Master SPI (MSPIM) • Bit 5:3 - Reserved Bits in MSPI mode When in MSPI mode, these bits are reserved for future use. For compatibility with future devices, these bits must be written to zero when UCSRnC is written. • Bit 2 - UDORDn: Data Order When set to one the LSB of the data word is transmitted first.
21. 2-wire Serial Interface 21.1 Features • • • • • • • • • • • 21.
Atmel ATmega328P [Preliminary] 21.2.1 TWI Terminology The following definitions are frequently encountered in this section. Table 21-1. TWI Terminology Term Description Master The device that initiates and terminates a transmission. The Master also generates the SCL clock. Slave The device addressed by a Master. Transmitter The device placing data on the bus. Receiver The device reading data from the bus.
21.3 21.3.1 Data Transfer and Frame Format Transferring Bits Each data bit transferred on the TWI bus is accompanied by a pulse on the clock line. The level of the data line must be stable when the clock line is high. The only exception to this rule is for generating start and stop conditions. Figure 21-2. Data Validity SDA SCL Data Stable Data Stable Data Change 21.3.2 START and STOP Conditions The Master initiates and terminates a data transmission.
Atmel ATmega328P [Preliminary] 21.3.3 Address Packet Format All address packets transmitted on the TWI bus are 9 bits long, consisting of 7 address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed. When a Slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle.
Figure 21-5. Data Packet Format Data MSB Data LSB ACK 8 9 Aggregate SDA SDA from Transmitter SDA from Receiver SCL from Master 1 2 7 SLA+R/W 21.3.5 STOP, REPEATED START or Next Data Byte Data Byte Combining Address and Data Packets into a Transmission A transmission basically consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition. An empty message, consisting of a START followed by a STOP condition, is illegal.
Atmel ATmega328P [Preliminary] 21.4 Multi-master Bus Systems, Arbitration and Synchronization The TWI protocol allows bus systems with several masters. Special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more masters initiate a transmission at the same time. Two problems arise in multi-master systems: • An algorithm must be implemented allowing only one of the masters to complete the transmission.
Arbitration will continue until only one Master remains, and this may take many bits. If several masters are trying to address the same Slave, arbitration will continue into the data packet. Figure 21-8. Arbitration Between Two Masters START SDA from Master A Master A Loses Arbitration, SDAA SDA SDA from Master B SDA Line Synchronized SCL Line Note that arbitration is not allowed between: • A REPEATED START condition and a data bit. • A STOP condition and a data bit.
Atmel ATmega328P [Preliminary] 21.5 Overview of the TWI Module The TWI module is comprised of several submodules, as shown in Figure 21-9. All registers drawn in a thick line are accessible through the AVR data bus. Figure 21-9.
21.5.2 Bit Rate Generator Unit This unit controls the period of SCL when operating in a Master mode. The SCL period is controlled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but the CPU clock frequency in the Slave must be at least 16 times higher than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period.
Atmel ATmega328P [Preliminary] 21.5.5 Control Unit The Control unit monitors the TWI bus and generates responses corresponding to settings in the TWI Control Register (TWCR). When an event requiring the attention of the application occurs on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Status Register (TWSR) is updated with a status code identifying the event. The TWSR only contains relevant status information when the TWI Interrupt Flag is asserted.
Application Action Figure 21-10. Interfacing the Application to the TWI in a Typical Transmission 1. Application writes to TWCR to initiate transmission of START TWI Hardware Action TWI bus 3. Check TWSR to see if START was sent. Application loads SLA+W into TWDR, and loads appropriate control signals into TWCR, makin sure that TWINT is written to one, and TWSTA is written to zero. START SLA+W 2. TWINT set. Status code indicates START condition sent 5.
Atmel ATmega328P [Preliminary] However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet. 6. When the data packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent.
Assembly Code Example ldi r16, (1<
Atmel ATmega328P [Preliminary] 21.7 Transmission Modes The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As an example, the TWI can use MT mode to write data into a TWI EEPROM, MR mode to read the data back from the EEPROM.
Figure 21-11. Data Transfer in Master Transmitter Mode VCC Device 1 Device 2 MASTER TRANSMITTER SLAVE RECEIVER Device 3 ........ Device n R1 R2 SDA SCL A START condition is sent by writing the following value to TWCR: TWCR value TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE 1 X 1 0 X 1 0 X TWEN must be set to enable the 2-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT Flag.
Atmel ATmega328P [Preliminary] After a repeated START condition (state 0x10) the 2-wire Serial Interface can access the same Slave again, or a new Slave without transmitting a STOP condition. Repeated START enables the Master to switch between Slaves, Master Transmitter mode and Master Receiver mode without losing control of the bus. Table 21-2.
Figure 21-12.
Atmel ATmega328P [Preliminary] Figure 21-13. Data Transfer in Master Receiver Mode VCC Device 1 Device 2 MASTER RECEIVER SLAVE TRANSMITTER Device 3 ........
Table 21-3.
Atmel ATmega328P [Preliminary] Figure 21-14. Formats and States in the Master Receiver Mode MR Successfull reception from a slave receiver S SLA $08 R A DATA A $40 DATA $50 A P $58 Next transfer started with a repeated start condition RS SLA R $10 Not acknowledge received after the slave address A W P $48 MT Arbitration lost in slave address or data byte A or A Other master continues A $38 Arbitration lost and addressed as slave A $68 From master to slave 21.7.
To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows: TWAR TWA6 TWA5 value TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device’s Own Slave Address The upper 7 bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
Atmel ATmega328P [Preliminary] Table 21-4.
Figure 21-16. Formats and States in the Slave Receiver Mode Reception of the own slave address and one or more data bytes.
Atmel ATmega328P [Preliminary] To initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows: TWAR TWA6 TWA5 value TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device’s Own Slave Address The upper seven bits are the address to which the 2-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
Table 21-5.
Atmel ATmega328P [Preliminary] Figure 21-18. Formats and States in the Slave Transmitter Mode Reception of the own slave address and one or more data bytes S SLA R A DATA $A8 Arbitration lost as master and addressed as slave A DATA $B8 A P or S $C0 A $B0 Last data byte transmitted. Switched to not addressed slave (TWEA = '0') A All 1's P or S $C8 DATA From master to slave From slave to master 21.7.
Note that data is transmitted both from Master to Slave and vice versa. The Master must instruct the Slave what location it wants to read, requiring the use of the MT mode. Subsequently, data must be read from the Slave, implying the use of the MR mode. Thus, the transfer direction must be changed. The Master must keep control of the bus during all these steps, and the steps should be carried out as an atomical operation.
Atmel ATmega328P [Preliminary] • Two or more masters are accessing different slaves. In this case, arbitration will occur in the SLA bits. Masters trying to output a one on SDA while another Master outputs a zero will lose the arbitration. Masters losing arbitration in SLA will switch to Slave mode to check if they are being addressed by the winning Master. If addressed, they will switch to SR or ST mode, depending on the value of the READ/WRITE bit.
• Bit 7 – TWINT: TWI Interrupt Flag This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT Flag is set, the SCL low period is stretched. The TWINT Flag must be cleared by software by writing a logic one to it. Note that this flag is not automatically cleared by hardware when executing the interrupt routine.
Atmel ATmega328P [Preliminary] • Bit 0 – TWIE: TWI Interrupt Enable When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be activated for as long as the TWINT Flag is high. 21.9.3 TWSR – TWI Status Register Bit 7 6 5 4 3 2 1 0 TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 Read/Write R R R R R R R/W R/W Initial Value 1 1 1 1 1 0 0 0 (0xB9) TWSR • Bits 7..
In the case of a lost bus arbitration, no data is lost in the transition from Master to Slave. Handling of the ACK bit is controlled automatically by the TWI logic, the CPU cannot access the ACK bit directly. • Bits 7..0 – TWD: TWI Data Register These eight bits constitute the next data byte to be transmitted, or the latest data byte received on the 2-wire Serial Bus. 21.9.
Atmel ATmega328P [Preliminary] Figure 21-22. TWI Address Match Logic, Block Diagram TWAR0 Address Match Address Bit 0 TWAMR0 Address Bit Comparator 0 Address Bit Comparator 6..1 • Bit 0 – Res: Reserved Bit This bit is an unused bit in the ATmega328P, and will always read as zero.
22. Analog Comparator 22.1 Overview The Analog Comparator compares the input values on the positive pin AIN0 and negative pin AIN1. When the voltage on the positive pin AIN0 is higher than the voltage on the negative pin AIN1, the Analog Comparator output, ACO, is set. The comparator’s output can be set to trigger the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate interrupt, exclusive to the Analog Comparator.
Atmel ATmega328P [Preliminary] Table 22-1. 22.3 22.3.1 Analog Comparator Multiplexed Input ACME ADEN MUX2..
• Bit 6 – ACBG: Analog Comparator Bandgap Select When this bit is set, a fixed bandgap reference voltage replaces the positive input to the Analog Comparator. When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator. When the bandgap referance is used as input to the Analog Comparator, it will take a certain time for the voltage to stabilize. If not stabilized, the first conversion may give a wrong value.
Atmel ATmega328P [Preliminary] 22.3.3 DIDR1 – Digital Input Disable Register 1 Bit 7 6 5 4 3 2 1 0 (0x7F) – – – – – – AIN1D AIN0D Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 DIDR1 • Bit 7..2 – Res: Reserved Bits These bits are unused bits in the ATmega328P, and will always read as zero. • Bit 1, 0 – AIN1D, AIN0D: AIN1, AIN0 Digital Input Disable When this bit is written logic one, the digital input buffer on the AIN1/0 pin is disabled.
23. Analog-to-Digital Converter 23.1 Features • • • • • • • • • • • • • • 23.2 10-bit Resolution 0.5 LSB Integral Non-linearity ± 2 LSB Absolute Accuracy 65 - 260 µs Conversion Time Up to 15 kSPS 6 Multiplexed Single Ended Input Channels 2 Additional Multiplexed Single Ended Input Channels Temperature Sensor Input Channel Optional Left Adjustment for ADC Result Readout 0 - VCC ADC Input Voltage Range Selectable 1.
Atmel ATmega328P [Preliminary] Figure 23-1. Analog to Digital Converter Block Schematic Operation, ADC CONVERSION COMPLETE IRQ ADC[9:0] ADPS1 0 ADC DATA REGISTER (ADCH/ADCL) ADPS0 ADPS2 ADIF ADFR ADEN ADSC MUX1 15 ADC CTRL. & STATUS REGISTER (ADCSRA) MUX0 MUX3 MUX2 ADLAR REFS0 REFS1 ADC MULTIPLEXER SELECT (ADMUX) ADIE ADIF 8-BIT DATA BUS MUX DECODER CHANNEL SELECTION PRESCALER AVCC CONVERSION LOGIC INTERNAL 1.
This means that if ADCL has been read, and a conversion completes before ADCH is read, neither register is updated and the result from the conversion is lost. When ADCH is read, ADC access to the ADCH and ADCL Registers is re-enabled. The ADC has its own interrupt which can be triggered when a conversion completes. When ADC access to the Data Registers is prohibited between reading of ADCH and ADCL, the interrupt will trigger even if the result is lost. 23.
Atmel ATmega328P [Preliminary] If Auto Triggering is enabled, single conversions can be started by writing ADSC in ADCSRA to one. ADSC can also be used to determine if a conversion is in progress. The ADSC bit will be read as one during a conversion, independently of how the conversion was started. 23.4 Prescaling and Conversion Timing Figure 23-3.
When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This assures a fixed delay from the trigger event to the start of conversion. In this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional CPU clock cycles are used for synchronization logic. In Free Running mode, a new conversion will be started immediately after the conversion completes, while ADSC remains high.
Atmel ATmega328P [Preliminary] Figure 23-6. ADC Timing Diagram, Auto Triggered Conversion One Conversion 1 Cycle Number 2 3 4 5 6 7 8 Next Conversion 10 9 11 12 13 1 2 ADC Clock Trigger Source ADATE ADIF ADCH Sign and MSB of Result ADCL LSB of Result Prescaler Reset Sample & Hold Prescaler Reset Conversion Complete MUX and REFS Update Figure 23-7.
23.5 Changing Channel or Reference Selection The MUXn and REFS1:0 bits in the ADMUX Register are single buffered through a temporary register to which the CPU has random access. This ensures that the channels and reference selection only takes place at a safe point during the conversion. The channel and reference selection is continuously updated until a conversion is started. Once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the ADC.
Atmel ATmega328P [Preliminary] If the user has a fixed voltage source connected to the AREF pin, the user may not use the other reference voltage options in the application, as they will be shorted to the external voltage. If no external voltage is applied to the AREF pin, the user may switch between AVCC and 1.1V as reference selection. The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result. 23.
Figure 23-8. Analog Input Circuitry IIH ADCn 1..100 kΩ CS/H= 14 pF IIL VCC/2 23.6.2 Analog Noise Canceling Techniques Digital circuitry inside and outside the device generates EMI which might affect the accuracy of analog measurements. If conversion accuracy is critical, the noise level can be reduced by applying the following techniques: a. Keep analog signal paths as short as possible.
Atmel ATmega328P [Preliminary] and ADC5) will only affect the conversion on ADC4 and ADC5 and not the other ADC channels. Analog Ground Plane PC2 (ADC2) PC3 (ADC3) PC4 (ADC4/SDA) PC5 (ADC5/SCL) VCC GND Figure 23-9. ADC Power Connections PC1 (ADC1) PC0 (ADC0) ADC7 ADC6 AVCC 100nF AREF 10µH GND PB5 23.6.3 ADC Accuracy Definitions An n-bit single-ended ADC converts a voltage linearly between GND and V REF in 2 n steps (LSBs). The lowest code is read as 0, and the highest code is read as 2n-1.
Figure 23-10. Offset Error Output Code Ideal ADC Actual ADC Offset Error VREF Input Voltage • Gain error: After adjusting for offset, the gain error is found as the deviation of the last transition (0x3FE to 0x3FF) compared to the ideal transition (at 1.5 LSB below maximum). Ideal value: 0 LSB Figure 23-11.
Atmel ATmega328P [Preliminary] Figure 23-12. Integral Non-linearity (INL) Output Code INL Ideal ADC Actual ADC VREF Input Voltage • Differential Non-linearity (DNL): The maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 LSB). Ideal value: 0 LSB. Figure 23-13.
23.7 ADC Conversion Result After the conversion is complete (ADIF is high), the conversion result can be found in the ADC Result Registers (ADCL, ADCH). For single ended conversion, the result is V IN ⋅ 1024 ADC = -------------------------V REF where VIN is the voltage on the selected input pin and VREF the selected voltage reference (see Table 23-3 on page 256 and Table 23-4 on page 257). 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. 23.
Atmel ATmega328P [Preliminary] Where:. a. ADCH & ADCL are the ADC data registers, b. is the temperature sensor gain c. TS_OFFSET is the temperature sensor offset correction term TS_GAIN is the unsigned fixed point 8-bit temperature sensor gain factor in 1/128th units stored in the signature row. TS_OFFSET is the signed twos complement temperature sensor offset reading stored in the signature row.
23.9 23.9.1 Register Description ADMUX – ADC Multiplexer Selection Register Bit 7 6 5 4 3 2 1 0 REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 Read/Write R/W R/W R/W R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 (0x7C) ADMUX • Bit 7:6 – REFS1:0: Reference Selection Bits These bits select the voltage reference for the ADC, as shown in Table 23-3.
Atmel ATmega328P [Preliminary] Table 23-4. Input Channel Selections MUX3..0 Note: 23.9.2 Single Ended Input 0000 ADC0 0001 ADC1 0010 ADC2 0011 ADC3 0100 ADC4 0101 ADC5 0110 ADC6 0111 ADC7 1000 ADC8(1) 1001 (reserved) 1010 (reserved) 1011 (reserved) 1100 (reserved) 1101 (reserved) 1110 1.1V (VBG) 1111 0V (GND) 1. For Temperature Sensor.
• Bit 5 – ADATE: ADC Auto Trigger Enable When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB. • Bit 4 – ADIF: ADC Interrupt Flag This bit is set when an ADC conversion completes and the Data Registers are updated. The ADC Conversion Complete Interrupt is executed if the ADIE bit and the I-bit in SREG are set.
Atmel ATmega328P [Preliminary] 23.9.3 23.9.3.1 ADCL and ADCH – The ADC Data Register ADLAR = 0 Bit 15 14 13 12 11 10 9 8 (0x79) – – – – – – ADC9 ADC8 ADCH (0x78) ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 ADCL 7 6 5 4 3 2 1 0 R R R R R R R R R R R R R R R R 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Read/Write Initial Value 23.9.3.
If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect. A conversion will be triggered by the rising edge of the selected Interrupt Flag. Note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion.
Atmel ATmega328P [Preliminary] 24. debugWIRE On-chip Debug System 24.1 Features • • • • • • • • • • 24.
When designing a system where debugWIRE will be used, the following observations must be made for correct operation: • Pull-up resistors on the dW/(RESET) line must not be smaller than 10kΩ. The pull-up resistor is not required for debugWIRE functionality. • Connecting the RESET pin directly to VCC will not work. • Capacitors connected to the RESET pin must be disconnected when using debugWire. • All external reset sources must be disconnected. 24.
Atmel ATmega328P [Preliminary] 25. Self-Programming the Flash, ATmega328P 25.1 Overview In ATmega328P, there is no Read-While-Write support, and no separate Boot Loader Section. The SPM instruction can be executed from the entire Flash. The device provides a Self-Programming mechanism for downloading and uploading program code by the MCU itself. The Self-Programming can use any available data interface and associated protocol to read code and write (program) that code into the Program memory.
25.1.3 Performing a Page Write To execute Page Write, set up the address in the Z-pointer, write “00000101” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer must be written to zero during this operation. • The CPU is halted during the Page Write operation. 25.2 Addressing the Flash During Self-Programming The Z-pointer is used to address the SPM commands.
Atmel ATmega328P [Preliminary] 25.2.1 EEPROM Write Prevents Writing to SPMCSR Note that an EEPROM write operation will block all software programming to Flash. Reading the Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEPE) in the EECR Register and verifies that the bit is cleared before writing to the SPMCSR Register. 25.2.
25.2.3 Preventing Flash Corruption During periods of low VCC, the Flash program can be corrupted because the supply voltage is too low for the CPU and the Flash to operate properly. These issues are the same as for board level systems using the Flash, and the same design solutions should be applied. A Flash program corruption can be caused by two situations when the voltage is too low. First, a regular write sequence to the Flash requires a minimum voltage to operate correctly.
Atmel ATmega328P [Preliminary] 25.2.5 Simple Assembly Code Example for a Boot Loader Note that the RWWSB bit will always be read as zero in ATmega328P. Nevertheless, it is recommended to check this bit as shown in the code example, to ensure compatibility with devices supporting Read-While-Write.
lpm ld cpse rjmp sbiw brne r0, Z+ r1, Y+ r0, r1 Error loophi:looplo, 1 Rdloop ;use subi for PAGESIZEB<=256 ; return to RWW section ; verify that RWW section is safe to read Return: in temp1, SPMCSR sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet ret ; re-enable the RWW section ldi spmcrval, (1<
Atmel ATmega328P [Preliminary] 25.3 25.3.1 Register Description’ SPMCSR – Store Program Memory Control and Status Register The Store Program Memory Control and Status Register contains the control bits needed to control the Program memory operations.
• Bit 0 – SELFPRGEN: Self Programming Enable This bit enables the SPM instruction for the next four clock cycles. If written to one together with either RWWSRE, BLBSET, PGWRT, or PGERS, the following SPM instruction will have a special meaning, see description above. If only SELFPRGEN is written, the following SPM instruction will store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of the Z-pointer is ignored.
Atmel ATmega328P [Preliminary] 26. Boot Loader Support – Read-While-Write Self-Programming 26.1 Features • • • • • • • Read-While-Write Self-Programming Flexible Boot Memory Size High Security (Separate Boot Lock Bits for a Flexible Protection) Separate Fuse to Select Reset Vector Optimized Page(1) Size Code Efficient Algorithm Efficient Read-Modify-Write Support Note: 26.2 1. A page is a section in the Flash consisting of several bytes (see Table 27-9 on page 290) used during programming.
26.4 Read-While-Write and No Read-While-Write Flash Sections Whether the CPU supports Read-While-Write or if the CPU is halted during a Boot Loader software update is dependent on which address that is being programmed. In addition to the two sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also divided into two fixed sections, the Read-While-Write (RWW) section and the No Read-While-Write (NRWW) section.
Atmel ATmega328P [Preliminary] Figure 26-1. Read-While-Write vs.
Figure 26-2.
Atmel ATmega328P [Preliminary] Table 26-2. BLB0 Mode BLB02 BLB01 1 1 1 No restrictions for SPM or LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 0 SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section.
26.7 Addressing the Flash During Self-Programming The Z-pointer is used to address the SPM commands. Bit 15 14 13 12 11 10 9 8 ZH (R31) Z15 Z14 Z13 Z12 Z11 Z10 Z9 Z8 ZL (R30) Z7 Z6 Z5 Z4 Z3 Z2 Z1 Z0 7 6 5 4 3 2 1 0 Since the Flash is organized in pages (see Table 27-9 on page 290), the Program Counter can be treated as having two different sections.
Atmel ATmega328P [Preliminary] 26.8 Self-Programming the Flash The program memory is updated in a page by page fashion. Before programming a page with the data stored in the temporary page buffer, the page must be erased.
26.8.3 Performing a Page Write To execute Page Write, set up the address in the Z-pointer, write “X0000101” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer must be written to zero during this operation. • Page Write to the RWW section: The NRWW section can be read during the Page Write. • Page Write to the NRWW section: The CPU is halted during the operation. 26.8.
Atmel ATmega328P [Preliminary] 26.8.8 EEPROM Write Prevents Writing to SPMCSR Note that an EEPROM write operation will block all software programming to Flash. Reading the Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEPE) in the EECR Register and verifies that the bit is cleared before writing to the SPMCSR Register. 26.8.
26.8.10 Reading the Signature Row from Software To read the Signature Row from software, load the Z-pointer with the signature byte address given in Table 26-5 on page 280 and set the SIGRD and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the SIGRD and SPMEN bits are set in SPMCSR, the signature byte value will be loaded in the destination register.
Atmel ATmega328P [Preliminary] 26.8.12 Programming Time for Flash when Using SPM The calibrated RC Oscillator is used to time Flash accesses. Table 26-6 shows the typical programming time for Flash accesses from the CPU. Table 26-6. Symbol Min Programming Time Max Programming Time Flash write (Page Erase, Page Write, and write Lock bits by SPM) 3.7 ms 4.5 ms Note: 26.8.13 SPM Programming Time(1) 1. Minimum and maximum programming time is per individual operation.
call Do_spm ; read back and check, optional ldi looplo, low(PAGESIZEB) ;init loop variable ldi loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256 subi YL, low(PAGESIZEB) ;restore pointer sbci YH, high(PAGESIZEB) Rdloop: lpm r0, Z+ ld r1, Y+ cpse r0, r1 jmp Error sbiw loophi:looplo, 1 ;use subi for PAGESIZEB<=256 brne Rdloop ; return to RWW section ; verify that RWW section is safe to read Return: in temp1, SPMCSR sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet ret ; re-enable the
Atmel ATmega328P [Preliminary] 26.8.14 ATmega328P Boot Loader Parameters In Table 26-7 through Table 26-9, the parameters used in the description of the self programming are given. Table 26-7.
26.9 26.9.1 Register Description SPMCSR – Store Program Memory Control and Status Register The Store Program Memory Control and Status Register contains the control bits needed to control the Boot Loader operations.
Atmel ATmega328P [Preliminary] If this bit is written to one at the same time as SELFPRGEN, the next SPM instruction within four clock cycles executes Page Write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a Page Write, or if no SPM instruction is executed within four clock cycles.
27. Memory Programming 27.1 Program And Data Memory Lock Bits The ATmega328P provides six Lock bits which can be left unprogrammed (“1”) or can be programmed (“0”) to obtain the additional features listed in Table 27-2. The Lock bits can only be erased to “1” with the Chip Erase command.The ATmega328P has no separate Boot Loader section. The SPM instruction is enabled for the whole Flash if the SELFPRGEN fuse is programmed (“0”), otherwise it is disabled. Table 27-1.
Atmel ATmega328P [Preliminary] Table 27-3. Lock Bit Protection Modes(1)(2) . BLB0 Mode BLB02 BLB01 1 1 1 No restrictions for SPM or LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 0 SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section.
Table 27-5. Extended Fuse Byte for ATmega328P Extended Fuse Byte Description Default Value – 7 – 1 – 6 – 1 – 5 – 1 – 4 – 1 – 3 – 1 BODLEVEL2(1) 2 Brown-out Detector trigger level 1 (unprogrammed) BODLEVEL1(1) 1 Brown-out Detector trigger level 1 (unprogrammed) BODLEVEL0(1) 0 Brown-out Detector trigger level 1 (unprogrammed) Note: 1. See Table 28-5 on page 308 for BODLEVEL Fuse decoding.. Table 27-6.
Atmel ATmega328P [Preliminary] Table 27-7.
27.5 Page Size Table 27-9. No. of Words in a Page and No. of Pages in the Flash Device Flash Size Page Size PCWORD No. of Pages PCPAGE PCMSB ATmega328P 16K words (32K bytes) 64 words PC[5:0] 256 PC[13:6] 13 Table 27-10. No. of Words in a Page and No. of Pages in the EEPROM 27.6 Device EEPROM Size Page Size PCWORD No.
Atmel ATmega328P [Preliminary] Table 27-11.
Table 27-14. Command Byte Bit Coding Command Byte 27.7 27.7.1 Command Executed 1000 0000 Chip Erase 0100 0000 Write Fuse bits 0010 0000 Write Lock bits 0001 0000 Write Flash 0001 0001 Write EEPROM 0000 1000 Read Signature Bytes and Calibration byte 0000 0100 Read Fuse and Lock bits 0000 0010 Read Flash 0000 0011 Read EEPROM Parallel Programming Enter Programming Mode The following algorithm puts the device in Parallel (High-voltage) Programming mode: 1.
Atmel ATmega328P [Preliminary] 27.7.2 Considerations for Efficient Programming The loaded command and address are retained in the device during programming. For efficient programming, the following should be considered. • The command needs only be loaded once when writing or reading multiple memory locations. • Skip writing the data value 0xFF, that is the contents of the entire EEPROM (unless the EESAVE Fuse is programmed) and Flash after a Chip Erase.
D. Load Data High Byte 1. Set BS1 to “1”. This selects high data byte. 2. Set XA1, XA0 to “01”. This enables data loading. 3. Set DATA = Data high byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the data byte. E. Latch Data 1. Set BS1 to “1”. This selects high data byte. 2. Give PAGEL a positive pulse. This latches the data bytes. (See Figure 27-3 for signal waveforms) F. Repeat B through E until the entire buffer is filled or until all data within the page is loaded.
Atmel ATmega328P [Preliminary] Figure 27-2. Addressing the Flash Which is Organized in Pages(1) PCMSB PROGRAM COUNTER PAGEMSB PCPAGE PCWORD PAGE ADDRESS WITHIN THE FLASH WORD ADDRESS WITHIN A PAGE PROGRAM MEMORY PAGE PAGE PCWORD[PAGEMSB:0]: 00 INSTRUCTION WORD 01 02 PAGEEND Note: 1. PCPAGE and PCWORD are listed in Table 27-9 on page 290. Figure 27-3. Programming the Flash Waveforms(1) F DATA A B 0x10 ADDR. LOW C DATA LOW D E DATA HIGH XX B ADDR.
5. E: Latch data (give PAGEL a positive pulse). K: Repeat 3 through 5 until the entire buffer is filled. L: Program EEPROM page 1. Set BS1 to “0”. 2. Give WR a negative pulse. This starts programming of the EEPROM page. RDY/BSY goes low. 3. Wait until to RDY/BSY goes high before programming the next page (See Figure 27-4 for signal waveforms). Figure 27-4. Programming the EEPROM Waveforms K DATA A G 0x11 ADDR. HIGH B ADDR. LOW C DATA E XX B ADDR.
Atmel ATmega328P [Preliminary] 27.7.8 Programming the Fuse Low Bits The algorithm for programming the Fuse Low bits is as follows (refer to “Programming the Flash” on page 293 for details on Command and Data loading): 1. A: Load Command “0100 0000”. 2. C: Load Data Low Byte. Bit n = “0” programs and bit n = “1” erases the Fuse bit. 3. Give WR a negative pulse and wait for RDY/BSY to go high. 27.7.
27.7.11 Programming the Lock Bits The algorithm for programming the Lock bits is as follows (refer to “Programming the Flash” on page 293 for details on Command and Data loading): 1. A: Load Command “0010 0000”. 2. C: Load Data Low Byte. Bit n = “0” programs the Lock bit. If LB mode 3 is programmed (LB1 and LB2 is programmed), it is not possible to program the Boot Lock bits by any External Programming mode. 3. Give WR a negative pulse and wait for RDY/BSY to go high.
Atmel ATmega328P [Preliminary] 27.7.14 Reading the Calibration Byte The algorithm for reading the Calibration byte is as follows (refer to “Programming the Flash” on page 293 for details on Command and Address loading): 1. A: Load Command “0000 1000”. 2. B: Load Address Low Byte, 0x00. 3. Set OE to “0”, and BS1 to “1”. The Calibration byte can now be read at DATA. 4. Set OE to “1”. 27.7.15 27.
27.8.1 Serial Programming Pin Mapping Table 27-15. Pin Mapping Serial Programming 27.8.2 Symbol Pins I/O Description MOSI PB3 I Serial Data in MISO PB4 O Serial Data out SCK PB5 I Serial Clock Serial Programming Algorithm When writing serial data to the ATmega328P, data is clocked on the rising edge of SCK. When reading data from the ATmega328P, data is clocked on the falling edge of SCK. See Figure 27-9 for timing details.
Atmel ATmega328P [Preliminary] If polling (RDY/BSY) is not used, the used must wait at least tWD_EEPROM before issuing the next byte (See Table 27-16). In a chip erased device, no 0xFF in the data file(s) need to be programmed. 6. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO. 7. At the end of the programming session, RESET can be set high to commence normal operation. 8.
Table 27-17.
Atmel ATmega328P [Preliminary] Figure 27-8. Serial Programming Instruction example Serial Programming Instruction Load Program Memory Page (High/Low Byte)/ Load EEPROM Memory Page (page access) Byte 1 Byte 2 Adr MSB A Bit 15 B Byte 3 Write Program Memory Page/ Write EEPROM Memory Page Byte 1 Byte 4 Byte 2 Adr LSB Adr MSB Bit 15 B 0 Byte 3 Byte 4 Adrr LSB B 0 Page Buffer Page Offset Page 0 Page 1 Page 2 Page Number Page N-1 Program Memory/ EEPROM Memory 27.8.
28. Electrical Characteristics All DC/AC characteristics contained in this datasheet are based on characterization of ATmega328P AVR microcontroller manufactured in an automotive process technology. 28.1 Absolute Maximum Ratings* Operating Temperature.................................. -55°C to +125°C *NOTICE: Storage Temperature ..................................... -65°C to +150°C Voltage on any Pin except RESET with respect to Ground ................................-0.5V to VCC+0.
Atmel ATmega328P [Preliminary] 28.2 DC Characteristics. TA = -40°C to 125°C, VCC = 2.7V to 5.5V (unless otherwise noted) Symbol Parameter Condition Min. VIL Input Low Voltage, except XTAL1 and RESET pin VCC = 2.7V - 5.5V VIH Input High Voltage, except XTAL1 and RESET pins VIL1 Max. Units -0.5 0.3VCC(1) V VCC = 2.7V - 5.5V 0.6VCC(2) VCC + 0.5 V Input Low Voltage, XTAL1 pin VCC = 2.7V - 5.5V -0.5 0.1VCC(1) V VIH1 Input High Voltage, XTAL1 pin VCC = 2.7V - 5.5V 0.7VCC(2) VCC + 0.
28.3 DC Characteristics TA = -40°C to 125°C, VCC = 2.7V to 5.5V (unless otherwise noted) Symbol Parameter Typ.(2) Max. Units Active 4 MHz, VCC = 3V 1.5 2.4 mA Active 8 MHz, VCC = 5V 5.2 10 mA Active 16 MHz, VCC = 5V 9.2 14 mA Idle 4 MHz, VCC = 3V 0.25 0.6 mA Idle 8 MHz, VCC = 5V 1.0 1.6 mA Idle 16 MHz, VCC = 5V 1.9 2.
Atmel ATmega328P [Preliminary] 28.5 Clock Characteristics 28.5.1 Calibrated Internal RC Oscillator Accuracy Table 28-1. Calibration Accuracy of Internal RC Oscillator Frequency Factory Calibration 28.5.2 VCC Temperature Calibration Accuracy 3V 25°C ±2% 2.7V - 5.5V -40°C - 125°C ±14% 8.0 MHz Watchdog Oscillator Accuracy Table 28-2. Accuracy of Watchdog Oscillator Symbol Fwdt 28.5.3 Parameter Condition Min Typ Max Units Watchdog oscillator frequency Vcc = 2.7 - 5.
28.6 System and Reset Characteristics Table 28-4. Symbol Reset, Brown-out and Internal Voltage Characteristics Parameter Min Brown-out Detector Hysteresis VHYST Table 28-5. Max Units 80 Bandgap reference voltage VBG Typ VCC=5V 1.0 1.1 mV 1.2 V BODLEVEL Fuse Coding(1) BODLEVEL 2:0 Fuses Min VBOT Typ VBOT 111 Max VBOT Units V BOD Disabled 110 Reserved 101 2.5 2.7 2.9 100 4.0 4.3 4.6 011 010 Reserved 001 000 Notes: 308 1.
Atmel ATmega328P [Preliminary] 28.7 SPI Timing Characteristics See Figure 28-3 and Figure 28-4 for details. Table 28-6. 1 SPI Timing Parameters Description Mode SCK period Master Min Typ Max See Table 18-5 2 SCK high/low Master 50% duty cycle 3 Rise/Fall time Master 3.6 4 Setup Master 10 5 Hold Master 10 6 Out to SCK Master 0.
Figure 28-4. SPI Interface Timing Requirements (Slave Mode) SS 10 9 16 SCK (CPOL = 0) 11 11 SCK (CPOL = 1) 13 MOSI (Data Input) 14 12 MSB ... LSB 15 MISO (Data Output) 310 MSB 17 ...
Atmel ATmega328P [Preliminary] 28.8 2-wire Serial Interface Characteristics Table 28-7 describes the requirements for devices connected to the 2-wire Serial Bus. The ATmega328P 2-wire Serial Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 28-5. Table 28-7. 2-wire Serial Bus Requirements Symbol Parameter Min Max Units VIL Input Low-voltage -0.5 0.3 VCC V VIH Input High-voltage 0.7 VCC VCC + 0.
Figure 28-5. 2-wire Serial Bus Timing tof tHIGH tr tLOW tLOW SCL tSU;STA tHD;STA tHD;DAT tSU;DAT tSU;STO SDA tBUF 28.9 ADC Characteristics Table 28-8. Symbol ADC Characteristics Parameter Condition Resolution Min Typ -40°c +125°c / 2.70 - 5.50V Max Units 10 bits ADC clock = 200kHz TUE Absolute accuracy Vcc = 4.0v, VRef = 4.0v 2.2 3.5 LSB INL Integral Non Linearity Vcc = 4.0v, VRef = 4.0v 0.6 1.5 LSB DNL Differential Non Linearity Vcc = 4.0v, VRef = 4.0v 0.3 0.
Atmel ATmega328P [Preliminary] Table 28-9. Parallel Programming Characteristics, VCC = 5V ± 10% (Continued) Symbol Parameter Min tPHPL PAGEL Pulse Width High 150 ns tPLBX BS1 Hold after PAGEL Low 67 ns tWLBX BS2/1 Hold after WR Low 67 ns tPLWL PAGEL Low to WR Low 67 ns tBVWL BS1 Valid to WR Low 67 ns tWLWH WR Pulse Width Low 150 ns tWLRL WR Low to RDY/BSY Low tWLRH WR Low to RDY/BSY High(1) (2) Max Units 0 1 µs 3.7 4.5 ms 7.
Figure 28-7. Parallel Programming Timing, Loading Sequence with Timing Requirements(1) LOAD ADDRESS (LOW BYTE) LOAD DATA LOAD DATA (HIGH BYTE) LOAD DATA (LOW BYTE) tXLPH t XLXH LOAD ADDRESS (LOW BYTE) tPLXH XTAL1 BS1 PAGEL DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte) XA0 XA1 Note: 1. The timing requirements shown in Figure 28-6 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation. Figure 28-8.
Atmel ATmega328P [Preliminary] 29. Typical Characteristics The data contained in this section are characterized values of actual automotive silicon. Unless otherwise specified, the data contained in this chapter are for -40° to 125°C. The following charts show typical behavior. These figures are not tested during manufacturing. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.
29.1 29.1.1 ATmega328P Typical Characteristics Active Supply Current Figure 29-1. Active Supply Current vs. Frequency. ACTIVE SUPPLY CURRENT vs. FREQUENCY 16 14 12 ICC ( mA) 10 5.5 8 5 6 4.5 3.6 4 3.3 3 2 2.7 0 0 2 4 6 8 10 12 14 16 18 20 Freq uency (MHz) Figure 29-2. Idle Supply Current vs. Frequency.. IDLE SUPPLY CURRENT vs . FREQUENCY 4 3.5 3 IC C (mA) 2.5 5.5 2 5 4.5 1.5 3.6 1 3.3 3 0.5 2.
Atmel ATmega328P [Preliminary] 29.1.2 Power-down Supply Current Figure 29-3. Power-Down Supply Current vs. VCC (Watchdog Timer Disabled). POWER-DOW N SUPPLY CURRENT vs. VCC WA TCHDOG TIMER DISABL ED - V t low par ts excluded 25 20 ICC (uA) 15 125 10 85 25 -45 5 0 2 2 .5 3 3.5 4 4.5 5 5.5 V CC (V ) Figure 29-4. Power-Down Supply Current vs. VCC (Watchdog Timer Enabled). POW ER-DOWN SUPPLY CURRENT vs.
29.1.3 Pin Pull-Up Figure 29-5. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V). I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE 160 140 120 125 IOP ( uA) 100 85 80 25 60 -45 40 20 0 0 0.5 1 1 .5 2 2.5 3 3.5 4 4.5 5 VOP (V ) Figure 29-6. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5 V). RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE 120 100 125 IRES E T (uA) 80 85 25 60 -45 40 20 0 0 0.5 1 1.5 2 2.5 3 3.5 4 4.
Atmel ATmega328P [Preliminary] 29.1.4 Pin Driver Strength Figure 29-7. I/O Pin Output Voltage vs. Sink Current (VCC = 3 V). I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT V cc = 3v 1.2 1 V OL ( V) 0.8 125 85 0.6 25 -45 0.4 0.2 0 0 2 4 6 8 10 12 14 16 18 20 IOL ( mA ) Figure 29-8. I/O Pin Output Voltage vs. Sink Current (VCC = 5 V). I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT V cc = 5v 0.7 0.6 0.5 V OL ( V) 125 0.4 85 25 0.3 -45 0.2 0.
Figure 29-9. I/O Pin Output Voltage vs. Source Current (Vcc = 3 V). I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT V cc = 3 v 3.5 3 2.5 VOH (V ) 125 2 85 25 1.5 -45 1 0.5 0 0 2 4 6 8 10 12 14 16 18 20 IOH ( mA ) Figure 29-10. I/O Pin Output Voltage vs. Source Current(VCC = 5 V). I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT Vc c = 5v 5.1 5 V OH ( V) 4.9 4.8 125 4.7 85 4.6 25 -45 4.5 4.4 4.3 4.
Atmel ATmega328P [Preliminary] 29.1.5 Pin Threshold and Hysteresis Figure 29-11. I/O Pin Input Threshold Voltage vs. VCC (VIH, I/O Pin read as ‘1’). I/O PIN INPUT THRESHOLD VOLTAGE vs. V CC V IH, IO PIN REA D A S '1' 3.5 3 Thresh old ( V) 2.5 125 2 85 25 1.5 -45 1 0.5 0 2 2.5 3 3.5 4 4.5 5 5 .5 V CC ( V) Figure 29-12. I/O Pin Input Threshold Voltage vs. VCC (VIL, I/O Pin read as ‘0’).. I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC V IL, IO PIN REA D A S '0' 2.5 Th resh old ( V) 2 125 1.
Figure 29-13. Reset Input Threshold Voltage vs. VCC (VIH, I/O Pin read as ‘1’). Figure 29-14. Reset Input Threshold Voltage vs. VCC (VIL, I/O Pin read as ‘0’).. RESET INPUT THRESHOLD VOLTAGE vs. V CC V IL, IO PIN REA D A S '0' 2.5 Thresh old ( V) 2 125 1.5 85 25 1 -45 0.5 0 2 2.5 3 3 .5 4 4.5 5 5.
Atmel ATmega328P [Preliminary] 29.1.6 BOD Threshold Figure 29-15. BOD Thresholds vs. Temperature (BODLEVEL is 2.7 V). BOD THRESHOLDS vs. TEMPERATURE BOD LEV EL IS 2.7 V 3 2.9 Th resh old ( V) 2.8 1 2.7 0 2.6 2.5 2.4 -60 -5 0 - 40 -30 - 20 -10 0 10 20 30 40 50 60 70 80 90 100 110 1 20 130 14 0 Te mp eratur e ( C) Figure 29-16. BOD Thresholds vs. Temperature (BODLEVEL is 4.3 V). BOD THRESHOLDS vs. TEMPERATURE BOD LEV EL IS 4.3 V 4.6 4.5 Th resh old ( V) 4.4 1 4.3 0 4.2 4.
29.1.7 Internal Oscilllator Speed Figure 29-17. Watchdog Oscillator Frequency vs. Temperature.. W ATCHDOG OSCILLATOR FREQUENCY vs. TEMPERATURE 160 150 140 FR C (k Hz) 130 5.5 120 5 110 4.5 100 3.3 3 90 2.7 80 - 40 -30 -20 - 10 0 10 20 30 40 50 60 70 80 90 100 1 10 120 Temper atur e Figure 29-18. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature 8 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE CALIBRATED XXXMHz 100 00 Cy cles s ample d w ith 250n S 8.4 8.3 FRC ( MHz) 8.
Atmel ATmega328P [Preliminary] Figure 29-19. Calibrated 8 MHz RC Oscillator Frequency vs. OSCCAL Value. CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE 1000 0 Cyc les sampled w ith 250nS - V cc = 5.
30.
Atmel ATmega328P [Preliminary] Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 (0xBF) Reserved – – – – – – – – – Page (0xBE) Reserved – – – – – – – (0xBD) TWAMR TWAM6 TWAM5 TWAM4 TWAM3 TWAM2 TWAM1 TWAM0 – 236 (0xBC) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE 233 (0xBB) TWDR (0xBA) TWAR TWA6 TWA5 TWA4 (0xB9) TWSR TWS7 TWS6 TWS5 (0xB8) TWBR (0xB7) Reserved – (0xB6) ASSR – (0xB5) Reserved – 2-wire Serial Interface Data Re
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 (0x7D) Reserved – – – – – – – – (0x7C) ADMUX REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 256 (0x7B) ADCSRB – ACME – – – ADTS2 ADTS1 ADTS0 259 (0x7A) ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 (0x79) ADCH ADC Data Register High byte Page 257 259 (0x78) ADCL (0x77) Reserved – – – – – – – – (0x76) Reserved – – – – – – – – (0x75) Reserved – – – – – – – – (0x74
Atmel ATmega328P [Preliminary] Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page 0x1F (0x3F) EECR – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE 21 0x1E (0x3E) GPIOR0 0x1D (0x3D) EIMSK – – – – – – INT1 INT0 63 0x1C (0x3C) EIFR – – – – – – INTF1 INTF0 63 0x1B (0x3B) PCIFR – – – – – PCIF2 PCIF1 PCIF0 0x1A (0x3A) Reserved – – – – – – – – 0x19 (0x39) Reserved – – – – – – – – 0x18 (0x38) Reserved – – – – – – – – 0x17 (0x
31.
Atmel ATmega328P [Preliminary] Mnemonics BRID Operands k Description Operation Flags #Clocks Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2 BIT AND BIT-TEST INSTRUCTIONS SBI P,b Set Bit in I/O Register I/O(P,b) ← 1 None 2 CBI P,b Clear Bit in I/O Register I/O(P,b) ← 0 None 2 LSL Rd Logical Shift Left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z,C,N,V 1 LSR Rd Logical Shift Right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z,C,N,V 1 ROL Rd Rotate Left Through Carry Rd(0)←C,Rd(n+1)
Mnemonics Operands Description Operation Flags #Clocks MCU CONTROL INSTRUCTIONS NOP No Operation None 1 SLEEP Sleep (see specific descr. for Sleep function) None 1 WDR BREAK Watchdog Reset Break (see specific descr.
Atmel ATmega328P [Preliminary] 32. Ordering Information 32.1 ATmega328P Speed (MHz)(2) Power Supply Ordering Code Package(1) Operational Range 16 2.7 - 5.5 ATmega328P- 15AZ MA Automotive (-40°C to 125°C) 16 2.7 - 5.5 ATmega328P- 15MZ PN Automotive (-40°C to 125°C) Notes: 1. Pb-free packaging complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).Also Halide free and fully Green. 2. See Figure 28-3 on page 309.
33. Packaging Information 33.
Atmel ATmega328P [Preliminary] 33.
34. Errata 34.1 Errata ATmega328P The revision letter in this section refers to the revision of the ATmega328P device. 34.1.1 Revision D No known errata. 34.1.2 Revision A to Revision C Not sampled. 35. Datasheet Revision History Please note that the referring page numbers in this section are referred to this document. The referring revision in this section are referring to the document revision. 35.1 Rev. C- 10/12 1. ATmega88P and ATmega168P references removed. 35.2 Rev. B - 03/12 1.
Atmel ATmega328P [Preliminary] 36. Table of Contents Features ..................................................................................................... 1 1 2 Pin Configurations ................................................................................... 2 1.1 Pin Descriptions .................................................................................................3 1.2 Disclaimer .................................................................................................
9 8.7 128 kHz Internal Oscillator ..............................................................................32 8.8 External Clock .................................................................................................33 8.9 Clock Output Buffer .........................................................................................34 8.10 Timer/Counter Oscillator ..................................................................................34 8.11 System Clock Prescaler .........
Atmel ATmega328P [Preliminary] 13 I/O-Ports .................................................................................................. 66 13.1 Overview ..........................................................................................................66 13.2 Ports as General Digital I/O .............................................................................67 13.3 Alternate Port Functions ..................................................................................71 13.
17.3 Timer/Counter Clock Sources .......................................................................137 17.4 Counter Unit ..................................................................................................137 17.5 Output Compare Unit .....................................................................................138 17.6 Compare Match Output Unit ..........................................................................140 17.7 Modes of Operation ............................
Atmel ATmega328P [Preliminary] 20.8 Register Description ......................................................................................203 21 2-wire Serial Interface .......................................................................... 206 21.1 Features ........................................................................................................206 21.2 2-wire Serial Interface Bus Definition ............................................................206 21.
25.2 Addressing the Flash During Self-Programming ...........................................264 25.3 Register Description’ .....................................................................................269 26 Boot Loader Support – Read-While-Write Self-Programming ......... 271 26.1 Features ........................................................................................................271 26.2 Overview ...................................................................................
Atmel ATmega328P [Preliminary] 30 Register Summary ............................................................................... 326 31 Instruction Set Summary .................................................................... 330 32 Ordering Information ........................................................................... 333 32.1 ATmega328P .................................................................................................333 33 Packaging Information .............................
Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131 USA Tel: (+1)(408) 441-0311 Fax: (+1)(408) 487-2600 Atmel Asia Limited Unit 01-5 & 16, 19/F BEA Tower, Millennium City 5 418 Kwun Tong Road Kwun Tong, Kowloon HONG KONG Tel: (+852) 2245-6100 Fax: (+852) 2722-1369 Atmel Munich GmbH Business Campus Parkring 4 D-85748 Garching b. Munich GERMANY Tel: (+49) 89-31970-0 Fax: (+49) 89-3194621 Atmel Japan 9F, Tonetsu Shinkawa Bldg.