This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| en:avr:adc [2010/10/30 19:15] – allan.pettai | en:avr:adc [2020/07/20 12:00] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Analog-to-digital Converter ====== | ||
| + | Analog-to-digital converter (ADC) transforms an analog voltage value to a digital value. The allowed voltage range on an ADC input of an AVR microcontroller is 0 to 5.5 V. The size of the digital value is 10 bits, but its precision is ±2 units. The error may be even larger, if the microcontroller' | ||
| + | |||
| + | AVR ADC works on the principal of successive approximation. In short, the measured voltage is compared to specific voltage levels and the results are reported as a bit array. This method is relatively slow, as each bit in the final result is calculated separately. AVR spends 13 clock cycles for each measuring, except the first (on start-up), which takes 25 cycles. These cycles are not the controller' | ||
| + | |||
| + | The measured value can be read as an 8- or 10-bit value. Since AVR itself is an 8-bit device, it has two 8-bit registers for storing the ADC values. It is possible to specify in the settings whether the first two or the last two bits go to a separate register. If the two younger bits, which characterize the result less, are separated, the result can be read as an 8-bit value - a combination like that is called a left-aligned result. The other combination, | ||
| + | |||
| + | A typical AVR has 8 analog voltage input channels, ATtiny series have only a few, some ATmega devices have 16, but there is always only one converter. To make it possible to use different inputs, the device has a built-in multiplexer. The input of the multiplexer is definable using a special register. The ADC unit has a few more properties: using the processor' | ||
| + | |||
| + | < | ||
| + | |||
| + | <box 100% round # | ||
| + | |||
| + | Task: measure the voltage in ADC channel 3 of an ATmega128. The voltage is in range of 0-5 V and the result should be at 8-bit precision. | ||
| + | |||
| + | <code c> | ||
| + | #include < | ||
| + | |||
| + | int main() | ||
| + | { | ||
| + | unsigned char result; | ||
| + | |||
| + | // Choose AREF pin for the comparison voltage | ||
| + | // (it is assumed AREF is connected to the +5V supply) | ||
| + | // Choose channel 3 in the multiplexer | ||
| + | // Left align the result | ||
| + | ADMUX = (1 << REFS0) | (1 << ADLAR) | (3); | ||
| + | |||
| + | // Start the ADC unit, | ||
| + | // set the conversion cycle 16 times slower than the duty cycle | ||
| + | ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADSC); | ||
| + | |||
| + | // Wait for the measuring process to finish | ||
| + | while (ADCSRA & (1 << ADSC)) continue; | ||
| + | |||
| + | // Read the 8-bit value | ||
| + | result = ADCH; | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | </ | ||