8-bit - zbasiccbga-pinout atmega640/1280/2560. 12 3 4 5 678 910 a gnd aref pf0 pf2 pf5 pk0 pk3 pk6...

449
2549K–AVR–01/07 Features High Performance, Low Power AVR ® 8-Bit Microcontroller Advanced RISC Architecture 135 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 Non-volatile Program and Data Memories 64K/128K/256K Bytes of In-System Self-Programmable Flash Endurance: 10,000 Write/Erase Cycles Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation 4K Bytes EEPROM Endurance: 100,000 Write/Erase Cycles 8K Bytes Internal SRAM Up to 64K Bytes Optional External Memory Space Programming Lock for Software Security JTAG (IEEE std. 1149.1 compliant) Interface Boundary-scan Capabilities According to the JTAG Standard Extensive On-chip Debug Support Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface Peripheral Features Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode Four 16-bit Timer/Counter with Separate Prescaler, Compare- and Capture Mode Real Time Counter with Separate Oscillator Four 8-bit PWM Channels Six/Twelve PWM Channels with Programmable Resolution from 2 to 16 Bits (ATmega1281/2561, ATmega640/1280/2560) Output Compare Modulator 8/16-channel, 10-bit ADC (ATmega1281/2561, ATmega640/1280/2560) Two/Four Programmable Serial USART (ATmega1281/2561,ATmega640/1280/2560) Master/Slave SPI Serial Interface Byte Oriented 2-wire Serial Interface Programmable Watchdog Timer with Separate On-chip Oscillator On-chip Analog Comparator Interrupt and Wake-up on Pin Change Special Microcontroller Features Power-on Reset and Programmable Brown-out Detection Internal Calibrated Oscillator External and Internal Interrupt Sources Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby I/O and Packages 54/86 Programmable I/O Lines (ATmega1281/2561, ATmega640/1280/2560) 64-pad QFN/MLF, 64-lead TQFP (ATmega1281/2561) 100-lead TQFP, 100-ball CBGA (ATmega640/1280/2560) RoHS/Fully Green Temperature Range: – -40°C to 85°C Industrial Ultra-Low Power Consumption Active Mode: 1 MHz, 1.8V: 510 μA Power-down Mode: 0.1 μA at 1.8V Speed Grade (see “Maximum speed vs. VCC” on page 377): – ATmega640V/ATmega1280V/ATmega1281V: 0 - 4 MHz @ 1.8 - 5.5V, 0 - 8 MHz @ 2.7 - 5.5V – ATmega2560V/ATmega2561V: 0 - 2 MHz @ 1.8 - 5.5V, 0 - 8 MHz @ 2.7 - 5.5V – ATmega640/ATmega1280/ATmega1281: 0 - 8 MHz @ 2.7 - 5.5V, 0 - 16 MHz @ 4.5 - 5.5V – ATmega2560/ATmega2561: 0 - 16 MHz @ 4.5 - 5.5V 8-bit Microcontroller with 64K/128K/256K Bytes In-System Programmable Flash ATmega640/V ATmega1280/V ATmega1281/V ATmega2560/V ATmega2561/V Preliminary

Upload: others

Post on 27-Jan-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

  • 2549K–AVR–01/07

    8-bit Microcontroller with 64K/128K/256K Bytes In-SystemProgrammable Flash

    ATmega640/VATmega1280/VATmega1281/VATmega2560/VATmega2561/V

    Preliminary

    Features• High Performance, Low Power AVR® 8-Bit Microcontroller• Advanced RISC Architecture

    – 135 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

    • Non-volatile Program and Data Memories– 64K/128K/256K Bytes of In-System Self-Programmable Flash

    Endurance: 10,000 Write/Erase Cycles– Optional Boot Code Section with Independent Lock Bits

    In-System Programming by On-chip Boot ProgramTrue Read-While-Write Operation

    – 4K Bytes EEPROMEndurance: 100,000 Write/Erase Cycles

    – 8K Bytes Internal SRAM– Up to 64K Bytes Optional External Memory Space– Programming Lock for Software Security

    • JTAG (IEEE std. 1149.1 compliant) Interface– Boundary-scan Capabilities According to the JTAG Standard– Extensive On-chip Debug Support– Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface

    • Peripheral Features– Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode– Four 16-bit Timer/Counter with Separate Prescaler, Compare- and Capture Mode– Real Time Counter with Separate Oscillator– Four 8-bit PWM Channels– Six/Twelve PWM Channels with Programmable Resolution from 2 to 16 Bits

    (ATmega1281/2561, ATmega640/1280/2560)– Output Compare Modulator– 8/16-channel, 10-bit ADC (ATmega1281/2561, ATmega640/1280/2560)– Two/Four Programmable Serial USART (ATmega1281/2561,ATmega640/1280/2560)– Master/Slave SPI Serial Interface– Byte Oriented 2-wire Serial Interface– Programmable Watchdog Timer with Separate On-chip Oscillator– On-chip Analog Comparator– Interrupt and Wake-up on Pin Change

    • Special Microcontroller Features– Power-on Reset and Programmable Brown-out Detection– Internal Calibrated Oscillator– External and Internal Interrupt Sources– Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby,

    and Extended Standby• I/O and Packages

    – 54/86 Programmable I/O Lines (ATmega1281/2561, ATmega640/1280/2560)– 64-pad QFN/MLF, 64-lead TQFP (ATmega1281/2561)– 100-lead TQFP, 100-ball CBGA (ATmega640/1280/2560)– RoHS/Fully Green

    • Temperature Range:– -40°C to 85°C Industrial

    • Ultra-Low Power Consumption– Active Mode: 1 MHz, 1.8V: 510 µA– Power-down Mode: 0.1 µA at 1.8V

    • Speed Grade (see “Maximum speed vs. VCC” on page 377):– ATmega640V/ATmega1280V/ATmega1281V:

    0 - 4 MHz @ 1.8 - 5.5V, 0 - 8 MHz @ 2.7 - 5.5V– ATmega2560V/ATmega2561V:

    0 - 2 MHz @ 1.8 - 5.5V, 0 - 8 MHz @ 2.7 - 5.5V– ATmega640/ATmega1280/ATmega1281:

    0 - 8 MHz @ 2.7 - 5.5V, 0 - 16 MHz @ 4.5 - 5.5V– ATmega2560/ATmega2561:

    0 - 16 MHz @ 4.5 - 5.5V

  • Pin Configurations

    Figure 1. TQFP-pinout ATmega640/1280/2560

    GN

    D

    VC

    C

    PA0

    (AD

    0)

    PA1

    (AD

    1)

    PA2

    (AD

    2)

    PA3 (AD3)

    PA4 (AD4)

    PA5 (AD5)

    PA6 (AD6)

    PA7 (AD7)

    PG2 (ALE)

    AV

    CC

    GN

    D

    AR

    EF

    PF

    0 (A

    DC

    0)

    PF

    1 (A

    DC

    1)

    PF

    2 (A

    DC

    2)

    PF

    3 (A

    DC

    3)

    PF

    4 (A

    DC

    4/T

    CK

    )

    PF

    5 (A

    DC

    5/T

    MS

    )

    PF

    6 (A

    DC

    6/T

    DO

    )

    PF

    7 (A

    DC

    7/T

    DI)

    ATmega640/1280/2560

    100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    75

    74

    73

    72

    71

    70

    69

    68

    67

    66

    65

    64

    63

    62

    61

    60

    59

    58

    57

    56

    55

    54

    53

    52

    51

    26 28 29 3127 3630 32 35 3733 34 38 39 40 41 42 43 44 45 46 47 48 49 50

    PK

    0 (A

    DC

    8/P

    CIN

    T16

    )

    PK

    1 (A

    DC

    9/P

    CIN

    T17

    )

    PK

    2 (A

    DC

    10/P

    CIN

    T18

    )

    PK

    3 (A

    DC

    11/P

    CIN

    T19

    )

    PK

    4 (A

    DC

    12/P

    CIN

    T20

    )

    PK

    5 (A

    DC

    13/P

    CIN

    T21

    )

    PK

    6 (A

    DC

    14/P

    CIN

    T22

    )

    PK

    7 (A

    DC

    15/P

    CIN

    T23

    )

    (OC2B) PH6

    (TO

    SC

    2) P

    G3

    (TO

    SC

    1) P

    G4

    RE

    SE

    T

    (T4)

    PH

    7

    (IC

    P4)

    PL0

    VC

    C

    GN

    D

    XTA

    L2

    XTA

    L1

    PL6

    PL7

    GND

    VCC

    (OC0B) PG5

    VCC

    GND

    (RXD2) PH0

    (TXD2) PH1

    (XCK2) PH2

    (OC4A) PH3

    (OC4B) PH4

    (OC4C) PH5

    (RXD0/PCINT8) PE0

    (TXD0) PE1

    (XCK0/AIN0) PE2

    (OC3A/AIN1) PE3

    (OC3B/INT4) PE4

    (OC3C/INT5) PE5

    (T3/INT6) PE6

    (CLKO/ICP3/INT7) PE7

    (SS/PCINT0) PB0

    (SCK/PCINT1) PB1

    (MOSI/PCINT2) PB2

    (MISO/PCINT3) PB3

    (OC2A/PCINT4) PB4

    (OC1A/PCINT5) PB5

    (OC1B/PCINT6) PB6

    (OC

    0A/O

    C1C

    /PC

    INT

    7) P

    B7

    PC7 (A15)

    PC6 (A14)

    PC5 (A13)

    PC4 (A12)

    PC3 (A11)

    PC2 (A10)

    PC1 (A9)

    PC0 (A8)

    PG1 (RD)

    PG0 (WR)

    (TX

    D1/

    INT

    3) P

    D3

    (IC

    P1)

    PD

    4

    (XC

    K1)

    PD

    5

    (T1)

    PD

    6

    (T0)

    PD

    7

    (SC

    L/IN

    T0)

    PD

    0

    (SD

    A/IN

    T1)

    PD

    1

    (RX

    D1/

    INT

    2) P

    D2

    (IC

    P5)

    PL1

    (T5)

    PL2

    (OC

    5A)

    PL3

    (OC

    5B)

    PL4

    PJ6 (PCINT15)

    PJ5 (PCINT14)

    PJ4 (PCINT13)

    PJ3 (PCINT12)

    PJ2 (XCK3/PCINT11)

    PJ1 (TXD3/PCINT10)

    PJ0 (RXD3/PCINT9)

    PJ7

    (OC

    5C)

    PL5

    INDEX CORNER

    2 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Figure 2. CBGA-pinout ATmega640/1280/2560

    Table 1. CBGA-pinout ATmega640/1280/2560.

    1 2 3 4 5 6 7 8 9 10

    A GND AREF PF0 PF2 PF5 PK0 PK3 PK6 GND VCC

    B AVCC PG5 PF1 PF3 PF6 PK1 PK4 PK7 PA0 PA2

    C PE2 PE0 PE1 PF4 PF7 PK2 PK5 PJ7 PA1 PA3

    D PE3 PE4 PE5 PE6 PH2 PA4 PA5 PA6 PA7 PG2

    E PE7 PH0 PH1 PH3 PH5 PJ6 PJ5 PJ4 PJ3 PJ2

    F VCC PH4 PH6 PB0 PL4 PD1 PJ1 PJ0 PC7 GND

    G GND PB1 PB2 PB5 PL2 PD0 PD5 PC5 PC6 VCC

    H PB3 PB4 RESET PL1 PL3 PL7 PD4 PC4 PC3 PC2

    J PH7 PG3 PB6 PL0 XTAL2 PL6 PD3 PC1 PC0 PG1

    K PB7 PG4 VCC GND XTAL1 PL5 PD2 PD6 PD7 PG0

    A

    B

    C

    D

    E

    F

    G

    H

    J

    K

    1 2 3 4 5 6 7 8 9 10

    A

    B

    C

    D

    E

    F

    G

    H

    J

    K

    10 9 8 7 6 5 4 3 2 1Top view Bottom view

    32549K–AVR–01/07

  • Figure 3. Pinout ATmega1281/2561

    Note: The large center pad underneath the QFN/MLF package is made of metal and internallyconnected to GND. It should be soldered or glued to the board to ensure good mechani-cal stability. If the center pad is left unconnected, the package might loosen from theboard.

    Disclaimer Typical values contained in this datasheet are based on simulations and characteriza-tion of other AVR microcontrollers manufactured on the same process technology. Min.and Max values will be available after the device is characterized.

    ATmega1281/2561

    (RXD0/PCINT8/PDI) PE0

    (TXD0/PDO) PE1

    (XCK0/AIN0) PE2

    (OC3A/AIN1) PE3

    (OC3B/INT4) PE4

    (OC3C/INT5) PE5

    (T3/INT6) PE6

    (ICP3/CLKO/INT7) PE7

    (SS/PCINT0) PB0

    (OC0B) PG5

    (SCK/PCINT1) PB1

    (MOSI/PCINT2) PB2

    (MISO/PCINT3) PB3

    (OC2A/ PCINT4) PB4

    (OC1A/PCINT5) PB5

    (OC1B/PCINT6) PB6

    (OC

    0A/O

    C1C

    /PC

    INT

    7) P

    B7

    (TO

    SC

    2) P

    G3

    (TO

    SC

    1) P

    G4

    RE

    SE

    T

    VC

    C

    GN

    D

    XTA

    L2

    XTA

    L1

    (SC

    L/IN

    T0)

    PD

    0

    (SD

    A/IN

    T1)

    PD

    1

    (RX

    D1/

    INT

    2) P

    D2

    (TX

    D1/

    INT

    3) P

    D3

    (IC

    P1)

    PD

    4

    (XC

    K1)

    PD

    5

    PA3 (AD3)

    PA4 (AD4)

    PA5 (AD5)

    PA6 (AD6)

    PA7 (AD7)

    PG2 (ALE)

    PC7 (A15)

    PC6 (A14)

    PC5 (A13)

    PC4 (A12)

    PC3 (A11)

    PC2 (A10)

    PC1 (A9)

    PC0 (A8)

    PG1 (RD)

    PG0 (WR)

    AV

    CC

    GN

    D

    AR

    EF

    PF

    0 (A

    DC

    0)

    PF

    1 (A

    DC

    1)

    PF

    2 (A

    DC

    2)

    PF

    3 (A

    DC

    3)

    PF

    4 (A

    DC

    4/T

    CK

    )

    PF

    5 (A

    DC

    5/T

    MS

    )

    PF

    6 (A

    DC

    6/T

    DO

    )

    PF

    7 (A

    DC

    7/T

    DI)

    GN

    D

    VC

    C

    PA0

    (AD

    0)

    PA1

    (AD

    1)

    PA2

    (AD

    2)

    (T1)

    PD

    6

    (T0)

    PD

    7

    INDEX CORNER

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49

    48

    47

    46

    45

    44

    43

    42

    41

    40

    39

    38

    37

    36

    35

    34

    33

    17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

    4 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    OverviewThe ATmega640/1280/1281/2560/2561 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISCarchitecture. By executing powerful instructions in a single clock cycle, the ATmega640/1280/1281/2560/2561 achievesthroughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processingspeed.

    Block Diagram

    Figure 4. Block Diagram

    CPU

    GND

    VCC

    RESET

    PowerSupervision

    POR / BOD &RESET

    WatchdogOscillator

    WatchdogTimer

    OscillatorCircuits /

    ClockGeneration

    XTAL1

    XTAL2

    PC7..0 PORT C (8)

    PA7..0 PORT A (8)

    PORT D (8)

    PD7..0

    PORT B (8)

    PB7..0

    PORT E (8)

    PE7..0

    PORT F (8)

    PF7..0

    PORT J (8)

    PJ7..0

    PG5..0 PORT G (6)

    PORT H (8)

    PH7..0

    PORT K (8)

    PK7..0

    PORT L (8)

    PL7..0

    XRAM

    TWI SPI

    EEPROM

    JTAG

    8bit T/C 0 8bit T/C 2

    16bit T/C 1

    16bit T/C 3

    SRAMFLASH

    16bit T/C 4

    16bit T/C 5

    USART 2

    USART 1

    USART 0

    Internal Bandgap reference

    Analog Comparator

    A/DConverter

    USART 3

    NOTE:Shaded parts only availablein the 100-pin version.

    Complete functionality forthe ADC, T/C4, and T/C5 only available in the 100-pin version.

    52549K–AVR–01/07

  • 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), allowingtwo independent registers to be accessed in one single instruction executed in one clockcycle. The resulting architecture is more code efficient while achieving throughputs up toten times faster than conventional CISC microcontrollers.

    The ATmega640/1280/1281/2560/2561 provides the following features: 64K/128K/256Kbytes of In-System Programmable Flash with Read-While-Write capabilities, 4K bytesEEPROM, 8K bytes SRAM, 54/86 general purpose I/O lines, 32 general purpose work-ing registers, Real Time Counter (RTC), six flexible Timer/Counters with comparemodes and PWM, 4 USARTs, a byte oriented 2-wire Serial Interface, a 16-channel, 10-bit ADC with optional differential input stage with programmable gain, programmableWatchdog Timer with Internal Oscillator, an SPI serial port, IEEE std. 1149.1 compliantJTAG test interface, also used for accessing the On-chip Debug system and program-ming and six software selectable power saving modes. The Idle mode stops the CPUwhile allowing the SRAM, Timer/Counters, SPI port, and interrupt system to continuefunctioning. The Power-down mode saves the register contents but freezes the Oscilla-tor, disabling all other chip functions until the next interrupt or Hardware Reset. InPower-save mode, the asynchronous timer continues to run, allowing the user to main-tain a timer base while the rest of the device is sleeping. The ADC Noise Reductionmode stops the CPU and all I/O modules except Asynchronous Timer and ADC, to min-imize switching noise during ADC conversions. In Standby mode, the Crystal/ResonatorOscillator is running while the rest of the device is sleeping. This allows very fast start-upcombined with low power consumption. In Extended Standby mode, both the mainOscillator and the Asynchronous Timer continue to run.

    The device is manufactured using Atmel’s high-density nonvolatile memory technology.The On-chip ISP Flash allows the program memory to be reprogrammed in-systemthrough an SPI serial interface, by a conventional nonvolatile memory programmer, orby an On-chip Boot program running on the AVR core. The boot program can use anyinterface to download the application program in the application Flash memory. Soft-ware in the Boot Flash section will continue to run while the Application Flash section isupdated, providing true Read-While-Write operation. By combining an 8-bit RISC CPUwith In-System Self-Programmable Flash on a monol i thic chip, the AtmelATmega640/1280/1281/2560/2561 is a powerful microcontroller that provides a highlyflexible and cost effective solution to many embedded control applications.

    The ATmega640/1280/1281/2560/2561 AVR is supported with a full suite of programand system development tools including: C compilers, macro assemblers, programdebugger/simulators, in-circuit emulators, and evaluation kits.

    6 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Comparison Between ATmega1281/2561 and ATmega640/1280/2560

    Each device in the ATmega640/1280/1281/2560/2561 family differs only in memory sizeand number of pins. Table 2 summarizes the different configurations for the six devices.

    Pin Descriptions

    VCC Digital supply voltage.

    GND Ground.

    Port A (PA7..PA0) Port A is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port A output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port A pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port A pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t A a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/1281/2560/2561 as listed on page 91.

    Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port B output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port B pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port B pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Port B has better driving capabilities than the other ports.

    Por t B a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/1281/2560/2561 as listed on page 92.

    Port C (PC7..PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port C output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port C pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port C pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t C a lso se rves the func t ions o f spec ia l fea tu res o f theATmega640/1280/1281/2560/2561 as listed on page 95.

    Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port D output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port D pins that are externally pulled low will source

    Table 2. Configuration Summary

    Device Flash EEPROM RAMGeneral

    Purpose I/O pins16 bits resolution

    PWM channelsSerial

    USARTsADC

    Channels

    ATmega640 64KB 4KB 8KB 86 12 4 16

    ATmega1280 128KB 4KB 8KB 86 12 4 16

    ATmega1281 128KB 4KB 8KB 54 6 2 8

    ATmega2560 256KB 4KB 8KB 86 12 4 16

    ATmega2561 256KB 4KB 8KB 54 6 2 8

    72549K–AVR–01/07

  • current if the pull-up resistors are activated. The Port D pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t D a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/1281/2560/2561 as listed on page 97.

    Port E (PE7..PE0) Port E is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port E output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port E pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port E pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t E a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/1281/2560/2561 as listed on page 99.

    Port F (PF7..PF0) Port F serves as analog inputs to the A/D Converter.

    Port F also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used.Port pins can provide internal pull-up resistors (selected for each bit). The Port F outputbuffers have symmetrical drive characteristics with both high sink and source capability.As inputs, Port F pins that are externally pulled low will source current if the pull-upresistors are activated. The Port F pins are tri-stated when a reset condition becomesactive, even if the clock is not running. If the JTAG interface is enabled, the pull-up resis-tors on pins PF7(TDI), PF5(TMS), and PF4(TCK) will be activated even if a resetoccurs.

    Port F also serves the functions of the JTAG interface.

    Port G (PG5..PG0) Port G is a 6-bit I/O port with internal pull-up resistors (selected for each bit). The Port Goutput buffers have symmetrical drive characteristics with both high sink and sourcecapability. As inputs, Port G pins that are externally pulled low will source current if thepull-up resistors are activated. The Port G pins are tri-stated when a reset conditionbecomes active, even if the clock is not running.

    Por t G a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/1281/2560/2561 as listed on page 105.

    Port H (PH7..PH0) Port H is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port H output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port H pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port H pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t H a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/2560 as listed on page 107.

    Port J (PJ7..PJ0) Port J is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port J output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port J pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port J pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t J a l so serves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/2560 as listed on page 109.

    Port K (PK7..PK0) Port K serves as analog inputs to the A/D Converter.

    8 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Port K is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port K output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port K pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port K pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t K a lso se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/2560 as listed on page 111.

    Port L (PL7..PL0) Port L is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for eachbit). The Port L output buffers have symmetrical drive characteristics with both high sinkand source capability. As inputs, Port L pins that are externally pulled low will sourcecurrent if the pull-up resistors are activated. The Port L pins are tri-stated when a resetcondition becomes active, even if the clock is not running.

    Por t L a l so se rves the func t ions o f va r ious spec ia l fea tu res o f theATmega640/1280/2560 as listed on page 113.

    RESET Reset input. A low level on this pin for longer than the minimum pulse length will gener-ate a reset, even if the clock is not running. The minimum pulse length is given in Table26 on page 58. Shorter pulses are not guaranteed to generate a reset.

    XTAL1 Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.

    XTAL2 Output from the inverting Oscillator amplifier.

    AVCC AVCC is the supply voltage pin for Port F and the A/D Converter. It should be externallyconnected to VCC, even if the ADC is not used. If the ADC is used, it should be con-nected to VCC through a low-pass filter.

    AREF This is the analog reference pin for the A/D Converter.

    Resources A comprehensive set of development tools and application notes, and datasheets areavailable for download on http://www.atmel.com/avr.

    About Code Examples This documentation contains simple code examples that briefly show how to use variousparts of the device. Be aware that not all C compiler vendors include bit definitions in theheader files and interrupt handling in C is compiler dependent. Please confirm with theC compiler documentation for more details.

    These code examples assume that the part specific header file is included before com-pilation. For I/O registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC","CBI", and "SBI" instructions must be replaced with instructions that allow access toextended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and"CBR".

    92549K–AVR–01/07

  • AVR CPU Core

    Introduction This section discusses the AVR core architecture in general. The main function of theCPU core is to ensure correct program execution. The CPU must therefore be able toaccess memories, perform calculations, control peripherals, and handle interrupts.

    Architectural Overview Figure 5. Block Diagram of the AVR Architecture

    In order to maximize performance and parallelism, the AVR uses a Harvard architecture– with separate memories and buses for program and data. Instructions in the programmemory are executed with a single level pipelining. While one instruction is being exe-cuted, the next instruction is pre-fetched from the program memory. This conceptenables instructions to be executed in every clock cycle. The program memory is In-System Reprogrammable Flash memory.

    The fast-access Register File contains 32 x 8-bit general purpose working registers witha 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,

    FlashProgramMemory

    InstructionRegister

    InstructionDecoder

    ProgramCounter

    Control Lines

    32 x 8GeneralPurpose

    Registrers

    ALU

    Statusand Control

    I/O Lines

    EEPROM

    Data Bus 8-bit

    DataSRAM

    Dire

    ct A

    ddre

    ssin

    g

    Indi

    rect

    Add

    ress

    ing

    InterruptUnit

    SPIUnit

    WatchdogTimer

    AnalogComparator

    I/O Module 2

    I/O Module1

    I/O Module n

    10 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    the operation is executed, and the result is stored back in the Register File – in oneclock cycle.

    Six of the 32 registers can be used as three 16-bit indirect address register pointers forData Space addressing – enabling efficient address calculations. One of the theseaddress pointers can also be used as an address pointer for look up tables in Flash pro-gram memory. These added function registers are the 16-bit X-, Y-, and Z-register,described later in this section.

    The ALU supports arithmetic and logic operations between registers or between a con-stant and a register. Single register operations can also be executed in the ALU. Afteran arithmetic operation, the Status Register is updated to reflect information about theresult of the operation.

    Program flow is provided by conditional and unconditional jump and call instructions,able to directly address the whole address space. Most AVR instructions have a single16-bit word format. Every program memory address contains a 16- or 32-bit instruction.

    Program Flash memory space is divided in two sections, the Boot Program section andthe Application Program section. Both sections have dedicated Lock bits for write andread/write protection. The SPM instruction that writes into the Application Flash memorysection must reside in the Boot Program section.

    During interrupts and subroutine calls, the return address Program Counter (PC) isstored on the Stack. The Stack is effectively allocated in the general data SRAM, andconsequently the Stack size is only limited by the total SRAM size and the usage of theSRAM. All user programs must initialize the SP in the Reset routine (before subroutinesor interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/Ospace. The data SRAM can easily be accessed through the five different addressingmodes supported in the AVR architecture.

    The memory spaces in the AVR architecture are all linear and regular memory maps.

    A flexible interrupt module has its control registers in the I/O space with an additionalGlobal Interrupt Enable bit in the Status Register. All interrupts have a separate InterruptVector in the Interrupt Vector table. The interrupts have priority in accordance with theirInterrupt Vector position. The lower the Interrupt Vector address, the higher the priority.

    The I/O memory space contains 64 addresses for CPU peripheral functions as ControlRegisters, SPI, and other I/O functions. The I/O Memory can be accessed directly, or asthe Data Space locations following those of the Register File, 0x20 - 0x5F. In addition,the ATmega640/1280/1281/2560/2561 has Extended I/O space from 0x60 - 0x1FF inSRAM where only the ST/STS/STD and LD/LDS/LDD instructions can be used.

    ALU – Arithmetic Logic Unit

    The high-performance AVR ALU operates in direct connection with all the 32 generalpurpose working registers. Within a single clock cycle, arithmetic operations betweengeneral purpose registers or between a register and an immediate are executed. TheALU operations are divided into three main categories – arithmetic, logical, and bit-func-tions. Some implementations of the architecture also provide a powerful multipliersupporting both signed/unsigned multiplication and fractional format. See the “Instruc-tion Set” section for a detailed description.

    Status Register The Status Register contains information about the result of the most recently executedarithmetic instruction. This information can be used for altering program flow in order toperform conditional operations. Note that the Status Register is updated after all ALUoperations, as specified in the Instruction Set Reference. This will in many cases

    112549K–AVR–01/07

  • remove the need for using the dedicated compare instructions, resulting in faster andmore compact code.

    The Status Register is not automatically stored when entering an interrupt routine andrestored when returning from an interrupt. This must be handled by software.

    SREG – AVR Status Register The AVR Status Register – SREG – is defined as:

    • Bit 7 – I: Global Interrupt Enable

    The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individ-ual interrupt enable control is then performed in separate control registers. If the GlobalInterrupt Enable Register is cleared, none of the interrupts are enabled independent ofthe individual interrupt enable settings. The I-bit is cleared by hardware after an interrupthas occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by the application with the SEI and CLI instructions, asdescribed in the instruction set reference.

    • Bit 6 – T: Bit Copy Storage

    The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source ordestination for the operated bit. A bit from a register in the Register File can be copiedinto T by the BST instruction, and a bit in T can be copied into a bit in a register in theRegister File by the BLD instruction.

    • Bit 5 – H: Half Carry Flag

    The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Isuseful in BCD arithmetic. See the “Instruction Set Description” for detailed information.

    • Bit 4 – S: Sign Bit, S = N ⊕ VThe S-bit is always an exclusive or between the Negative Flag N and the Two’s Comple-ment Overflow Flag V. See the “Instruction Set Description” for detailed information.

    • Bit 3 – V: Two’s Complement Overflow Flag

    The Two’s Complement Overflow Flag V supports two’s complement arithmetics. Seethe “Instruction Set Description” for detailed information.

    • Bit 2 – N: Negative Flag

    The Negative Flag N indicates a negative result in an arithmetic or logic operation. Seethe “Instruction Set Description” for detailed information.

    • Bit 1 – Z: Zero Flag

    The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the“Instruction Set Description” for detailed information.

    • Bit 0 – C: Carry Flag

    The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruc-tion Set Description” for detailed information.

    Bit 7 6 5 4 3 2 1 0

    0x3F (0x5F) I T H S V N Z C SREG

    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

    12 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    General Purpose Register File

    The Register File is optimized for the AVR Enhanced RISC instruction set. In order toachieve the required performance and flexibility, the following input/output schemes aresupported by the Register File:

    • One 8-bit output operand and one 8-bit result input

    • Two 8-bit output operands and one 8-bit result input

    • Two 8-bit output operands and one 16-bit result input

    • One 16-bit output operand and one 16-bit result input

    Figure 6 shows the structure of the 32 general purpose working registers in the CPU.

    Figure 6. AVR CPU General Purpose Working Registers

    Most of the instructions operating on the Register File have direct access to all registers,and most of them are single cycle instructions.

    As shown in Figure 6 on page 13, each register is also assigned a data memoryaddress, mapping them directly into the first 32 locations of the user Data Space.Although not being physically implemented as SRAM locations, this memory organiza-tion provides great flexibility in access of the registers, as the X-, Y- and Z-pointerregisters can be set to index any register in the file.

    7 0 Addr.

    R0 0x00

    R1 0x01

    R2 0x02

    R13 0x0D

    General R14 0x0E

    Purpose R15 0x0F

    Working R16 0x10

    Registers R17 0x11

    R26 0x1A X-register Low Byte

    R27 0x1B X-register High Byte

    R28 0x1C Y-register Low Byte

    R29 0x1D Y-register High Byte

    R30 0x1E Z-register Low Byte

    R31 0x1F Z-register High Byte

    132549K–AVR–01/07

  • 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 7.

    Figure 7. The X-, Y-, and Z-registers

    In the different addressing modes these address registers have functions as fixed dis-placement, automatic increment, and automatic decrement (see the instruction setreference for details).

    Stack Pointer The Stack is mainly used for storing temporary data, for storing local variables and forstoring return addresses after interrupts and subroutine calls. The Stack Pointer Regis-ter always points to the top of the Stack. Note that the Stack is implemented as growingfrom higher memory locations to lower memory locations. This implies that a StackPUSH command decreases the Stack Pointer.

    The Stack Pointer points to the data SRAM Stack area where the Subroutine and Inter-rupt Stacks are located. This Stack space in the data SRAM must be defined by theprogram before any subroutine calls are executed or interrupts are enabled. The StackPointer must be set to point above 0x0200. The initial value of the stack pointer is thelast address of the internal SRAM. The Stack Pointer is decremented by one when datais pushed onto the Stack with the PUSH instruction, and it is decremented by two forATmega640/1280/1281 and three for ATmega2560/2561 when the return address ispushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incre-mented by one when data is popped from the Stack with the POP instruction, and it isincremented by two for ATmega640/1280/1281 and three for ATmega2560/2561 whendata is popped from the Stack with return from subroutine RET or return from interruptRETI.

    The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The num-ber of bits actually used is implementation dependent. Note that the data space in someimplementations of the AVR architecture is so small that only SPL is needed. In thiscase, the SPH Register will not be present.

    15 XH XL 0

    X-register 7 0 7 0

    R27 (0x1B) R26 (0x1A)

    15 YH YL 0

    Y-register 7 0 7 0

    R29 (0x1D) R28 (0x1C)

    15 ZH ZL 0

    Z-register 7 0 7 0

    R31 (0x1F) R30 (0x1E)

    Bit 15 14 13 12 11 10 9 8

    0x3E (0x5E) SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH

    0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL

    7 6 5 4 3 2 1 0

    Read/Write R/W R/W R/W R/W R/W R/W R/W R/W

    R/W R/W R/W R/W R/W R/W R/W R/W

    Initial Value 0 0 1 0 0 0 0 1

    1 1 1 1 1 1 1 1

    14 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    RAMPZ – Extended Z-pointer Register for ELPM/SPM

    For ELPM/SPM instructions, the Z-pointer is a concatenation of RAMPZ, ZH, and ZL, asshown in Figure 8. Note that LPM is not affected by the RAMPZ setting.

    Figure 8. The Z-pointer used by ELPM and SPM

    The actual number of bits is implementation dependent. Unused bits in an implementa-tion will always read as zero. For compatibility with future devices, be sure to write thesebits to zero.

    EIND – Extended Indirect Register

    For EICALL/EIJMP instructions, the Indirect-pointer to the subroutine/routine is a con-catenation of EIND, ZH, and ZL, as shown in Figure 9. Note that ICALL and IJMP arenot affected by the EIND setting.

    Figure 9. The Indirect-pointer used by EICALL and EIJMP

    The actual number of bits is implementation dependent. Unused bits in an implementa-tion will always read as zero. For compatibility with future devices, be sure to write thesebits to zero.

    Bit 7 6 5 4 3 2 1 0

    0x3B (0x5B) RAMPZ7 RAMPZ6 RAMPZ5 RAMPZ4 RAMPZ3 RAMPZ2 RAMPZ1 RAMPZ0 RAMPZ

    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

    Bit (Individually)

    7 0 7 0 7 0

    RAMPZ ZH ZL

    Bit (Z-pointer) 23 16 15 8 7 0

    Bit 7 6 5 4 3 2 1 0

    0x3C (0x5C) EIND7 EIND6 EIND5 EIND4 EIND3 EIND2 EIND1 EIND0 EIND

    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

    Bit (Individual-ly)

    7 0 7 0 7 0

    EIND ZH ZL

    Bit (Indirect-pointer)

    23 16 15 8 7 0

    152549K–AVR–01/07

  • Instruction Execution Timing

    This section describes the general access timing concepts for instruction execution. TheAVR CPU is driven by the CPU clock clkCPU, directly generated from the selected clocksource for the chip. No internal clock division is used.

    Figure 10 shows the parallel instruction fetches and instruction executions enabled bythe Harvard architecture and the fast-access Register File concept. This is the basicpipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique resultsfor functions per cost, functions per clocks, and functions per power-unit.

    Figure 10. The Parallel Instruction Fetches and Instruction Executions

    Figure 11 shows the internal timing concept for the Register File. In a single clock cyclean ALU operation using two register operands is executed, and the result is stored backto the destination register.

    Figure 11. Single Cycle ALU Operation

    clk

    1st Instruction Fetch

    1st Instruction Execute2nd Instruction Fetch

    2nd Instruction Execute3rd Instruction Fetch

    3rd Instruction Execute4th Instruction Fetch

    T1 T2 T3 T4

    CPU

    Total Execution Time

    Register Operands Fetch

    ALU Operation Execute

    Result Write Back

    T1 T2 T3 T4

    clkCPU

    16 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Reset and Interrupt Handling

    The AVR provides several different interrupt sources. These interrupts and the separateReset Vector each have a separate program vector in the program memory space. Allinterrupts are assigned individual enable bits which must be written logic one togetherwith the Global Interrupt Enable bit in the Status Register in order to enable the interrupt.Depending on the Program Counter value, interrupts may be automatically disabledwhen Boot Lock bits BLB02 or BLB12 are programmed. This feature improves softwaresecurity. See the section “Memory Programming” on page 342 for details.

    The lowest addresses in the program memory space are by default defined as the Resetand Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 69.The list also determines the priority levels of the different interrupts. The lower theaddress the higher is the priority level. RESET has the highest priority, and next is INT0– the External Interrupt Request 0. The Interrupt Vectors can be moved to the start ofthe Boot Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR).Refer to “Interrupts” on page 69 for more information. The Reset Vector can also bemoved to the start of the Boot Flash section by programming the BOOTRST Fuse, see“Memory Programming” on page 342.

    When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interruptsare disabled. The user software can write logic one to the I-bit to enable nested inter-rupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit isautomatically set when a Return from Interrupt instruction – RETI – is executed.

    There are basically two types of interrupts. The first type is triggered by an event thatsets the Interrupt Flag. For these interrupts, the Program Counter is vectored to theactual Interrupt Vector in order to execute the interrupt handling routine, and hardwareclears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing alogic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while thecorresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remem-bered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one ormore interrupt conditions occur while the Global Interrupt Enable bit is cleared, the cor-responding Interrupt Flag(s) will be set and remembered until the Global InterruptEnable bit is set, and will then be executed by order of priority.

    The second type of interrupts will trigger as long as the interrupt condition is present.These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disap-pears before the interrupt is enabled, the interrupt will not be triggered.

    When the AVR exits from an interrupt, it will always return to the main program and exe-cute one more instruction before any pending interrupt is served.

    Note that the Status Register is not automatically stored when entering an interrupt rou-tine, nor restored when returning from an interrupt routine. This must be handled bysoftware.

    When using the CLI instruction to disable interrupts, the interrupts will be immediatelydisabled. No interrupt will be executed after the CLI instruction, even if it occurs simulta-

    172549K–AVR–01/07

  • neously with the CLI instruction. The following example shows how this can be used toavoid interrupts during the timed EEPROM write sequence.

    When using the SEI instruction to enable interrupts, the instruction following SEI will beexecuted before any pending interrupts, as shown in this example.

    Interrupt Response Time The interrupt execution response for all the enabled AVR interrupts is five clock cyclesminimum. After five clock cycles the program vector address for the actual interrupt han-dling routine is executed. During these five clock cycle period, the Program Counter ispushed onto the Stack. The vector is normally a jump to the interrupt routine, and thisjump takes three clock cycles. If an interrupt occurs during execution of a multi-cycleinstruction, this instruction is completed before the interrupt is served. If an interruptoccurs when the MCU is in sleep mode, the interrupt execution response time isincreased by five clock cycles. This increase comes in addition to the start-up time fromthe selected sleep mode.

    A return from an interrupt handling routine takes five clock cycles. During these fiveclock cycles, the Program Counter (three bytes) is popped back from the Stack, theStack Pointer is incremented by three, and the I-bit in SREG is set.

    Assembly Code Example

    in r16, SREG ; store SREG value

    cli ; 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 */

    __disable_interrupt();

    EECR |= (1

  • ATmega640/1280/1281/2560/2561

    AVR MemoriesThis section describes the different memories in the ATmega640/1280/1281/2560/2561.The AVR architecture has two main memory spaces, the Data Memory and the ProgramMemory space. In addition, the ATmega640/1280/1281/2560/2561 features anEEPROM Memory for data storage. All three memory spaces are linear and regular.

    In-System Reprogrammable Flash Program Memory

    The ATmega640/1280/1281/2560/2561 contains 64K/128K/256K bytes On-chip In-Sys-tem Reprogrammable Flash memory for program storage, see Table 3 on page 19.Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as32K/64K/128K x 16. For software security, the Flash Program memory space is dividedinto two sections, Boot Program section and Application Program section.

    The Flash memory has an endurance of at least 10,000 write/erase cycles. TheATmega640/1280/1281/2560/2561 Program Counter (PC) is 15/16/17 bits wide, thusaddressing the 32K/64K/128K program memory locations. The operation of Boot Pro-gram section and associated Boot Lock bits for software protection are described indetail in “Boot Loader Support – Read-While-Write Self-Programming” on page 323.“Memory Programming” on page 342 contains a detailed description on Flash dataserial downloading using the SPI pins or the JTAG interface.

    Constant tables can be allocated within the entire program memory address space (seethe LPM – Load Program Memory instruction description and ELPM - Extended LoadProgram Memory instruction description).

    Timing diagrams for instruction fetch and execution are presented in “Instruction Execu-tion Timing” on page 16.

    Table 3. Program Flash Memory Map

    Address (HEX)

    0Application Flash Section

    Boot Flash Section0x7FFF/0xFFFF/0x1FFFF

    192549K–AVR–01/07

  • SRAM Data Memory Table 4 on page 21 shows how the ATmega640/1280/1281/2560/2561 SRAM Memoryis organized.

    The ATmega640/1280/1281/2560/2561 is a complex microcontroller with more periph-eral units than can be supported within the 64 location reserved in the Opcode for the INand OUT instructions. For the Extended I/O space from $060 - $1FF in SRAM, only theST/STS/STD and LD/LDS/LDD instructions can be used.

    The first 4,608/8,704 Data Memory locations address both the Register File, the I/OMemory, Extended I/O Memory, and the internal data SRAM. The first 32 locationsaddress the Register file, the next 64 location the standard I/O Memory, then 416 loca-tions of Extended I/O memory and the next 8,192 locations address the internal dataSRAM.

    An op t iona l ex te rna l da ta SRAM can be used w i th theATmega640/1280/1281/2560/2561. This SRAM will occupy an area in the remainingaddress locations in the 64K address space. This area starts at the address followingthe internal SRAM. The Register file, I/O, Extended I/O and Internal SRAM occupies thelowest 4,608/8,704 bytes, so when using 64KB (65,536 bytes) of External Memory,60,478/56,832 Bytes of External Memory are available. See “External Memory Inter-face” on page 26 for details on how to take advantage of the external memory map.

    When the addresses accessing the SRAM memory space exceeds the internal datamemory locations, the external data SRAM is accessed using the same instructions asfor the internal data memory access. When the internal data memories are accessed,the read and write strobe pins (PG0 and PG1) are inactive during the whole accesscycle. External SRAM operation is enabled by setting the SRE bit in the XMCRARegister.

    Accessing external SRAM takes one additional clock cycle per byte compared to accessof the internal SRAM. This means that the commands LD, ST, LDS, STS, LDD, STD,PUSH, and POP take one additional clock cycle. If the Stack is placed in externalSRAM, interrupts, subroutine calls and returns take three clock cycles extra because thethree-byte program counter is pushed and popped, and external memory access doesnot take advantage of the internal pipe-line memory access. When external SRAM inter-face is used with wait-state, one-byte external access takes two, three, or four additionalclock cycles for one, two, and three wait-states respectively. Interrupts, subroutine callsand returns will need five, seven, or nine clock cycles more than specified in the instruc-tion set manual for one, two, and three wait-states.

    The five different addressing modes for the data memory cover: Direct, Indirect with Dis-placement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. Inthe Register file, registers R26 to R31 feature the indirect addressing pointer registers.

    The direct addressing reaches the entire data space.

    The Indirect with Displacement mode reaches 63 address locations from the baseaddress given by the Y- or Z-register.

    When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented.

    The 32 general purpose working registers, 64 I/O registers, and the 4,196/8,192 bytes ofinternal data SRAM in the ATmega640/1280/1281/2560/2561 are all accessible through

    20 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    all these addressing modes. The Register File is described in “General Purpose Regis-ter File” on page 13.

    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 Figure12.

    Figure 12. On-chip Data SRAM Access Cycles

    Table 4. Data Memory Map

    Address (HEX)

    0 - 1F 32 Registers

    20 - 5F 64 I/O Registers

    60 - 1FF 416 External I/O Registers

    200 Internal SRAM

    (8192 x 8)21FF

    2200 External SRAM

    (0 - 64K x 8)

    FFFF

    clk

    WR

    RD

    Data

    Data

    Address Address valid

    T1 T2 T3

    Compute Address

    Rea

    dW

    rite

    CPU

    Memory Access Instruction Next Instruction

    212549K–AVR–01/07

  • EEPROM Data Memory The ATmega640/1280/1281/2560/2561 contains 4K bytes of data EEPROM memory. Itis organized as a separate data space, in which single bytes can be read and written.The EEPROM has an endurance of at least 100,000 write/erase cycles. The accessbetween the EEPROM and the CPU is described in the following, specifying theEEPROM Address Registers, the EEPROM Data Register, and the EEPROM ControlRegister.

    For a detailed description of SPI, JTAG and Parallel data downloading to the EEPROM,see “Serial Downloading” on page 356, “Programming via the JTAG Interface” on page361, and “Programming the EEPROM” on page 350 respectively.

    EEPROM Read/Write Access The EEPROM Access Registers are accessible in the I/O space, see “Register Descrip-tion” on page 32.

    The write access time for the EEPROM is given in Table 5 on page 22. A self-timingfunction, however, lets the user software detect when the next byte can be written. If theuser code contains instructions that write the EEPROM, some precautions must betaken. In heavily filtered power supplies, VCC is likely to rise or fall slowly on power-up/down. This causes the device for some period of time to run at a voltage lower thanspecified as minimum for the clock frequency used. See “Preventing EEPROM Corrup-tion” on page 24. for details on how to avoid problems in these situations.

    In order to prevent unintentional EEPROM writes, a specific write procedure must be fol-lowed. See the description of the EEPROM Control Register for details on this, “RegisterDescription” on page 32.

    When the EEPROM is read, the CPU is halted for four clock cycles before the nextinstruction is executed. When the EEPROM is written, the CPU is halted for two clockcycles before the next instruction is executed.

    The calibrated Oscillator is used to time the EEPROM accesses. Table 5 lists the typicalprogramming time for EEPROM access from the CPU.

    The following code examples show one assembly and one C function for writing to theEEPROM. The examples assume that interrupts are controlled (e.g. by disabling inter-rupts globally) so that no interrupts will occur during execution of these functions. Theexamples also assume that no Flash Boot Loader is present in the software. If suchcode is present, the EEPROM write function must also wait for any ongoing SPM com-mand to finish.

    Table 5. EEPROM Programming Time

    Symbol Number of Calibrated RC Oscillator Cycles Typ Programming Time

    EEPROM write (from CPU)

    26,368 3.3 ms

    22 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Note: 1. See “About Code Examples” on page 9.

    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(1)

    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. Theexamples assume that interrupts are controlled so that no interrupts will occur duringexecution of these functions.

    Note: 1. See “About Code Examples” on page 9.

    Preventing EEPROM Corruption

    During periods of low VCC, the EEPROM data can be corrupted because the supply volt-age is too low for the CPU and the EEPROM to operate properly. These issues are thesame as for board level systems using EEPROM, and the same design solutions shouldbe applied.

    An EEPROM data corruption can be caused by two situations when the voltage is toolow. First, a regular write sequence to the EEPROM requires a minimum voltage tooperate correctly. Secondly, the CPU itself can execute instructions incorrectly, if thesupply voltage is too low.

    EEPROM data corrupt ion can easi ly be avoided by fo l lowing th is designrecommendation:

    Keep the AVR RESET active (low) during periods of insufficient power supply voltage.This can be done by enabling the internal Brown-out Detector (BOD). If the detectionlevel of the internal BOD does not match the needed detection level, an external lowVCC reset Protection circuit can be used. If a reset occurs while a write operation is inprogress, the write operation will be completed provided that the power supply voltage issufficient.

    Assembly Code Example(1)

    EEPROM_read:

    ; Wait for completion of previous write

    sbic EECR,EEPE

    rjmp EEPROM_read

    ; Set up address (r18:r17) in address register

    out EEARH, r18

    out EEARL, r17

    ; Start eeprom read by writing EERE

    sbi EECR,EERE

    ; Read data from Data Register

    in r16,EEDR

    ret

    C Code Example(1)

    unsigned char EEPROM_read(unsigned int uiAddress)

    {

    /* Wait for completion of previous write */

    while(EECR & (1

  • ATmega640/1280/1281/2560/2561

    I/O Memory The I/O space definition of the ATmega640/1280/1281/2560/2561 is shown in “RegisterSummary” on page 416.

    All ATmega640/1280/1281/2560/2561 I/Os and peripherals are placed in the I/O space.All I/O locations may be accessed by the LD/LDS/LDD and ST/STS/STD instructions,transferring data between the 32 general purpose working registers and the I/O space.I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using theSBI and CBI instructions. In these registers, the value of single bits can be checked byusing the SBIS and SBIC instructions. Refer to the instruction set section for moredetails. When using the I/O specific commands IN and OUT, the I/O addresses 0x00 -0x3F must be used. When addressing I/O Registers as data space using LD and STins t ruc t ions , 0x20 mus t be added to these addresses . TheATmega640/1280/1281/2560/2561 is a complex microcontroller with more peripheralunits than can be supported within the 64 location reserved in Opcode for the IN andOUT instructions. For the Extended I/O space from 0x60 - 0x1FF in SRAM, only theST/STS/STD and LD/LDS/LDD instructions can be used.

    For compatibility with future devices, reserved bits should be written to zero if accessed.Reserved I/O memory addresses should never be written.

    Some of the Status Flags are cleared by writing a logical one to them. Note that, unlikemost other AVRs, the CBI and SBI instructions will only operate on the specified bit, andcan therefore be used on registers containing such Status Flags. The CBI and SBIinstructions work with registers 0x00 to 0x1F only.

    The I/O and peripherals control registers are explained in later sections.

    General Purpose I/O Registers The ATmega640/1280/1281/2560/2561 contains three General Purpose I/O Registers.These registers can be used for storing any information, and they are particularly usefulfor storing global variables and Status Flags. General Purpose I/O Registers within theaddress range 0x00 - 0x1F are directly bit-accessible using the SBI, CBI, SBIS, andSBIC instructions. See “Register Description” on page 32.

    252549K–AVR–01/07

  • External Memory Interface

    With all the features the External Memory Interface provides, it is well suited to operateas an interface to memory devices such as External SRAM and Flash, and peripheralssuch as LCD-display, A/D, and D/A. The main features are:

    • Four different wait-state settings (including no wait-state).• Independent wait-state setting for different External Memory sectors (configurable sector

    size)• The number of bits dedicated to address high byte is selectable• Bus keepers on data lines to minimize current consumption (optional)

    Overview When the eXternal MEMory (XMEM) is enabled, address space outside the internalSRAM becomes available using the dedicated External Memory pins (see Figure 3 onpage 4, Table 39 on page 91, Table 45 on page 95, and Table 57 on page 105). Thememory configuration is shown in Figure 13.

    Figure 13. External Memory with Sector Select

    Using the External Memory Interface

    The interface consists of:

    • AD7:0: Multiplexed low-order address bus and data bus.

    • A15:8: High-order address bus (configurable number of bits).

    • ALE: Address latch enable.

    • RD: Read strobe.

    • WR: Write strobe.

    The control bits for the External Memory Interface are located in two registers, the Exter-nal Memory Control Register A – XMCRA, and the External Memory Control Register B– XMCRB.

    When the XMEM interface is enabled, the XMEM interface will override the setting in thedata direction registers that corresponds to the ports dedicated to the XMEM interface.

    Memory Configuration A

    0x0000

    0x21FF

    External Memory(0-60K x 8)

    0xFFFF

    Internal memory

    SRL[2..0]

    SRW11SRW10

    SRW01SRW00

    Lower sector

    Upper sector

    0x2200

    26 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    For details about the port override, see the alternate functions in section “I/O-Ports” onpage 83. The XMEM interface will auto-detect whether an access is internal or external.If the access is external, the XMEM interface will output address, data, and the controlsignals on the ports according to Figure 15 (this figure shows the wave forms withoutwait-states). When ALE goes from high-to-low, there is a valid address on AD7:0. ALE islow during a data transfer. When the XMEM interface is enabled, also an internal accesswill cause activity on address, data and ALE ports, but the RD and WR strobes will nottoggle during internal access. When the External Memory Interface is disabled, the nor-mal pin and data direction settings are used. Note that when the XMEM interface isdisabled, the address space above the internal SRAM boundary is not mapped into theinternal SRAM. Figure 14 illustrates how to connect an external SRAM to the AVR usingan octal latch (typically “74 x 573” or equivalent) which is transparent when G is high.

    Address Latch Requirements Due to the high-speed operation of the XRAM interface, the address latch must beselected with care for system frequencies above 8 MHz @ 4V and 4 MHz @ 2.7V.When operating at conditions above these frequencies, the typical old style 74HC serieslatch becomes inadequate. The External Memory Interface is designed in compliance tothe 74AHC series latch. However, most latches can be used as long they comply withthe main timing parameters. The main parameters for the address latch are:

    • D to Q propagation delay (tPD).

    • Data setup time before G low (tSU).

    • Data (address) hold time after G low (TH).

    The External Memory Interface is designed to guaranty minimum address hold timeafter G is asserted low of th = 5 ns. Refer to tLAXX_LD/tLLAXX_ST in “External Data MemoryTiming” Tables 173 through Tables 180 on pages 385 - 387. The D-to-Q propagationdelay (tPD) must be taken into consideration when calculating the access time require-ment of the external component. The data setup time before G low (tSU) must notexceed address valid to ALE low (tAVLLC) minus PCB wiring delay (dependent on thecapacitive load).

    Figure 14. External SRAM Connected to the AVR

    D[7:0]

    A[7:0]

    A[15:8]

    RD

    WR

    SRAM

    D Q

    G

    AD7:0

    ALE

    A15:8

    RD

    WR

    AVR

    272549K–AVR–01/07

  • Pull-up and Bus-keeper The pull-ups on the AD7:0 ports may be activated if the corresponding Port register iswritten to one. To reduce power consumption in sleep mode, it is recommended to dis-able the pull-ups by writing the Port register to zero before entering sleep.

    The XMEM interface also provides a bus-keeper on the AD7:0 lines. The bus-keepercan be disabled and enabled in software as described in “XMCRB – External MemoryControl Register B” on page 36. When enabled, the bus-keeper will keep the previousvalue on the AD7:0 bus while these lines are tri-stated by the XMEM interface.

    Timing External Memory devices have different timing requirements. To meet these require-ments, the XMEM interface provides four different wait-states as shown in Table 8. It isimportant to consider the timing specification of the External Memory device beforeselecting the wait-state. The most important parameters are the access time for theexternal memory compared to the set-up requirement. The access time for the ExternalMemory is defined to be the time from receiving the chip select/address until the data ofthis address actually is driven on the bus. The access time cannot exceed the time fromthe ALE pulse must be asserted low until data is stable during a read sequence (SeetLLRL+ tRLRH - tDVRH in Tables 173 through Tables 180 on pages 385 - 387). The differentwait-states are set up in software. As an additional feature, it is possible to divide theexternal memory space in two sectors with individual wait-state settings. This makes itpossible to connect two different memory devices with different timing requirements tothe same XMEM interface. For XMEM interface timing details, please refer to Table 173to Table 180 and Figure 163 to Figure 166 in the “External Data Memory Timing” onpage 385.

    Note that the XMEM interface is asynchronous and that the waveforms in the followingfigures are related to the internal system clock. The skew between the internal andexternal clock (XTAL1) is not guarantied (varies between devices temperature, and sup-ply voltage). Consequently, the XMEM interface is not suited for synchronous operation.

    Figure 15. External Data Memory Cycles without Wait-state (SRWn1=0 and SRWn0=0)

    Note: 1. SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (uppersector) or SRW00 (lower sector). The ALE pulse in period T4 is only present if thenext instruction accesses the RAM (internal or external).

    ALE

    T1 T2 T3

    Writ

    eR

    ead

    WR

    T4

    A15:8 AddressPrev. addr.

    DA7:0 Address DataPrev. data XX

    RD

    DA7:0 (XMBK = 0) DataPrev. data Address

    DataPrev. data AddressDA7:0 (XMBK = 1)

    System Clock (CLKCPU)

    XXXXX XXXXXXXX

    28 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Figure 16. External Data Memory Cycles with SRWn1 = 0 and SRWn0 = 1(1)

    Note: 1. SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (uppersector) or SRW00 (lower sector).The ALE pulse in period T5 is only present if the next instruction accesses the RAM(internal or external).

    Figure 17. External Data Memory Cycles with SRWn1 = 1 and SRWn0 = 0(1)

    Note: 1. SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (uppersector) or SRW00 (lower sector).The ALE pulse in period T6 is only present if the next instruction accesses the RAM(internal or external).

    ALE

    T1 T2 T3

    Writ

    eR

    ead

    WR

    T5

    A15:8 AddressPrev. addr.

    DA7:0 Address DataPrev. data XX

    RD

    DA7:0 (XMBK = 0) DataPrev. data Address

    DataPrev. data AddressDA7:0 (XMBK = 1)

    System Clock (CLKCPU)

    T4

    ALE

    T1 T2 T3

    Writ

    eR

    ead

    WR

    T6

    A15:8 AddressPrev. addr.

    DA7:0 Address DataPrev. data XX

    RD

    DA7:0 (XMBK = 0) DataPrev. data Address

    DataPrev. data AddressDA7:0 (XMBK = 1)

    System Clock (CLKCPU)

    T4 T5

    292549K–AVR–01/07

  • Figure 18. External Data Memory Cycles with SRWn1 = 1 and SRWn0 = 1(1)

    Note: 1. SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (uppersector) or SRW00 (lower sector).The ALE pulse in period T7 is only present if the next instruction accesses the RAM(internal or external).

    Using all Locations of External Memory Smaller than 64 KB

    Since the external memory is mapped after the internal memory as shown in Figure 13,the external memory is not addressed when addressing the first 8,704 bytes of dataspace. It may appear that the first 8,704 bytes of the external memory are inaccessible(external memory addresses 0x0000 to 0x21FF). However, when connecting an exter-nal memory smaller than 64 KB, for example 32 KB, these locations are easily accessedsimply by addressing from address 0x8000 to 0xA1FF. Since the External MemoryAddress bit A15 is not connected to the external memory, addresses 0x8000 to 0xA1FFwill appear as addresses 0x0000 to 0x21FF for the external memory. Addressing aboveaddress 0xA1FF is not recommended, since this will address an external memory loca-tion that is already accessed by another (lower) address. To the Application software,the external 32 KB memory will appear as one linear 32 KB address space from 0x2200to 0xA1FF. This is illustrated in Figure 19.

    Figure 19. Address Map with 32 KB External Memory

    ALE

    T1 T2 T3

    Writ

    eR

    ead

    WR

    T7

    A15:8 AddressPrev. addr.

    DA7:0 Address DataPrev. data XX

    RD

    DA7:0 (XMBK = 0) DataPrev. data Address

    DataPrev. data AddressDA7:0 (XMBK = 1)

    System Clock (CLKCPU)

    T4 T5 T6

    0x0000

    0x21FF 0x2200

    0x7FFF 0x8000

    0x90FF 0x9100

    0x0000

    0x7FFF

    Internal Memory

    AVR Memory Map External 32K SRAM

    External

    Memory

    30 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Using all 64KB Locations of External Memory

    Since the External Memory is mapped after the Internal Memory as shown in Figure 13,only 56KB of External Memory is available by default (address space 0x0000 to 0x21FFis reserved for internal memory). However, it is possible to take advantage of the entireExternal Memory by masking the higher address bits to zero. This can be done by usingthe XMMn bits and control by software the most significant bits of the address. By set-ting Port C to output 0x00, and releasing the most significant bits for normal Port Pinoperation, the Memory Interface will address 0x0000 - 0x2FFF. See the following codeexamples.

    Care must be exercised using this option as most of the memory is masked away.

    Note: 1. See “About Code Examples” on page 9.

    Assembly Code Example(1)

    ; OFFSET is defined to 0x4000 to ensure; external memory access; Configure Port C (address high byte) to; output 0x00 when the pins are released; for normal Port Pin operation

    ldi r16, 0xFFout DDRC, r16ldi r16, 0x00out PORTC, r16; release PC7:6ldi r16, (1

  • Register Description

    EEPROM registers

    EEARH and EEARL – The EEPROM Address Register

    • Bits 15:12 – Res: Reserved Bits

    These bits are reserved bits and will always read as zero.

    • Bits 11:0 – EEAR8:0: EEPROM Address

    The EEPROM Address Registers – EEARH and EEARL specify the EEPROM addressin the 4K bytes EEPROM space. The EEPROM data bytes are addressed linearlybetween 0 and 4096. The initial value of EEAR is undefined. A proper value must bewritten before the EEPROM may be accessed.

    EEDR – The EEPROM Data Register

    • Bits 7:0 – EEDR7:0: EEPROM Data

    For the EEPROM write operation, the EEDR Register contains the data to be written tothe EEPROM in the address given by the EEAR Register. For the EEPROM read oper-ation, the EEDR contains the data read out from the EEPROM at the address given byEEAR.

    EECR – The EEPROM Control Register

    • Bits 7:6 – Res: Reserved Bits

    These bits are reserved bits and will always read as zero.

    • Bits 5, 4 – EEPM1 and EEPM0: EEPROM Programming Mode Bits

    The EEPROM Programming mode bit setting defines which programming action that willbe triggered when writing EEPE. It is possible to program data in one atomic operation(erase the old value and program the new value) or to split the Erase and Write opera-tions in two different operations. The Programming times for the different modes areshown in Table 6. While EEPE is set, any write to EEPMn will be ignored. During reset,the EEPMn bits will be reset to 0b00 unless the EEPROM is busy programming.

    Bit 15 14 13 12 11 10 9 8

    0x22 (0x42) – – – – EEAR11 EEAR10 EEAR9 EEAR8 EEARH

    0x21 (0x41) EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL

    7 6 5 4 3 2 1 0

    Read/Write R R R R R/W R/W R/W R/W

    R/W R/W R/W R/W R/W R/W R/W R/W

    Initial Value 0 0 0 0 X X X X

    X X X X X X X X

    Bit 7 6 5 4 3 2 1 0

    0x20 (0x40) MSB LSB EEDR

    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

    Bit 7 6 5 4 3 2 1 0

    0x1F (0x3F) – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE EECR

    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

    32 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    • Bit 3 – EERIE: EEPROM Ready Interrupt Enable

    Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set.Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates aconstant interrupt when EEPE is cleared.

    • Bit 2 – EEMPE: EEPROM Master Programming Enable

    The EEMPE bit determines whether setting EEPE to one causes the EEPROM to bewritten. When EEMPE is set, setting EEPE within four clock cycles will write data to theEEPROM at the selected address If EEMPE is zero, setting EEPE will have no effect.When EEMPE has been written to one by software, hardware clears the bit to zero afterfour clock cycles. See the description of the EEPE bit for an EEPROM write procedure.

    • Bit 1 – EEPE: EEPROM Programming Enable

    The EEPROM Write Enable Signal EEPE is the write strobe to the EEPROM. Whenaddress and data are correctly set up, the EEPE bit must be written to one to write thevalue into the EEPROM. The EEMPE bit must be written to one before a logical one iswritten to EEPE, otherwise no EEPROM write takes place. The following procedureshould be followed when writing the EEPROM (the order of steps 3 and 4 is notessential):

    1. Wait until EEPE becomes zero.

    2. Wait until SPMEN in SPMCSR becomes zero.

    3. Write new EEPROM address to EEAR (optional).

    4. Write new EEPROM data to EEDR (optional).

    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. Thesoftware must check that the Flash programming is completed before initiating a newEEPROM write. Step 2 is only relevant if the software contains a Boot Loader allowingthe CPU to program the Flash. If the Flash is never being updated by the CPU, step 2can be omitted. See “Memory Programming” on page 342 for details about Bootprogramming.

    Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since theEEPROM Master Write Enable will time-out. If an interrupt routine accessing theEEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will bemodified, causing the interrupted EEPROM access to fail. It is recommended to havethe Global Interrupt Flag cleared during all the steps to avoid these problems.

    When the write access time has elapsed, the EEPE bit is cleared by hardware. The usersoftware can poll this bit and wait for a zero before writing the next byte. When EEPEhas been set, the CPU is halted for two cycles before the next instruction is executed.

    Table 6. EEPROM Mode Bits

    EEPM1 EEPM0Programming

    Time Operation

    0 0 3.4 ms Erase and Write in one operation (Atomic Operation)

    0 1 1.8 ms Erase Only

    1 0 1.8 ms Write Only

    1 1 – Reserved for future use

    332549K–AVR–01/07

  • • Bit 0 – EERE: EEPROM Read Enable

    The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When thecorrect address is set up in the EEAR Register, the EERE bit must be written to a logicone to trigger the EEPROM read. The EEPROM read access takes one instruction, andthe requested data is available immediately. When the EEPROM is read, the CPU ishalted for four cycles before the next instruction is executed.

    The user should poll the EEPE bit before starting the read operation. If a write operationis in progress, it is neither possible to read the EEPROM, nor to change the EEARRegister.

    General Purpose registers

    GPIOR2 – General Purpose I/O Register 2

    GPIOR1 – General Purpose I/O Register 1

    GPIOR0 – General Purpose I/O Register 0

    External Memory registers

    XMCRA – External Memory Control Register A

    • Bit 7 – SRE: External SRAM/XMEM Enable

    Writing SRE to one enables the External Memory Interface.The pin functions AD7:0,A15:8, ALE, WR, and RD are activated as the alternate pin functions. The SRE bit over-rides any pin direction settings in the respective data direction registers. Writing SRE tozero, disables the External Memory Interface and the normal pin and data direction set-tings are used.

    • Bit 6:4 – SRL2:0: Wait-state Sector Limit

    It is possible to configure different wait-states for different External Memory addresses.The external memory address space can be divided in two sectors that have separatewait-state bits. The SRL2, SRL1, and SRL0 bits select the split of the sectors, see Table7 and Figure 13. By default, the SRL2, SRL1, and SRL0 bits are set to zero and theentire external memory address space is treated as one sector. When the entire SRAM

    Bit 7 6 5 4 3 2 1 0

    0x2B (0x4B) MSB LSB GPIOR2

    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

    Bit 7 6 5 4 3 2 1 0

    0x2A (0x4A) MSB LSB GPIOR1

    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

    Bit 7 6 5 4 3 2 1 0

    0x1E (0x3E) MSB LSB GPIOR0

    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

    Bit 7 6 5 4 3 2 1 0

    “(0x74)” SRE SRL2 SRL1 SRL0 SRW11 SRW10 SRW01 SRW00 XMCRA

    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

    34 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    address space is configured as one sector, the wait-states are configured by theSRW11 and SRW10 bits.

    • Bit 3:2 – SRW11, SRW10: Wait-state Select Bits for Upper Sector

    The SRW11 and SRW10 bits control the number of wait-states for the upper sector ofthe external memory address space, see Table 8.

    • Bit 1:0 – SRW01, SRW00: Wait-state Select Bits for Lower Sector

    The SRW01 and SRW00 bits control the number of wait-states for the lower sector ofthe external memory address space, see Table 8.

    Note: 1. n = 0 or 1 (lower/upper sector).For further details of the timing and wait-states of the External Memory Interface, seeFigures 15 through Figures 18 for how the setting of the SRW bits affects the timing.

    Table 7. Sector limits with different settings of SRL2:0

    SRL2 SRL1 SRL0 Sector Limits

    0 0 xLower sector = N/AUpper sector = 0x2200 - 0xFFFF

    0 1 0Lower sector = 0x2200 - 0x3FFFUpper sector = 0x4000 - 0xFFFF

    0 1 1Lower sector = 0x2200 - 0x5FFFUpper sector = 0x6000 - 0xFFFF

    1 0 0Lower sector = 0x2200 - 0x7FFFUpper sector = 0x8000 - 0xFFFF

    1 0 1Lower sector = 0x2200 - 0x9FFFUpper sector = 0xA000 - 0xFFFF

    1 1 0Lower sector = 0x2200 - 0xBFFFUpper sector = 0xC000 - 0xFFFF

    1 1 1Lower sector = 0x2200 - 0xDFFFUpper sector = 0xE000 - 0xFFFF

    Table 8. Wait States(1)

    SRWn1 SRWn0 Wait States

    0 0 No wait-states

    0 1 Wait one cycle during read/write strobe

    1 0 Wait two cycles during read/write strobe

    1 1 Wait two cycles during read/write and wait one cycle before driving out new address

    352549K–AVR–01/07

  • XMCRB – External Memory Control Register B

    • Bit 7– XMBK: External Memory Bus-keeper Enable

    Writing XMBK to one enables the bus keeper on the AD7:0 lines. When the bus keeperis enabled, AD7:0 will keep the last driven value on the lines even if the XMEM interfacehas tri-stated the lines. Writing XMBK to zero disables the bus keeper. XMBK is notqualified with SRE, so even if the XMEM interface is disabled, the bus keepers are stillactivated as long as XMBK is one.

    • Bit 6:3 – Res: Reserved Bits

    These bits are reserved and will always read as zero. When writing to this address loca-tion, write these bits to zero for compatibility with future devices.

    • Bit 2:0 – XMM2, XMM1, XMM0: External Memory High Mask

    When the External Memory is enabled, all Port C pins are default used for the highaddress byte. If the full 60KB address space is not required to access the External Mem-ory, some, or all, Port C pins can be released for normal Port Pin function as describedin Table 9. As described in “Using all 64KB Locations of External Memory” on page 31,it is possible to use the XMMn bits to access all 64KB locations of the External Memory.

    Bit 7 6 5 4 3 2 1 0

    (0x75) XMBK – – – – XMM2 XMM1 XMM0 XMCRB

    Read/Write R/W R R R R R/W R/W R/W

    Initial Value 0 0 0 0 0 0 0 0

    Table 9. Port C Pins Released as Normal Port Pins when the External Memory isEnabled

    XMM2 XMM1 XMM0 # Bits for External Memory Address Released Port Pins

    0 0 0 8 (Full 56KB space) None

    0 0 1 7 PC7

    0 1 0 6 PC7 - PC6

    0 1 1 5 PC7 - PC5

    1 0 0 4 PC7 - PC4

    1 0 1 3 PC7 - PC3

    1 1 0 2 PC7 - PC2

    1 1 1 No Address high bits Full Port C

    36 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    System Clock and Clock Options

    This section describes the clock options for the AVR microcontroller.

    Overview Figure 20 presents the principal clock systems in the AVR and their distribution. All ofthe clocks need not be active at a given time. In order to reduce power consumption, theclocks to modules not being used can be halted by using different sleep modes, asdescribed in “Power Management and Sleep Modes” on page 50. The clock systemsare detailed below.

    Figure 20. Clock Distribution

    General I/OModules

    AsynchronousTimer/Counter

    CPU Core RAM

    clkI/O

    clkASY

    AVR ClockControl Unit

    clkCPU

    Flash andEEPROM

    clkFLASH

    Source clock

    Watchdog Timer

    WatchdogOscillator

    Reset Logic

    ClockMultiplexer

    Watchdog clock

    Calibrated RCOscillator

    Timer/CounterOscillator

    CrystalOscillator

    Low-frequencyCrystal Oscillator

    External Clock

    ADC

    clkADC

    System ClockPrescaler

    372549K–AVR–01/07

  • Clock Systems and their Distribution

    CPU Clock – clkCPU The CPU clock is routed to parts of the system concerned with operation of the AVRcore. Examples of such modules are the General Purpose Register File, the Status Reg-ister and the data memory holding the Stack Pointer. Halting the CPU clock inhibits thecore from performing general operations and calculations.

    I/O Clock – clkI/O The I/O clock is used by the majority of the I/O modules, like Timer/Counters, SPI, andUSART. The I/O clock is also used by the External Interrupt module, but note that someexternal interrupts are detected by asynchronous logic, allowing such interrupts to bedetected even if the I/O clock is halted. Also note that start condition detection in the USImodule is carried out asynchronously when clkI/O is halted, TWI address recognition inall sleep modes.

    Flash Clock – clkFLASH The Flash clock controls operation of the Flash interface. The Flash clock is usuallyactive simultaneously with the CPU clock.

    Asynchronous Timer Clock – clkASY

    The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clockeddirectly from an external clock or an external 32 kHz clock crystal. The dedicated clockdomain allows using this Timer/Counter as a real-time counter even when the device isin sleep mode.

    ADC Clock – clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU andI/O clocks in order to reduce noise generated by digital circuitry. This gives more accu-rate ADC conversion results.

    38 ATmega640/1280/1281/2560/25612549K–AVR–01/07

  • ATmega640/1280/1281/2560/2561

    Clock Sources The device has the following clock source options, selectable by Flash Fuse bits asshown below. The clock from the selected source is input to the AVR clock generator,and routed to the appropriate modules.

    Note: 1. For all fuses “1” means unprogrammed while “0” means programmed.

    Default Clock Source The device is shipped with internal RC oscillator at 8.0 MHz and with the fuse CKDIV8programmed, resulting in 1.0 MHz system clock. The startup time is set to maximumand time-out period enabled. (CKSEL = "0010", SUT = "10", CKDIV8 = "0"). The defaultsetting ensures that all users can make their desired clock source setting using anyavailable programming interface.

    Clock Start-up Sequence Any clock source needs a sufficient VCC to start oscillating and a minimum number ofoscillating cycles before it can be considered stable.

    To ensure sufficient VCC, the device issues an internal reset with a time-out delay (tTOUT)after the device reset is released by all other reset sources. “On-chip Debug System” onpage 53 describes the start conditions for the internal reset. The delay (tTOUT) is timedfrom the Watchdog Oscillator and the number of cycles in the delay is set by the SUTxand CKSELx fuse bits. The selectable delays are shown in Table 11. The frequency ofthe Watchdog Oscillator is voltage dependent as shown in “Typical Characteristics” onpage 390.

    Main purpose of the delay is to keep the AVR in reset until it is supplied with minimumVcc. The delay will not monitor the actual voltage and it will be required to select a delaylonger than the Vcc rise time. If this is not possible, an internal or external Brown-OutDetection circuit should be used. A BOD circuit will ensure sufficient Vcc before itreleases the reset, and the time-out delay can be disabled. Disabling the time-out delaywithout utilizing a Brown-Out Detection circuit is not recommended.

    The oscillator is required to oscillate for a minimum number of cycles before the clock isconsidered stable. An internal ripple counter monitors the oscillator output clock, andkeeps the internal reset active for a given number of clock cycles. The reset is thenreleased and the device will start to execute. The recommended oscillator start-up time

    Table 10. Device Clocking Options Select(1)

    Device Clocking Option CKSEL3:0

    Low Power Crystal Oscillator 1111 - 1000

    Full Swing Crystal Oscillator 0111 - 0110

    Low Frequency Crystal Oscillator 0101 - 0100

    Internal 128 kHz RC Oscillator 0011

    Calibrated Internal RC Oscillator 0010

    External Clock 0000

    Reserved 0001

    Table 11. 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)

    392549K–AVR–01/07

  • is dependent on the clock type, and varies from 6 cycles for an externally applied clockto 32K cycles for a low frequency crystal.

    The start-up sequence for the clock includes both the time-out delay and the start-uptime when the device starts up from reset. When starting up from Power-save or Power-down mode, Vcc is assumed to be at a sufficient level and only the start-up time isincluded.

    Low Power Crystal Oscillator

    Pins XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifierwhich can be configured for use as an On-chip Oscillator, as shown in Figure 21. Eithera quartz crystal or a ceramic resonator may be used.

    This Crystal Oscillator is a low power oscillator, with reduced voltage swing on theXTAL2 output. It gives the lowest power consumption, but is not capable of driving otherclock inputs, and may be more susceptible to noise in noisy environments. In thesecases, refer to the “Full Swing Crystal Oscillator” on page 42.

    C1 and C2 should always be equal for both crystals and resonators. The optimal valueof the capacitors depends on the crystal or resonator in use, the amount of stray capac-itance, and the electromagnetic noise of the environment. Some initial guidelines forchoosing capacitors for use with crystals are given in Table 12. For ceramic resonators,the capacitor values given by the manufacturer should be used.

    Figure 21. Crystal Oscillator Connections

    The Low Power Oscillator can operate in three different modes, each optimized for aspecific frequency range. The operating mode is selected by the fuses CKSEL3:1 asshown in Table 12.

    Notes: 1. The frequency ranges are preliminary values. Actual values are TBD.2. This option should not be used with crystals, only with ceramic resonators.3. If 8 MHz frequency exceeds the specification of the device (depends on VCC), the

    CKDIV8 Fuse can be programmed in order to divide the internal frequency by 8. Itmust be ensured that the resulting divided clock meets the frequency specification ofthe device.

    Table 12. Low Power Crystal Oscillator Operating Modes(3)

    Frequency Range(1) (MHz) CKSEL3:1Recommended Range for Capacitors

    C1 and C2 (pF)

    0.4 - 0.9 100(2) –

    0.9 - 3.0 101 12 - 22

    3.0 - 8.0 110 12 - 22

    8.0 - 16.0(4) 111 12 - 22