The ATmega3208/3209/4808/4809 microcontrollers of the megaAVR® 0-series are using the AVR
processor with hardware multiplier, running at up to 20 MHz, with a wide range of Flash sizes up to 48
KB, up to 6 KB of SRAM, and 256 bytes of EEPROM in 28-, 32-, or 48-pin package. The series uses the
latest technologies from Microchip with a flexible and low-power architecture including Event System and
SleepWalking, accurate analog features and advanced peripherals.
This Manual contains the general descriptions of the peripherals. While the available peripherals have
identical features and show the same behavior across the series, packages with fewer pins support a
subset of signals. Refer to the Data Sheet of the individual device for available pins and signals.
®
Features
•AVR® CPU
–Single-cycle I/O access
–Two-level interrupt controller
–Two-cycle hardware multiplier
•Memories
–Up to 48 KB In-system self-programmable Flash memory
R/WRead/Write accessible register bit. The user can read from and write to this bit.
RRead-only accessible register bit. The user can only read this bit. Writes will be
ignored.
megaAVR® 0-Series
Conventions
WWrite-only accessible register bit. The user can only write this bit. Reading this bit will
return an undefined value.
BITFIELDBitfield names are shown in uppercase. Example: INTMODE.
BITFIELD[n:m] A set of bits from bit n down to m. Example: PINA[3:0] = {PINA3, PINA2, PINA1,
PINA0}.
ReservedReserved bits are unused and reserved for future use. Bitfields in the Register
Summary or Register Description chapters that have gray background are Reserved
bits.
For compatibility with future devices, always write reserved bits to zero when the
register is written. Reserved bits will always return zero when read.
Reserved bit field values must not be written to a bit field. A reserved value won't be
read from a read-only bit field.
PERIPHERALnIf several instances of the peripheral exist, the peripheral name is followed by a single
number to identify one instance. Example: USARTn is the collection of all instances of
the USART module, while USART3 is one specific instance of the USART module.
PERIPHERALx If several instances of the peripheral exist, the peripheral name is followed by a single
capital letter (A-Z) to identify one instance. Example: PORTx is the collection of all
instances of the PORT module, while PORTB is one specific instance of the PORT
module.
ResetValue of a register after a power Reset. This is also the value of registers in a
peripheral after performing a software Reset of the peripheral, except for the Debug
Control registers.
SET/CLRRegisters with SET/CLR suffix allows the user to clear and set bits in a register without
doing a read-modify-write operation. These registers always come in pairs. Writing a ‘1’
to a bit in the CLR register will clear the corresponding bit in both registers, while
writing a ‘1’ to a bit in the SET register will set the corresponding bit in both registers.
Both registers will return the same value when read. If both registers are written
simultaneously, the write to the CLR register will take precedence.
3.4.1 Addressing Registers from Header Files
In order to address registers in the supplied C header files, the following rules apply:
1.A register is identified by <peripheral_instance_name>.<register_name>, e.g. CPU.SREG,
USART2.CTRLA, or PORTB.DIR.
2.The peripheral name is written in the peripheral's register summary heading, e.g. "Register
Summary - ACn", where "ACn" is the peripheral name.
3.<peripheral_instance_name> is obtained by substituting any n or x in the peripheral name with the
correct instance identifier.
The main memories are SRAM data memory, EEPROM data memory, and Flash program memory. In
addition, the peripheral registers are located in the I/O memory space.
5.2 Memory Map
The figure below shows the memory map for the biggest memory derivative in the series. Refer to the
subsequent subsections for details on memory sizes and start addresses for devices with smaller
memory sizes.
The ATmega3208/3209/4808/4809 contains up to 48 KB On-Chip In-System Reprogrammable Flash
memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized
with 16-bit data width. For write protection, the Flash Program memory space can be divided into three
sections: Boot Loader section, Application code section, and Application data section. Code placed in one
section may be restricted from writing to addresses in other sections, see the NVMCTRL documentation
for more details.
The program counter is able to address the whole program memory. The procedure for writing Flash
memory is described in detail in the documentation of the Non-Volatile Memory Controller (NVMCTRL)
peripheral.
The Flash memory is mapped into the data space and is accessible with normal LD/ST instructions. For
LD/ST instructions, the Flash is mapped from address 0x4000. The Flash memory can be read with the
LPM instruction. For the LPM instruction, the Flash start address is 0x0000.
The ATmega3208/3209/4808/4809 has a CRC module that is a master on the bus.
Table 5-1. Physical Properties of Flash Memory
PropertyATmega320xATmega480x
Size32 KB48 KB
Page size128 B128 B
Number of pages256384
Start address in Data Space0x40000x4000
Start address in Code Space0x00x0
5.4 SRAM Data Memory
The primary task of the SRAM memory is to store application data. It is not possible to execute code from
SRAM.
Table 5-2. Physical Properties of SRAM
PropertyATmega320xATmega480x
Size4 KB6 KB
Start address0x30000x2800
5.5 EEPROM Data Memory
The primary task of the EEPROM memory is to store nonvolatile application data. The EEPROM memory
supports single byte read and write. The EEPROM is controlled by the Non-Volatile Memory Controller
(NVMCTRL).
Table 5-3. Physical Properties of EEPROM
PropertyATmega320xATmega480x
Size256B256B
Page size64B64B
Number of pages44
Start address0x14000x1400
5.6 User Row (USERROW)
In addition to the EEPROM, the ATmega3208/3209/4808/4809 has one extra page of EEPROM memory
that can be used for firmware settings, the User Row (USERROW). This memory supports single byte
read and write as the normal EEPROM. The CPU can write and read this memory as normal EEPROM
and the UPDI can write and read it as a normal EEPROM memory if the part is unlocked. The User Row
can also be written by the UPDI when the part is locked. USERROW is not affected by a chip erase. The
USERROW can be used for final configuration without having programming or debugging capabilities
enabled.
5.7 Signature Row (SIGROW)
The content of the Signature Row fuses (SIGROW) is pre-programmed and cannot be altered. SIGROW
holds information such as device ID, serial number, and calibration values.
All AVR microcontrollers have a three-byte device ID which identifies the device. This device ID can be
read in both serial and parallel mode, also when the device is locked. The three bytes reside in the
Signature Row. The signature bytes are given in the following table.
Each device has a device ID identifying the device and its properties; such as memory sizes, pin count,
and die revision. This can be used to identify a device and hence, the available features by software. The
Device ID consists of three bytes: SIGROW.DEVICEID[2:0].
Each device has an individual serial number, representing a unique ID. This can be used to identify a
specific device in the field. The serial number consists of ten bytes: SIGROW.SERNUM[9:0].
These registers contain correction factors for temperature measurements by the ADC.
SIGROW.TEMPSENSE0 is a correction factor for the gain/slope (unsigned), SIGROW.TEMPSENSE1 is
a correction factor for the offset (signed).
Bit 76543210
Access
Reset xxxxxxxx
RRRRRRRR
Bits 7:0 – TEMPSENSE[7:0] Temperature Sensor Calibration Byte n
Refer to the ADC chapter for a description on how to use this register.
Bits 7:0 – OSC16ERR3V[7:0] OSC16 Error at 3V
These registers contain the signed oscillator frequency error value when running at internal 16 MHz at 3V,
as measured during production.
Bits 7:0 – OSC16ERR5V[7:0] OSC16 Error at 5V
These registers contain the signed oscillator frequency error value when running at internal 16 MHz at 5V,
as measured during production.
Bits 7:0 – OSC20ERR3V[7:0] OSC20 Error at 3V
These registers contain the signed oscillator frequency error value when running at internal 20 MHz at 3V,
as measured during production.
Bits 7:0 – OSC20ERR5V[7:0] OSC20 Error at 5V
These registers contain the signed oscillator frequency error value when running at internal 20 MHz at 5V,
as measured during production.
5.8 Fuses (FUSE)
Fuses are part of the nonvolatile memory and hold factory calibration data and device configuration. The
fuses are available from device power-up. The fuses can be read by the CPU or the UPDI, but can only
be programmed or cleared by the UPDI. The configuration and calibration values stored in the fuses are
written to their respective target registers at the end of the start-up sequence.
OSC20ERR5V[7:0]
The fuses are pre-programmed but can be altered by the user. Altered values in the configuration fuse
will be effective only after a Reset.
Note: When writing the fuses write all reserved bits to ‘1’.
Bits 7:4 – WINDOW[3:0] Watchdog Window Time-out Period
This value is loaded into the WINDOW bit field of the Watchdog Control A register (WDT.CTRLA) during
Reset.
Bits 3:0 – PERIOD[3:0] Watchdog Time-out Period
This value is loaded into the PERIOD bit field of the Watchdog Control A register (WDT.CTRLA) during
Reset.
Bit 4 – SAMPFREQ BOD Sample Frequency
This value is loaded into the SAMPFREQ bit of the BOD Control A register (BOD.CTRLA) during Reset.
ValueDescription
0x0Sample frequency is 1 kHz
0x1Sample frequency is 125 Hz
Bits 3:2 – ACTIVE[1:0] BOD Operation Mode in Active and Idle
This value is loaded into the ACTIVE bit field of the BOD Control A register (BOD.CTRLA) during Reset.
ValueDescription
0x0Disabled
0x1Enabled
0x2Sampled
0x3Enabled with wake-up halted until BOD is ready
Bits 1:0 – SLEEP[1:0] BOD Operation Mode in Sleep
This value is loaded into the SLEEP bit field of the BOD Control A register (BOD.CTRLA) during Reset.
Bit 7 – OSCLOCK Oscillator Lock
This fuse bit is loaded to LOCK in CLKCTRL.OSC20MCALIBB during Reset.
ValueDescription
0Calibration registers of the 20 MHz oscillator are accessible
1Calibration registers of the 20 MHz oscillator are locked
Bits 1:0 – FREQSEL[1:0] Frequency Select
These bits select the operation frequency of the 20 MHz internal oscillator (OSC20M) and determine the
respective factory calibration values to be written to CAL20M in CLKCTRL.OSC20MCALIBA and
TEMPCAL20M in CLKCTRL.OSC20MCALIBB.
ValueDescription
0x0Reserved
0x1Run at 16 MHz
0x2Run at 20 MHz
0x3Reserved
Bits 7:6 – CRCSRC[1:0] CRC Source
See the CRC description for more information about the functionality.
ValueNameDescription
00FLASHCRC of full Flash (boot, application code, and application data)
01BOOTCRC of boot section
10BOOTAPPCRC of application code and boot sections
11NOCRCNo CRC
CRCSRC[1:0]RSTPINCFGEESAVE
RRRR
Bit 3 – RSTPINCFG Reset Pin Configuration
This bit selects the pin configuration for the reset pin.
ValueDescription
0x0GPIO
0x1RESET
Bit 0 – EESAVE EEPROM Save During Chip Erase
If the device is locked the EEPROM is always erased by a chip erase, regardless of this bit.
ValueDescription
0EEPROM erased during chip erase
1EEPROM not erased under chip erase
Bits 7:0 – APPEND[7:0] Application Code Section End
These bits set the end of the application code section in blocks of 256 bytes. The end of the application
code section should be set as BOOT size plus application code size. The remaining Flash will be
application data. A value of 0x00 defines the Flash from BOOTEND*256 to end of Flash as application
code. When both FUSE.APPEND and FUSE.BOOTEND are 0x00, the entire Flash is BOOT section.
Bits 7:0 – BOOTEND[7:0] Boot Section End
These bits set the end of the boot section in blocks of 256 bytes. A value of 0x00 defines the whole Flash
as BOOT section. When both FUSE.APPEND and FUSE.BOOTEND are 0x00, the entire Flash is BOOT
section.
Bits 7:0 – LOCKBIT[7:0] Lockbits
When the part is locked, UPDI cannot access the system bus, so it cannot read out anything but CSspace.
ValueDescription
0xC5Valid key - the device is open
otherInvalid - the device is locked
LOCKBIT[7:0]
5.9 Memory Section Access from CPU and UPDI on Locked Device
The device can be locked so that the memories cannot be read using the UPDI. The locking protects both
the Flash (all BOOT, APPCODE, and APPDATA sections), SRAM, and the EEPROM including the FUSE
data. This prevents successful reading of application data or code using the debugger interface. Regular
memory access from within the application still is enabled.
The device is locked by writing any non-valid value to the LOCKBIT bit field in FUSE.LOCKBIT.
Table 5-5. Memory Access in Unlocked Mode (FUSE.LOCKBIT Valid)
Table 5-6. Memory Access in Locked Mode (FUSE.LOCKBIT Invalid)
Memory SectionCPU AccessUPDI Access
ReadWriteReadWrite
SRAMYesYesNoNo
RegistersYesYesNoNo
FlashYesYesNoNo
EEPROMYesNoNoNo
USERROWYesYesNoYes
SIGROWYesNoYesNo
Other FusesYesNoNoNo
Note:
1.Read operations marked No in the tables may appear to be successful, but the data is corrupt.
Hence, any attempt of code validation through the UPDI will fail on these memory sections.
2.In Locked mode, the USERROW can be written blindly using the fuse Write command, but the
current USERROW values cannot be read out.
(1)
(2)
Important: The only way to unlock a device is a CHIPERASE, which will erase all device
memories to factory default so that no application data is retained.
5.10 I/O Memory
All ATmega3208/3209/4808/4809 I/Os and peripherals are located in the I/O space. The I/O address
range from 0x00 to 0x3F can be accessed in a single cycle using IN and OUT instructions. The Extended
I/O space from 0x0040 - 0x0FFF can be accessed by the LD/LDS/LDD and ST/STS/STD instructions,
transferring data between the 32 general purpose working registers and the I/O space.
I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI
instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC
instructions. Refer to the Instruction Set section for more details.
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 interrupt flags are cleared by writing a '1' to them. On ATmega3208/3209/4808/4809 devices,
the CBI and SBI instructions will only operate on the specified bit, and can, therefore, be used on
registers containing such interrupt flags. The CBI and SBI instructions work with registers 0x00 - 0x1F
only.
General Purpose I/O Registers
The ATmega3208/3209/4808/4809 devices provide four General Purpose I/O Registers. These registers
can be used for storing any information, and they are particularly useful for storing global variables and
interrupt flags. General Purpose I/O Registers, which reside in the address range 0x1C - 0x1F, are
directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
The address map shows the base address for each peripheral. For complete register description and
summary for each peripheral module, refer to the respective module chapters.
Each of the interrupt vectors is connected to one peripheral instance, as shown in the table below. A
peripheral can have one or more interrupt sources. See the 'Interrupts' section in the 'Functional
Description' of the respective peripheral for more details on the available interrupt sources.
When the interrupt condition occurs, an Interrupt Flag is set in the Interrupt Flags register of the
peripheral (peripheral.INTFLAGS).
An interrupt is enabled or disabled by writing to the corresponding Interrupt Enable bit in the peripheral's
Interrupt Control register (peripheral.INTCTRL).
An interrupt request is generated when the corresponding interrupt is enabled and the Interrupt Flag is
set. The interrupt request remains active until the Interrupt Flag is cleared. See the peripheral's
INTFLAGS register for details on how to clear Interrupt Flags.
Note: Interrupts must be enabled globally for interrupt requests to be generated.
The system configuration contains the revision ID of the part. The revision ID is readable from the CPU,
making it useful for implementing application changes between part revisions.
•Direct addressing of up to 64 KB of unified memory
•Efficient support for 8-, 16-, and 32-bit arithmetic
•Configuration Change Protection for system-critical features
•Native OCD support
–Two hardware breakpoints
–Change of flow, interrupt and software breakpoints
–Run-time readout of Stack Pointer register, program counter (PC), and Status register
–Register file read- and writable in stopped mode
megaAVR® 0-Series
AVR CPU
7.2 Overview
All AVR devices use the 8-bit AVR CPU. The CPU is able to access memories, perform calculations,
control peripherals, and execute instructions in the program memory. Interrupt handling is described in a
separate section.
7.3 Architecture
In order to maximize performance and parallelism, the AVR CPU uses a Harvard architecture with
separate buses for program and data. Instructions in the program memory are executed with single-level
pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program
memory. This enables instructions to be executed on every clock cycle.
The Arithmetic Logic Unit (ALU) supports arithmetic and logic operations between registers or between a
constant and a register. Single-register operations can also be executed in the ALU. After an arithmetic
operation, the status register is updated to reflect information about the result of the operation.
The ALU is directly connected to the fast-access register file. The 32 8-bit general purpose working
registers all have single clock cycle access time. This allows single-cycle arithmetic logic unit operation
between registers or between a register and an immediate operand. Six of the 32 registers can be used
as three 16-bit address pointers for program and data space addressing, enabling efficient address
calculations.
For a summary of all AVR instructions, refer to the Instruction Set Summary.
7.4 Arithmetic Logic Unit (ALU)
The Arithmetic Logic Unit (ALU) supports arithmetic and logic operations between registers, or between a
constant and a register. Also, single-register operations can be executed.
The ALU operates in direct connection with all 32 general purpose registers. Arithmetic operations
between general purpose registers or between a register and an immediate are executed in a single clock
cycle, and the result is stored in the register file. After an arithmetic or logic operation, the Status register
(CPU.SREG) is updated to reflect information about the result of the operation.
ALU operations are divided into three main categories – arithmetic, logical, and bit functions. Both 8- and
16-bit arithmetic are supported, and the instruction set allows for efficient implementation of 32-bit
arithmetic. The hardware multiplier supports signed and unsigned multiplication and fractional format.
7.4.1 Hardware Multiplier
The multiplier is capable of multiplying two 8-bit numbers into a 16-bit result. The hardware multiplier
supports different variations of signed and unsigned integer and fractional numbers:
megaAVR® 0-Series
AVR CPU
•Multiplication of signed/unsigned integers
•Multiplication of signed/unsigned fractional numbers
•Multiplication of a signed integer with an unsigned integer
•Multiplication of a signed fractional number with an unsigned one
A multiplication takes two CPU clock cycles.
7.5 Functional Description
7.5.1 Program Flow
After Reset, the CPU will execute instructions from the lowest address in the Flash program memory,
0x0000. The Program Counter (PC) addresses the next instruction to be fetched.
Program flow is supported by conditional and unconditional JUMP and CALL instructions, capable of
addressing the whole address space directly. Most AVR instructions use a 16-bit word format, and a
limited number use a 32-bit format.
During interrupts and subroutine calls, the return address PC is stored on the stack as a word pointer.
The stack is allocated in the general data SRAM, and consequently, the stack size is only limited by the
total SRAM size and the usage of the SRAM. After Reset, the Stack Pointer (SP) points to the highest
address in the internal SRAM. The SP is read/write accessible in the I/O memory space, enabling easy
implementation of multiple stacks or stack areas. The data SRAM can easily be accessed through the
five different addressing modes supported by the AVR CPU.
7.5.2 Instruction Execution Timing
The AVR CPU is clocked by the CPU clock: CLK_CPU. No internal clock division is applied. The figure
below shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast-access register file concept. This is the basic pipelining concept enabling up to 1
MIPS/MHz performance with high efficiency.
Figure 7-2. The Parallel Instruction Fetches and Instruction Executions
The following figure shows the internal timing concept for the register file. In a single clock cycle, an ALU
operation using two register operands is executed and the result is stored in the destination register.
Figure 7-3. Single Cycle ALU Operation
7.5.3 Status Register
7.5.4 Stack and Stack Pointer
The Status register (CPU.SREG) contains information about the result of the most recently executed
arithmetic or logic instruction. This information can be used for altering program flow in order to perform
conditional operations.
CPU.SREG is updated after all ALU operations, as specified in the Instruction Set Summary. This will in
many cases remove the need for using the dedicated compare instructions, resulting in faster and more
compact code. CPU.SREG is not automatically stored/restored when entering/returning from an Interrupt
Service Routine. Maintaining the Status register between context switches must, therefore, be handled by
user-defined software. CPU.SREG is accessible in the I/O memory space.
The stack is used for storing return addresses after interrupts and subroutine calls. Also, it can be used
for storing temporary data. The Stack Pointer (SP) always points to the top of the stack. The SP is
defined by the Stack Pointer bits in the Stack Pointer register (CPU.SP). The CPU.SP is implemented as
two 8-bit registers that are accessible in the I/O memory space.
Data is pushed and popped from the stack using the PUSH and POP instructions. The stack grows from
higher to lower memory locations. This implies that pushing data onto the stack decreases the SP, and
popping data off the stack increases the SP. The Stack Pointer is automatically set to the highest address
of the internal SRAM after Reset. If the stack is changed, it must be set to point above address 0x2000,
and it must be defined before any subroutine calls are executed and before interrupts are enabled.
During interrupts or subroutine calls the return address is automatically pushed on the stack as a word
pointer and the SP is decremented by '2'. The return address consists of two bytes and the Least
Significant Byte is pushed on the stack first (at the higher address). As an example, a byte pointer return
address of 0x0006 is saved on the stack as 0x0003 (shifted one bit to the right), pointing to the fourth 16bit instruction word in the program memory. The return address is popped off the stack with RETI (when
returning from interrupts) and RET (when returning from subroutine calls) and the SP is incremented by
...
...
7
0
R0
R1
R2
R13
R14
R15
R16
R17
R26
R27
R28
R29
R30
R31
Addr.
0x00
0x01
0x02
0x0D
0x0E
0x0F
0x10
0x11
0x1A
0x1B
0x1C
0x1D
0x1E
0x1F
X-register Low Byte
X-register High Byte
Y-register Low Byte
Y-register High Byte
Z-register Low Byte
Z-register High Byte
two.
The SP is decremented by '1' when data is pushed on the stack with the PUSH instruction, and
incremented by '1' when data is popped off the stack using the POP instruction.
To prevent corruption when updating the Stack Pointer from software, a write to SPL will automatically
disable interrupts for up to four instructions or until the next I/O memory write.
7.5.5 Register File
The register file consists of 32 8-bit general purpose working registers with single clock cycle access time.
The register file supports the following input/output schemes:
•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
Six of the 32 registers can be used as three 16-bit Address Register Pointers for data space addressing,
enabling efficient address calculations.
megaAVR® 0-Series
AVR CPU
Figure 7-4. AVR CPU General Purpose Working Registers
The register file is located in a separate address space and is, therefore, not accessible through
instructions operation on data memory.
7.5.5.1 The X-, Y-, and Z-Registers
Registers R26...R31 have added functions besides their general purpose usage.
These registers can form 16-bit Address Pointers for addressing data memory. These three address
registers are called the X-register, Y-register, and Z-register. Load and store instructions can use all X-,
Y-, and Z-registers, while the LPMand SPM instructions can only use the Z-register. Indirect calls and
jumps (ICALL and IJMP ) also use the Z-register.
Refer to the instruction set or Instruction Set Summary for more information about how the X-, Y-, and Zregisters are used.
The lowest register address holds the Least Significant Byte (LSB), and the highest register address
holds the Most Significant Byte (MSB). In the different addressing modes, these address registers
function as fixed displacement, automatic increment, and automatic decrement.
7.5.6 Accessing 16-Bit Registers
The AVR data bus has a width of 8 bit, and so accessing 16-bit registers requires atomic operations.
These registers must be byte accessed using two read or write operations. 16-bit registers are connected
to the 8-bit bus and a temporary register using a 16-bit bus.
megaAVR® 0-Series
AVR CPU
7.5.7 Configuration Change Protection (CCP)
7.5.7.1 Sequence for Write Operation to Configuration Change Protected I/O Registers
For a write operation, the low byte of the 16-bit register must be written before the high byte. The low byte
is then written into the temporary register. When the high byte of the 16-bit register is written, the
temporary register is copied into the low byte of the 16-bit register in the same clock cycle.
For a read operation, the low byte of the 16-bit register must be read before the high byte. When the low
byte register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register
in the same clock cycle as the low byte is read. When the high byte is read, it is then read from the
temporary register.
This ensures that the low and high bytes of 16-bit registers are always accessed simultaneously when
reading or writing the register.
Interrupts can corrupt the timed sequence if an interrupt is triggered and accesses the same 16-bit
register during an atomic 16-bit read/write operation. To prevent this, interrupts can be disabled when
writing or reading 16-bit registers.
The temporary registers can be read and written directly from user software.
System critical I/O register settings are protected from accidental modification. Flash self-programming
(via store to NVM controller) is protected from accidental execution. This is handled globally by the
Configuration Change Protection (CCP) register.
Changes to the protected I/O registers or bits, or execution of protected instructions, are only possible
after the CPU writes a signature to the CCP register. The different signatures are listed in the description
of the CCP register (CPU.CCP).
There are two modes of operation: one for protected I/O registers, and one for the protected selfprogramming.
In order to write to registers protected by CCP, these steps are required:
1.The software writes the signature that enables change of protected I/O registers to the CCP bit field
in the CPU.CCP register.
2.Within four instructions, the software must write the appropriate data to the protected register.
Most protected registers also contain a write enable/change enable/lock bit. This bit must be written
to '1' in the same operation as the data are written.
The protected change is immediately disabled if the CPU performs write operations to the I/O
register or data memory, if load or store accesses to Flash, NVMCTRL, EEPROM are conducted,
or if the SLEEP instruction is executed.
7.5.7.2 Sequence for Execution of Self-Programming
In order to execute self-programming (the execution of writes to the NVM controller's command register),
the following steps are required:
1.The software temporarily enables self-programming by writing the SPM signature to the CCP
register (CPU.CCP).
2.Within four instructions, the software must execute the appropriate instruction. The protected
change is immediately disabled if the CPU performs accesses to the Flash, NVMCTRL, or
EEPROM, or if the SLEEP instruction is executed.
Once the correct signature is written by the CPU, interrupts will be ignored for the duration of the
configuration change enable period. Any interrupt request (including non-maskable interrupts) during the
CCP period will set the corresponding interrupt flag as normal, and the request is kept pending. After the
CCP period is completed, any pending interrupts are executed according to their level and priority.
Bits 7:0 – CCP[7:0] Configuration Change Protection
Writing the correct signature to this bit field allows changing protected I/O registers or executing protected
instructions within the next four CPU instructions executed.
All interrupts are ignored during these cycles. After these cycles, interrupts will automatically be handled
again by the CPU, and any pending interrupts will be executed according to their level and priority.
CCP[7:0]
When the protected I/O register signature is written, CCP[0] will read as '1' as long as the CCP feature is
enabled.
When the protected self-programming signature is written, CCP[1] will read as '1' as long as the CCP
feature is enabled.
Name: SP
Offset: 0x0D
Reset: Top of stack
Property: -
The CPU.SP holds the Stack Pointer (SP) that points to the top of the stack. After Reset, the Stack
Pointer points to the highest internal SRAM address.
Only the number of bits required to address the available data memory including external memory (up to
64 KB) is implemented for each device. Unused bits will always read as zero.
The CPU.SPL and CPU.SPH register pair represents the 16-bit value, CPU.SP. The low byte [7:0] (suffix
L) is accessible at the original offset. The high byte [15:8] (suffix H) can be accessed at offset + 0x01.
To prevent corruption when updating the SP from software, a write to CPU.SPL will automatically disable
interrupts for the next four instructions or until the next I/O memory write.
Bit 15141312111098
Access
Reset
R/WR/WR/WR/WR/WR/WR/WR/W
SP[15:8]
Bit 76543210
Access
Reset
R/WR/WR/WR/WR/WR/WR/WR/W
SP[7:0]
Bits 15:8 – SP[15:8] Stack Pointer High Byte
These bits hold the MSB of the 16-bit register.
Bits 7:0 – SP[7:0] Stack Pointer Low Byte
These bits hold the LSB of the 16-bit register.
The Status register contains information about the result of the most recently executed arithmetic or logic
instruction. For details about the bits in this register and how they are affected by the different
instructions, see the Instruction Set Summary.
Bit 76543210
Access
Reset 00000000
ITHSVNZC
R/WR/WR/WR/WR/WR/WR/WR/W
Bit 7 – I Global Interrupt Enable
Writing a '1' to this bit enables interrupts on the device.
Writing a '0' to this bit disables interrupts on the device, independent of the individual interrupt enable
settings of the peripherals.
This bit is not cleared by hardware after an interrupt has occurred.
This bit can be set and cleared by software with the SEI and CLI instructions.
Changing the I flag through the I/O register results in a one-cycle Wait state on the access.
Bit 6 – T Bit Copy Storage
The bit copy instructions bit load (BLD) and bit store (BST) use the T bit as source or destination for the
operated bit.
A bit from a register in the register file can be copied into this bit by the BST instruction, and this bit can
be copied into a bit in a register in the register file by the BLD instruction.
Bit 5 – H Half Carry Flag
This bit indicates a half carry in some arithmetic operations. Half carry is useful in BCD arithmetic.
Bit 4 – S Sign Bit, S = N ⊕ V
The sign bit (S) is always an exclusive or (xor) between the negative flag (N) and the two’s complement
overflow flag (V).
Bit 3 – V Two’s Complement Overflow Flag
The two’s complement overflow flag (V) supports two’s complement arithmetic.
Bit 2 – N Negative Flag
The negative flag (N) indicates a negative result in an arithmetic or logic operation.
Bit 1 – Z Zero Flag
The zero flag (Z) indicates a zero result in an arithmetic or logic operation.
–Boot section for boot loader code or application code
–Application code section for application code
–Application data section for application code or data storage
•Signature Row for Factory-Programmed Data:
–ID for each device type
–Serial number for each device
–Calibration bytes for factory calibrated peripherals
•User Row for Application Data:
–Can be read and written from software
–Can be written from UPDI on locked device
–Content is kept after chip erase
megaAVR® 0-Series
8.2 Overview
The NVM Controller (NVMCTRL) is the interface between the device, the Flash, and the EEPROM. The
Flash and EEPROM are reprogrammable memory blocks that retain their values even when not powered.
The Flash is mainly used for program storage and can be used for data storage. The EEPROM is used
for data storage and can be programmed while the CPU is running the program from the Flash.
The Flash is divided into a set of pages. A page is the basic unit addressed when programming the Flash.
It is only possible to write or erase a whole page at a time. One page consists of several words.
The Flash can be divided into three sections in blocks of 256 bytes for different security. The three
different sections are BOOT, Application Code (APPCODE), and Application Data (APPDATA).
Figure 8-2. Flash Sections
megaAVR® 0-Series
Nonvolatile Memory Controller (NVMCTRL)
Section Sizes
The sizes of these sections are set by the Boot Section End fuse (FUSE.BOOTEND) and Application
Code Section End fuse (FUSE.APPEND).
The fuses select the section sizes in blocks of 256 bytes. The BOOT section stretches from the start of
the Flash until BOOTEND. The APPCODE section runs from BOOTEND until APPEND. The remaining
area is the APPDATA section. If APPEND is written to 0, the APPCODE section runs from BOOTEND to
the end of Flash (removing the APPDATA section). If BOOTEND and APPEND are written to 0, the entire
Flash is regarded as BOOT section. APPEND should either be set to 0 or a value greater or equal than
BOOTEND.
•Interrupt vectors are by default located after the BOOT section. This can be changed in the
interrupt controller.
If FUSE.BOOTEND is written to 0x04 and FUSE.APPEND is written to 0x08, the first
4*256 bytes will be BOOT, the next 4*256 bytes will be APPCODE, and the remaining
Flash will be APPDATA.
Inter-Section Write Protection
Between the three Flash sections, a directional write protection is implemented:
•Code in the BOOT section can write to APPCODE and APPDATA
•Code in APPCODE can write to APPDATA
•Code in APPDATA cannot write to Flash or EEPROM
0 to 256*BOOTEND-256*BOOTEND to
FLASHEND
0 to 256*BOOTEND256*BOOTEND to
256*APPEND
256*APPEND to
FLASHEND
Boot Section Lock and Application Code Section Write Protection
The two lockbits (APCWP and BOOTLOCK in NVMCTRL.CTRLB) can be set to lock further updates of
the respective APPCODE or BOOT section until the next Reset.
The CPU can never write to the BOOT section. NVMCTRL_CTRLB.BOOTLOCK prevents reads and
execution of code from the BOOT section.
8.3.1.2 EEPROM
The EEPROM is divided into a set of pages where one page consists of multiple bytes. The EEPROM
has byte granularity on erase/write. Within one page only the bytes marked to be updated will be erased/
written. The byte is marked by writing a new value to the page buffer for that address location.
8.3.1.3 User Row
The User Row is one extra page of EEPROM. This page can be used to store various data, such as
calibration/configuration data and serial numbers. This page is not erased by a chip erase. The User Row
is written as normal EEPROM, but in addition, it can be written through UPDI on a locked device.
8.3.2 Memory Access
8.3.2.1 Read
Reading of the Flash and EEPROM is done by using load instructions with an address according to the
memory map. Reading any of the arrays while a write or erase is in progress will result in a bus wait, and
the instruction will be suspended until the ongoing operation is complete.
8.3.2.2 Page Buffer Load
The page buffer is loaded by writing directly to the memories as defined in the memory map. Flash,
EEPROM, and User Row share the same page buffer so only one section can be programmed at a time.
The Least Significant bits (LSb) of the address are used to select where in the page buffer the data is
written. The resulting data will be a binary and operation between the new and the previous content of the
page buffer. The page buffer will automatically be erased (all bits set) after:
•A device Reset
•Any page write or erase operation
•A Clear Page Buffer command
•The device wakes up from any sleep mode
8.3.2.3 Programming
For page programming, filling the page buffer and writing the page buffer into Flash, User Row, and
EEPROM are two separate operations.
Before programming a Flash page with the data in the page buffer, the Flash page must be erased. The
page buffer is also erased when the device enters a sleep mode. Programming an unerased Flash page
will corrupt its content.
The Flash can either be written with the erase and write separately, or one command handling both:
Alternative 1:
•Fill the page buffer
•Write the page buffer to Flash with the Erase/Write Page command
megaAVR® 0-Series
Nonvolatile Memory Controller (NVMCTRL)
Alternative 2:
•Write to a location in the page to set up the address
•Perform an Erase Page command
•Fill the page buffer
•Perform a Write Page command
The NVM command set supports both a single erase and write operation, and split Page Erase and Page
Write commands. This split commands enable shorter programming time for each command, and the
erase operations can be done during non-time-critical programming execution.
The EEPROM programming is similar, but only the bytes updated in the page buffer will be written or
erased in the EEPROM.
8.3.2.4 Commands
Reading of the Flash/EEPROM and writing of the page buffer is handled with normal load/store
instructions. Other operations, such as writing and erasing the memory arrays, are handled by commands
in the NVM.
To execute a command in the NVM:
1.Confirm that any previous operation is completed by reading the Busy Flags (EEBUSY and
FBUSY) in the NVMCTRL.STATUS register.
2.Write the NVM command unlock to the Configuration Change Protection register in the CPU
(CPU.CCP).
3.Write the desired command value to the CMD bits in the Control A register (NVMCTRL.CTRLA)
within the next four instructions.
Write Command
The Write command of the Flash controller writes the content of the page buffer to the Flash or EEPROM.
If the write is to the Flash, the CPU will stop executing code as long as the Flash is busy with the write
operation. If the write is to the EEPROM, the CPU can continue executing code while the operation is
ongoing.
The page buffer will be automatically cleared after the operation is finished.
Erase Command
The Erase command erases the current page. There must be one byte written in the page buffer for the
Erase command to take effect.
For erasing the Flash, first, write to one address in the desired page, then execute the command. The
whole page in the Flash will then be erased. The CPU will be halted while the erase is ongoing.
For the EEPROM, only the bytes written in the page buffer will be erased when the command is
executed. To erase a specific byte, write to its corresponding address before executing the command. To
erase a whole page all the bytes in the page buffer have to be updated before executing the command.
The CPU can continue running code while the operation is ongoing.
The page buffer will automatically be cleared after the operation is finished.
Erase-Write Operation
The Erase/Write command is a combination of the Erase and Write command, but without clearing the
page buffer after the Erase command: The erase/write operation first erases the selected page, then it
writes the content of the page buffer to the same page.
When executed on the Flash, the CPU will be halted when the operations are ongoing. When executed
on EEPROM, the CPU can continue executing code.
The page buffer will automatically be cleared after the operation is finished.
Page Buffer Clear Command
The Page Buffer Clear command clears the page buffer. The contents of the page buffer will be all 1’s
after the operation. The CPU will be halted when the operation executes (seven CPU cycles).
Chip Erase Command
The Chip Erase command erases the Flash and the EEPROM. The EEPROM is unaltered if the
EEPROM Save During Chip Erase (EESAVE) fuse in FUSE.SYSCFG0 is set. The Flash will not be
protected by Boot Section Lock (BOOTLOCK) or Application Code Section Write Protection (APCWP) in
NVMCTRL.CTRLB. The memory will be all 1’s after the operation.
EEPROM Erase Command
The EEPROM Erase command erases the EEPROM. The EEPROM will be all 1’s after the operation.
The CPU will be halted while the EEPROM is being erased.
Fuse Write Command
The Fuse Write command writes the fuses. It can only be used by the UPDI, the CPU cannot start this
command.
Follow this procedure to use this command:
•Write the address of the fuse to the Address register (NVMCTRL.ADDR)
•Write the data to be written to the fuse to the Data register (NVMCTRL.DATA)
•Execute the Fuse Write command.
•After the fuse is written, a Reset is required for the updated value to take effect.
For reading fuses, use a regular read on the memory location.
8.3.3 Preventing Flash/EEPROM Corruption
During periods of low VDD, the Flash program or EEPROM data can be corrupted if the supply voltage is
too low for the CPU and the Flash/EEPROM to operate properly. These issues are the same as for board
level systems using Flash/EEPROM, and the same design solutions should be applied.
A Flash/EEPROM corruption can be caused by two situations when the voltage is too low:
1.A regular write sequence to the Flash, which requires a minimum voltage to operate correctly.
2.The CPU itself can execute instructions incorrectly when the supply voltage is too low.
See the Electrical Characteristics chapter for Maximum Frequency vs. VDD.
Flash/EEPROM corruption can be avoided by these measures:
•Keep the device in Reset during periods of insufficient power supply voltage. This can be done by
enabling the internal Brown-Out Detector (BOD).
•The voltage level monitor in the BOD can be used to prevent starting a write to the EEPROM close
to the BOD level.
•If the detection levels of the internal BOD don’t match the required detection level, an external low
VDD Reset protection circuit can be used. If a Reset occurs while a write operation is ongoing, the
write operation will be aborted.
8.3.4 Interrupts
Table 8-2. Available Interrupt Vectors and Sources
OffsetNameVector DescriptionConditions
megaAVR® 0-Series
Nonvolatile Memory Controller (NVMCTRL)
0x00EEREADYNVMThe EEPROM is ready for new write/erase operations.
When an interrupt condition occurs, the corresponding interrupt flag is set in the Interrupt Flags register of
the peripheral (NVMCTRL.INTFLAGS).
An interrupt source is enabled or disabled by writing to the corresponding bit in the peripheral's Interrupt
Enable register (NVMCTRL.INTEN).
An interrupt request is generated when the corresponding interrupt source is enabled and the interrupt
flag is set. The interrupt request remains active until the interrupt flag is cleared. See the peripheral's
INTFLAGS register for details on how to clear interrupt flags.
8.3.5 Sleep Mode Operation
If there is no ongoing write operation, the NVMCTRL will enter sleep mode when the system enters sleep
mode.
If a write operation is ongoing when the system enters a sleep mode, the NVM block, the NVM Controller,
and the system clock will remain ON until the write is finished. This is valid for all sleep modes, including
Power-Down Sleep mode.
The EEPROM Ready interrupt will wake up the device only from Idle Sleep mode.
The page buffer is cleared when waking up from Sleep.
8.3.6 Configuration Change Protection
This peripheral has registers that are under Configuration Change Protection (CCP). In order to write to
these, a certain key must be written to the CPU.CCP register first, followed by a write access to the
protected bits within four CPU instructions.
It is possible to try writing to these registers at any time, but the values are not altered.
Bits 2:0 – CMD[2:0] Command
Write this bit field to issue a command. The Configuration Change Protection key for self-programming
(SPM) has to be written within four instructions before this write.
ValueNameDescription
0x0-No command
0x1WPWrite page buffer to memory (NVMCTRL.ADDR selects which memory)
0x2ERErase page (NVMCTRL.ADDR selects which memory)
0x3ERWP Erase and write page (NVMCTRL.ADDR selects which memory)
0x4PBCPage buffer clear
0x5CHERChip erase: erase Flash and EEPROM (unless EESAVE in FUSE.SYSCFG is '1')
0x6EEEREEPROM Erase
0x7WFUWrite fuse (only accessible through UPDI)
Bit 2 – WRERROR Write Error
This bit will read '1' when a write error has happened. A write error could be writing to different sections
before doing a page write or writing to a protected area. This bit is valid for the last operation.
Bit 1 – EEBUSY EEPROM Busy
This bit will read '1' when the EEPROM is busy with a command.
Bit 0 – FBUSY Flash Busy
This bit will read '1' when the Flash is busy with a command.
Bit 0 – EEREADY EEPROM Ready Interrupt
Writing a '1' to this bit enables the interrupt, which indicates that the EEPROM is ready for new write/
erase operations.
This is a level interrupt that will be triggered only when the EEREADY flag in the INTFLAGS register is set
to zero. Thus, the interrupt should not be enabled before triggering an NVM command, as the EEREADY
flag will not be set before the NVM command issued. The interrupt should be disabled in the interrupt
handler.
The NVMCTRL.DATAL and NVMCTRL.DATAH register pair represents the 16-bit value,
NVMCTRL.DATA. The low byte [7:0] (suffix L) is accessible at the original offset. The high byte [15:8]
(suffix H) can be accessed at offset + 0x01.
Bit 15141312111098
Access
Reset 00000000
Bit 76543210
Access
Reset 00000000
R/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
DATA[15:8]
DATA[7:0]
Bits 15:0 – DATA[15:0] Data Register
This register is used by the UPDI for fuse write operations.
The NVMCTRL.ADDRL and NVMCTRL.ADDRH register pair represents the 16-bit value,
NVMCTRL.ADDR. The low byte [7:0] (suffix L) is accessible at the original offset. The high byte [15:8]
(suffix H) can be accessed at offset + 0x01.
Bit 15141312111098
Access
Reset 00000000
Bit 76543210
Access
Reset 00000000
R/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
ADDR[15:8]
ADDR[7:0]
Bits 15:0 – ADDR[15:0] Address
The Address register contains the address to the last memory location that has been updated.
•All clocks and clock sources are automatically enabled when requested by peripherals
•Internal Oscillators:
–20 MHz Oscillator (OSC20M)
–32 KHz Ultra Low-Power Oscillator (OSCULP32K)
•External Clock Options:
–32.768 kHz Crystal Oscillator (XOSC32K)
–External clock
•Main Clock Features:
–Safe run-time switching
–Prescaler with 1x to 64x division in 12 different settings
megaAVR® 0-Series
Clock Controller (CLKCTRL)
9.2 Overview
The Clock Controller peripheral (CLKCTRL) controls, distributes, and prescales the clock signals from the
available oscillators. The CLKCTRL supports internal and external clock sources.
The CLKCTRL is based on an automatic clock request system, implemented in all peripherals on the
device. The peripherals will automatically request the clocks needed. If multiple clock sources are
available, the request is routed to the correct clock source.
The Main Clock (CLK_MAIN) is used by the CPU, RAM, and the I/O bus. The main clock source can be
selected and prescaled. Some peripherals can share the same clock source as the main clock, or run
asynchronously to the main clock domain.
The clock system consists of the main clock and other asynchronous clocks:
•Main Clock
This clock is used by the CPU, RAM, Flash, the I/O bus, and all peripherals connected to the I/O
bus. It is always running in Active and Idle Sleep mode and can be running in Standby Sleep mode
if requested.
The main clock CLK_MAIN is prescaled and distributed by the clock controller:
•Clocks running asynchronously to the main clock domain:
•CLK_CPU is used by the CPU, SRAM, and the NVMCTRL peripheral to access the
nonvolatile memory
•CLK_PER is used by all peripherals that are not listed under asynchronous clocks.
–CLK_RTC is used by the RTC/PIT. It will be requested when the RTC/PIT is enabled. The
clock source for CLK_RTC should only be changed if the peripheral is disabled.
–CLK_WDT is used by the WDT. It will be requested when the WDT is enabled.
–CLK_BOD is used by the BOD. It will be requested when the BOD is enabled in Sampled
CAUTION
mode.
The clock source for the for the main clock domain is configured by writing to the Clock Select bits
(CLKSEL) in the Main Clock Control A register (CLKCTRL.MCLKCTRLA). The asynchronous clock
sources are configured by registers in the respective peripheral.
9.2.2 Signal Description
SignalTypeDescription
CLKOUTDigital outputCLK_PER output
9.3 Functional Description
9.3.1 Sleep Mode Operation
When a clock source is not used/requested it will turn OFF. It is possible to request a clock source directly
by writing a '1' to the Run Standby bit (RUNSTDBY) in the respective oscillator's Control A register
(CLKCTRL.[osc]CTRLA). This will cause the oscillator to run constantly, except for Power-Down Sleep
mode. Additionally, when this bit is written to '1' the oscillator start-up time is eliminated when the clock
source is requested by a peripheral.
megaAVR® 0-Series
Clock Controller (CLKCTRL)
The main clock will always run in Active and Idle Sleep mode. In Standby Sleep mode, the main clock will
only run if any peripheral is requesting it, or the Run in Standby bit (RUNSTDBY) in the respective
oscillator's Control A register (CLKCTRL.[osc]CTRLA) is written to '1'.
In Power-Down Sleep mode, the main clock will stop after all NVM operations are completed.
9.3.2 Main Clock Selection and Prescaler
All internal oscillators can be used as the main clock source for CLK_MAIN. The main clock source is
selectable from software, and can be safely changed during normal operation.
Upon selection of an external clock source, a switch to the chosen clock source will only occur if edges
are detected, indicating it is stable. Until a sufficient number of clock edges are detected, the switch will
not occur and it will not be possible to change to another clock source again without executing a Reset.
An ongoing clock source switch is indicated by the System Oscillator Changing flag (SOSC) in the Main
Clock Status register (CLKCTRL.MCLKSTATUS). The stability of the external clock sources is indicated
by the respective status flags (EXTS and XOSC32KS in CLKCTRL.MCLKSTATUS).
If an external clock source fails while used as CLK_MAIN source, only the WDT can provide a
mechanism to switch back via System Reset.
CLK_MAIN is fed into a prescaler before it is used by the peripherals (CLK_PER) in the device. The
prescaler divide CLK_MAIN by a factor from 1 to 64.
The Main Clock and Prescaler configuration registers (CLKCTRL.MCLKCTRLA,
CLKCTRL.MCLKCTRLB) are protected by the Configuration Change Protection Mechanism, employing a
timed write procedure for changing these registers.
9.3.3 Main Clock After Reset
After any Reset, CLK_MAIN is provided by the 20 MHz Oscillator (OSC20M) and with a prescaler division
factor of 6. The actual frequency of the OSC20M is determined by the Frequency Select bits (FREQSEL)
of the Oscillator Configuration fuse (FUSE.OSCCFG). Refer to the description of FUSE.OSCCFG for
details of the possible frequencies after Reset.
9.3.4 Clock Sources
All internal clock sources are enabled automatically when they are requested by a peripheral. The crystal
oscillator, based on an external crystal, must be enabled by writing a '1' to the ENABLE bit in the 32 KHz
Crystal Oscillator Control A register (CLKCTRL.XOSC32KCTRLA) before it can serve as a clock source.
megaAVR® 0-Series
Clock Controller (CLKCTRL)
The respective Oscillator Status bits in the Main Clock Status register (CLKCTRL.MCLKSTATUS) indicate
whether the clock source is running and stable.
9.3.4.1 Internal Oscillators
The internal oscillators do not require any external components to run. See the related links for accuracy
and electrical characteristics.
20 MHz Oscillator (OSC20M)
This oscillator can operate at multiple frequencies, selected by the value of the Frequency Select bits
(FREQSEL) in the Oscillator Configuration Fuse (FUSE.OSCCFG).
After a system Reset, FUSE.OSCCFG determines the initial frequency of CLK_MAIN.
During Reset, the calibration values for the OSC20M are loaded from fuses. There are two different
calibration bit fields. The Calibration bit field (CAL20M) in the Calibration A register
(CLKCTRL.OSC20MCALIBA) enables calibration around the current center frequency. The Oscillator
Temperature Coefficient Calibration bit field (TEMPCAL20M) in the Calibration B register
(CLKCTRL.OSC20MCALIBB) enables adjustment of the slope of the temperature drift compensation.
For applications requiring more fine-tuned frequency setting than the oscillator calibration provides,
factory stored frequency error after calibrations are available.
The oscillator calibration can be locked by the Oscillator Lock (OSCLOCK) Fuse (FUSE.OSCCFG). When
this fuse is '1', it is not possible to change the calibration. The calibration is locked if this oscillator is used
as main clock source and the Lock Enable bit (LOCKEN) in the Control B register
(CLKCTRL.OSC20MCALIBB) is '1'.
The calibration bits are protected by the Configuration Change Protection Mechanism, requiring a timed
write procedure for changing the main clock and prescaler settings.
Refer to the Electrical Characteristics section for the start-up time.
This oscillator can operate at multiple frequencies, selected by the value of the Frequency Select bits
(FREQSEL) in the Oscillator Configuration fuse (FUSE.OSCCFG) at Reset. As previously mentioned
appropriate calibration values are loaded to adjust to center frequency (OSC20M), and temperature drift
compensation (TEMPCAL20M), meeting the specifications defined in the internal oscillator
characteristics. For applications requiring wider operating range, the relative factory stored frequency
error after calibrations can be used. The four errors are measured at different settings and are available in
the signature row as signed byte values.
•SIGROW.OSC16ERR3V is the frequency error from 16 MHz measured at 3V
•SIGROW.OSC16ERR5V is the frequency error from 16 MHz measured at 5V
•SIGROW.OSC20ERR3V is the frequency error from 20 MHz measured at 3V
•SIGROW.OSC20ERR5V is the frequency error from 20 MHz measured at 5V
The error is stored as a compressed Q1.10 fixed point 8-bit value, in order not to lose resolution, where
the MSB is the sign bit and the seven LSBs the lower bits of the Q.10.
BAUD
act
= BAUD
+
BAUD
*
1024
The minimum legal BAUD register value is 0x40, the target BAUD register value should therefore not be
lower than 0x4A to ensure that the compensated BAUD value stays within the legal range, even for parts
with negative compensation values. The example code below, demonstrates how to apply this value for
more accurate USART baud rate:
#include <assert.h>
/* Baud rate compensated with factory stored frequency error *//* Asynchronous communication without Auto-baud (Sync Field) *//* 16MHz Clock, 3V and 600 BAUD */
int8_t sigrow_val = SIGROW.OSC16ERR3V; // read signed errorint32_t baud_reg_val = 600; // ideal BAUD register value
assert (baud_reg_val >= 0x4A); // Verify legal min BAUD register
value with max neg comp
baud_reg_val *= (1024 + sigrow_val); // sum resolution + error
baud_reg_val /= 1024; // divide by resolution
USART0.BAUD = (int16_t) baud_reg_val; // set adjusted baud rate
32 KHz Oscillator (OSCULP32K)
The 32 KHz oscillator is optimized for Ultra Low-Power (ULP) operation. Power consumption is
decreased at the cost of decreased accuracy compared to an external crystal oscillator.
This oscillator provides the 1 KHz signal for the Real-Time Counter (RTC), the Watchdog Timer (WDT),
and the Brown-out Detector (BOD).
The start-up time of this oscillator is the oscillator start-up time plus four oscillator cycles. Refer to the
Electrical Characteristics chapter for the start-up time.
9.3.4.2 External Clock Sources
These external clock sources are available:
•External Clock from pin. (EXTCLK).
•The TOSC1 and TOSC2 pins are dedicated to driving a 32.768 kHz Crystal Oscillator (XOSC32K).
•Instead of a crystal oscillator, TOSC1 can be configured to accept an external clock source.
This oscillator supports two input options: Either a crystal is connected to the pins TOSC1 and TOSC2, or
an external clock running at 32 KHz is connected to TOSC1. The input option must be configured by
writing the Source Select bit (SEL) in the XOSC32K Control A register (CLKCTRL.XOSC32KCTRLA).
The XOSC32K is enabled by writing a '1' to its ENABLE bit in CLKCTRL.XOSC32KCTRLA. When
enabled, the configuration of the GPIO pins used by the XOSC32K is overridden as TOSC1, TOSC2 pins.
The Enable bit needs to be set for the oscillator to start running when requested.
The start-up time of a given crystal oscillator can be accommodated by writing to the Crystal Start-up
Time bits (CSUT) in CLKCTRL.XOSC32KCTRLA.
When XOSC32K is configured to use an external clock on TOSC1, the start-up time is fixed to two cycles.
External Clock (EXTCLK)
The EXTCLK is taken directly from the pin. This GPIO pin is automatically configured for EXTCLK if any
peripheral is requesting this clock.
This clock source has a start-up time of two cycles when first requested.
9.3.5 Configuration Change Protection
This peripheral has registers that are under Configuration Change Protection (CCP). In order to write to
these, a certain key must be written to the CPU.CCP register first, followed by a write access to the
protected bits within four CPU instructions.
megaAVR® 0-Series
Clock Controller (CLKCTRL)
It is possible to try writing to these registers at any time, but the values are not altered.
The following registers are under CCP:
Table 9-1. CLKCTRL - Registers Under Configuration Change Protection
Bits 4:1 – PDIV[3:0] Prescaler Division
If the Prescaler Enable (PEN) bit is written to ‘1’, these bits define the division ratio of the main clock
prescaler.
These bits can be written during run-time to vary the clock frequency of the system to suit the application
requirements.
The user software must ensure a correct configuration of input frequency (CLK_MAIN) and prescaler
settings, such that the resulting frequency of CLK_PER never exceeds the allowed maximum (see
Electrical Characteristics).
Name: MCLKLOCK
Offset: 0x02
Reset: Based on OSCLOCK in FUSE.OSCCFG
Property: Configuration Change Protection
Bit 76543210
Access
Reset x
LOCKEN
Bit 0 – LOCKEN Lock Enable
Writing this bit to '1' will lock the CLKCTRL.MCLKCTRLA and CLKCTRL.MCLKCTRLB registers, and, if
applicable, the calibration settings for the current main clock source from further software updates. Once
locked, the CLKCTRL.MCLKLOCK registers cannot be accessed until the next hardware Reset.
This provides protection for the CLKCTRL.MCLKCTRLA and CLKCTRL.MCLKCTRLB registers and
calibration settings for the main clock source from unintentional modification by software.
R/W
At Reset, the LOCKEN bit is loaded based on the OSCLOCK bit in FUSE.OSCCFG.
Bit 6 – XOSC32KS XOSC32K Status
The Status bit will only be available if the source is requested as the main clock or by another module. If
the oscillator RUNSTDBY bit is set but the oscillator is unused/not requested, this bit will be 0.
ValueDescription
0XOSC32K is not stable
1XOSC32K is stable
Bit 5 – OSC32KS OSCULP32K Status
The Status bit will only be available if the source is requested as the main clock or by another module. If
the oscillator RUNSTDBY bit is set but the oscillator is unused/not requested, this bit will be 0.
ValueDescription
0OSCULP32K is not stable
1OSCULP32K is stable
Bit 4 – OSC20MS OSC20M Status
The Status bit will only be available if the source is requested as the main clock or by another module. If
the oscillator RUNSTDBY bit is set but the oscillator is unused/not requested, this bit will be 0.
ValueDescription
0OSC20M is not stable
1OSC20M is stable
Bit 0 – SOSC Main Clock Oscillator Changing
ValueDescription
0The clock source for CLK_MAIN is not undergoing a switch
1The clock source for CLK_MAIN is undergoing a switch and will change as soon as the new
Bit 1 – RUNSTDBY Run Standby
This bit forces the oscillator ON in all modes, even when unused by the system. In Standby Sleep mode
this can be used to ensure immediate wake-up and not waiting for oscillator start-up time.
When not requested by peripherals, no oscillator output is provided.
It takes four oscillator cycles to open the clock gate after a request but the oscillator analog start-up time
will be removed when this bit is set.
Name: OSC20MCALIBB
Offset: 0x12
Reset: Based on FUSE.OSCCFG
Property: Configuration Change Protection
Bit 76543210
LOCKTEMPCAL20M[3:0]
Access
Reset xxxxx
RR/WR/WR/WR/W
Bit 7 – LOCK Oscillator Calibration Locked by Fuse
When this bit is set, the calibration settings in CLKCTRL.OSC20MCALIBA and
CLKCTRL.OSC20MCALIBB cannot be changed.
The Reset value is loaded from the OSCLOCK bit in the Oscillator Configuration Fuse (FUSE.OSCCFG).
Bits 3:0 – TEMPCAL20M[3:0] Oscillator Temperature Coefficient Calibration
These bits tune the slope of the temperature compensation.
At Reset, the factory calibrated values are loaded based on the FREQSEL bits in FUSE.OSCCFG.
Bit 1 – RUNSTDBY Run Standby
This bit forces the oscillator ON in all modes, even when unused by the system. In Standby Sleep mode
this can be used to ensure immediate wake-up and not waiting for the oscillator start-up time.
When not requested by peripherals, no oscillator output is provided.
It takes four oscillator cycles to open the clock gate after a request but the oscillator analog start-up time
will be removed when this bit is set.
The SEL and CSUT bits cannot be changed as long as the ENABLE bit is set or the XOSC32K Stable bit
(XOSC32KS) in CLKCTRL.MCLKSTATUS is high.
To change settings in a safe way: write a '0' to the ENABLE bit and wait until XOSC32KS is '0' before reenabling the XOSC32K with new settings.
Bit 76543210
Access
Reset 00000
CSUT[1:0]SELRUNSTDBYENABLE
R/WR/WR/WR/WR/W
Bits 5:4 – CSUT[1:0] Crystal Start-Up Time
These bits select the start-up time for the XOSC32K. It is write protected when the oscillator is enabled
(ENABLE=1).
Bit 2 – SEL Source Select
This bit selects the external source type. It is write protected when the oscillator is enabled (ENABLE=1).
ValueDescription
0External crystal
1External clock on TOSC1 pin
Bit 1 – RUNSTDBY Run Standby
Writing this bit to '1' starts the crystal oscillator and forces the oscillator ON in all modes, even when
unused by the system if the ENABLE bit is set. In Standby Sleep mode this can be used to ensure
immediate wake-up and not waiting for oscillator start-up time. When this bit is '0', the crystal oscillator is
only running when requested and the ENABLE bit is set.
The output of XOSC32K is not sent to other peripherals unless it is requested by one or more peripherals.
When the RUNSTDBY bit is set there will only be a delay of two to three crystal oscillator cycles after a
request until the oscillator output is received, if the initial crystal start-up time has already completed.
According to RUNSTBY bit, the oscillator will be turned ON all the time if the device is in Active, Idle, or
Standby Sleep mode, or only be enabled when requested.
This bit is I/O protected to prevent unintentional enabling of the oscillator.
When this bit is written to '1', the configuration of the respective input pins is overridden to TOSC1 and
TOSC2. Also, the Source Select bit (SEL) and Crystal Start-Up Time (CSUT) become read-only.
This bit is I/O protected to prevent unintentional enabling of the oscillator.
•Power management for adjusting power consumption and functions
•Three sleep modes:
–Idle
–Standby
–Power-Down
•Configurable Standby Sleep mode where peripherals can be configured as ON or OFF.
10.2 Overview
Sleep modes are used to shut down peripherals and clock domains in the device in order to save power.
The Sleep Controller (SLPCTRL) controls and handles the transitions between active and sleep mode.
There are in total four modes available, one active mode in which software is executed, and three sleep
modes. The available sleep modes are; Idle, Standby, and Power-Down.
megaAVR® 0-Series
Sleep Controller (SLPCTRL)
All sleep modes are available and can be entered from active mode. In active mode, the CPU is
executing application code. When the device enters sleep mode, program execution is stopped and
interrupts or a reset is used to wake the device again. The application code decides which sleep mode to
enter and when.
Interrupts are used to wake the device from sleep. The available interrupt wake-up sources depend on
the configured sleep mode. When an interrupt occurs, the device will wake up and execute the interrupt
service routine before continuing normal program execution from the first instruction after the SLEEP
instruction. Any Reset will take the device out of a sleep mode.
The content of the register file, SRAM and registers are kept during sleep. If a Reset occurs during sleep,
the device will reset, start, and execute from the Reset vector.
To put the device into a sleep mode, follow these steps:
•Configure and enable the interrupts that shall be able to wake the device from sleep. Also, enable
global interrupts.
If there are no interrupts enabled when going to sleep, the device cannot wake up again.
Only a Reset will allow the device to continue operation.
•Select the sleep mode to be entered and enable the Sleep Controller by writing to the Sleep Mode
bits (SMODE) and the Enable bit (SEN) in the Control A register (SLPCTRL.CTRLA). A SLEEP
instruction must be run to make the device actually go to sleep.
10.3.2 Operation
10.3.2.1 Sleep Modes
In addition to Active mode, there are three different sleep modes, with decreasing power consumption
and functionality.
megaAVR® 0-Series
Sleep Controller (SLPCTRL)
IdleThe CPU stops executing code, no peripherals are disabled.
All interrupt sources can wake the device.
StandbyThe user can configure peripherals to be enabled or not, using the respective RUNSTBY
bit. This means that the power consumption is highly dependent on what functionality is
enabled, and thus may vary between the Idle and Power-Down levels.
SleepWalking is available for the ADC module.
PowerDown
BOD, WDT, and PIT (a component of the RTC) are active.
The only wake-up sources are the pin change interrupt, PIT, VLM, TWI address match and
1.RUNSTBY bit of the corresponding peripheral must be set to enter the active state.
2.CCL can select between multiple clock sources.
3.PIT only
4.CCL can wake up the device if no internal clock source is required.
10.3.2.2 Wake-Up Time
The normal wake-up time for the device is six main clock cycles (CLK_PER), plus the time it takes to start
up the main clock source:
•In Idle Sleep mode, the main clock source is kept running so it will not be any extra wake-up time.
•In Standby Sleep mode, the main clock might be running so it depends on the peripheral
configuration.
•In Power-Down Sleep mode, only the ULP 32 KHz oscillator and RTC clock may be running if it is
used by the BOD or WDT. All other clock sources will be OFF.
INTn and Pin ChangeXXX
TWI Address MatchXXX
Periodic Interrupt TimerXXX
CCLXX
RTCXX
UART Start-of-FrameXX
TCBnXX
ADCn WindowXX
ACnXX
(1)
(1)
(1)
(1)
(1)
(1)
X
All other InterruptsX
(4)
Table 10-2. Sleep Modes and Start-Up Time
Sleep ModeStart-Up Time
IDLE6 CLK
Standby6 CLK + OSC start-up
Power-Down6 CLK + OSC start-up
The start-up time for the different clock sources is described in the Clock Controller (CLKCTRL) section.
In addition to the normal wake-up time, it is possible to make the device wait until the BOD is ready
before executing code. This is done by writing 0x3 to the BOD Operation mode in Active and Idle bits
(ACTIVE) in the BOD Configuration fuse (FUSE.BODCFG). If the BOD is ready before the normal wakeup time, the net wake-up time will be the same. If the BOD takes longer than the normal wake-up time,
the wake-up time will be extended until the BOD is ready. This ensures correct supply voltage whenever
code is executed.
10.3.3 Debug Operation
When run-time debugging, this peripheral will continue normal operation. The SLPCTRL is only affected
by a break in debug operation: If the SLPCTRL is in a sleep mode when a break occurs, the device will
wake up and the SLPCTRL will go to Active mode, even if there are no pending interrupt requests.
If the peripheral is configured to require periodical service by the CPU through interrupts or similar,
improper operation or data loss may result during halted debugging.
Bits 2:1 – SMODE[1:0] Sleep Mode
Writing these bits selects the sleep mode entered when the Sleep Enable bit (SEN) is written to '1' and
the SLEEP instruction is executed.
The Reset Controller (RSTCTRL) manages the Reset of the device. It issues a device Reset, sets the
device to its initial state, and allows the Reset source to be identified by software.
The Reset Controller (RSTCTRL) is always enabled, but some of the Reset sources must be enabled
(either by fuses or by software) before they can request a Reset.
After any Reset, the Reset source that caused the Reset is found in the Reset Flag register
(RSTCTRL.RSTFR).
After a Power-on Reset, only the POR flag will be set.
The flags are kept until they are cleared by writing a '1' to them.
After Reset from any source, all registers that are loaded from fuses are reloaded.
11.3.2 Operation
11.3.2.1 Reset Sources
There are two kinds of sources for Resets:
•Power supply Resets, which are caused by changes in the power supply voltage: Power-on Reset
(POR) and Brown-out Detector (BOD).
•User Resets, which are issued by the application, by the debug operation, or by pin changes
(Software Reset, Watchdog Reset, UPDI Reset, and external Reset pin RESET).
megaAVR® 0-Series
Reset Controller (RSTCTRL)
Power-On Reset (POR)
A Power-on-Reset (POR) is generated by an on-chip detection circuit. The POR is activated when the
VDD rises until it reaches the POR threshold voltage. The POR is always enabled and will also detect
when the VDD falls below the threshold voltage.
Brown-Out Detector (BOD) Reset
The on-chip Brown-out Detection circuit will monitor the VDD level during operation by comparing it to a
fixed trigger level. The trigger level for the BOD can be selected by fuses. If BOD is unused in the
application it is forced to a minimum level in order to ensure a safe operation during internal Reset and
chip erase.
Software Reset
The software Reset makes it possible to issue a system Reset from software. The Reset is generated by
writing a '1' to the Software Reset Enable bit (SWRE) in the Software Reset register (RSTCTRL.SWRR).
The Reset will take place immediately after the bit is written and the device will be kept in reset until the
Reset sequence is completed.
External Reset
The external Reset is enabled by a fuse, see the RSTPINCFG field in FUSE.SYSCFG0.
When enabled, the external Reset requests a Reset as long as the RESET pin is low. The device will stay
in Reset until RESET is high again.
Watchdog Reset
The Watchdog Timer (WDT) is a system function for monitoring correct program operation. If the WDT is
not reset from software according to the programmed time-out period, a Watchdog Reset will be issued.
See the WDT documentation for further details.