AVR055: Using a 32kHz XTAL for run-time calibration of the internal RC. 8-bit Microcontrollers. Application Note. Features.

Similar documents
ATA6140. Flasher Application Module. Application Note. ATA Flasher Application Module. 1. Description

Application Note. 8-bit Microcontrollers. AVR092: Replacing ATtiny11/12 by ATtiny13. Features. Introduction

Flasher, 18-mΩ Shunt, Frequency Doubling Disabling U6433B

Flasher, 30 mω Shunt, Pilot Lamp to GND or V Batt U2043B

Current Monitor IC U4793B

Flasher IC with U643B

8-bit Microcontroller. Application Note. AVR400: Low Cost A/D Converter

AVR443: Sensor-based control of three phase Brushless DC motor. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

Digital Window Watchdog Timer U5021M

8-bit RISC Microcontroller. Application Note. AVR182: Zero Cross Detector

Zero-voltage Switch with Adjustable Ramp T2117

PWM Power Control IC with Interference Suppression U6083B

Application Note. 8-Bit Microcontrollers. AVR433: Power Factor Corrector (PFC) with AT90PWM2 Re-triggable High Speed PSC

Application Note. How to Connect C51 Microcontroller to ATR Microcontrollers

Rear Window Heating Timer/ Long-term Timer U6046B

8-bit Microcontroller. Application Note. AVR084: Replacing ATmega323 by ATmega32. Features. Introduction. ATmega323 Errata Corrected in ATmega32

AVR053: Calibration of the internal RC oscillator. 8-bit Microcontrollers. Application Note. Features. Introduction

Application Note. Preliminary. 8-bit Microcontrollers

Low-power Flasher IC with 18-m Shunt U6432B

AVR443: Sensorbased control of three phase Brushless DC motor. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

300-MHz Quadrature Modulator U2793B

Transceiver Base Station Board ATAB542x-x-B. Application Note. Bill of Materials and Implementation of the Transceiver Base Station Board ATAB542x-x-B

Zero-voltage Switch with Adjustable Ramp T2117

AVR122: Calibration of the AVR's internal temperature reference. 8-bit Microcontrollers. Application Note. Features.

Low-power Audio Amplifier for Telephone Applications U4083B

Transceiver Base Station Board ATAB5823-x-B/ ATAB5824-x-B. Application Note

Read/Write Crypto Transponder for Short Cycle Time TK5561A-PP

IR Receiver for Data Communication U2538B

Programmable SLI AT94K AT94S. Application Note. DTMF Generator

Two-relay Flasher ATA6140

Low-cost Phase-control IC with Soft Start U2008B

8-bit Microcontroller. Application Note. AVR083: Replacing ATmega163 by ATmega16

AVR1606: XMEGA Internal RC Oscillator Calibration. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

AVR1302: Using the XMEGA Analog Comparator. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

8-bit Microcontroller. Application Note. AVR085: Replacing AT90S8515 by ATmega8515. Features. Introduction. AT90S8515 Errata Corrected in ATmega8515

AVR1311: Using the XMEGA Timer/Counter Extensions. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

MHz High Linearity SiGe Active Receive Mixer T0782. Preliminary

Read-only Transponder TK5530

1000-MHz Quadrature Modulator U2790B. Features. Benefits. Description. Electrostatic sensitive device. Observe precautions for handling.

1-Megabit (64K x 16) OTP EPROM AT27C1024

Standard Read/Write ID Transponder with Anticollision TK5551

ATAVRAUTO User Guide

8-bit Microcontroller. Application Note. AVR086: Replacing AT90S8535 by ATmega8535

8-bit RISC Microcontroller. Application Note. AVR314: DTMF Generator

1-Megabit (128K x 8) OTP EPROM AT27C010

2-Megabit (128K x 16) OTP EPROM AT27C2048

UHF ASK Transmitter U2745B

Phase-control IC with Current Feedback and. Overload. Protection U2010B

AVR1003: Using the XMEGA Clock System. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

Special Fail-safe IC U6808B

UHF ASK/FSK Receiver ATA5721 ATA5722. Features

128-bit Read-only IDIC for RF Identification. e5530

8-Megabit (1M x 8) OTP EPROM AT27C080. Features. Description. Pin Configurations

UHF ASK/FSK Transmitter U2741B

8-bit Microcontroller with 2K Bytes In-System Programmable Flash. ATtiny261A. Appendix A. Appendix A ATtiny261A Specification at 105 C

2.4-GHz SiGe Power Amplifier for b/g WLAN Systems T7031. Preliminary

APPLICATION NOTE. AT11009: Migration from ATxmega64D3/128D3/192D3/256D3 Revision E to Revision I. Introduction. Features.

8-bit RISC Microcontroller. Application Note. AVR042: AVR Hardware Design Considerations

High-speed CAN Transceiver ATA6660

Highperformance EE PLD ATF16LV8C

UHF ASK/FSK. Transmitter T5754

Read/Write Base Station U2270B

8-bit. Application Note. Microcontrollers. AVR077: Opto Isolated Emulation for the DebugWIRE

Multifunction Timer IC U2102B

Flasher IC with 18-mΩ Shunt U6043B

APPLICATION NOTE. Atmel AVR127: Understanding ADC Parameters. Atmel 8-bit Microcontroller. Features. Introduction

AT91 ARM Thumb Microcontroller s. AT91R40807 Electrical Characteristics

Smart RF AT86RF401-EK1. Application Note. AT86RF401-EK1 Smart RF MicroTransmitter Evaluation Kit Application Note. Functional Description

Atmel ATA6629/ Atmel ATA6631 Development Board V2.2. Application Note. Atmel ATA6629/ATA6631 Development Board V

3-wire Serial EEPROM AT93C86. Features. Description. Pin Configurations. 16K (2048 x 8 or 1024 x 16)

Phase Control IC for Tacho Applications U209B

Atmel U6032B. Automotive Toggle Switch IC DATASHEET. Features. Description

3-wire Serial EEPROM AT93C86. Features. Description. Pin Configurations 8-lead PDIP. 16K (2048 x 8 or 1024 x 16)

ATF15xx Power-On Reset Hysteresis Feature. Abstract. Features. Complex Programmable Logic Device APPLICATION NOTE

Power Management AT73C211

AT91 ARM Thumb Microcontrollers. AT91R40008 Electrical Characteristics. Features. Description

3-wire Serial EEPROM AT93C86A. Preliminary. Features. Description. Pin Configurations. 16K (2048 x 8 or 1024 x 16) VCC DC ORG GND CS SK DI DO

AT91 ARM Thumb Microcontrollers. AT91R40008 Electrical Characteristics

8-bit Microcontroller. Application Note. AVR081: Replacing AT90S4433 by ATmega8. Features. Introduction. AT90S4433 Errata Corrected in ATmega8

ATAK57xx Software Description. Application Note. Preliminary. Software Description RF Design Kit ATAK57xx. Description

Rad Hard 128K x volt Very Low Power CMOS SRAM M65609E

1-Megabit (64K x 16) OTP EPROM AT27C1024

4-Megabit (256K x 16) OTP EPROM AT27C4096

Power Meter Front End Design: The Delta Connection. Application Note. Power Meter Front End Design: The Delta Connection. Three-Phase Basics

AT15291: Migrating QTouch Designs from SAM D MCUs to SAM C MCUs. Scope. Features. QTouch APPLICATION NOTE

Low-cost Phase-control IC with Soft Start

Time-code Receiver T4227

AVR440: Sensorless Control of Two-Phase Brushless DC Motor. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

256K (32K x 8) Unregulated Battery-Voltage High-Speed OTP EPROM AT27BV256

AT14164: User Calibration of Internal Temperature Sensor - SAM R21. Introduction. SMART ARM-based MCUs APPLICATION NOTE

L-band Down-converter for DAB Receivers U2730B-N. Preliminary

Rad. Tolerant 8K x 8-5 volts Very Low Power CMOS SRAM AT65609EHW

AVR042: AVR Hardware Design Considerations. 8-bit Microcontrollers. Application Note. Features. 1 Introduction

Standard Read/Write Crypto Identification IC. e5561

Very Highresolution. Linear CCD Image Sensor (12000 Pixels) TH7834C. Features. Description

Low-noise, High-dynamicrange. Antenna Amplifier IC ATR4251. Preliminary

2-megabit (256K x 8) Unregulated Battery-Voltage High-speed OTP EPROM AT27BV020

8-bit Microcontroller. Application Note. AVR040: EMC Design Considerations. Scope. Introduction

Rad. Tolerant 128Kx8, 5-Volt Very Low Power CMOS SRAM M65608E

APPLICATION NOTE. Atmel AVR2067: Crystal Characterization for AVR RF. Atmel MCU Wireless. Features. Description

Transcription:

AVR055: Using a 32kHz XTAL for run-time calibration of the internal RC Features Calibration using a 32 khz external crystal Adjustable RC frequency with maximum +/-2% accuracy Tune RC oscillator at any operating voltage and temperature Tune RC oscillator to any frequency within specification Full source code written in C Support for all AVRs with tunable RC oscillator and asynchronous timer Selectable calibration clock frequency 8-bit Microcontrollers Application Note 1 Introduction The majority of the present AVR microcontrollers offer the possibility to run from an internal RC oscillator. The internal RC oscillator frequency can in most AVRs be calibrated to within +/-2% of the frequency specified in the datasheet for the device, for some devices even +/-1% accuracy is achievable. The calibration performed in the Atmel factory is made at a fixed operating voltage and temperature. As the frequency of the internal RC oscillator is affected by both operating voltage and temperature, it is sometimes desirable to perform a secondary calibration. AVR devices with internal RC Oscillator and an OSCCAL Calibration Register can be calibrated very accurately by using an external signal with stable frequency such as a 32 khz watch crystal. This secondary calibration can be useful if running the device at a temperature or supply voltage level different from the default values (25 C, typically 5V) matching the specific application environment, or even to tune the oscillator to a different frequency. Using an external watch crystal for internal oscillator run-time calibration results in a cost efficient solution for applications that needs an accurate system clock over the entire temperature range, and independent of operating voltage. This application note describes a fast and accurate way to calibrate the internal RC oscillator using an external 32.768 khz crystal as input to an asynchronous Timer/Counter. Rev.

2 Theory of operation the internal RC oscillator In production the internal RC is calibrated at either 5V or 3.3V. Refer to the datasheet of the individual devices for information about the operating voltage used during calibration. The accuracy of the factory calibration is within +/-3 or +/-10% (refer to the datasheet). If a design s need for accuracy is beyond what can be offered by the standard calibration in factory by Atmel, it is possible to perform a secondary calibration of the RC oscillator. By doing this it is possible to obtain frequency accuracy within +/-1 (+/-2% for those with an 10% accuracy from factory calibration). A secondary calibration can thus be performed to improve or tailor the accuracy or frequency of the oscillator. 3 Clock selection 4 Crystal Connection 5 Base-frequency 2 AVR055 The AVR fuse settings control the system clock source being used. To use the internal oscillator, the corresponding fuse setting must be selected. An overview of the fuses is available in the datasheets. When calibrating using an external crystal, the system clock must run from the internal oscillator. In most AVR devices, external capacitors need to be connected to the TOSC1/2 pins, when connecting an external crystal. This applies to all parts with 1.8V capabilities. In other parts, the crystal can be connected directly between the TOSC1/2 pins. Refer do the device datasheet for details on crystal connections. The following sections provide an overview of the internal RC oscillators available in the AVR microcontrollers. Some AVRs have one RC oscillator, while others have up to 4 different RC oscillators to choose from. The frequency ranges from 1MHz to 9.6MHz. To make the internal RC oscillator sufficiently accurate, an Oscillator Calibration register, OSCCAL, is present in the AVR I/O file. The OSCCAL register is one byte wide. The purpose of this register is to be able to tune the oscillator frequency. This tuning is utilized when calibrating the RC oscillator. When calibrating using an external crystal, the device timer must have the possibility to operate asynchronously of the system clock. When a device is calibrated by Atmel, the calibration byte is stored in the Signature Row of the device. The calibration byte can vary from one device to the other, as the RC oscillator frequency is process dependent. If a device has more than one oscillator, a calibration byte for each of the RC oscillators is stored in the Signature Row. The default RC oscillator calibration byte is in most devices automatically loaded from the Signature Row and copied into the OSCCAL register at start-up. For example, the default ATmega8 clock setting is the internal 1MHz RC oscillator; for this device the calibration byte corresponding to the 1MHz RC oscillator is automatically loaded at start-up. If the fuses are altered so that the 4MHz oscillator is used instead of the default setting, the calibration byte must be loaded into the OSCCAL register manually. A programming tool can be used to read the 4MHz calibration byte from the

AVR055 Signature Row, and store it in a Flash or EEPROM location, which is read by the main program and copied into OSCCAL at run-time. In addition to the oscillator tuning using the OSCCAL register, some devices feature a system clock prescaler. The prescaler register (CLKPR) can be used to scale the system clock with predefined twos complement factors. Also, this prescaler can be preset through the AVR fuses; programming the CKDIV8 fuse will set the CLKPR to divide the system clock by 8. This can be done to ensure that the device is operated below a maximum frequency specification. The CLKPR can be modified at run-time to change the frequency of the system clock internally. The base frequency of an oscillator is defined as the unscaled oscillator frequency. 6 RC Oscillator overview 6.1 Version 1.x oscillators 6.2 Version 2.x oscillators Different RC oscillators have been utilized in the AVR microcontrollers throughout the history. An overview of the RC oscillators and some example devices is seen in Table 6-1. The device list is sorted by oscillator type, which is also more or less equivalent to sorting them by release date. Only example devices with tunable oscillators, and the possibility to operate asynchronously from an external crystal are listed in the table. For a complete list of supported devices, refer to the device_specific.h header file of the source code. Table 6-1.Oscillator frequencies and features of devices with internal RC oscillator(s). Grouped by oscillator version. Oscillator version Device RC oscillator frequency [MHz] CKDIV CLKPR 2.0 ATmega163 1.0 - - 3.0 ATmega16 1.0, 2.0, 4.0, and 8.0 - - 3.1 ATmega128 (1) 1.0, 2.0, 4.0, and 8.0 - XDIV (2) 4.0 ATmega169 8.0 Yes Yes 5.0 ATmega169P 8.0 Yes Yes Notes: 1. The ATmega103 Compatible Mode fuse must be unprogrammed. Programming this fuse prevents using extended I/O and hence tuning the internal oscillator. 2. The prescaler register is in these devices named XDIV. Note the when calibrating the ATCAN90 device (oscillator version 5.0) using the STK501 top module, an external crystal other than the 32kHz crystal of the STK501 is required for calibration within the accuracy limits of +/-2%. Refer to the device datasheet for details on external crystal connection. This version is the earliest internal RC for AVR that can be calibrated, though asynchronous operation is not possible. Due to this, parts having this version of the internal oscillator cannot be calibrated using an external crystal and does not appear in Table 6-1. This oscillator is offered with a frequency of 1MHz. The dependency between the oscillator frequency and operating voltage and temperature is reduced significantly compared to version 1.x. 3

6.3 Version 3.x oscillators 6.4 Version 4.x oscillators 6.5 Version 5.x oscillators 7 Oscillator characteristics This version was introduced along with the first devices produced in the 35.5k process. The oscillator system is expanded to offer multiple oscillator frequencies. Four different RC oscillators with the frequencies 1, 2, 4, and 8MHz are present in the device. This version features automatic loading of the 1MHz calibration byte from the Signature Row. Due to the fact that 4 different RC oscillators are present, 4 different calibration bytes are stored in the Signature Row. If frequencies other than the default 1MHz are desired, the OSCCAL register should be loaded with the corresponding calibration byte at run-time. A single oscillator frequency of 8MHz is offered in version 4.0. For later 4.x versions, two frequencies are offered: 4 and 8MHz for ATtiny2313, and 4.8 and 9.6MHz for the ATtiny13. The OSCCAL register is changed so that only 7 bits are used to tune the frequency for the selected oscillator. The MSB is not used. Auto loading of the default calibration value and system clock prescaler is present. A single oscillator frequency of 8MHz is offered in version 5.0 All 8 bits in the OSCCAL register are used to tune the oscillator frequency. Auto loading of the default calibration value and system clock prescaler is present. The OSCCAL register is split in two parts. As seen in Figure 7-2, the MSB of OSCCAL selects one of two overlapping frequency ranges, while the 7 least significant bits are used to tune the frequency within this range. The frequency of the internal RC oscillator is depending on the temperature and operating voltage. An example of this dependency is seen in Figure 7-1, showing the frequency of the 8MHz RC oscillator of the ATmega3290. As seen from the figure, the frequency increases with increasing temperature and operating voltage. These characteristics will vary from device to device. For details on a specific device refer to its datasheet. 4 AVR055

AVR055 Figure 7-1. Oscillator frequency and influence by temperature and operating voltage. ATmega3290 calibrated 8MHz RC oscillator frequency vs. V CC. 8.6 CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. V CC F RC (MHz) 8.4 8.2 8 7.8 85 C 25 C -40 C 7.6 7.4 7.2 1.5 2 2.5 3 3.5 4 4.5 5 5.5 V CC (V) All devices with tunable oscillators have an OSCCAL register for tuning the oscillator frequency. An increasing value in OSCCAL will result in a pseudo-monotone increase in frequency. The reason for calling it pseudo-monotone is that for some unity increases of the OSCCAL value, the frequency will not increase, or even decrease slightly. However, the next unity increase will always increase the frequency again. In other words, incrementing the OSCCAL register by one may not increase the frequency, but increasing the OSCCAL value by two will always increase the frequency. This information is very relevant when searching for the best calibration value to fit a given frequency. An example of the pseudo-monotone relation between the OSCCAL value and the oscillator frequency can be seen in Figure 7-2, which is the 8MHz RC oscillator of ATmega3290. Note that some OSCCAL registers, that is OSCCAL registers in devices with version 5.0 oscillators, uses 7 bits for tuning the oscillator, as is the case in ATmega3290. The eight bit determines the range of operation. The two ranges are overlapping, as seen in Figure 7-2. Other devices use all 8 (or sometimes 7) bits in one continuous range 5

Figure 7-2. ATmega3290 calibrated RC oscillator frequency as a function of the OSCCAL value. CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE 16 14 85 C 25 C -40 C 12 F RC (M Hz) 10 8 6 7.1 Frequency settling time 8 Calibration using a 32.768 khz crystal 4 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 OSCCAL VALUE For all tunable oscillators it is important to notice that it is not recommended to tune the oscillator more than 10% off the base frequency specified in the datasheet. The reason for this is that the internal timing related to writing EEPROM and flash in the device is dependent on the RC-oscillator frequency. Knowing the fundamental characteristics of the RC oscillators, it is possible to make an efficient calibration routine that calibrates the RC oscillator to a given frequency, within 10% of the base frequency, at any operating voltage and at any temperature with an accuracy of +/-1%. When a new OSCCAL value has been set, it can take some time for the internal RC oscillator to settle at the new frequency. This settling time will vary on the different versions of the RC oscillator. Generally, the oscillator settles faster for small changes in OSCCAL, than for large changes. This settling time is under no circumstances any longer than 5 microseconds. Allow the oscillator to settle at its new frequency before making any frequency measurements for calibration. The calibration is executed in a 6 or 7 cycles loop, depending on whether the asynchronous timer/counter register is located in extended I/O space or not. In every loop, a counter is incremented, and the value of the 32 khz timer is read. After a (predefined) number of ticks on the 32 khz watch crystal, a counter which speed depends on the internal RC oscillator, is compared with the timer value. Then the value of the oscillator calibration register OSCCAL is written according to the desired calibration frequency, using binary and neighbor search. 6 AVR055

AVR055 The relation between the repeat count value and the frequency can be obtained from the following equation: Equation 8-1. Calculating the count value Loop Cycles Count value RC period = XTAL period XTAL ticks where : RC period = desired 1 frequency XTAL period = 1 XTAL frequency 9 Binary and Neighbor search Three different calibration methods are described in this application note. They are different in the way the search is performed and have different code sizes and durations. In section 7 it was pointed out that some internal oscillators have a divided OSCCAL register which is overlapping for some of the frequencies in the frequency range. For these oscillators, a search in both ranges of the OSCCAL is needed to guarantee calibration to all frequencies. Figure 7-2 illustrates that it may also be convenient to compare calibrations in both ranges of the OSCCAL for overlapping frequencies in order to obtain the optimal OSCCAL value since, for instance, a frequency of 8 MHz is reached for both OSCCAL values ~104 and ~144 in ATmega3290. 9.1 The binary search A binary search is used to find the OSCCAL value that will make the internal RC oscillator produce the desired frequency. The binary search works in the following way: 1. Start with an OSCCAL value in the middle of the search-range. 2. Set step-size to 1/4 of the search range. 3. Decide if the current frequency is too high or too low. 4. If the current frequency is too high, subtract step-size from OSCCAL. If it is too low, add step-size to OSCCAL. If frequency is just right, do not change OSCCAL and abort since no further calibration is needed. 5. Divide step-size by 2. 6. If step-size is 0, the search is complete. Jump to neighbor search (described later). 7. Jump to step 3 This search method is optimal (when it comes to worst-case run time) when searching data with a strictly monotone relationship. As mentioned in section 7, the relationship between OSCCAL and resulting oscillator frequency is not completely monotone. However, it is close enough for the binary search to be the most efficient way to find a value in the neighborhood of the optimal OSCCAL value. From this point it is easy to find the optimal value. 7

9.2 The neighbor search 9.3 Simple search 9.4 Accuracy 8 AVR055 In this search method, the neighbor values have to be examined. A binary search has to be done prior to using this method. Since an increase in clock frequency is guaranteed when increasing OSCCAL by a value of 2 or more, problems are only expected at the last iteration of the binary search, when the step-size is 1. In this case an increased OSCCAL value might result in a decrease in clock frequency, and vice versa. One more step in the same direction guarantees a frequency change in the desired direction. This step might however just be large enough to counter the effect of the last step. Thus, to make sure that the optimal OSCCAL value is found, one more step should be taken. The Timer/Counter0 value of each of these iterations is then saved, and compared with the desired number of clock cycles. The OSCCAL value that produces the clock frequency closest to the desired frequency is used. This will be referred to as a neighbor search. Since additional code is required to implement the neighbor search, this could be omitted when the need for accuracy is less important than the code size. This method is very easy to implement, and gives reduced code size compared to binary search and binary with neighbor search. It has, however, a higher worst-case run-time. The search works as follows: 1. Start with an OSCCAL value in the middle of the search-range i.e. ½ of the OSCCAL resolution. 2. If the frequency is to high, subtract OSCCAL with one. Add one if frequency is to low. Abort if oscillator frequency has reached desired frequency. 3. Repeat step n times, where n is OSCCAL resolution divided by two. This last method is obviously slower than the first, but occupies less memory space due to its small code size. This method can also be used in fine-tuning, where step 1 is omitted and calibration is run from current OSCCAL. The repeat factor n can in this case be reduced considerably, sometimes just a few steps might be needed. A big drawback is that the simple search does not evaluate the goodness of the calibration, and hence will continue until it has done calibration cycles equal to ½ of the OSCCAL resolution unless perfect calibration is obtained. The accuracy of the search depends on the search method used: If only the binary search is used, the optimal OSCCAL value is not always found. However, the frequency found should still be within +/-2% of the desired frequency for parts that can be calibrated to +/-1% of target frequency. When the binary search is used alone, the search should abort when a system clock frequency within the required accuracy limits is found. This should be done to avoid problems in the last step due to the pseudo-monotone relation between OSCCAL and internal RC oscillator frequency. When the neighbor search is used in addition to the binary search, the optimal OSCCAL value will always be found if it lies inside the search range. The resulting clock frequency will be within +/-1% of the desired frequency for parts supporting this accuracy. The search is only aborted if a perfect match is found, i.e. the measured number of CPU cycles during a given amount of ticks on the external crystal exactly matches the desired number of CPU clock cycles. When the search is finished

AVR055 without finding a perfect match, the calibrated OSCCAL value is the value that best matches the desired frequency. Even if there is an OSCCAL value that produces a clock frequency closer to the desired value, we will not be able to measure the difference. Further search is thus not necessary. Accuracy can also be adjusted by increasing the amount of ticks on the external crystal, improving measurement accuracy. Few ticks will give fast calibration, but lower accuracy. Increasing the number up to a certain limit will increase accuracy. Notice that a higher amount of ticks does not necessarily increase the accuracy, since the resolution on the OSCCAL register is fixed. Improving the measurement accuracy does not improve the OSCCAL accuracy. 10 Implementation 10.1 Hardware 10.2 Software This section describes how the run-time calibration can be implemented on an AVR. A working implementation written in C is included with this application note. Full documentation of the source code and compilation information is found by opening the readme.html file included with the source code. This application uses a 32.768 khz watch crystal for oscillator calibration, as it is the optimal choice, both economically, and when it comes to frequency stability. The lowfrequency crystal oscillator is designed for use with crystal running at this frequency. It is important to notice that the external watch crystal needs time to stabilize. This applies to situations when the crystal is not already running prior to calibration. In the following sections, the firmware needed to do run-time calibration is described. The main idea is to run a counter asynchronously on a separate 32KHz watch crystal for a certain number of cycles. Meanwhile a simple CPU loop is done, incrementing a word. Knowing the number of cycles of the inner loop, and assuming the asynchronous timer is correct; the CPU will count to a certain level. Then comparing to a number corresponding to the desired frequency, one can adjust the CPU frequency up/down through OSCCAL. 10.2.1 Defining the search range Some devices have a divided OSCCAL register. As shown in Figure 7-2, the ATmega3290 OSCCAL register has two ranges, one going from values 0 to 127, the other from 128 to 255. When calibrating to a frequency between ~7 MHz and ~10 MHz, there are two possible OSCCAL values that gives an appropriate and satisfying frequency. Before calibration can start, knowledge about the device OSCCAL register size is needed. A macro checks if the OSCCAL register is divided in two or not for the specific device. If the OSCCAL is divided, the search is first done in the lower part of OSCCAL followed by a search in the upper part as long as no perfect match is obtained during the first search. After a second search, the two calibrations are compared, and the optimal value found. 9

For devices with one 8 bit (or 7 bit in some devices) range containing all possible frequencies, only one search range is defined and a double search and comparison is unnecessary. 10.2.2 Initiating calibration Before starting the calibration, OSCCAL should be written according to the value equal to ½ of the search range. For parts with a two-range OSCCAL, calibration starts in the lower OSCCAL, and OSCCAL is written to ½ of the lower search range. This is done to make the binary search work properly. The asynchronous timer must be set up properly in order to use an external watch crystal as clock source. The Asynchronous (AS) bit in the ASSR register must be set to ensure that the timer is asynchronous from the CPU clock with at external crystal driving it. If interrupts are used, these must be disabled prior to using the counter function in order to ensure correct calibration. 10.2.3 Defining the count value When calibrating to a desired frequency, the count value in Equation 8-1 is needed. This equation is implemented as a macro, using the device specific loop cycle value. The number of loop cycles is 6 for devices with the TCNT register located in standard I/O space, and 7 in devices with the TCNT register located in extended I/O. Now having the count value, and using the counter function to increment the counter, the counter and the desired count value can be compared to proceed with the calibration. Figure 10-1. The counter function Counter Set counter = 0 Reset asynchronous timer Wait for update on asynchronous timer counter < XTAL ticks No Increment counter Return Yes It is important that interrupt is disabled in order to ensure proper operation of the counter function and the asynchronous timer. 10.3 Searching When a fast calibration procedure is needed, a binary search performs better than any other search method. When combining it with neighbor search, greater accuracy is achieved, since the relation between the OSCCAL value and the oscillator frequency is pseudo-monotone. There is no guarantee that the binary search will reach the optimal value when the relationship is not strictly monotone. The neighbor search can be omitted without a considerable loss of accuracy as mentioned in section 9.4, and also improve run-time and reduce code size. The neighbor search will be omitted whenever perfect calibration is reached. 10 AVR055

AVR055 Figure 10-2. The binary- and neighbor search functions Binary Search Neighbor Search Counter < Count Value Set sign = 1 Compare counter with Count Value Counter > Count Value Set sign = -1 No Increment neighbors searched Sufficient neighbors searched? Yes Inrease OSCCAL with stepsize Perfect match Calibration finished Divide stepsize by two Derease OSCCAL with stepsize Increment OSSCAL with sign Write best OSCCAL Calibration finished Return Return It can be noticed that when the OSCCAL value of the desired calibration frequency is close to the OSCCAL value of the running frequency, the simple search method may be a better choice. Leaving the OSCCAL register unchanged prior to calibrating, only a few steps might be necessary. This may be interesting in cases such as fine-tuning or re-calibrating as it reduces code size and can outperform binary search when it comes to time consumption. 10.3.1 Calibration The calibration routine will do a binary search until the step size reaches zero, or finish if a prefect match should occur during binary searching. When the step-size has reached zero, neighbor search begins. The optimal OSCCAL is obtained by evaluating the difference between the count value corresponding to the desired frequency, and the value returned by the counter function. The lowest deviation and the corresponding OSCCAL value is saved and the OSCCAL register is written according to the lowest deviation when the search is finished, in order to obtain the optimal value. 11

Figure 10-3. The calibrate routine, implementing neighbor and binary search Calibrate Calibration status Running Binary Search Counter No Stepsize = 0? Not started Yes Neighbor search status Finished Running Compute count difference Compute count difference Count differnce decreased? Yes Save OSCCAL value and count difference Save OSCCAL value and count difference No Prepare and start neighbor search Neighbor Search Return In devices where the OSCCAL register contains two ranges, both of the ranges may hold a value that matches the desired frequency, but the value in one range may give a more accurate calibration than the other. The two calibrations are compared to guarantee that the best possible solution is found. When using devices with one OSCCAL range, double search is unnecessary. 12 AVR055

AVR055 Figure 10-4. The main routine Calibrate using XTAL Initiate Calibration Prepare calibration Calibrate Do a second search Save OSCCAL value and count difference Set search range to higher part of OSCCAL No Initiate Calibration Compute Count Value from desired frequency Write Default OSCCAL value Splitted OSCCAL register? Yes, second search performed Yes Count Difference = 0? Set Up Timer to be driven asynchronously by XTAL No Compare count differences Return First calibration closer to desired count Write OSCCAL according to first search Yes Return 10.4 Code size The source code included with this application note results in quite different code sizes when compiled, depending on calibration method, timer resolution, and type of OSCCAL register used. Table 10-1 shows some examples of code size for two devices, ATmega3290 with a divided OSCCAL register, and ATmega32 with a continuous OSCCAL register. Calibration cycles are also given to illustrate the duration. A calibration cycle means running the counter with or without a write to OSCCAL, using binary, neighbor or simple search. Table 10-1.Compiled code size and calibration cycles Device Calibration method Calibration Cycles Code size ATmega3290 ATmega32 Simple search max 128 ~270 B Binary search max 14 ~370 B Binary with neighbor search max 22 ~380 B Simple search max 128 ~240 B Binary search max 8 ~280 B Binary with neighbor search max 12 ~290 B 13

10.5 Performance of the Calibration firmware 10.6 Calibration Clock Accuracy The code has been written with focus on efficiency: The entire calibration should be performed fairly quickly. The performance therefore depends on the size of the calibration firmware and the time it takes to complete the calibration. The calibration firmware is 240 to 380 bytes, depending on the target device and calibration method used, giving short programming time. The calibration routine is completed in less than 22 (worst-case) calibration cycles for ATmega3290 and 12 for ATmega32, using binary with neighbor search. The duration is dependent on whether perfect calibration is reached during binary search or not. The accuracy of the calibration is highly dependent on the accuracy of the external calibration clock. It is therefore important to know the exact frequency of the crystal used and enter it into the interface specific source file. Using a 32.768 khz watch crystal, optimal accuracy is achieved. 11 Getting started The source code is compatible with all current AVR devices with a tunable internal oscillator and a timer with asynchronous operation mode. These devices are listed in the device_specific.h header file coming with the source code. Download the source code for AVR055 from www.atmel.com and unzip it. 11.1 Calibration source code All functions and the main routine are all collected in one file, calib_32khz.c. Macros, calibration specific values and flags, and device specific definitions are in separate header files. 11.1.1 Source code files The root file calib_32khz.c refers to the following files: 1. A device specific file, device_specific.h. This file will ensure that the root file uses the proper bit and register definitions corresponding to the selected device. 2. A calibration interface specific file, calib_values.h. This file holds the desired calibration value along with other values relevant to the calibration. Some macros are also defined, as well as flags choosing different calibration methods. 11.1.2 Performing a calibration calib_values.h contains several flags that must be set before compiling. Complete the following steps to tailor the source code for your needs. 1. If a search method other than binary with neighbor search is desired, uncomment one of the two CALIBRATION_METHOD_XXXXX lines. 2. Change the frequency to desired calibration frequency by modifying the CALIBRATION_FREQUENCY value, which is set to 1MHZ by default. 14 AVR055

AVR055 3. If crystals other than a 32.768 khz watch crystal is used, change XTAL_FREQUENCY according to the crystal used for calibration. 4. EXTERNAL_TICKS can be modified to decrease/increase accuracy and calibration running time. 100 ticks are recommended to guarantee +/-1% accuracy, but this number can be reduced to speed up the calibration. The maximum value is 255 due to the size of the asynchronous timer register. For most devices 40 ticks is feasible, but a higher value gives increased accuracy. 15

Disclaimer Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600 Regional Headquarters Europe Atmel Sarl Route des Arsenaux 41 Case Postale 80 CH-1705 Fribourg Switzerland Tel: (41) 26-426-5555 Fax: (41) 26-426-5500 Asia Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimshatsui East Kowloon Hong Kong Tel: (852) 2721-9778 Fax: (852) 2722-1369 Japan 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581 Atmel Operations Memory 2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314 Microcontrollers 2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314 La Chantrerie BP 70602 44306 Nantes Cedex 3, France Tel: (33) 2-40-18-18-18 Fax: (33) 2-40-18-19-60 ASIC/ASSP/Smart Cards Zone Industrielle 13106 Rousset Cedex, France Tel: (33) 4-42-53-60-00 Fax: (33) 4-42-53-60-01 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759 Scottish Enterprise Technology Park Maxwell Building East Kilbride G75 0QR, Scotland Tel: (44) 1355-803-000 Fax: (44) 1355-242-743 RF/Automotive Theresienstrasse 2 Postfach 3535 74025 Heilbronn, Germany Tel: (49) 71-31-67-0 Fax: (49) 71-31-67-2340 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759 Biometrics/Imaging/Hi-Rel MPU/ High Speed Converters/RF Datacom Avenue de Rochepleine BP 123 38521 Saint-Egreve Cedex, France Tel: (33) 4-76-58-30-00 Fax: (33) 4-76-58-34-80 Literature Requests www.atmel.com/literature Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel s products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. Atmel Corporation 2006. All rights reserved. Atmel, logo and combinations thereof, Everywhere You Are, AVR, AVR Studio and others, are the registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.