Features • High-performance, Low-power AVR® 8-bit Microcontroller • Advanced RISC Architecture • • • • • • • – 130 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 Nonvolatile Program and Data Memories – 16K Bytes of In-System Self-Programmable Flash Endurance: 1,000 Write/Erase Cycles – Optional Boot Code Section with Independent Lock Bits In-System Programmin
Pin Configurations Figure 1.
ATmega16(L) Overview The ATmega16 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the ATmega16 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed. Block Diagram Figure 2.
The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
ATmega16(L) Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tristated when a reset condition becomes active, even if the clock is not running.
AVR CPU Core Introduction This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. Architectural Overview Figure 3.
ATmega16(L) an arithmetic operation, the Status Register is updated to reflect information about the result 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 single 16-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 and the Application program section.
• Bit 7 - I: Global Interrupt Enable The global interrupt enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts.
ATmega16(L) Figure 4. AVR CPU General Purpose Working Registers 7 0 Addr.
Stack Pointer The stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The stack pointer register always points to the top of the stack. Note that the stack is implemented as growing from higher memory locations to lower memory locations. This implies that a stack PUSH command decreases the stack pointer. The Stack Pointer points to the data SRAM stack area where the Subroutine and Interrupt Stacks are located.
ATmega16(L) Figure 7. Single Cycle ALU Operation T1 T2 T3 T4 clkCPU Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back Reset and Interrupt Handling The AVR provides several different interrupt sources. These interrupts and the separate reset vector each have a separate program vector in the program memory space.
Note that the status register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software. When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example shows how this can be used to avoid interrupts during the timed EEPROM write sequence..
ATmega16(L) AVR ATmega16 Memories This section describes the different memories in the ATmega16. The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega16 features an EEPROM Memory for data storage. All three memory spaces are linear and regular. In-system Reprogrammable Flash Program Memory The ATmega16 contains 16K bytes On-chip In-System Reprogrammable Flash memory for program storage.
SRAM Data Memory Figure 9 shows how the ATmega16 SRAM Memory is organized. The lower 1120 Data Memory locations address the Register file, the I/O Memory, and the internal data SRAM. The first 96 locations address the Register file and I/O Memory, and the next 1024 locations address the internal data SRAM. The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment.
ATmega16(L) Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 10. Figure 10.
EEPROM Data Memory The ATmega16 contains 512 bytes of data EEPROM memory. It is 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 access between the EEPROM and the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register.
ATmega16(L) tion, the EEDR contains the data read out from the EEPROM at the address given by EEAR. The EEPROM Control Register – EECR Bit 7 6 5 4 3 2 1 0 – – – – EERIE EEMWE EEWE EERE Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 X 0 EECR • Bits 7..4 - Res: Reserved Bits These bits are reserved bits in the ATmega16 and will always read as zero.
EEWE has been set, the CPU is halted for two cycles before the next instruction is executed. • Bit 0 - EERE: EEPROM Read Enable The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately.
ATmega16(L) The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (for example by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash boot loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish.
The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions.
ATmega16(L) I/O Memory The I/O space definition of the ATmega16 is shown in “Register Summary” on page 290. All ATmega16 I/Os and peripherals are placed in the I/O space. The I/O locations are accessed by the IN and OUT instructions, transferring data between the 32 general purpose working registers and the I/O space. I/O registers within the address range $00 $1F are directly bit-accessible using the SBI and CBI instructions.
System Clock and Clock Options Clock Systems and their Distribution Figure 11 presents the principal clock systems in the AVR and their distribution. All of the clocks need not be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in “Power Management and Sleep Modes” on page 30. The clock systems are detailed Figure 11. Figure 11.
ATmega16(L) Asynchronous Timer Clock – clkASY The Asynchronous Timer clock allows the Asynchronous Timer/Counter to be clocked directly from an external 32 kHz clock crystal. The dedicated clock domain allows using this Timer/Counter as a real-time counter even when the device is in sleep mode. ADC Clock – clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce noise generated by digital circuitry.
For resonators, the maximum frequency is 8 MHz with CKOPT unprogrammed and 16 MHz with CKOPT programmed. C1 and C2 should always be equal for both crystals and resonators. The optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. Some initial guidelines for choosing capacitors for use with crystals are given in Table 4.
ATmega16(L) The CKSEL0 fuse together with the SUT1..0 fuses select the start-up times as shown in Table 5. Table 5. Start-up Times for the Crystal Oscillator Clock Selection CKSEL0 SUT1..
When this oscillator is selected, start-up times are determined by the SUT fuses as shown in Table 6. Table 6. Start-up Times for the Low Frequency Crystal Oscillator Clock Selection SUT1..0 Start-up Time from Power-down and Power-save Additional Delay from Reset (VCC = 5.0V) 1K CK 4 ms Fast rising power or BOD enabled 01 1K CK (1) 64 ms Slowly rising power 10 32K CK 64 ms Stable frequency at start-up 00 11 Note: External RC Oscillator Recommended Usage (1) Reserved 1.
ATmega16(L) Table 8. Start-up Times for the External RC Oscillator Clock Selection SUT1..0 Start-up Time from Power-down and Power-save Additional Delay from Reset (VCC = 5.0V) 00 18 CK – 01 18 CK 4 ms Fast rising power 10 18 CK 64 ms Slowly rising power 11 (1) 4 ms Fast rising power or BOD enabled Note: Calibrated Internal RC Oscillator 6 CK Recommended Usage BOD enabled 1. This option should not be used when operating close to the maximum frequency of the device.
Oscillator Calibration Register – OSCCAL Bit Read/Write 7 6 5 4 3 2 1 0 CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 R/W R/W R/W R/W R/W R/W R/W R/W Initial Value OSCCAL Device Specific Calibration Value • Bits 7..0 - CAL7..0: Oscillator Calibration Value Writing the calibration byte to this address will trim the internal oscillator to remove process variations from the oscillator frequency. This is done automatically during chip reset.
ATmega16(L) When this clock source is selected, start-up times are determined by the SUT fuses as shown in Table 12. Table 12. Start-up Times for the External Clock Selection SUT1..0 Start-up Time from Power-down and Power-save Additional Delay from Reset (VCC = 5.
Power Management and Sleep Modes Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to the application’s requirements. To enter any of the six sleep modes, the SE bit in MCUCR must be written to logic one and a SLEEP instruction must be executed.
ATmega16(L) Idle Mode When the SM2..0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle Mode, stopping the CPU but allowing SPI, USART, Analog Comparator, ADC, 2wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system to continue operating. This sleep mode basically halts clkCPU and clkFLASH, while allowing the other clocks to run.
asynchronous timer should be considered undefined after wake-up in Power-save mode if AS2 is 0. This sleep mode basically halts all clocks except clkASY, allowing operation only of asynchronous modules, including Timer/Counter 2 if clocked asynchronously. Standby Mode When the SM2..0 bits are 110 and an external crystal/resonator clock option is selected, the SLEEP instruction makes the MCU enter Standby mode. This mode is identical to Power-down with the exception that the oscillator is kept running.
ATmega16(L) Analog Comparator When entering Idle Mode, the Analog Comparator should be disabled if not used. When entering ADC Noise Reduction Mode, the Analog Comparator should be disabled. In the other sleep modes, the Analog Comparator is automatically disabled. However, if the Analog Comparator is set up to use the Internal Voltage Reference as input, the Analog Comparator should be disabled in all sleep modes. Otherwise, the Internal Voltage Reference will be enabled, independent of sleep mode.
System Control and Reset Resetting the AVR During reset, all I/O registers are set to their initial values, and the program starts execution from the Reset Vector. The instruction placed at the Reset Vector must be a JMP – absolute jump – instruction to the reset handling routine. If the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations.
ATmega16(L) Figure 15. Reset Logic DATA BUS PORF BORF EXTRF WDRF JTRF MCU Control and Status Register (MCUCSR) Brown-Out Reset Circuit BODEN BODLEVEL Pull-up Resistor SPIKE FILTER JTAG Reset Register Watchdog Oscillator Clock Generator CK Delay Counters TIMEOUT CKSEL[3:0] SUT[1:0] Table 15. Reset Characteristics(1) Symbol Min Typ Max Units Power-on Reset Threshold Voltage (rising) TBD TBD 2.3 V Power-on Reset Threshold Voltage (falling)(2) TBD TBD 2.
Power-on Reset A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level is defined in Table 15. The POR is activated whenever VCC is below the detection level. The POR circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. A Power-on Reset (POR) circuit ensures that the device is reset from power-on.
ATmega16(L) Figure 18. External Reset During Operation CC Brown-out Detection ATmega16 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VCC level during operation by comparing it to a fixed trigger level. The trigger level for the BOD can be selected by the fuse BODLEVEL to be 2.7V (BODLEVEL unprogrammed), or 4.0V (BODLEVEL programmed). The trigger level has a hysteresis to ensure spike free Brown-out Detection.
Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of 1 CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period tTOUT. Refer to page 39 for details on operation of the Watchdog Timer. Figure 20. Watchdog Reset During Operation CC CK MCU Control and Status Register – MCUCSR The MCU Control and Status Register provides information on which reset source caused an MCU reset.
ATmega16(L) Internal Voltage Reference ATmega16 features an internal bandgap reference. This reference is used for Brownout Detection, and it can be used as an input to the Analog Comparator or the ADC. The 2.56V reference to the ADC is generated from the internal bandgap reference. Voltage Reference Enable Signals and Start-up Time The voltage reference has a start-up time that may influence the way it should be used. The start-up time is given in Table 16.
Figure 21. Watchdog Timer WATCHDOG OSCILLATOR Watchdog Timer Control Register – WDTCR Bit 7 6 5 4 3 2 1 0 – – – WDTOE WDE WDP2 WDP1 WDP0 Read/Write R R R R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 WDTCR • Bits 7..5 - Res: Reserved Bits These bits are reserved bits in the ATmega16 and will always read as zero. • Bit 4 - WDTOE: Watchdog Turn-off Enable This bit must be set when the WDE bit is written to logic zero. Otherwise, the watchdog will not be disabled.
ATmega16(L) Table 17. Watchdog Timer Prescale Select(1) WDP2 WDP1 WDP0 Number of WDT Oscillator Cycles Typical Time-out at VCC = 3.0V Typical Time-out at VCC = 5.0V 0 0 0 16K TBD 16 ms 0 0 1 32K TBD 32 ms 0 1 0 64K TBD 64 ms 0 1 1 128K TBD 0.13 s 1 0 0 256K TBD 0.26 s 1 0 1 512K TBD 0.5 s 1 1 0 1,024K TBD 1.0 s 1 1 1 2,048K TBD 2.0 s Note: 1. Values are guidelines only. Actual values are TBD.
Interrupts Interrupt Vectors in ATmega16 This section describes the specifics of the interrupt handling as performed in ATmega16. For a general explanation of the AVR interrupt handling, refer to “Reset and Interrupt Handling” on page 11. Table 18. Reset and Interrupt Vectors Vector No.
ATmega16(L) Table 19. Reset and Interrupt Vectors Placement(1) BOOTRST IVSEL Reset address Interrupt Vectors Start Address 1 0 $0000 $0002 1 1 $0000 Boot Reset Address + $0002 0 0 Boot Reset Address $0002 0 1 Boot Reset Address Boot Reset Address + $0002 Note: 1. The Boot Reset Address is shown in Table 100 on page 252. For the BOOTRST fuse “1” means unprogrammed while “0” means programmed.
When the BOOTRST fuse is unprogrammed, the boot section size set to 2K bytes and the IVSEL bit in the GICR register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is: Address Labels $000 RESET: $001 $002 Code Comments ldi r16,high(RAMEND) ; Main program start out SPH,r16 ldi ; Set stack pointer to top of RAM r16,low(RAMEND) $003 out SPL,r16 $004 sei $005 ; Enable interrupts xxx ; .
ATmega16(L) Moving Interrupts Between Application and Boot Space General Interrupt Control Register – GICR The General Interrupt Control Register controls the placement of the interrupt vector table. Bit 7 6 5 4 3 2 1 0 INT1 INT0 INT2 – – – IVSEL IVCE Read/Write R/W R/W R/W R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 GICR • Bit 1 - IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (zero), the interrupt vectors are placed at the start of the Flash memory.
Assembly Code Example Move_interrupts: ; Enable change of interrupt vectors ldi r16, (1<
ATmega16(L) I/O Ports Introduction All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input).
Ports as General Digital I/O The ports are bi-directional I/O ports with optional internal pull-ups. Figure 23 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 23.
ATmega16(L) enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in the SFIOR register can be set to disable all pull-ups in all ports. Switching between input with pull-up and output low generates the same problem. The user must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn} = 0b10) as an intermediate step.
ceeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between ½ and 1-½ system clock period depending upon the time of assertion. When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 25. The out instruction sets the “SYNC LATCH” signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is 1 system clock period. Figure 25.
ATmega16(L) Assembly Code Example(1) ... ; Define pull-ups and set outputs high ; Define directions for port pins ldi r16,(1<
Alternate Port Functions Most port pins have alternate functions in addition to being general digital I/Os. Figure 26 shows how the port pin control signals from the simplified Figure 23 can be overridden by alternate functions. The overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the AVR microcontroller family. Figure 26.
ATmega16(L) Table 21. Generic Description of Overriding Signals for Alternate Functions Signal Name Full Name Description PUOE Pull-up Override Enable If this signal is set, the pull-up enable is controlled by the PUOV signal. If this signal is cleared, the pull-up is enabled when {DDxn, PORTxn, PUD} = 0b010. PUOV Pull-up Override Value If PUOE is set, the pull-up is enabled/disabled when PUOV is set/cleared, regardless of the setting of the DDxn, PORTxn, and PUD register bits.
Alternate Functions of Port A Port A has an alternate function as analog input for the ADC as shown in Table 22. If some Port A pins are configured as outputs, it is essential that these do not switch when a conversion is in progress. This might corrupt the result of the conversion. Table 22.
ATmega16(L) Table 24. Overriding Signals for Alternate Functions in PA3..PA0 Signal Name PA2/ADC2 PA1/ADC1 PA0/ADC0 PUOE 0 0 0 0 PUOV 0 0 0 0 DDOE 0 0 0 0 DDOV 0 0 0 0 PVOE 0 0 0 0 PVOV 0 0 0 0 DIEOE 0 0 0 0 DIEOV 0 0 0 0 DI – – – – ADC3 INPUT ADC2 INPUT ADC1 INPUT ADC0 INPUT AIO Alternate Functions of Port B PA3/ADC3 The Port B pins with alternate functions are shown in Table 25. Table 25.
• MOSI - Port B, Bit 5 MOSI: SPI Master data output, slave data input for SPI channel. When the SPI is enabled as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit. • SS - Port B, Bit 4 SS: Slave Select input.
ATmega16(L) Table 26. Overriding Signals for Alternate Functions in PB7..
Alternate Functions of Port C The Port C pins with alternate functions are shown in Table 28. If the JTAG interface is enabled, the pull-up resistors on pins PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset occurs. Table 28.
ATmega16(L) an open drain driver with slew-rate limitation. When this pin is used by the 2-wire Serial Interface, the pull-up can still be controlled by the PORTC1 bit. • SCL - Port C, Bit 0 SCL, 2-wire Serial Interface Clock: When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC0 is disconnected from the port and becomes the Serial Clock I/O pin for the 2-wire Serial Interface.
Alternate Functions of Port D The Port D pins with alternate functions are shown in Table 31. Table 31.
ATmega16(L) USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit. Table 32 and Table 33 relate the alternate functions of Port D to the overriding signals shown in Figure 26 on page 52. Table 32. Overriding Signals for Alternate Functions PD7..
Register Description for I/O Ports Port A Data Register – PORTA Bit Port A Data Direction Register – DDRA Port A Input Pins Address – PINA 7 6 5 4 3 2 1 0 PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 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 DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 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
ATmega16(L) Port C Input Pins Address – PINC Bit 7 6 5 4 3 2 1 0 PINC7 PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 Read/Write R R R R R R R R Initial Value N/A N/A N/A N/A N/A N/A N/A N/A PINC Port D Data Register – PORTD Bit Port D Data Direction Register – DDRD Port D Input Pins Address – PIND 7 6 5 4 3 2 1 0 PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0
External Interrupts The external interrupts are triggered by the INT0, INT1, and INT2 pins. Observe that, if enabled, the interrupts will trigger even if the INT0..2 pins are configured as outputs. This feature provides a way of generating a software interrupt. The external interrupts can be triggered by a falling or rising edge or a low level (INT2 is only an edge triggered interrupt).
ATmega16(L) • Bit 1, 0 - ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0 The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt mask are set. The level and edges on the external INT0 pin that activate the interrupt are defined in Table 35. The value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt.
interrupt is activated on rising and/or falling edge of the INT1 pin or level sensed. Activity on the pin will cause an interrupt request even if INT1 is configured as an output. The corresponding interrupt of External Interrupt Request 1 is executed from the INT1 interrupt vector. • Bit 6 - INT0: External Interrupt Request 0 Enable When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is enabled.
ATmega16(L) 8-bit Timer/Counter0 with PWM Timer/Counter0 is a general purpose, single channel, 8-bit Timer/Counter module. The main features are: • Single Channel Counter • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) • Frequency Generator • External Event Counter • 10-bit Clock Prescaler • Overflow and Compare Match Interrupt Sources (TOV0 and OCF0) Overview A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 27.
The double buffered Output Compare Register (OCR0) is compared with the Timer/Counter value at all times. The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the Output Compare Pin (OC0). See “Output Compare Unit” on page 69. for details. The compare match event will also set the compare flag (OCF0) which can be used to generate an output compare interrupt request.
ATmega16(L) Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0). clkT0 can be generated from an external or internal clock source, selected by the clock select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of whether clkT0 is present or not. A CPU write overrides (has priority over) all counter clear or count operations.
OCR0 compare register to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. The OCR0 register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR0 buffer register, and if double buffering is disabled the CPU will access the OCR0 directly.
ATmega16(L) Figure 30. Compare Match Output Unit, Schematic COMn1 COMn0 FOCn Waveform Generator D Q 1 OCn DATABUS D 0 OCn Pin Q PORT D Q DDR clk I/O The general I/O port function is overridden by the output compare (OC0) from the waveform generator if either of the COM01:0 bits are set. However, the OC0 pin direction (input or output) is still controlled by the data direction register (DDR) for the port pin.
Normal Mode The simplest mode of operation is the normal mode (WGM01:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter overflow flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero.
ATmega16(L) quency of fOC0 = fclk_I/O/2 when OCR0 is set to zero (0x00). The waveform frequency is defined by the following equation: f clk_I/O f OCn = ---------------------------------------------2 ⋅ N ⋅ ( 1 + OCRn ) The N variable represents the prescale factor (1, 8, 64, 256, or 1024). As for the normal mode of operation, the TOV0 flag is set in the same timer clock cycle that the counter counts from MAX to 0x00.
pin is set as output. The PWM waveform is generated by setting (or clearing) the OC0 register at the compare match between OCR0 and TCNT0, and clearing (or setting) the OC0 register at the timer clock cycle the counter is cleared (changes from MAX to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnPWM = ----------------N ⋅ 256 The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
ATmega16(L) Figure 33. Phase Correct PWM Mode, Timing Diagram OCn Interrupt Flag Set OCRn Update TOVn Interrupt Flag Set TCNTn OCn (COMn1:0 = 2) OCn (COMn1:0 = 3) Period 1 2 3 The Timer/Counter overflow flag (TOV0) is set each time the counter reaches BOTTOM. The interrupt flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0 pin.
Figure 34. Timer/Counter Timing Diagram, no Prescaling clkI/O clkTn (clkI/O /1) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 35 shows the same timing data, but with the prescaler enabled. Figure 35. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O /8) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 36 shows the setting of OCF0 in all modes except CTC mode. Figure 36.
ATmega16(L) Figure 37 shows the setting of OCF0 and the clearing of TCNT0 in CTC mode. Figure 37.
Table 38. Waveform Generation Mode Bit Description(1) Mode WGM01 (CTC0) WGM00 (PWM0) Timer/Counter Mode of Operation TOP Update of OCR0 TOV0 Flag Set-on 0 0 0 Normal 0xFF Immediate MAX 1 0 1 PWM, Phase Correct 0xFF TOP BOTTOM 2 1 0 CTC OCR0 Immediate MAX 3 1 1 Fast PWM 0xFF TOP MAX Note: 1. The CTC0 and PWM0 bit definition names are now obsolete. Use the WGM01:0 definitions.
ATmega16(L) Table 41. Compare Output Mode, Phase Correct PWM Mode(1) COM01 COM00 0 0 Normal port operation, OC0 disconnected. 0 1 Reserved 1 0 Clear OC0 on compare match when up-counting. Set OC0 on compare match when downcounting. 1 1 Set OC0 on compare match when up-counting. Clear OC0 on compare match when downcounting. Note: Description 1. A special case occurs when OCR0 equals TOP and COM01 is set. In this case, the compare match is ignored, but the set or clear is done at TOP.
Output Compare Register – OCR0 Bit 7 6 5 4 3 2 1 0 OCR0[7:0] OCR0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 The Output Compare Register contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an output compare interrupt, or to generate a waveform output on the OC0 pin.
ATmega16(L) Timer/Counter0 and Timer/Counter1 Prescalers Timer/Counter1 and Timer/Counter0 share the same prescaler module, but the timer/counters can have different prescaler settings. The description below applies to both Timer/Counter1 and Timer/Counter0. Internal Clock Source The timer/counter can be clocked directly by the system clock (by setting the CSn2:0 = 1). This provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (fCLK_I/O).
than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
ATmega16(L) 16-bit Timer/Counter1 The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are: • True 16-bit Design (i.e.
Figure 40. 16-bit Timer/Counter Block Diagram(1) Count Clear Direction TOVn (Int.Req.) Control Logic clkTn Clock Select Edge Detector TOP Tn BOTTOM ( From Prescaler ) Timer/Counter TCNTn = =0 OCnA (Int.Req.) Waveform Generation = OCnA DATABUS OCRnA OCnB (Int.Req.) Fixed TOP Values Waveform Generation = OCRnB OCnB ( From Analog Comparator Ouput ) ICFn (Int.Req.) Edge Detector ICRn Noise Canceler ICPn TCCRnA Note: Registers TCCRnB 1.
ATmega16(L) (OC1A/B). See “Output Compare Units” on page 91. The compare match event will also set the compare match flag (OCF1A/B) which can be used to generate an output compare interrupt request. The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered) event on either the Input Capture Pin (ICP1) or on the analog comparator pins (See “Analog Comparator” on page 192.
Accessing 16-bit Registers The TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. Each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. The same temporary register is shared between all 16-bit registers within each 16-bit timer. Accessing the low byte triggers the 16-bit read or write operation.
ATmega16(L) The following code examples show how to do an atomic read of the TCNT1 register contents. Reading any of the OCR1A/B or ICR1 registers can be done by using the same principle.
The following code examples show how to do an atomic write of the TCNT1 register contents. Writing any of the OCR1A/B or ICR1 registers can be done by using the same principle.
ATmega16(L) Figure 41. Counter Unit Block Diagram DATABUS (8-bit) TOVn (Int.Req.) TEMP (8-bit) Clock Select Count TCNTnH (8-bit) TCNTnL (8-bit) TCNTn (16-bit Counter) Clear Direction Control Logic clkTn Edge Detector Tn ( From Prescaler ) TOP BOTTOM Signal description (internal signals): Count Increment or decrement TCNT1 by 1. Direction Select between increment and decrement. Clear Clear TCNT1 (set all bits to zero). clkT1 Timer/counter clock.
Input Capture Unit The Timer/Counter incorporates an input capture unit that can capture external events and give them a time-stamp indicating time of occurrence. The external signal indicating an event, or multiple events, can be applied via the ICP1 pin or alternatively, via the analog-comparator unit. The time-stamps can then be used to calculate frequency, dutycycle, and other features of the signal applied. Alternatively the time-stamps can be used for creating a log of the events.
ATmega16(L) For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers” on page 86. Input Capture Trigger Source The main trigger source for the input capture unit is the input capture pin (ICP1). Timer/counter 1 can alternatively use the analog comparator output as trigger source for the input capture unit.
cleared by software by writing a logical one to its I/O bit location. The waveform generator uses the match signal to generate an output according to operating mode set by the waveform generation mode (WGM13:0) bits and compare output mode (COM1x1:0) bits. The TOP and BOTTOM signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation (See “Modes of Operation” on page 94.
ATmega16(L) I/O location is written by the CPU, the TEMP register will be updated by the value written. Then when the low byte (OCR1xL) is written to the lower 8 bits, the high byte will be copied into the upper 8-bits of either the OCR1x buffer or OCR1x compare register in the same system clock cycle. For more information of how to access the 16-bit registers refer to “Accessing 16-bit Registers” on page 86.
Figure 44. Compare Match Output Unit, Schematic COMnx1 COMnx0 FOCnx Waveform Generator D Q 1 OCnx DATABUS D 0 OCnx Pin Q PORT D Q DDR clk I/O The general I/O port function is overridden by the output compare (OC1x) from the waveform generator if either of the COM1x1:0 bits are set. However, the OC1x pin direction (input or output) is still controlled by the data direction register (DDR) for the port pin.
ATmega16(L) Normal Mode The simplest mode of operation is the normal mode (WGM13:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the BOTTOM (0x0000). In normal operation the Timer/Counter overflow flag (TOV1) will be set in the same timer clock cycle as the TCNT1 becomes zero.
this feature is not desirable. An alternative will then be to use the fast PWM mode using OCR1A for defining TOP (WGM13:0 = 15) since the OCR1A then will be double buffered. For generating a waveform output in CTC mode, the OC1A output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (COM1A1:0 = 1). The OC1A value will not be visible on the port pin unless the data direction for the pin is set to output (DDR_OC1A = 1).
ATmega16(L) Figure 46. Fast PWM Mode, Timing Diagram OCRnx / TOP Update and TOVn Interrupt Flag Set and OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) TCNTn OCnx (COMnx1:0 = 2) OCnx (COMnx1:0 = 3) Period 1 2 3 4 5 6 7 8 The Timer/Counter overflow flag (TOV1) is set each time the counter reaches TOP. In addition the OC1A or ICF1 flag is set at the same timer clock cycle as TOV1 is set when either OCR1A or ICR1 is used for defining the TOP value.
seting (or clearing) the OC1x register at the compare match between OCR1x and TCNT1, and clearing (or setting) the OC1x register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ---------------------------------N ⋅ ( 1 + TOP ) The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
ATmega16(L) Figure 47. Phase Correct PWM Mode, Timing Diagram OCRnx / TOP Update and OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) TOVn Interrupt Flag Set (Interrupt on Bottom) TCNTn OCnx (COMnx1:0 = 2) OCnx (COMnx1:0 = 3) Period 1 2 3 4 The Timer/Counter overflow flag (TOV1) is set each time the counter reaches BOTTOM.
for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnxPCPWM = --------------------------2 ⋅ N ⋅ TOP The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x register represent special cases when generating a PWM waveform output in the phase correct PWM mode.
ATmega16(L) Figure 48. Phase and Frequency Correct PWM Mode, Timing Diagram OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on TOP) OCRnx / TOP Update and TOVn Interrupt Flag Set (Interrupt on Bottom) TCNTn OCnx (COMnx1:0 = 2) OCnx (COMnx1:0 = 3) Period 1 2 3 4 The Timer/Counter overflow flag (TOV1) is set at the same timer clock cycle as the OCR1x registers are updated with the double buffer value (at BOTTOM).
The extreme values for the OCR1x register represents special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the output will be continuously low and if set equal to TOP the output will be set to high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
ATmega16(L) Figure 51 shows the count sequence close to TOP in various modes. When using phase and frequency correct PWM mode the OCR1x register is updated at BOTTOM. The timing diagrams will be the same, but TOP should be replaced by BOTTOM, TOP-1 by BOTTOM+1 and so on. The same renaming applies for modes that set the TOV1 flag at BOTTOM. Figure 51.
16-bit Timer/Counter Register Description Timer/Counter 1 Control Register A – TCCR1A Bit 7 6 5 4 3 2 1 0 COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 Read/Write R/W R/W R/W R/W W W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR1A • Bit 7:6 - COM1A1:0: Compare Output Mode for Channel A • Bit 5:4 - COM1B1:0: Compare Output Mode for Channel B The COM1A1:0 and COM1B1:0 control the output compare pins (OC1A and OC1B respectively) behavior.
ATmega16(L) Table 46 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase correct or the phase and frequency correct, PWM mode. Table 46. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM (1) COM1A1/COM1B1 COM1A0/COM1B0 0 0 Normal port operation, OC1A/OC1B disconnected. 0 1 WGM13 = 0: Normal port operation, OC1A/OC1B disconnected. WGM13 = 1: Toggle OC1A on compare match, OC1B reserved. 1 0 Clear OC1A/OC1B on compare match when up-counting.
Table 47.
ATmega16(L) Timer/Counter 1 Control Register B – TCCR1B Bit 7 6 5 4 3 2 1 0 ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 Read/Write R/W R/W R R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 TCCR1B • Bit 7 - ICNC1: Input Capture Noise Canceler Setting this bit (to one) activates the input capture noise canceler. When the noise canceler is activated, the input from the Input Capture Pin (ICP1) is filtered.
If external pin modes are used for the Timer/Counter1, transitions on the T1 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting.
ATmega16(L) The input capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin (or optionally on the analog comparator output for Timer/Counter1). The input capture can be used for defining the counter TOP value. The input capture register is 16 bit in size. To ensure that both the high and low bytes are read simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary high byte register (TEMP).
• Bit 5 - ICF1: Timer/Counter1, Input Capture Flag This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register (ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 flag is set when the counter reaches the TOP value. ICF1 is automatically cleared when the Input Capture Interrupt vector is executed. Alternatively, ICF1 can be cleared by writing a logic one to its bit location.
ATmega16(L) 8-bit Timer/Counter2 with PWM and Asynchronous Operation Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module.
The double buffered Output Compare Register (OCR2) is compared with the Timer/Counter value at all times. The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on the Output Compare Pin (OC2). See “Output Compare Unit” on page 113. for details. The compare match event will also set the compare flag (OCF2) which can be used to generate an output compare interrupt request.
ATmega16(L) top Signalizes that TCNT2 has reached maximum value. bottom Signalizes that TCNT2 has reached minimum value (zero). Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source, selected by the clock select bits (CS22:0). When no clock source is selected (CS22:0 = 0) the timer is stopped.
OCR2 compare register to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. The OCR2 register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR2 buffer register, and if double buffering is disabled the CPU will access the OCR2 directly.
ATmega16(L) Figure 56. Compare Match Output Unit, Schematic COMn1 COMn0 FOCn Waveform Generator D Q 1 OCn DATABUS D 0 OCn Pin Q PORT D Q DDR clk I/O The general I/O port function is overridden by the output compare (OC2) from the waveform generator if either of the COM21:0 bits are set. However, the OC2 pin direction (input or output) is still controlled by the data direction register (DDR) for the port pin.
restarts from the bottom (0x00). In normal operation the Timer/Counter overflow flag (TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero. The TOV2 flag in this case behaves like a 9th bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV2 flag, the timer resolution can be increased by software. There are no special cases to consider in the normal mode, a new counter value can be written anytime.
ATmega16(L) The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). As for the normal mode of operation, the TOV2 flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. Fast PWM Mode The fast pulse width modulation or fast PWM mode (WGM21:0 = 1) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to MAX then restarts from BOTTOM.
The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnPWM = ----------------N ⋅ 256 The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). The extreme values for the OCR2 register represent special cases when generating a PWM waveform output in the fast PWM mode. If the OCR2 is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle.
ATmega16(L) Figure 59. Phase Correct PWM Mode, Timing Diagram OCn Interrupt Flag Set OCRn Update TOVn Interrupt Flag Set TCNTn OCn (COMn1:0 = 2) OCn (COMn1:0 = 3) Period 1 2 3 The Timer/Counter overflow flag (TOV2) is set each time the counter reaches BOTTOM. The interrupt flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC2 pin.
Figure 60. Timer/Counter Timing Diagram, no Prescaling clkI/O clkTn (clkI/O /1) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 61 shows the same timing data, but with the prescaler enabled. Figure 61. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8) clkI/O clkTn (clkI/O /8) TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1 TOVn Figure 62 shows the setting of OCF2 in all modes except CTC mode. Figure 62.
ATmega16(L) Figure 63 shows the setting of OCF2 and the clearing of TCNT2 in CTC mode. Figure 63.
Table 50. Waveform Generation Mode Bit Description(1) Mode WGM21 (CTC2) WGM20 (PWM2) Timer/Counter Mode of Operation TOP Update of OCR2 TOV2 Flag Set on 0 0 0 Normal 0xFF Immediate MAX 1 0 1 PWM, Phase Correct 0xFF TOP BOTTOM 2 1 0 CTC OCR2 Immediate MAX 3 1 1 Fast PWM 0xFF TOP MAX Note: 1. The CTC2 and PWM2 bit definition names are now obsolete. Use the WGM21:0 definitions.
ATmega16(L) . Table 53. Compare Output Mode, Phase Correct PWM Mode(1) COM21 COM20 0 0 Normal port operation, OC2 disconnected. 0 1 Reserved 1 0 Clear OC2 on compare match when up-counting. Set OC2 on compare match when downcounting. 1 1 Set OC2 on compare match when up-counting. Clear OC2 on compare match when downcounting. Note: Description 1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, the compare match is ignored, but the set or clear is done at TOP.
Asynchronous Operation of the Timer/Counter Asynchronous Status Register – ASSR Bit 7 6 5 4 3 2 1 0 – – – – AS2 TCN2UB OCR2UB TCR2UB Read/Write R R R R R/W R R R Initial Value 0 0 0 0 0 0 0 0 ASSR • Bit 3 - AS2: Asynchronous Timer/Counter2 When AS2 is written to zero, Timer/Counter 2 is clocked from the I/O clock, clkI/O. When AS2 is written to one, Timer/Counter 2 is clocked from a crystal oscillator connected to the Timer Oscillator 1 (TOSC1) pin.
ATmega16(L) The CPU main clock frequency must be more than four times the oscillator frequency. • When writing to one of the registers TCNT2, OCR2, or TCCR2, the value is transferred to a temporary register, and latched after two positive edges on TOSC1. The user should not write a new value before the contents of the temporary register have been transferred to its destination.
unpredictable, as it depends on the wake-up time. The recommended procedure for reading TCNT2 is thus as follows: 1. Write any value to either of the registers OCR2 or TCCR2. 2. Wait for the corresponding Update Busy Flag to be cleared. 3. Read TCNT2. • Timer/Counter Interrupt Mask Register – TIMSK During asynchronous operation, the synchronization of the interrupt flags for the asynchronous timer takes 3 processor cycles plus one timer cycle.
ATmega16(L) Figure 64. Prescaler for Timer/Counter2 clkT2S PSR2 clkT2S/1024 clkT2S/256 clkT2S/8 AS2 clkT2S/128 10-BIT T/C PRESCALER Clear TOSC1 clkT2S/64 clkI/O clkT2S/32 Timer/Counter Prescaler 0 CS20 CS21 CS22 TIMER/COUNTER2 CLOCK SOURCE clkT2 The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main system I/O clock clkIO. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously clocked from the TOSC1 pin.
Serial Peripheral Interface – SPI The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega16 and peripheral devices or between several AVR devices.
ATmega16(L) When configured as a Master, the SPI interface has no automatic control of the SS line. This must be handled by user software before communication can start. When this is done, writing a byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the 8 bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of transmission flag (SPIF). If the SPI interrupt enable bit (SPIE) in the SPCR register is set, an interrupt is requested.
The following code examples show how to initialize the SPI as a master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actual data direction register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. For example if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB.
ATmega16(L) The following code examples show how to initialize the SPI as a slave and how to perform a simple reception.
will immediately reset the send and receive logic, and drop any partially received data in the shift register. Master Mode When the SPI is configured as a master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI slave. If SS is configured as an input, it must be held high to ensure Master SPI operation.
ATmega16(L) • Bit 3 - CPOL: Clock Polarity When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low when idle. Refer to Figure 67 and Figure 68 for an example. The CPOL functionality is summarized below: Table 56. CPOL Functionality CPOL Leading Edge Trailing Edge 0 Rising Falling 1 Falling Rising • Bit 2 - CPHA: Clock Phase The settings of the clock phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK.
SPIF bit is cleared by first reading the SPI status register with SPIF set, then accessing the SPI Data Register (SPDR). • Bit 6 - WCOL: Write COLlision flag The WCOL bit is set if the SPI data register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. • Bit 5..1 - Res: Reserved Bits These bits are reserved bits in the ATmega16 and will always read as zero.
ATmega16(L) Figure 67. SPI Transfer Format with CPHA = 0 SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS MSB first (DORD = 0) MSB LSB first (DORD = 1) LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB Figure 68.
USART The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a highly flexible serial communication device.
ATmega16(L) The dashed boxes in the block diagram separate the three main parts of the USART (listed from the top): clock generator, transmitter and receiver. Control registers are shared by all units. The clock generation logic consists of synchronization logic for external clock input used by synchronous slave operation, and the baud rate generator. The XCK (transfer clock) pin is only used by synchronous transfer mode.
Figure 70. Clock Generation Logic, Block Diagram UBRR U2X fosc Prescaling Down-Counter UBRR+1 /2 /4 /2 0 1 0 OSC DDR_XCK xcki XCK Pin Sync Register Edge Detector UCPOL DDR_XCK 0 UMSEL 1 xcko txclk 1 1 rxclk 0 Signal description: Internal Clock Generation – The Baud Rate Generator txclk Transmitter clock. (Internal Signal) rxclk Receiver base clock. (Internal Signal) xcki Input from XCK pin (internal Signal). Used for synchronous slave operation.
ATmega16(L) Table 60.
Figure 71. Synchronous Mode XCK Timing. UCPOL = 1 XCK RxD / TxD Sample UCPOL = 0 XCK RxD / TxD Sample The UCPOL bit UCRSC selects which XCK clock edge is used for data sampling and which is used for data change. As Figure 71 shows, when UCPOL is zero the data will be changed at rising XCK edge and sampled at falling XCK edge. If UCPOL is set, the data will be changed at falling XCK edge and sampled at rising XCK edge.
ATmega16(L) The USART Character SiZe (UCSZ2:0) bits select the number of data bits in the frame. The USART Parity Mode (UPM1:0) bits enable and set the type of parity bit. The selection between one or two stop bits is done by the USART Stop Bit Select (USBS) bit. The receiver ignores the second stop bit. An FE (Frame Error) will therefore only be detected in the cases where the first stop bit is zero. Parity Bit Calculation The parity bit is calculated by doing an exclusive-or of all the data bits.
USART Initialization The USART has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. For interrupt driven USART operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization.
ATmega16(L) Data Transmission – The USART Transmitter The USART transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRB register. When the transmitter is enabled, the normal port operation of the TxD pin is overridden by the USART and given the function as the transmitter’s serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions.
Sending Frames with 9 Data Bit If 9-bit characters are used (UCSZ = 7), the ninth bit must be written to the TXB8 bit in UCSRB before the low byte of the character is written to UDR. The following code examples show a transmit function that handles 9 bit characters. For the assembly code, the data to be sent is assumed to be stored in Registers R17:R16.
ATmega16(L) either write new data to UDR in order to clear UDRE or disable the data register empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. The Transmit Complete (TXC) flag bit is set one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer.
Data Reception – The USART Receiver The USART receiver is enabled by writing the Receive Enable (RXEN) bit in the UCSRB register to one. When the receiver is enabled, the normal pin operation of the RxD pin is overridden by the USART and given the function as the receiver’s serial input. The baud rate, mode of operation and frame format must be set up once before any serial reception can be done. If synchronous operation is used, the clock on the XCK pin will be used as transfer clock.
ATmega16(L) Receiving Frames with 9 Databits If 9 bit characters are used (UCSZ=7) the ninth bit must be read from the RXB8 bit in UCSRB before reading the low bits from the UDR. This rule applies to the FE, DOR and PE status flags as well. Read status from UCSRA, then data from UDR. Reading the UDR I/O location will change the state of the receive buffer FIFO and consequently the TXB8, FE, DOR and PE bits, which all are stored in the FIFO, will change.
The receive function example reads all the I/O registers into the register file before any computation is done. This gives an optimal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. Receive Compete Flag and Interrupt The USART receiver has one flag that indicates the receiver state. The Receive Complete (RXC) flag indicates if there are unread data present in the receive buffer.
ATmega16(L) The PE bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (UPM1 = 1). This bit is valid until the receive buffer (UDR) is read. Disabling the Receiver In contrast to the transmitter, disabling of the receiver will be immediate. Data from ongoing receptions will therefore be lost. When disabled (i.e.
Asynchronous Data Reception The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the RxD pin. The data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the receiver.
ATmega16(L) The decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. The center samples are emphasized on the figure by having the sample number inside boxes. The majority voting process is done as follows: If two or all three samples have high levels, the received bit is registered to be a logic 1. If two or all three samples have low levels, the received bit is registered to be a logic 0.
SM Middle sample number used for majority voting. SM = 9 for normal speed and SM = 5 for double speed mode. Rslow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. R fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. Table 61 and Table 62 list the maximum receiver baud rate error that can be tolerated. Note that normal speed mode has higher toleration of baud rate variations. Table 61.
ATmega16(L) Multi-processor Communication Mode Setting the Multi-processor Communication Mode (MPCM) bit in UCSRA enables a filtering function of incoming frames received by the USART receiver. Frames that do not contain address information will be ignored and not put into the receive buffer. This effectively reduces the number of incoming frames that has to be handled by the CPU, in a system with multiple MCUs that communicate via the same serial bus.
Accessing UBRRH/ UCSRC Registers The UBRRH register shares the same I/O location as the UCSRC register. Therefore some special consideration must be taken when accessing this I/O location. Write Access When doing a write access of this I/O location, the high bit of the value written, the USART Register Select (URSEL) bit, controls which one of the two registers that will be written. If URSEL is zero during a write operation, the UBRRH value will be updated.
ATmega16(L) Read Access Doing a read access to the UBRRH or the UCSRC register is a more complex operation. However, in most applications, it is rarely necessary to read any of these registers. The read access is controlled by a timed sequence. Reading the I/O location once returns the UBRRH register contents. If the register location was read in previous system clock cycle, reading the register in the current clock cycle will return the UCSRC contents.
The transmit buffer can only be written when the UDRE flag in the UCSRA register is set. Data written to UDR when the UDRE flag is not set, will be ignored by the USART transmitter. When data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into the transmit shift register when the shift register is empty. Then the data will be serially transmitted on the TxD pin. The receive buffer consists of a two level FIFO.
ATmega16(L) • Bit 1 - U2X: Double the USART tranSmission Speed This bit only has effect for the asynchronous operation. Write this bit to zero when using synchronous operation. Writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively doubling the transfer rate for asynchronous communication. • Bit 0 - MPCM: Multi-processor Communication Mode This bit enables the Multi-processor Communication Mode.
• Bit 0 - TXB8: Transmit Data Bit 8 TXB8 is the 9th data bit in the character to be transmitted when operating with serial frames with 9 data bits. Must be written before writing the low bits to UDR. USART Control and Status Register C – UCSRC Bit 7 6 5 4 3 2 1 0 URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 0 0 0 0 1 1 0 UCSRC The UCSRC register shares the same I/O location as the UBRRH register.
ATmega16(L) • Bit 2:1 - UCSZ1:0: Character Size The UCSZ1:0 bits combined with the UCSZ2 bit in UCSRB sets the number of data bits (character size) in a frame the receiver and transmitter use. Table 66. UCSZ Bits Settings UCSZ2 UCSZ1 UCSZ0 Character Size 0 0 0 5-bit 0 0 1 6-bit 0 1 0 7-bit 0 1 1 8-bit 1 0 0 (reserved) 1 0 1 (reserved) 1 1 0 (reserved) 1 1 1 9-bit • Bit 0 - UCPOL: Clock Polarity This bit is used for synchronous mode only.
• Bit 11:0 - UBRR11:0: USART Baud Rate Register This is a 12-bit register which contains the USART baud rate. The UBRRH contains the 4 most significant bits, and the UBRRL contains the 8 least significant bits of the USART baud rate. Ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed. Writing UBRRL will trigger an immediate update of the baud rate prescaler.
ATmega16(L) Table 69. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 3.6864 MHz fosc = 4.0000 MHz fosc = 7.3728 MHz Baud Rate (bps) UBRR 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 23 0.0% 47 0.0% 25 0.2% 51 0.2% 47 0.0% 95 0.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.
Table 70. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued) fosc = 11.0592 MHz fosc = 8.0000 MHz fosc = 14.7456 MHz Baud Rate (bps) UBRR 0.5M 0 0.0% 1 0.0% - - 2 -7.8% 1 -7.8% 3 -7.8% 1M - - 0 0.0% - - - - 0 -7.8% 1 -7.8% Max (1) 1. U2X = 0 Error 0.5Mbps U2X = 1 UBRR Error 1Mbps U2X = 0 UBRR Error 691.2kbps U2X = 1 UBRR Error 1.3824Mbps U2X = 0 UBRR Error 921.6kbps U2X = 1 UBRR Error 1.8432Mbps UBRR = 0, Error = 0.0% Table 71.
ATmega16(L) Two-wire Serial Interface Features • • • • • • • • • • Two-wire Serial Interface Bus Definition The Two-Wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The TWI protocol allows the systems designer to interconnect up to 128 different devices using only two bidirectional bus lines, one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines.
Electrical Interconnection As depicted in Figure 76, both bus lines are connected to the positive supply voltage through pull-up resistors. The bus drivers of all TWI-compliant devices are open-drain or open-collector. This implements a wired-AND function which is essential to the operation of the interface. A low level on a TWI bus line is generated when one or more TWI devices output a zero.
ATmega16(L) Figure 78. START, REPEATED START and STOP Conditions SDA SCL START Address Packet Format REPEATED START STOP START STOP All address packets transmitted on the TWI bus are 9 bits long, consisting of 7 address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed.
more bytes, it should inform the transmitter by sending a NACK after the final byte. The MSB of the data byte is transmitted first. Figure 80. Data Packet Format Data MSB Data LSB ACK 8 9 Aggregate SDA SDA from Transmitter SDA from receiverR SCL from Master 1 2 7 SLA+R/W Combining Address and Data Packets into a Transmission STOP, REPEATED START or Next Data Byte Data Byte A transmission basically consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition.
ATmega16(L) • Different masters may use different SCL frequencies. A scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. This will facilitate the arbitration process. The wired-ANDing of the bus lines is used to solve both these problems. The serial clocks from all masters will be wired-ANDed, yielding a combined clock with a high period equal to the one from the master with the shortest high period.
Figure 83. Arbitration between Two Masters START SDA from Master A Master A Loses Arbitration, SDAA SDA SDA from Master B SDA Line Synchronized SCL Line Note that arbitration is not allowed between: • A REPEATED START condition and a data bit • A STOP condition and a data bit • A REPEATED START and a STOP condition It is the user software’s responsibility to ensure that these illegal arbitration conditions never occur.
ATmega16(L) Overview of the TWI Module The TWI module is comprised of several submodules, as shown in Figure 84. All registers drawn in a thick line are accessible through the AVR data bus. Figure 84.
Bus Interface Unit This unit contains the Data and Address Shift register (TWDR), a START/STOP Controller and Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted, or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also contains a register containing the (N)ACK bit to be transmitted or received. This (N)ACK register is not directly accessible by the application software.
ATmega16(L) TWI register description TWI Bit Rate Register – TWBR Bit 7 6 5 4 3 2 1 0 TWBR7 TWBR6 TWBR5 TWBR4 TWBR3 TWBR2 TWBR1 TWBR0 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 TWBR • Bits 7..0 - TWI Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the master modes.
• Bit 4 - TWSTO: TWI STOP Condition Bit Writing the TWSTO bit to one in master mode will generate a STOP condition on the 2wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically. In slave mode, setting the TWSTO bit can be used to recover from an error condition. This will not generate a STOP condition, but the TWI returns to a well-defined unaddressed slave mode and releases the SCL and SDA lines to a high impedance state.
ATmega16(L) shifting a byte. This occurs when the TWI interrupt flag (TWINT) is set by hardware. Note that the data register cannot be initialized by the user before the first interrupt occurs. The data in TWDR remains stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted in. TWDR always contains the last byte present on the bus, except after a wake up from a sleep mode by the TWI interrupt. In this case, the contents of TWDR is undefined.
Figure 85. Interfacing the Application to the TWI in a Typical Transmission Application Action 1. Application writes to TWCR to initiate transmission of START TWI bus TWI Hardware Action 3. Check TWSR to see if START was sent. Application loads SLA+W into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one START SLA+W 5. Check TWSR to see if SLA+W was sent and ACK received.
ATmega16(L) written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet. 6. When the data packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not. 7.
Assembly code example 1 ldi r16, (1<
ATmega16(L) Transmission Modes The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As an example, the TWI can use MT mode to write data into a TWI EEPROM, MR mode to read the data back from the EEPROM. If other masters are present in the system, some of these might transmit data to the TWI, and then SR mode would be used.
Figure 86. Data Transfer in Master Transmitter Mode VCC Device 1 Device 2 MASTER TRANSMITTER SLAVE RECEIVER Device 3 ........ Device n R1 R2 SDA SCL A START condition is sent by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE Value 1 X 1 0 X 1 0 X TWEN must be set to enable the 2-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT flag.
ATmega16(L) After a repeated START condition (state $10) the 2-wire Serial Interface can access the same slave again, or a new slave without transmitting a STOP condition. Repeated START enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control of the bus. Table 73.
Figure 87.
ATmega16(L) Figure 88. Data Transfer in Master Receiver Mode VCC Device 1 Device 2 MASTER RECEIVER SLAVE TRANSMITTER Device 3 ........ Device n R1 R2 SDA SCL A START condition is sent by writing the following value to TWCR: TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE Value 1 X 1 0 X 1 0 X TWEN must be written to one to enable the 2-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be set to clear the TWINT flag.
Table 74.
ATmega16(L) Figure 89.
The upper 7 bits are the address to which the 2-wire Serial Interface will respond when addressed by a master. If the LSB is set, the TWI will respond to the general call address ($00), otherwise it will ignore the general call address. TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE Value 0 1 0 0 0 1 0 X TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the device’s own slave address or the general call address.
ATmega16(L) Table 75.
Figure 91. Formats and States in the Slave Receiver Mode Reception of the own slave address and one or more data bytes.
ATmega16(L) The upper 7 bits are the address to which the 2-wire Serial Interface will respond when addressed by a master. If the LSB is set, the TWI will respond to the general call address ($00), otherwise it will ignore the general call address. TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE Value 0 1 0 0 0 1 0 X TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgement of the device’s own slave address or the general call address.
Table 76.
ATmega16(L) Figure 93. Formats and States in the Slave Transmitter Mode Reception of the own slave address and one or more data bytes S SLA R A DATA $A8 Arbitration lost as master and addressed as slave A DATA $B8 A P or S $C0 A $B0 Last data byte transmitted.
Combining Several TWI Modes In some cases, several TWI modes must be combined in order to complete the desired action. Consider for example reading data from a serial EEPROM. Typically, such a transfer involves the following steps: 1. The transfer must be initiated 2. The EEPROM must be instructed what location should be read 3. The reading must be performed 4. The transfer must be finished Note that data is transmitted both from master to slave and vice versa.
ATmega16(L) Several different scenarios may arise during arbitration, as described below: • Two or more masters are performing identical communication with the same slave. In this case, neither the slave nor any of the masters will know about the bus contention. • Two or more masters are accessing the same slave with different data or direction bit. In this case, arbitration will occur, either in the READ/WRITE bit or in the data bits.
Analog Comparator The analog comparator compares the input values on the positive pin AIN0 and negative pin AIN1. When the voltage on the positive pin AIN0 is higher than the voltage on the negative pin AIN1, the Analog Comparator Output, ACO, is set. The comparator’s output can be set to trigger the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate interrupt, exclusive to the Analog Comparator.
ATmega16(L) • Bit 7 - ACD: Analog Comparator Disable When this bit is written logic one, the power to the analog comparator is switched off. This bit can be set at any time to turn off the analog comparator. This will reduce power consumption in active and idle mode. When changing the ACD bit, the Analog Comparator Interrupt must be disabled by clearing the ACIE bit in ACSR. Otherwise an interrupt can occur when the bit is changed.
Analog Comparator Multiplexed Input It is possible to select any of the ADC7..0 pins to replace the negative input to the analog comparator. The ADC multiplexer is used to select this input, and consequently, the ADC must be switched off to utilize this feature. If the Analog Comparator Multiplexer Enable bit (ACME in SFIOR) is set and the ADC is switched off (ADEN in ADCSRA is zero), MUX2..0 in ADMUX select the input pin to replace the negative input to the Analog Comparator, as shown in Table 79.
ATmega16(L) Analog to Digital Converter Features • • • • • • • • • • • • • • • 10-bit Resolution 0.5 LSB Integral Non-Linearity ±2 LSB Absolute Accuracy TBD - 260 µs Conversion Time Up to TBD kSPS at Maximum Resolution 8 Multiplexed Single Ended Input Channels 7 Differential Input Channels 2 Differential Input Channels with Optional Gain of 10x and 200x Optional Left adjustment for ADC Result Readout 0 - VCC ADC Input Voltage Range Selectable 2.
Figure 98. Analog to Digital Converter Block Schematic ADC CONVERSION COMPLETE IRQ INTERRUPT FLAGS ADTS[2:0] TRIGGER SELECT ADC[9:0] ADPS1 0 ADC DATA REGISTER (ADCH/ADCL) ADPS0 ADPS2 ADIF ADATE ADEN ADSC MUX1 15 ADC CTRL. & STATUS REGISTER (ADCSRA) MUX0 MUX3 MUX2 MUX4 ADLAR REFS0 REFS1 ADC MULTIPLEXER SELECT (ADMUX) ADIE ADIF 8-BIT DATA BUS AVCC PRESCALER START GAIN SELECTION CHANNEL SELECTION MUX DECODER CONVERSION LOGIC INTERNAL 2.
ATmega16(L) amplified value then becomes the analog input to the ADC. If single ended channels are used, the gain amplifier is bypassed altogether. The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA. Voltage reference and input channel selections will not go into effect until ADEN is set. The ADC does not consume power when ADEN is cleared, so it is recommended to switch off the ADC before entering power saving sleep modes.
Figure 99. ADC Auto Trigger Logic ADTS[2:0] PRESCALER START ADIF CLKADC ADATE SOURCE 1 . . . . CONVERSION LOGIC EDGE DETECTOR SOURCE n ADSC Using the ADC Interrupt Flag as a trigger source makes the ADC start a new conversion as soon as the ongoing conversion has finished. The ADC then operates in Free Running Mode, constantly sampling and updating the ADC Data Register. The first conversion must be started by writing a logical one to the ADSC bit in ADCSRA.
ATmega16(L) setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low. When initiating a single ended conversion by setting the ADSC bit in ADCSRA, the conversion starts at the following rising edge of the ADC clock cycle. See “Differential Gain Channels” on page 201 for details on differential conversion timing. A normal conversion takes 13 ADC clock cycles.
Figure 102. ADC Timing Diagram, Single Conversion One Conversion Cycle number 2 1 3 4 5 6 7 8 Next Conversion 10 9 11 12 13 1 2 3 ADC clock ADSC ADIF ADCH Sign and MSB of result ADCL LSB of result Sample & hold MUX and REFS update Conversion complete MUX and REFS update Figure 103.
ATmega16(L) Table 80. ADC Conversion Time Sample & Hold (Cycles from Start of Conversion) Conversion Time (Cycles) First conversion 14.5 25 Normal conversions, single ended 1.5 13 2 13.5 1.5/2.5 13/14 Condition Auto Triggered conversions Normal conversions, differential Differential Gain Channels When using differential gain channels, certain aspects of the conversion need to be taken into consideration.
If Auto Triggering is used, the exact time of the triggering event can be indeterministic. Special care must be taken when updating the ADMUX register, in order to control which conversion will be affected by the new settings. If both ADATE and ADEN is written to one, an interrupt event can occur at any time. If the ADMUX register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. ADMUX can be safely updated in the following ways: 1.
ATmega16(L) If the user has a fixed voltage source connected to the AREF pin, the user may not use the other reference voltage options in the application, as they will be shorted to the external voltage. If no external voltage is applied to the AREF pin, the user may switch between AVCC and 2.56V as reference selection. The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result.
Figure 105. Analog Input Circuitry IIH ADCn 1..100 kΩ CS/H= 14 pF IIL VCC/2 Analog Noise Canceling Techniques Digital circuitry inside and outside the device generates EMI which might affect the accuracy of analog measurements. If conversion accuracy is critical, the noise level can be reduced by applying the following techniques: 1. Keep analog signal paths as short as possible. Make sure analog tracks run over the analog ground plane, and keep them well away from high-speed switching digital tracks. 2.
ATmega16(L) Analog Ground Plane PA3 (ADC3) PA2 (ADC2) PA1 (ADC1) PA0 (ADC0) VCC GND Figure 106. ADC Power Connections PA4 (ADC4) PA5 (ADC5) PA6 (ADC6) GND AVCC 100nF AREF 10µH PA7 (ADC7) PC7 Offset Compensation Schemes The gain stage has a built-in offset cancellation circuitry that nulls the offset of differential measurements as much as possible. The remaining offset in the analog path can be measured directly by selecting the same channel for both differential inputs.
Figure 107. Offset Error Output code Ideal ADC Actual ADC Offset Error • VREF Input voltage Gain error: After adjusting for offset, the gain error is found as the deviation of the last transition (0x3FE to 0x3FF) compared to the ideal transition (at 1.5 LSB below maximum). Ideal value: 0 LSB Figure 108.
ATmega16(L) Figure 109. Integral non-Linearity (INL) Output code INL Ideal ADC Actual ADC VREF • Input voltage Differential Non-Linearity (DNL): The maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 LSB). Ideal value: 0 LSB. Figure 110.
ADC Conversion Result After the conversion is complete (ADIF is high), the conversion result can be found in the ADC Result registers (ADCL, ADCH). For single ended conversion, the result is V IN ⋅ 1024 ADC = -------------------------V REF where VIN is the voltage on the selected input pin and VREF the selected voltage reference (see Table 82 on page 209 and Table 83 on page 210). 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB.
ATmega16(L) Table 81. Correlation between Input Voltage and Output Codes VADCn Read code Corresponding decimal value VADCm + VREF / GAIN 0x1FF 511 VADCm + 0.999 VREF / GAIN 0x1FF 511 VADCm + 0.998 VREF / GAIN 0x1FE 510 ... ... ... VADCm + 0.001 VREF / GAIN 0x001 1 VADCm 0x000 0 VADCm - 0.001 VREF / GAIN 0x3FF -1 ... ... ... VADCm - 0.999 VREF / GAIN 0x201 -511 VADCm - VREF / GAIN 0x200 -512 Example: ADMUX = 0xED (ADC3 - ADC2, 10x gain, 2.
• Bits 4:0 - MUX4:0: Analog Channel and Gain Selection Bits The value of these bits selects which combination of analog inputs are connected to the ADC. These bits also select the gain for the differential channels. See Table 83 for details. If these bits are changed during a conversion, the change will not go in effect until this conversion is complete (ADIF in ADCSRA is set). Table 83. Input Channel and Gain Selections MUX4..
ATmega16(L) Table 83. Input Channel and Gain Selections (Continued) MUX4..0 Single Ended Input 11101 ADC Control and Status Register A – ADCSRA 11110 1.
Table 84.
ATmega16(L) Special FunctionIO Register – SFIOR Bit 7 6 5 4 3 2 1 0 ADTS2 ADTS1 ADTS0 ADHSM ACME PUD PSR2 PSR10 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 SFIOR • Bit 7:5 - ADTS2:0: ADC Auto Trigger Source If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect.
JTAG Interface and On-chip Debug System Features • JTAG (IEEE std. 1149.1 Compliant) Interface • Boundary-scan Capabilities According to the IEEE std. 1149.
ATmega16(L) The IEEE std. 1149.1 also specifies an optional TAP signal; TRST – Test ReSeT – which is not provided. When the JTAGEN fuse is unprogrammed, these four TAP pins are normal port pins, and the TAP controller is in reset. When programmed, the input TAP signals are internally pulled high and the JTAG is enabled for Boundary-scan and programming. The device is shipped with this fuse programmed.
Figure 113. TAP Controller State Diagram 1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 1 Select-IR Scan 0 0 1 1 Capture-DR Capture-IR 0 0 Shift-DR Shift-IR 0 1 Exit1-DR 0 Pause-DR 0 0 Pause-IR 1 1 0 Exit2-DR Exit2-IR 1 1 Update-DR TAP Controller 1 Exit1-IR 0 1 0 1 1 0 1 Update-IR 0 1 0 The TAP controller is a 16-state finite state machine that controls the operation of the Boundary-scan circuitry, JTAG programming circuitry, or On-chip Debug system.
ATmega16(L) is left by setting TMS high. While the instruction is shifted in from the TDI pin, the captured IR-state 0x01 is shifted out on the TDO pin. The JTAG Instruction selects a particular Data Register as path between TDI and TDO and controls the circuitry surrounding the selected Data Register. • Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched onto the parallel output from the shift register path in the Update-IR state.
• 2 single Program Memory break-points + 1 Program Memory break point with mask (“range break point”) • 2 single Program Memory break-points + 1 Data Memory break point with mask (“range break point”) A debugger, like the AVR Studio, may however use one or more of these resources for its internal purpose, leaving less flexibility to the end-user. A list of the On-chip Debug specific JTAG instructions is given in “On-chip Debug Specific JTAG Instructions” on page 218.
ATmega16(L) On-chip Debug Related Register in I/O Memory On-chip Debug Register – OCDR Bit 7 6 5 4 3 2 1 MSB/IDRD 0 LSB 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 OCDR The OCDR register provides a communication channel from the running program in the microcontroller to the debugger. The CPU can transfer a byte to the debugger by writing to this location.
IEEE 1149.1 (JTAG) Boundary-scan Features • • • • • System Overview The Boundary-scan chain has the capability of driving and observing the logic levels on the digital I/O pins, as well as the boundary between digital and analog logic for analog circuitry having off-chip connections. At system level, all ICs having JTAG capabilities are connected serially by the TDI/TDO signals to form a long shift register.
ATmega16(L) Bypass Register The Bypass register consists of a single shift-register stage. When the Bypass register is selected as path between TDI and TDO, the register is reset to 0 when leaving the Capture-DR controller state. The Bypass register can be used to shorten the scan chain on a system when the other devices are to be tested. Device Identification Register Figure 114 shows the structure of the Device Identification register. Figure 114.
Figure 115. Reset Register To TDO From other internal and external reset sources From TDI D Q Internal reset ClockDR · AVR_RESET Boundary-scan Chain The Boundary-scan Chain has the capability of driving and observing the logic levels on the digital I/O pins, as well as the boundary between digital and analog logic for analog circuitry having off-chip connections. See “Boundary-scan Chain” on page 224 for a complete description.
ATmega16(L) SAMPLE_PRELOAD; $2 Mandatory JTAG instruction for pre-loading the output latches and talking a snap-shot of the input/output pins without affecting the system operation. However, the output latches are not connected to the pins. The Boundary-scan Chain is selected as Data Register. The active states are: AVR_RESET; $C • Capture-DR: Data on the external pins are sampled into the Boundary-scan Chain. • Shift-DR: The Boundary-scan Chain is shifted by the TCK input.
Boundary-scan Chain The Boundary-scan chain has the capability of driving and observing the logic levels on the digital I/O pins, as well as the boundary between digital and analog logic for analog circuitry having off-chip connection. Scanning the Digital Port Pins Figure 116 shows the Boundary-scan Cell for a bidirectional port pin with pull-up function.
ATmega16(L) Figure 117.
Figure 118. Additional Scan Signal for the Two-wire Interface PUExn OCxn ODxn TWIEN Pxn SRC Slew-rate Limited IDxn Scanning the RESET Pin The RESET pin accepts 5V active low logic for standard reset operation, and 12V active high logic for High Voltage Parallel programming. An observe-only cell as shown in Figure 119 is inserted both for the 5V reset signal; RSTT, and the 12V reset signal; RSTHV. Figure 119.
ATmega16(L) Figure 120. Boundary-scan Cells for Oscillators and Clock Options To Next Cell From Digital Logic ShiftDR XTAL2/TOSC2 Oscillator EXTEST To Next Cell ShiftDR 0 ENABLE OUTPUT 1 FF1 0 D Q D Q 0 1 D G From Previous Cell ClockDR To System Logic XTAL1/TOSC1 Q 1 UpdateDR From Previous Cell ClockDR Table 89 summaries the scan registers for the external clock pin XTAL1, oscillators with XTAL1/XTAL2 connections as well as 32kHz Timer oscillator. Table 89.
Figure 121. Analog Comparator BANDGAP REFERENCE ACBG ACO AC_IDLE ACME ADCEN ADC MULTIPLEXER OUTPUT Figure 122.
ATmega16(L) Table 90.
Table 91.
ATmega16(L) Table 91.
If the ADC is not to be used during scan, the recommended input values from Table 91 should be used. The user is recommended not to use the Differential Gain stages during scan. Switch-Cap based gain stages require fast operation and accurate timing which is difficult to obtain when used in a scan chain. Details concerning operations of the differential gain stage is therefore not provided. For the same reason, the ADC High Speed Mode (ADHSM) bit does not make any sense during boundary-scan operation.
ATmega16(L) Figure 124. ADC Timing Diagram and Timing Constraints thold t hp ts th HOLD PRECH COMP 0x200 DAC 0x200 0x td As an example, consider the task of verifying a 1.5V ± 5% input signal at ADC channel 3 when the power supply is 5.0V and AREF is externally connected to VCC. The lower limit is: The upper limit is: 1024 ⋅ 1.5V ⋅ 0,95 ⁄ 5V = 291 = 0x123 1024 ⋅ 1.5V ⋅ 1.05 ⁄ 5V = 323 = 0x143 The recommended values from Table 91 are used unless other values are given in the algorithm in Table 93.
Table 93. Algorithm for Using the ADC (Continued) Step Actions ADCEN DAC MUXEN HOLD PRECH PA3. Data PA3. Control PA3. Pullup_ Enable 9 1 0x143 0x08 1 1 0 0 0 10 1 0x143 0x08 1 0 0 0 0 1 0x200 0x08 1 1 0 0 0 11 Verify the COMP bit scanned out to be 1 Using this algorithm, the timing constraint on the HOLD signal constrains the TCK clock frequency.
ATmega16(L) ATmega16 Boundaryscan Order Table 94 shows the Scan order between TDI and TDO when the Boundary-scan chain is selected as data path. Bit 0 is the LSB; the first bit scanned in, and the first bit scanned out. The scan order follows the pin-out order as far as possible. Therefore, the bits of Port A is scanned in the opposite bit order of the other ports.
Table 94. ATmega16 Boundary-scan Order (Continued) 236 Bit Number Signal Name Module 112 MUXEN_7 ADC 111 MUXEN_6 110 MUXEN_5 109 MUXEN_4 108 MUXEN_3 107 MUXEN_2 106 MUXEN_1 105 MUXEN_0 104 NEGSEL_2 103 NEGSEL_1 102 NEGSEL_0 101 PASSEN 100 PRECH 99 SCTEST 98 ST 97 VCCREN 96 PB0.Data 95 PB0.Control 94 PB0.Pullup_Enable 93 PB1.Data 92 PB1.Control 91 PB1.Pullup_Enable 90 PB2.Data 89 PB2.Control 88 PB2.Pullup_Enable 87 PB3.Data 86 PB3.Control 85 PB3.
ATmega16(L) Table 94. ATmega16 Boundary-scan Order (Continued) Bit Number Signal Name Module 81 PB5.Data Port B 80 PB5.Control 79 PB5.Pullup_Enable 78 PB6.Data 77 PB6.Control 76 PB6.Pullup_Enable 75 PB7.Data 74 PB7.Control 73 PB7.Pullup_Enable 72 RSTT 71 RSTHV Reset Logic (Observe-Only) 70 EXTCLKEN Enable signals for main clock/oscillators 69 OSCON 68 RCOSCEN 67 OSC32EN 66 EXTCLK (XTAL1) 65 OSCCK 64 RCCK 63 OSC32CK 62 TWIEN TWI 61 PD0.Data Port D 60 PD0.
Table 94. ATmega16 Boundary-scan Order (Continued) 238 Bit Number Signal Name Module 46 PD5.Data Port D 45 PD5.Control 44 PD5.Pullup_Enable 43 PD6.Data 42 PD6.Control 41 PD6.Pullup_Enable 40 PD7.Data 39 PD7.Control 38 PD7.Pullup_Enable 37 PC0.Data 36 PC0.Control 35 PC0.Pullup_Enable 34 PC1.Data 33 PC1.Control 32 PC1.Pullup_Enable 31 PC6.Data 30 PC6.Control 29 PC6.Pullup_Enable 28 PC7.Data 27 PC7.Control 26 PC7.Pullup_Enable 25 TOSC 24 TOSCON 23 PA7.
ATmega16(L) Table 94. ATmega16 Boundary-scan Order (Continued) Bit Number Signal Name Module 11 PA3.Data Port A 10 PA3.Control 9 PA3.Pullup_Enable 8 PA2.Data 7 PA2.Control 6 PA2.Pullup_Enable 5 PA1.Data 4 PA1.Control 3 PA1.Pullup_Enable 2 PA0.Data 1 PA0.Control 0 PA0.Pullup_Enable Note: Boundary-scan Description Language Files PRIVATE_SIGNAL1 should always be scanned in as zero.
Boot Loader Support – Read-While-Write Self-Programming The Boot Loader Support provides a real Read-While-Write self-programming mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a Flash-resident Boot Loader program.
ATmega16(L) Note that the user software can never read any code that is located inside the RWW section during a Boot Loader software operation. The syntax “Read-While-Write section” refers to which section that is being programmed (erased or written), not which section that actually is being read during a Boot Loader software update.
Figure 125. Read-While-Write vs.
ATmega16(L) Figure 126.
Table 96. Boot Lock Bit0 Protection Modes (Application Section)(1) BLB0 Mode BLB02 BLB01 1 1 1 No restrictions for SPM or LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 0 SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section.
ATmega16(L) Table 98. Boot Reset Fuse(1) BOOTRST Note: Store Program Memory Control Register – SPMCR Reset Address 1 Reset Vector = Application reset (address $0000) 0 Reset Vector = Boot Loader reset (see Table 100 on page 252) 1. "1" means unprogrammed, "0´means programmed The Store Program Memory Control Register contains the control bits needed to control the Boot Loader operations.
page address is taken from the high part of the Z pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a page write, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire page write operation if the NRWW section is addressed. • Bit 1 -PGERS: Page Erase If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes page erase.
ATmega16(L) Figure 127. Addressing the Flash during SPM(1) BIT 15 ZPCMSB ZPAGEMSB Z - REGISTER 1 0 0 PCMSB PROGRAM COUNTER PAGEMSB PCPAGE PCWORD PAGE ADDRESS WITHIN THE FLASH WORD ADDRESS WITHIN A PAGE PROGRAM MEMORY PAGE PAGE INSTRUCTION WORD PCWORD[PAGEMSB:0]: 00 01 02 PAGEEND Note: Self-Programming the Flash 1. The different variables used in Figure 127 are listed in Table 102 on page 252. The program memory is updated in a page by page fashion.
Performing Page Erase by SPM To execute page erase, set up the address in the Z pointer, write "X0000011" to SPMCR and execute SPM within four clock cycles after writing SPMCR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE in the Z-register. Other bits in the Z pointer will be ignored during this operation. • Page Erase to the RWW section: The NRWW section can be read during the page erase. • Page Erase to the NRWW section: The CPU is halted during the operation.
ATmega16(L) See Table 96 and Table 97 for how the different settings of the Boot Loader Bits affect the Flash access. If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock Bit will be programmed if an SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCR. The Z-pointer is don"t care during this operation, but for future compatibility it is recommended to load the Z-pointer with $0001 (same as used for reading the lock-bits).
correctly. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltage for executing instructions is too low. Flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. If there is no need for a Boot Loader update in the system, program the Boot Loader Lock bits to prevent any Boot Loader software updates. 2. Keep the AVR RESET active (low) during periods of insufficient power supply voltage.
ATmega16(L) call adiw sbiw brne Do_spm ZH:ZL, 2 loophi:looplo, 2 Wrloop ;use subi for PAGESIZEB<=256 ; execute page write subi ZL, low(PAGESIZEB) ;restore pointer sbci ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256 ldi spmcrval, (1<
Table 100. Boot Size Configuration(1) Boot Size End Application section Boot Reset Address (start Boot Loader Section) BOOTSZ1 BOOTSZ0 1 1 128 words 2 $0000 $1F7F $1F80 $1FFF $1F7F $1F80 1 0 256 words 4 $0000 $1EFF $1F00 $1FFF $1EFF $1F00 0 1 512 words 8 $0000 $1DFF $1E00 $1FFF $1DFF $1E00 0 0 1024 words 16 $0000 $1BFF $1C00 $1FFF $1BFF $1C00 Note: Pages Application Flash Section Boot Loader Flash Section 1.
ATmega16(L) Memory Programming Program And Data Memory Lock Bits The ATmega16 provides six Lock bits which can be left unprogrammed ("1") or can be programmed ("0") to obtain the additional features listed in Table 104. The Lock bits can only be erased to "1" with the Chip Erase command. Table 103.
Table 104. Lock Bit Protection Modes (Continued) Memory Lock Bits(2) BLB1 Mode BLB12 BLB11 1 1 1 No restrictions for SPM or LPM accessing the Boot Loader section. 2 1 0 SPM is not allowed to write to the Boot Loader section. 0 SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section.
ATmega16(L) Table 106. Fuse Low Byte Fuse Low Byte Bit No.
The XA1/XA0 pins determine the action executed when the XTAL1 pin is given a positive pulse. The bit coding is shown in Table 109. When pulsing WR or OE, the command loaded determines the action executed. The different Commands are shown in Table 110. Figure 128. Parallel Programming +5V RDY/BSY PD1 OE PD2 WR PD3 BS1 PD4 XA0 PD5 XA1 PD6 PAGEL PD7 VCC PB7 - PB0 +12 V BS2 DATA RESET PA0 XTAL1 GND Table 107.
ATmega16(L) Table 108. Pin Values used to Enter Programming Mode Pin Symbol Value PAGEL Prog_enable[3] 0 XA1 Prog_enable[2] 0 XA0 Prog_enable[1] 0 BS1 Prog_enable[0] 0 Table 109. XA1 and XA0 Coding XA1 XA0 Action when XTAL1 is Pulsed 0 0 Load Flash or EEPROM Address (High or low address byte determined by BS1) 0 1 Load Data (High or Low data byte for Flash determined by BS1) 1 0 Load Command 1 1 No Action, Idle Table 110.
Parallel Programming Enter Programming Mode The following algorithm puts the device in parallel programming mode: 1. Apply 4.5 - 5.5V between VCC and GND. 2. Set RESET to "0" and toggle XTAL1 at least 6 times 3. Set the Prog_enable pins listed in Table 108 on page 257 to "0000" and wait at least 100 ns. 4. Apply 11.5 - 12.5V to RESET. Any activity on Prog_enable pins within 100 ns after +12V has been applied to RESET, will cause the device to fail entering programming mode.
ATmega16(L) 4. Give XTAL1 a positive pulse. This loads the address low byte. C. Load Data Low Byte 1. Set XA1, XA0 to '01'. This enables data loading. 2. Set DATA = Data low byte ($00 - $FF). 3. Give XTAL1 a positive pulse. This loads the data byte. D. Load Data High Byte 1. Set BS1 to '1'. This selects high data byte. 2. Set XA1, XA0 to '01'. This enables data loading. 3. Set DATA = Data high byte ($00 - $FF). 4. Give XTAL1 a positive pulse. This loads the data byte. E. Latch Data 1. Set BS1 to '1'.
Figure 129. Addressing the Flash which is Organized in Pages PCMSB PROGRAM COUNTER PAGEMSB PCPAGE PCWORD PAGE ADDRESS WITHIN THE FLASH WORD ADDRESS WITHIN A PAGE PROGRAM MEMORY PAGE PAGE PCWORD[PAGEMSB:0]: 00 INSTRUCTION WORD 01 02 PAGEEND Note: 1. PCPAGE and PCWORD are listed in Table 111 on page 257. Figure 130. Programming the Flash Waveforms(1) F A DATA $10 B C ADDR. LOW DATA LOW D DATA HIGH E B C D E G XX ADDR. LOW DATA LOW DATA HIGH XX ADDR.
ATmega16(L) Programming the EEPROM The EEPROM is organized in pages, see Table 112 on page 257. When programming the EEPROM, the program data is latched into a page buffer. This allows one page of data to be programmed simultaneously. The programming algorithm for the EEPROM data memory is as follows (refer to “Programming the Flash” on page 258 for details on Command, Address and Data loading): 1. A: Load Command "0001 0001". 2. G: Load Address High Byte ($00 - $FF) 3.
5. Set BS1 to "1". The Flash word high byte can now be read at DATA. 6. Set OE to "1". Reading the EEPROM The algorithm for reading the EEPROM memory is as follows (refer to “Programming the Flash” on page 258 for details on Command and Address loading): 1. A: Load Command "0000 0011". 2. G: Load Address High Byte ($00 - $FF) 3. B: Load Address Low Byte ($00 - $FF) 4. Set OE to "0", and BS1 to "0". The EEPROM Data byte can now be read at DATA. 5. Set OE to "1".
ATmega16(L) Figure 132. Mapping between BS1, BS2 and the Fuse- and Lock Bits during Read 0 Fuse low byte DATA 0 Lock bits 1 BS1 Fuse high byte 1 BS2 Reading the Signature Bytes The algorithm for reading the Signature bytes is as follows (refer to “Programming the Flash” on page 258 for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. B: Load Address Low Byte ($00 - $02). 3. Set OE to "0", and BS1 to "0". The selected Signature byte can now be read at DATA. 4.
Figure 134. Parallel Programming Timing, Loading Sequence with Timing Requirements(1) LOAD ADDRESS (LOW BYTE) LOAD DATA LOAD DATA (HIGH BYTE) LOAD DATA (LOW BYTE) tXLPH t XLXH LOAD ADDRESS (LOW BYTE) tPLXH XTAL1 BS1 PAGEL DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte) XA0 XA1 Note: 1. The timing requirements shown in Figure 133 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation. Figure 135.
ATmega16(L) Table 113. Parallel Programming Characteristics, VCC = 5 V ± 10% Symbol Parameter Min VPP Programming Enable Voltage 11.
Serial Programming Pin Mapping Table 114. Pin Mapping Serial Programming Symbol Pins I/O Description MOSI PB5 I Serial data in MISO PB6 O Serial data out SCK PB7 I Serial clock Figure 136. Serial Programming and Verify +2.7 - 5.5V VCC MOSI PB5 MISO PB6 SCK PB7 XTAL1 RESET GND Note: If the device is clocked by the internal oscillator, it is no need to connect a clock source to the XTAL1 pin.
ATmega16(L) power-up. In this case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to "0". 2. Wait for at least 20 ms and enable serial programming by sending the Programming Enable serial instruction to pin MOSI. 3. The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte ($53), will echo back when issuing the third byte of the Programming Enable instruction.
least t WD_EEPROM before programming the next byte. See Table 115 for tWD_EEPROM value. Table 115. Minimum Wait Delay before Writing the Next Flash or EEPROM Location Symbol Minimum Wait Delay tWD_FLASH 4.5 ms tWD_EEPROM 9.0 ms tWD_ERASE 9.0 ms Figure 137.
ATmega16(L) Table 116. Serial Programming Instruction Set Instruction Format Instruction Programming Enable Chip Erase Read Program Memory Byte 1 Byte 2 Byte 3 Byte4 1010 1100 0101 0011 xxxx xxxx xxxx xxxx Enable Serial Programming after RESET goes low. 1010 1100 100x xxxx xxxx xxxx xxxx xxxx Chip Erase EEPROM and Flash. 0010 H000 00aa aaaa bbbb bbbb oooo oooo Read H (high or low) data o from Program memory at word address a:b.
Serial Programming Characteristics Figure 138. Serial Programming Timing MOSI tSHOX tOVSH SCK tSLSH tSHSL MISO tSLIV Table 117. Serial Programming Characteristics, TA = -40°C to 85°C, VCC = 2.7V - 5.5V (Unless otherwise noted) Symbol Parameter 1/tCLCL Oscillator Frequency (ATmega16L) tCLCL tSHSL Oscillator Period (ATmega16, VCC = 4.5 - 5.
ATmega16(L) Figure 139. State Machine Sequence for Changing the Instruction Word 1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 1 Select-IR Scan 0 0 1 1 Capture-DR Capture-IR 0 0 0 Shift-DR 1 1 Exit1-DR 0 0 Pause-DR 0 Pause-IR 1 1 0 Exit2-DR Exit2-IR 1 1 Update-DR AVR_RESET ($C) 1 Exit1-IR 0 1 0 Shift-IR 1 0 1 Update-IR 0 1 0 The AVR specific public JTAG instruction for setting the AVR device in the Reset Mode or taking the device out from the Reset Mode.
PROG_COMMANDS ($5) PROG_PAGELOAD ($6) The AVR specific public JTAG instruction for entering programming commands via the JTAG port. The 15-bit Programming Command register is selected as data register. The active states are the following: • Capture-DR: the result of the previous command is loaded into the data register. • Shift-DR: the data register is shifted by the TCK input, shifting out the result of the previous command and shifting in the new command.
ATmega16(L) When the contents of the register is equal to the programming enable signature, programming via the JTAG port is enabled. The register is reset to 0 on power-on reset, and should always be reset when leaving programming mode. Figure 140. Programming Enable Register TDI D A T A $A370 = D Q Programming enable ClockDR & PROG_ENABLE TDO Programming Command Register The Programming Command register is a 15-bit register.
Table 118. JTAG Programming Instruction Set a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don"t care Instruction TDI sequence TDO sequence 1a. Chip erase 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx 1b. Poll for chip erase complete 0110011_10000000 xxxxxox_xxxxxxxx 2a. Enter Flash Write 0100011_00010000 xxxxxxx_xxxxxxxx 2b.
ATmega16(L) Table 118. JTAG Programming Instruction Set (Continued) a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don"t care Instruction TDI sequence TDO sequence 5c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 5d. Read Data Byte 0110011_bbbbbbbb 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 0100011_01000000 xxxxxxx_xxxxxxxx 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3) 6c.
Table 118. JTAG Programming Instruction Set (Continued) a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don"t care Instruction TDI sequence TDO sequence 10a. Enter Calibration Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx 10b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx 10c. Read Calibration Byte 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo 11a.
ATmega16(L) Figure 142. State Machine Sequence for Changing/Reading the Data Word 1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 1 Select-IR Scan 0 0 1 1 Capture-DR Capture-IR 0 0 0 Shift-DR 1 1 Exit1-DR 0 0 Pause-DR 0 Pause-IR 1 1 0 Exit2-DR Exit2-IR 1 1 Update-DR Virtual Flash Page Load Register 1 Exit1-IR 0 1 0 Shift-IR 1 0 1 Update-IR 0 1 0 The Virtual Flash Page Load register is a virtual scan chain with length equal to the number of bits in one Flash page.
Figure 143. Virtual Flash Page Load Register STROBES TDI State machine ADDRESS Flash EEPROM Fuses Lock Bits D A T A TDO Virtual Flash Page Read Register The Virtual Flash Page Read register is a virtual scan chain with length equal to the number of bits in one Flash page plus 8. Internally the shift register is 8-bit, and the data are automatically transferred from the Flash data page byte by byte.
ATmega16(L) Programming Algorithm All references below of type “1a”, “1b”, and so on, refer to Table 118. Entering Programming Mode 1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset register. 2. Enter instruction PROG_ENABLE and shift 1010_0011_0111_0000 in the Programming Enable register. Leaving Programming Mode 1. Enter JTAG instruction PROG_COMMANDS. 2. Disable all programming instructions by usning no operation instruction 11a. 3.
6. Enter JTAG instruction PROG_COMMANDS. 7. Write the page using programming instruction 2g. 8. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH (refer to Table 113 on page 265). 9. Repeat steps 3 to 8 until all data have been programmed. Reading the Flash 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 3. Load address using programming instructions 3b and 3c. 4. Read data using programming instruction 3d. 5.
ATmega16(L) Programming the Fuses 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse write using programming instruction 6a. 3. Load data high byte using programming instructions 6b. A bit value of "0" will program the corresponding fuse, a "1" will unprogram the fuse. 4. Write Fuse high byte using programming instruction 6c. 5. Poll for Fuse write complete using programming instruction 6d, or wait for tWLRH (refer to Table 113 on page 265). 6. Load data low byte using programming instructions 6e.
Electrical Characteristics Absolute Maximum Ratings* Operating Temperature.................................. -55°C to +125°C *NOTICE: Storage Temperature ..................................... -65°C to +150°C Voltage on any Pin except RESET with respect to Ground ................................-1.0V to VCC+0.5V Voltage on RESET with respect to Ground......-1.0V to +13.0V Stresses beyond those listed under “Absolute Maximum Ratings” may cause permanent damage to the device.
ATmega16(L) DC Characteristics (Continued) TA = -40°C to 85°C, VCC = 2.7V to 5.
8] The sum of all IOH, for ports D4-D7, should not exceed 100 mA If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition. 5. Minimum VCC for Power-down is 2.5V. External Clock Drive Waveforms Figure 145. External Clock Drive Waveforms V IH1 V IL1 External Clock Drive Table 119. External Clock Drive VCC = 2.7V to 5.5V VCC = 4.5V to 5.
ATmega16(L) 2-wire Serial Interface Characteristics Table 121 describes the requirements for devices connected to the 2-wire Serial Bus. The ATmega16 2-wire Serial Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 146. Table 121. 2-wire Serial Bus Requirements Symbol Parameter VIL Min Max Units Input Low-voltage -0.5 0.3 VCC V VIH Input High-voltage 0.7 VCC VCC + 0.5 V Vhys(1) Hysteresis of Schmitt Trigger Inputs 0.
5. This requirement applies to all ATmega16 2-wire Serial Interface operation. Other devices connected to the 2-wire Serial Bus need only obey the general fSCL requirement. 6. The actual low period generated by the ATmega16 2-wire Serial Interface is (1/fSCL 2/fCK), thus fCK must be greater than 6 MHz for the low time requirement to be strictly met at fSCL = 100 kHz. 7.
ATmega16(L) Figure 147. SPI Interface Timing Requirements (Master Mode) SS 6 1 SCK (CPOL = 0) 2 2 SCK (CPOL = 1) 4 MISO (Data Input) 5 3 MSB ... LSB 7 MOSI (Data Output) MSB 8 ... LSB Figure 148. SPI Interface Timing Requirements (Slave Mode) SS 10 9 16 SCK (CPOL = 0) 11 11 SCK (CPOL = 1) 13 MOSI (Data Input) 14 12 MSB ... LSB 15 MISO (Data Output) MSB 17 ...
ADC Characteristics – Preliminary Data Table 123. ADC Characteristics Symbol Typ(1) Max(1) Condition Resolution Single Ended Conversion 10 Bits Differential Conversion Gain = 1x or 20x 8 Bits Differential Conversion Gain = 200x 7 Bits Absolute accuracy Units Single Ended Conversion VREF = 4 V ADC clock = 200 kHz ADHSM = 0 1 TBD LSB Single Ended Conversion VREF = 4V ADC clock = 1 MHz ADHSM = 1 TBD TBD LSB Integral Non-Linearity VREF = 4 V 0.
ATmega16(L) ATmega16 Typical Characteristics – Preliminary Data The following charts show typical behavior. These figures are not tested during manufacturing. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A sine wave generator with railto-rail output is used as clock source. The power consumption in Power-down Mode is independent of clock selection.
Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 $3F ($5F) SREG I T H S V N Z C 7 $3E ($5E) SPH - - - - - SP10 SP9 SP8 10 SP4 SP3 SP2 SP1 SP0 10 - - - IVSEL IVCE 45, 65 $3D ($5D) SPL $3C ($5C) OCR0 $3B ($5B) GICR SP7 SP6 SP5 Timer/Counter0 Output Compare Register INT1 INT0 Page 80 INT2 $3A ($5A) GIFR INTF1 INTF0 INTF2 - - - - - 66 $39 ($59) TIMSK OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0 80, 109
ATmega16(L) Register Summary (Continued) Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page $02 ($22) TWAR TWA6 TWSR TWS7 TWA4 TWS5 TWA3 TWS4 TWA2 TWS3 TWA1 $01 ($21) TWA5 TWS6 TWA0 TWPS1 TWGCE TWPS0 172 $00 ($20) TWBR Notes: 2-wire Serial Interface Bit Rate Register - 173 171 1. When the OCDEN fuse is unprogrammed, the OSCCAL register is always accessed on this address. Refer to the debugger specific documentation for details on how to use the OCDR register. 2.
Instruction Set Summary Mnemonics Operands Description Operation Flags #Clocks ARITHMETIC AND LOGIC INSTRUCTIONS ADD Rd, Rr Add two Registers Rd ← Rd + Rr Z,C,N,V,H 1 ADC Rd, Rr Add with Carry two Registers Rd ← Rd + Rr + C Z,C,N,V,H 1 2 ADIW Rdl,K Add Immediate to Word Rdh:Rdl ← Rdh:Rdl + K Z,C,N,V,S SUB Rd, Rr Subtract two Registers Rd ← Rd - Rr Z,C,N,V,H 1 SUBI Rd, K Subtract Constant from Register Rd ← Rd - K Z,C,N,V,H 1 1 SBC Rd, Rr Subtract with Carry two Registers
ATmega16(L) Instruction Set Summary (Continued) BRIE k Branch if Interrupt Enabled if ( I = 1) then PC ← PC + k + 1 None 1/2 BRID k Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2 DATA TRANSFER INSTRUCTIONS MOV Rd, Rr Move Between Registers 1 Rd, Rr Copy Register Word Rd ← Rr Rd+1:Rd ← Rr+1:Rr None MOVW None 1 LDI Rd, K Load Immediate Rd ← K None 1 LD Rd, X Load Indirect Rd ← (X) None 2 LD Rd, X+ Load Indirect and Post-Inc.
Instruction Set Summary (Continued) CLH MCU CONTROL INSTRUCTIONS NOP SLEEP WDR BREAK 294 Clear Half Carry Flag in SREG H←0 H No Operation Sleep Watchdog Reset Break (see specific descr. for Sleep function) (see specific descr.
ATmega16(L) Ordering Information Speed (MHz) Power Supply 8 2.7 - 5.5V 16 4.5 - 5.5V Ordering Code Package ATmega16L-8AC ATmega16L-8PC 44A 40P6 Operation Range Commercial (0oC to 70oC) ATmega16L-8AI ATmega16L-8PI 44A 40P6 Industrial (-40oC to 85oC) ATmega16-16AC ATmega16-16PC 44A 40P6 Commercial (0oC to 70oC) ATmega16-16AI ATmega16-16PI 44A 40P6 Industrial (-40oC to 85oC) Package Type 44A 44-lead, Thin (1.0 mm) Plastic Gull Wing Quad Flat Package (TQFP) 40P6 40-pin, 0.
Packaging Information 44A 44-lead, Thin (1.0mm) Plastic Quad Flat Package (TQFP), 10x10mm body, 2.0mm footprint, 0.8mm pitch. Dimension in Millimeters and (Inches)* JEDEC STANDARD MS-026 ACB 12.25(0.482) SQ 11.75(0.462) PIN 1 ID PIN 1 0.45(0.018) 0.30(0.012) 0.80(0.0315) BSC 10.10(0.394) SQ 9.90(0.386) 1.20(0.047) MAX 0.20(0.008) 0.09(0.004) 0˚~7˚ 0.75(0.030) 0.45(0.018) 0.15(0.006) 0.05(0.002) *Controlling dimension: millimetter REV.
ATmega16(L) 40P6 40-lead, Plastic Dual Inline Parkage (PDIP), 0.600" wide Demension in Millimeters and (Inches)* JEDEC STANDARD MS-011 AC 52.71(2.075) 51.94(2.045) PIN 1 13.97(0.550) 13.46(0.530) 48.26(1.900) REF 4.83(0.190)MAX SEATING PLANE 0.38(0.015)MIN 3.56(0.140) 3.05(0.120) 2.54(0.100)BSC 1.65(0.065) 1.27(0.050) 0.56(0.022) 0.38(0.015) 15.88(0.625) 15.24(0.600) 0º ~ 15º REF 0.38(0.015) 0.20(0.008) 17.78(0.700)MAX *Controlling dimension: Inches REV.
Atmel Headquarters Atmel Product Operations Corporate Headquarters Atmel Colorado Springs 2325 Orchard Parkway San Jose, CA 95131 TEL (408) 441-0311 FAX (408) 487-2600 Europe Atmel SarL Route des Arsenaux 41 Casa Postale 80 CH-1705 Fribourg Switzerland TEL (41) 26-426-5555 FAX (41) 26-426-5500 Asia Atmel Asia, Ltd. Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimhatsui East Kowloon Hong Kong TEL (852) 2721-9778 FAX (852) 2722-1369 Japan Atmel Japan K.K. 9F, Tonetsu Shinkawa Bldg.