ATMEGA16L-8AI Atmel, ATMEGA16L-8AI Datasheet
![IC AVR MCU 16K LV 8MHZ IND44TQFP](/photos/6/70/67042/313-44-tqfp_sml.jpg)
ATMEGA16L-8AI
Specifications of ATMEGA16L-8AI
Available stocks
Related parts for ATMEGA16L-8AI
ATMEGA16L-8AI Summary of contents
Page 1
... ATmega16L – 4.5V - 5.5V for ATmega16 • Speed Grades – MHz for ATmega16L – MHz for ATmega16 • Power Consumption @ 1 MHz, 3V, and 25°C for ATmega16L – Active: 1.1 mA – Idle Mode: 0.35 mA – Power-down Mode: < 1 µA ® ® AVR ...
Page 2
Pin Figure 1. Pinout ATmega16 Configurations Disclaimer Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers manufactured on the same process technology. Min and Max values will be available after the device is ...
Page 3
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 ...
Page 4
... Application Flash section is updated, providing true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel ATmega16 is a powerful microcontroller that provides a highly-flexible and cost-effec- tive solution to many embedded control applications. The ATmega16 AVR is supported with a full suite of program and system development tools including: C compilers, macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits ...
Page 5
Port B (PB7..PB0) Port 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins ...
Page 6
... Resources A comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr. Note: Data Retention Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C. ...
Page 7
About Code This documentation contains simple code examples that briefly show how to use various parts of the device. These code examples assume that the part specific header file is included before Examples compilation. Be aware that not all C ...
Page 8
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 ...
Page 9
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 for- mat. Every program memory address contains a 16-bit or 32-bit instruction. ...
Page 10
Bit 6 – T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or desti- nation for the operated bit. A bit from a register in the Register File ...
Page 11
General Purpose The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve Register File the required performance and flexibility, the following input/output schemes are supported by the Register File: • One 8-bit output operand ...
Page 12
The X-register, Y- The registers R26..R31 have some added functions to their general purpose usage. These reg- register and Z-register isters are 16-bit address pointers for indirect addressing of the Data Space. The three indirect address registers X, Y, and ...
Page 13
Instruction This section describes the general access timing concepts for instruction execution. The AVR Execution Timing CPU is driven by the CPU clock clk chip. No internal clock division is used. Figure 6 vard architecture and the fast-access Register File ...
Page 14
The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL bit in the General Interrupt Control Register (GICR). Refer to information. The Reset Vector can also be moved to the start ...
Page 15
When using the SEI instruction to enable interrupts, the instruction following SEI will be exe- cuted before any pending interrupts, as shown in this example. Assembly Code Example sei sleep ; enter sleep, waiting for interrupt ; note: will enter ...
Page 16
AVR ATmega16 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 Memories ATmega16 features an EEPROM Memory for data storage. All ...
Page 17
SRAM Data Figure 9 Memory The lower 1120 Data Memory locations address the Register File, the I/O Memory, and the inter- nal data SRAM. The first 96 locations address the Register File and I/O Memory, and the next 1024 locations ...
Page 18
Data Memory Access This section describes the general access timing concepts for internal memory access. The Times internal data SRAM access is performed in two clk Figure 10. On-chip Data SRAM Access Cycles EEPROM Data The ATmega16 contains 512 bytes ...
Page 19
The EEPROM Address Register – EEARH and Bit EEARL Read/Write Initial Value • Bits 15..9 – Res: Reserved Bits These bits are reserved bits in the ATmega16 and will always read as zero. • Bits 8..0 – EEAR8..0: EEPROM Address ...
Page 20
Bit 1 – EEWE: EEPROM Write Enable The EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM. When address and data are correctly set up, the EEWE bit must be written to one to write the ...
Page 21
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. Assembly Code Example EEPROM_write: C Code Example void EEPROM_write(unsigned ...
Page 22
The next code examples show assembly and C functions for reading the EEPROM. The exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. Assembly Code Example EEPROM_read: C Code Example unsigned ...
Page 23
EEPROM data corruption can easily be avoided by following this design recommendation: Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal Brown-out Detector (BOD). If the detection level ...
Page 24
System Clock and Clock Options Clock Systems Figure 11 need not be active at a given time. In order to reduce power consumption, the clocks to modules and their not being used can be halted by using different sleep modes, ...
Page 25
ADC Clock – clk The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks ADC in order to reduce noise generated by digital circuitry. This gives more accurate ADC conversion results. Clock Sources ...
Page 26
Figure 12. Crystal Oscillator Connections The Oscillator can operate in three different modes, each optimized for a specific frequency range. The operating ...
Page 27
The CKSEL0 Fuse together with the SUT1..0 Fuses select the start-up times as shown in 5. Table 5. Start-up Times for the Crystal Oscillator Clock Selection CKSEL0 Notes: 2466T–AVR–07/10 Start-up Time from ...
Page 28
Low-frequency To use a 32.768 kHz watch crystal as the clock source for the device, the Low-frequency Crystal Crystal Oscillator Oscillator must be selected by setting the CKSEL Fuses to “1001”. The crystal should be con- nected as shown in ...
Page 29
... MHz or 8.0 MHz Oscillator frequency selected, this calibration gives a frequency within ±3% of the nominal frequency. Using calibration methods as described in application notes available at www.atmel.com/avr it is possible to achieve ±1% accuracy at any given V When this Oscillator is used as the Chip Clock, the Watchdog Oscillator will still be used for the Watchdog Timer and for the reset time-out ...
Page 30
Oscillator Calibration Register – OSCCAL Bit Read/Write Initial Value • Bits 7..0 – CAL7..0: Oscillator Calibration Value Writing the calibration byte to this address will trim the Internal Oscillator to remove process vari- ations from the Oscillator frequency. This is ...
Page 31
External Clock To drive the device from an external clock source, XTAL1 should be driven as shown in 14. To run the device on an external clock, the CKSEL Fuses must be programmed to “0000”. By programming the CKOPT Fuse, ...
Page 32
Power Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consump- Management tion to the application’s requirements. and Sleep To ...
Page 33
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, Two-wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system to continue ...
Page 34
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. ...
Page 35
Minimizing Power There are several issues to consider when trying to minimize the power consumption in an AVR Consumption controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so ...
Page 36
JTAG Interface and If the On-chip debug system is enabled by the OCDEN Fuse and the chip enter Power down or On-chip Debug Power save sleep mode, the main clock source remains enabled. In these sleep modes, this will System ...
Page 37
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 ...
Page 38
... V antees that a Brown-out Reset will occur before V operation of the microcontroller is no longer guaranteed. The test is performed using BODLEVEL = 1 for ATmega16L and BODLEVEL = 0 for ATmega16. BODLEVEL = 1 is not applicable for ATmega16. ATmega16(L) DATA BUS ...
Page 39
Power-on Reset A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level is defined in POR circuit can be used to trigger the Start-up Reset, as well as to detect a failure in supply voltage. ...
Page 40
External Reset An External Reset is generated by a low level on the RESET pin. Reset pulses longer than the minimum pulse width (see Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset ...
Page 41
Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period t page 42 Figure 20. Watchdog ...
Page 42
Internal Voltage ATmega16 features an internal bandgap reference. This reference is used for Brown-out Detec- Reference tion, and it can be used as an input to the Analog Comparator or the ADC. The 2.56V reference to the ADC is generated ...
Page 43
Watchdog Timer Control Register – Bit WDTCR Read/Write Initial Value • 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 ...
Page 44
The following code example shows one assembly and one C function for turning off the WDT. The example assumes that interrupts are controlled (for example by disabling interrupts globally) so that no interrupts will occur during execution of these functions. ...
Page 45
Interrupts This section describes the specifics of the interrupt handling as performed in ATmega16. For a general explanation of the AVR interrupt handling, refer to page 13. Interrupt Vectors in ATmega16 Table 18. Reset and Interrupt Vectors Vector No. 1 ...
Page 46
Table 19. Reset and Interrupt Vectors Placement BOOTRST Note: The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega16 is: Address $000 $002 $004 $006 $008 $00A $00C $00E $010 $012 $014 $016 $018 ...
Page 47
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2 Kbytes 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 ...
Page 48
Moving Interrupts The General Interrupt Control Register controls the placement of the Interrupt Vector table. Between Application and Boot Space General Interrupt Control Register – Bit GICR Read/Write Initial Value • Bit 1 – IVSEL: Interrupt Vector Select When the ...
Page 49
Assembly Code Example Move_interrupts: C Code Example void Move_interrupts(void 2466T–AVR–07/10 ; Enable change of interrupt vectors ldi r16, (1<<IVCE) out GICR, r16 ; Move interrupts to boot Flash section ldi r16, (1<<IVSEL) out GICR, r16 ret /* ...
Page 50
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 ...
Page 51
Figure 23. General Digital I/O Note: Configuring the Pin Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in Description for I/O Ports” on page PORTxn bits at the PORTx I/O address, and the PINxn ...
Page 52
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} = 0b11 intermediate step. Table 20 Table 20. ...
Page 53
When reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in clock. In this case, the delay t Figure 25. Synchronization when Reading a Software Assigned Pin Value SYSTEM CLK INSTRUCTIONS SYNC LATCH ...
Page 54
The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from input with pull-ups assigned to port pins 6 and 7. The ...
Page 55
Unconnected pins If some pins are unused recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, float- ing inputs should ...
Page 56
Table 21 ure 26 the modules having the alternate function. Table 21. Generic Description of Overriding Signals for Alternate Functions Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO The following subsections shortly describe the alternate functions ...
Page 57
Special Function I/O Register – SFIOR Bit Read/Write Initial Value • Bit 2 – PUD: Pull-up disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and PORTxn Registers are ...
Page 58
Table 24. Overriding Signals for Alternate Functions in PA3..PA0 Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO Alternate Functions of The Port B pins with alternate functions are shown in Port B Table 25. Port B ...
Page 59
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 ...
Page 60
Table 26. Overriding Signals for Alternate Functions in PB7..PB4 Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO Table 27. Overriding Signals for Alternate Functions in PB3..PB0 Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV ...
Page 61
Alternate Functions of The Port C pins with alternate functions are shown in Port C the pull-up resistors on pins PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset occurs. Table 28. Port C Pins Alternate Functions Port ...
Page 62
SDA – Port C, Bit 1 SDA, Two-wire Serial Interface Data: When the TWEN bit in TWCR is set (one) to enable the Two-wire Serial Interface, pin PC1 is disconnected from the port and becomes the Serial Data I/O ...
Page 63
Table 30. Overriding Signals for Alternate Functions in PC3..PC0 Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO Note: Alternate Functions of The Port D pins with alternate functions are shown in Port D Table 31. Port ...
Page 64
OC1A – Port D, Bit 5 OC1A, Output Compare Match A output: The PD5 pin can serve as an external output for the Timer/Counter1 Output Compare A. The pin has to be configured as an output (DDD5 set (one)) ...
Page 65
Table 33. Overriding Signals for Alternate Functions in PD3..PD0 Signal Name PUOE PUOV DDOE DDOV PVOE PVOV DIEOE DIEOV DI AIO 2466T–AVR–07/10 PD3/INT1 PD2/INT0 INT1 ENABLE INT0 ENABLE ...
Page 66
Register Description for I/O Ports Port A Data Register – PORTA Bit Read/Write Initial Value Port A Data Direction Register – DDRA Bit Read/Write Initial Value Port A Input Pins Address – PINA Bit Read/Write Initial Value Port B Data ...
Page 67
Port C Data Register – PORTC Bit Read/Write Initial Value Port C Data Direction Register – DDRC Bit Read/Write Initial Value Port C Input Pins Address – PINC Bit Read/Write Initial Value Port D Data Register – PORTD Bit Read/Write ...
Page 68
External 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 Interrupts a way of generating a software ...
Page 69
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 corre- sponding interrupt mask are set. The ...
Page 70
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 ...
Page 71
Timer/Counter0 is a general purpose, single compare unit, 8-bit Timer/Counter module. The main features are: Timer/Counter0 • Single Compare Unit Counter with PWM • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) ...
Page 72
Unit” on page 73. which can be used to generate an output compare interrupt request. Definitions Many register and bit references in this document are written in general form. A lower case “n” replaces the Timer/Counter number, in this case ...
Page 73
The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the Timer/Counter Control Register (TCCR0). There are close connections between how the counter behaves (counts) and how waveforms are generated ...
Page 74
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. ...
Page 75
Figure 30. Compare Match Output Unit, Schematic 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 ...
Page 76
Modes of The mode of operation, that is, the behavior of the Timer/Counter and the Output Compare pins, Operation is defined by the combination of the Waveform Generation mode (WGM01:0) and Compare Out- put mode (COM01:0) bits. The Compare Output ...
Page 77
If the new value written to OCR0 is lower than the current value of TCNT0, the counter will miss the compare match. The counter will then have to count to its max- imum value (0xFF) and ...
Page 78
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0 pin. Set- ting the COM01:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM01:0 ...
Page 79
Phase Correct PWM The phase correct PWM mode (WGM01 provides a high resolution phase correct PWM Mode waveform generation option. The phase correct PWM mode is based on a dual-slope operation. The counter counts repeatedly from BOTTOM to ...
Page 80
PWM frequency for the output when using phase correct PWM can be calculated by the follow- ing equation: The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0 Register represent special ...
Page 81
Timer/Counter The Timer/Counter is a synchronous design and the timer clock (clk Timing Diagrams clock enable signal in the following figures. The figures include information on when Interrupt Flags are set. shows the count sequence close to the MAX value ...
Page 82
Figure 36. Timer/Counter Timing Diagram, Setting of OCF0, with Prescaler (f clk clk (clk TCNTn OCRn OCFn Figure 37 Figure 37. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with Pres- caler (f clk_I/O clk clk (clk TCNTn (CTC) ...
Page 83
Timer/Counter Register Description Timer/Counter Control Register – TCCR0 Bit Read/Write Initial Value • Bit 7 – FOC0: Force Output Compare The FOC0 bit is only active when the WGM00 bit specifies a non-PWM mode. However, for ensuring compatibility with ...
Page 84
When OC0 is connected to the pin, the function of the COM01:0 bits depends on the WGM01:0 bit setting. normal or CTC mode (non-PWM). Table 39. Compare Output Mode, non-PWM Mode COM01 Table 40 mode. Table ...
Page 85
Bit 2:0 – CS02:0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter. Table 42. Clock Select Bit Description CS02 external pin ...
Page 86
Bit 0 – TOIE0: Timer/Counter0 Overflow Interrupt Enable When the TOIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an ...
Page 87
Timer/Counter0 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 and Timer/Counter0. Timer/Counter1 Prescalers Internal Clock Source The Timer/Counter can be clocked directly by the ...
Page 88
However, due to variation of the system clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) ...
Page 89
The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are: Timer/Counter1 • True 16-bit Design (that is, allows 16-bit PWM) • Two Independent Output Compare Units • Double ...
Page 90
Figure 40. 16-bit Timer/Counter Block Diagram Note: Registers The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Regis- ter (ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16- bit registers. These procedures are described ...
Page 91
The Input Capture Register can capture the Timer/Counter value at a given external (edge trig- gered) event on either the Input Capture Pin (ICP1 the Analog Comparator pins “Analog Comparator” on page Canceler) for reducing the chance of ...
Page 92
Accessing 16-bit The TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVR CPU via Registers the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. Each 16-bit timer ...
Page 93
The following code examples show how atomic read of the TCNT1 Register contents. Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Assembly Code Example TIM16_ReadTCNT1: C Code Example unsigned ...
Page 94
The following code examples show how atomic write of the TCNT1 Register contents. Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle. Assembly Code Example TIM16_WriteTCNT1: C Code Example void ...
Page 95
Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 41 Figure 41. Counter Unit Block Diagram Signal description (internal signals): Count Direction Clear clk T 1 TOP BOTTOM The 16-bit counter is ...
Page 96
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 mul- tiple events, can be applied via the ICP1 ...
Page 97
For more information on how to access the 16-bit registers refer to on page Input Capture Pin The main trigger source for the Input Capture unit is the Input Capture pin (ICP1). Source Timer/Counter1 can alternatively use the Analog Comparator ...
Page 98
Output Compare The 16-bit comparator continuously compares TCNT1 with the Output Compare Register Units (OCR1x). If TCNT equals OCR1x the comparator signals a match. A match will set the Output Compare Flag (OCF1x) at the next timer clock cycle. If ...
Page 99
However good practice to read the Low byte first as when accessing other 16-bit registers. Writing the OCR1x Registers must be done via the TEMP Reg- ister since the compare of all 16 bits ...
Page 100
Compare Match The Compare Output mode (COM1x1:0) bits have two functions. The Waveform Generator uses Output Unit the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next compare match. Secondly the COM1x1:0 bits control the OC1x pin ...
Page 101
Modes of The mode of operation, that is, the behavior of the Timer/Counter and the output compare pins, Operation is defined by the combination of the Waveform Generation mode (WGM13:0) and Compare Out- put mode (COM1x1:0) bits. The Compare Output ...
Page 102
An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag according to the register used to define the TOP value. If the interrupt is enabled, the interrupt ...
Page 103
Figure 46. Fast PWM Mode, Timing Diagram TCNTn OCnx OCnx Period 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 ...
Page 104
The PWM frequency for the output can be calculated by the following equation: The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x Register represents special cases when generating a PWM ...
Page 105
Figure 47. Phase Correct PWM Mode, Timing Diagram TCNTn OCnx OCnx Period The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ...
Page 106
The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: The N variable represents the prescaler divider (1, 8, 64, 256, or 1024). The extreme values for the OCR1x ...
Page 107
Figure 48. Phase and Frequency Correct PWM Mode, Timing Diagram TCNTn OCnx OCnx Period The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x Registers are updated with the double buffer value (at BOTTOM). ...
Page 108
TOP the output will be set to high for non- inverted PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A is used to define ...
Page 109
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. Timer/Counter Timing Diagram, no Prescaling (CTC and FPWM) ...
Page 110
Timer/Counter Register Description Timer/Counter1 Control Register A – Bit TCCR1A Read/Write Initial Value • Bit 7:6 – COM1A1:0: Compare Output Mode for Channel A • Bit 5:4 – COM1B1:0: Compare Output Mode for Channel B The COM1A1:0 and COM1B1:0 ...
Page 111
Table 45. Compare Output Mode, Fast PWM COM1A1/COM1B1 Note: Table 46 rect or the phase and frequency correct, PWM mode. Table 46. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM COM1A1/COM1B1 Note: • Bit 3 – FOC1A: ...
Page 112
A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear Timer on Compare match (CTC) mode using OCR1A as TOP. The FOC1A/FOC1B bits are always read as zero. • Bit 1:0 – WGM11:0: Waveform ...
Page 113
Timer/Counter1 Control Register B – Bit TCCR1B Read/Write Initial Value • 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 ...
Page 114
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. Timer/Counter1 – TCNT1H and TCNT1L ...
Page 115
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. ...
Page 116
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 used as the TOP value, ...
Page 117
Timer/Counter2 is a general purpose, single compare unit, 8-bit Timer/Counter module. The main features are: Timer/Counter2 • Single Compare unit Counter with PWM and • Clear Timer on Compare Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator ...
Page 118
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 ...
Page 119
Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk selected by the Clock Select bits (CS22:0). When no clock source is selected (CS22 the timer is stopped. ...
Page 120
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 ...
Page 121
Compare Match The Compare Output mode (COM21:0) bits have two functions. The Waveform Generator uses Output Unit the COM21:0 bits for defining the Output Compare (OC2) state at the next compare match. Also, the COM21:0 bits control the OC2 pin ...
Page 122
Modes of The mode of operation, that is, the behavior of the Timer/Counter and the output compare pins, Operation is defined by the combination of the Waveform Generation mode (WGM21:0) and Compare Out- put mode (COM21:0) bits. The Compare Output ...
Page 123
TCNT2, the counter will miss the compare match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the compare match can occur. For generating a waveform output in ...
Page 124
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2 pin. Set- ting the COM21:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM21:0 ...
Page 125
Figure 59. Phase Correct PWM Mode, Timing Diagram The Timer/Counter Overflow Flag ( 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 ...
Page 126
Timer/Counter The following figures show the Timer/Counter in Synchronous mode, and the timer clock (clk Timing Diagrams is therefore shown as a clock enable signal. In Asynchronous mode, clk the Timer/Counter Oscillator clock. The figures include information on when Interrupt ...
Page 127
Figure 62. Timer/Counter Timing Diagram, Setting of OCF2, with Prescaler (f clk clk (clk TCNTn OCRn OCFn Figure 63 Figure 63. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with Pres- caler (f clk_I/O clk clk (clk TCNTn (CTC) ...
Page 128
Timer/Counter Register Description Timer/Counter Control Register – TCCR2 Bit Read/Write Initial Value • Bit 7 – FOC2: Force Output Compare The FOC2 bit is only active when the WGM bits specify a non-PWM mode. However, for ensur- ing compatibility ...
Page 129
When OC2 is connected to the pin, the function of the COM21:0 bits depends on the WGM21:0 bit setting. normal or CTC mode (non-PWM). Table 51. Compare Output Mode, non-PWM Mode COM21 Table 52 mode. Table ...
Page 130
Bit 2:0 – CS22:0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter, see 54. Table 54. Clock Select Bit Description CS22 Timer/Counter ...
Page 131
Asynchronous Operation of the Timer/Counter Asynchronous Status Register – ASSR Bit Read/Write Initial Value • Bit 3 – AS2: Asynchronous Timer/Counter2 When AS2 is written to zero, Timer/Counter 2 is clocked from the I/O clock, clk written to one, Timer/Counter2 ...
Page 132
The Oscillator is optimized for use with a 32.768 kHz watch crystal. Applying an external clock to the TOSC1 pin may result in incorrect Timer/Counter2 operation. The CPU main clock frequency must be more than four times the Oscillator ...
Page 133
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. • During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous timer ...
Page 134
Timer/Counter Figure 64. Prescaler for Timer/Counter2 Prescaler The clock source for Timer/Counter2 is named clk system I/O clock clk clocked from the TOSC1 pin. This enables use of Timer/Counter2 as a Real Time Counter (RTC). When AS2 is set, pins ...
Page 135
Serial The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega16 and peripheral devices or between several AVR devices. The ATmega16 SPI Peripheral includes the following features: Interface – SPI • Full-duplex, Three-wire Synchronous Data Transfer • ...
Page 136
SPI Data Register starts the SPI clock generator, and the hardware shifts the eight bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI ...
Page 137
Note: 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 ...
Page 138
Assembly Code Example SPI_MasterInit: SPI_MasterTransmit: Wait_Transmit: C Code Example void SPI_MasterInit(void void SPI_MasterTransmit(char cData Note: 2466T–AVR–07/10 (1) ; Set MOSI and SCK output, all others input ldi r17,(1<<DD_MOSI)|(1<<DD_SCK) out DDR_SPI,r17 ; Enable SPI, Master, set clock ...
Page 139
The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example SPI_SlaveInit: SPI_SlaveReceive: C Code Example void SPI_SlaveInit(void char SPI_SlaveReceive(void Note: 2466T–AVR–07/10 (1) ; ...
Page 140
SS Pin Functionality Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the ...
Page 141
Bit 4 – MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero configured as an input and is driven low while MSTR is set, ...
Page 142
SPI Status Register – SPSR Bit Read/Write Initial Value • Bit 7 – SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global ...
Page 143
Data Modes There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in 67 and ensuring sufficient time for data ...
Page 144
USART The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART highly flexible serial communication device. The main features are: • Full Duplex Operation (Independent Serial Receive and Transmit Registers) • Asynchronous or Synchronous Operation • Master or ...
Page 145
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 ...
Page 146
Figure 70. Clock Generation Logic, Block Diagram DDR_XCK Signal description: txclk rxclk xcki xcko fosc Internal Clock Internal clock generation is used for the asynchronous and the synchronous Master modes of Generation – The operation. The description in this section ...
Page 147
Table 60. Equations for Calculating Baud Rate Register Setting Operating Mode Asynchronous Normal Mode (U2X = 0) Asynchronous Double Speed Mode (U2X = 1) Synchronous Master Mode Note: BAUD Baud rate (in bits per second, bps) f OSC UBRR Contents ...
Page 148
Synchronous Clock When Synchronous mode is used (UMSEL = 1), the XCK pin will be used as either clock input Operation (Slave) or clock output (Master). The dependency between the clock edges and data sampling or data change is the ...
Page 149
IDLE The frame format used by the USART is set by the UCSZ2:0, UPM1:0, and USBS bits in UCSRB and UCSRC. The Receiver and Transmitter use the same setting. Note that changing the setting of any of these bits will ...
Page 150
Assembly Code Example USART_Init: C Code Example #define FOSC 1843200// Clock Speed #define BAUD 9600 #define MYUBRR FOSC/16/BAUD-1 void main( void ) { } void USART_Init( unsigned int ubrr Note: More advanced initialization routines can be made that ...
Page 151
The Shift Register is loaded with new data idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. When the Shift Register is loaded with new data, ...
Page 152
Sending Frames with If 9-bit characters are used (UCSZ = 7), the ninth bit must be written to the TXB8 bit in UCSRB 9 Data Bit before the Low byte of the character is written to UDR. The following code ...
Page 153
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. The TXC Flag bit is automatically ...
Page 154
Data Reception – The USART Receiver is enabled by writing the Receive Enable (RXEN) bit in the UCSRB Regis- The USART ter to one. When the receiver is enabled, the normal pin operation of the RxD pin is overridden by ...
Page 155
Receiving Frames with If 9 bit characters are used (UCSZ=7) the ninth bit must be read from the RXB8 bit in UCSRB 9 Databits before reading the low bits from the UDR. This rule applies to the FE, DOR and ...
Page 156
The receive function example reads all the I/O Registers into the Register File before any com- putation is done. This gives an optimal receive buffer utilization since the buffer location read will be free to accept new data as early ...
Page 157
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 (that is, the RXEN is set to zero) the Receiver will no longer override the ...
Page 158
If two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the receiver starts looking for ...
Page 159
Asynchronous The operational range of the receiver is dependent on the mismatch between the received bit Operational Range rate and the internally generated baud rate. If the Transmitter is sending frames at too fast or too slow bit rates, or ...
Page 160
Table 62. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode (U2X = 1) # (Data+Parity Bit) The recommendations of the maximum receiver baud rate error was made under the assump- tion that the receiver and transmitter equally divides ...
Page 161
Multi-processor Setting the Multi-processor Communication mode (MPCM) bit in UCSRA enables a filtering Communication 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. ...
Page 162
Accessing The UBRRH Register shares the same I/O location as the UCSRC Register. Therefore some UBRRH/ UCSRC special consideration must be taken when accessing this I/O location. Registers Write Access When doing a write access of this I/O location, the ...
Page 163
The following code example shows how to read the UCSRC Register contents. Assembly Code Example USART_ReadUCSRC: C Code Example unsigned char USART_ReadUCSRC( void ) { } Note: The assembly code example returns the UCSRC value in r16. Reading the UBRRH ...
Page 164
USART Control and Status Register A – Bit UCSRA Read/Write Initial Value • Bit 7 – RXC: USART Receive Complete This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer ...
Page 165
Bit 0 – MPCM: Multi-processor Communication Mode This bit enables the Multi-processor Communication mode. When the MPCM bit is written to one, all the incoming frames received by the USART receiver that do not contain address infor- mation will ...
Page 166
Bit 0 – TXB8: Transmit Data Bit 8 TXB8 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. Must be written before writing the low bits to UDR. ...
Page 167
Bit 2:1 – UCSZ1:0: Character Size The UCSZ1:0 bits combined with the UCSZ2 bit in UCSRB sets the number of data bits (Char- acter Size frame the Receiver and Transmitter use. Table 66. UCSZ Bits Settings UCSZ2 ...
Page 168
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 four most significant bits, and the UBRRL contains the 8 least significant bits of the USART ...
Page 169
Table 69. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued 3.6864 MHz osc Baud U2X = 0 Rate (bps) UBRR Error UBRR 2400 95 0.0% 191 4800 47 0.0% 95 9600 23 0.0% 47 14.4k 15 ...
Page 170
Table 70. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued 8.0000 MHz osc Baud U2X = 0 Rate (bps) UBRR Error UBRR 2400 207 0.2% 416 4800 103 0.2% 207 9600 51 0.2% 103 14.4k 34 ...
Page 171
Table 71. Examples of UBRR Settings for Commonly Used Oscillator Frequencies (Continued 16.0000 MHz osc Baud U2X = 0 Rate (bps) UBRR Error UBRR 2400 416 -0.1% 832 4800 207 0.2% 416 9600 103 0.2% 207 14.4k 68 ...
Page 172
Two-wire Serial Interface Features • Simple Yet Powerful and Flexible Communication Interface, Only Two Bus Lines Needed • Both Master and Slave Operation Supported • Device Can Operate as Transmitter or Receiver • 7-bit Address Space allows up to 128 ...
Page 173
Electrical As depicted in Interconnection 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 ...
Page 174
Figure 78. START, REPEATED START, and STOP Conditions SDA SCL Address Packet All address packets transmitted on the TWI bus are nine bits long, consisting of seven address Format bits, one READ/WRITE control bit and an acknowledge bit. If the ...
Page 175
Data Packet Format All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the Master generates the clock and the START and STOP conditions, while ...
Page 176
Multi-master Bus The TWI protocol allows bus systems with several Masters. Special concerns have been taken Systems, in order to ensure that transmissions will proceed as normal, even if two or more Masters initiate a transmission at the same time. ...
Page 177
Figure 83. Arbitration between Two Masters Synchronized 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 ...
Page 178
Overview of the The TWI module is comprised of several submodules, as shown in TWI Module in a thick line are accessible through the AVR data bus. Figure 84. Overview of the TWI Module SCL and SDA Pins These pins ...
Page 179
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 Regis- ter is not directly accessible by the ...
Page 180
TWI Register Description TWI Bit Rate Register – TWBR Bit Read/Write Initial Value • 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 ...
Page 181
START condition to claim the bus Master status. TWSTA must be cleared by software when the START condition has been transmitted. • Bit 4 – TWSTO: TWI STOP Condition Bit Writing the TWSTO ...
Page 182
Bits 1..0 – TWPS: TWI Prescaler Bits These bits can be read and written, and control the bit rate prescaler. Table 73. TWI Bit Rate Prescaler To calculate bit rates, see used in the equation. TWI Data Register – ...
Page 183
Bit 0 – TWGCE: TWI General Call Recognition Enable Bit If set, this bit enables the recognition of a General Call given over the Two-wire Serial Bus. Using the TWI The AVR TWI is byte-oriented and interrupt based. Interrupts ...
Page 184
SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Which value to write is described later on. However important that the TWINT bit is set in ...
Page 185
Assembly code example ldi r16, (1<<TWINT)|(1<<TWSTA)| 1 (1<<TWEN) out TWCR, r16 wait1 r16,TWCR sbrs r16,TWINT rjmp wait1 in r16,TWSR 3 andi r16, 0xF8 cpi r16, START brne ERROR ldi r16, SLA_W out TWDR, r16 ldi r16, (1<<TWINT) | ...
Page 186
Transmission The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Modes Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As ...
Page 187
A START condition is sent by writing the following value to TWCR: TWCR Value TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written ...
Page 188
Table 74. Status Codes for Master Transmitter Mode $18 SLA+W has been transmitted; ACK has been received $20 SLA+W has been transmitted; NOT ACK has been received $28 Data byte has been transmitted; ACK has been received $30 Data byte ...
Page 189
Figure 87. Formats and States in the Master Transmitter Mode Successfull transmission to a slave receiver Next transfer started with a repeated start condition Not acknowledge received after the slave address Not acknowledge received after a data byte Arbitration lost ...
Page 190
Figure 88. Data Transfer in Master Receiver Mode SDA SCL A START condition is sent by writing the following value to TWCR: TWCR Value TWEN must be written to one to enable the Two-wire Serial Interface, TWSTA must be written ...
Page 191
Table 75. Status Codes for Master Receiver Mode (Continued) $08 A START condition has been transmitted $10 A repeated START condition has been transmitted $38 Arbitration lost in SLA+R or NOT ACK bit $40 SLA+R has been transmitted; ACK has ...
Page 192
Slave Receiver Mode In the Slave Receiver mode, a number of data bytes are received from a Master Transmitter (see Figure zero or are masked to zero. Figure 90. Data Transfer in Slave Receiver Mode SDA SCL To initiate the ...
Page 193
Note that the Two-wire Serial Interface Data Register – TWDR does not reflect the last byte present on the bus when waking up from these sleep modes. 2466T–AVR–07/10 ATmega16(L) 193 ...
Page 194
Table 76. Status Codes for Slave Receiver Mode Status Code (TWSR) Status of the Two-wire Serial Bus Prescaler Bits and Two-wire Serial Interface are 0 Hardware $60 Own SLA+W has been received; ACK has been returned $68 Arbitration lost in ...
Page 195
Figure 91. Formats and States in the Slave Receiver Mode Slave Transmitter In the Slave Transmitter mode, a number of data bytes are transmitted to a Master Receiver Mode (see Figure zero or are masked to zero. Figure 92. Data ...
Page 196
The upper seven bits are the address to which the Two-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 ...
Page 197
Table 77. Status Codes for Slave Transmitter Mode Status Code (TWSR) Status of the Two-wire Serial Bus Prescaler Bits and Two-wire Serial Interface are 0 Hardware $A8 Own SLA+R has been received; ACK has been returned $B0 Arbitration lost in ...
Page 198
Figure 93. Formats and States in the Slave Transmitter Mode Reception of the own slave address and one or more data bytes Arbitration lost as master and addressed as slave Last data byte transmitted. Switched to not addressed slave (TWEA ...
Page 199
Combining Several In some cases, several TWI modes must be combined in order to complete the desired action. TWI Modes Consider for example reading data from a serial EEPROM. Typically, such a transfer involves the following steps: 1. The transfer ...
Page 200
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. ...