# Analog to Digital Converter

#### Introduction

A lot of times when you deal with robotics, working only with +Vcc (Logic 1) and Ground (Logic 0) might not be enough. What if we have an analog input, i.e., value varies over a range, say 0V to +5V?
Then we require a tool that converts this analog voltage to discrete values. Analog to Digital Converter (ADC) is such a tool. In this tutorial, we shall learn the basic implementation of ADC in Atmel megaAVR devices in Single ended mode with code examples on ATmega16 to get started.

The ATmega16 ADC has 10-bit resolution. This means that an analog voltage between 0V and 5V will be encoded into one of 1024 binary representations via 8 channels that are port A pins from A0 to A7.

The reference voltage as shown in figure can be either less or equal to the supply voltage of the microcontroller.
This means that if you are using a 10 bit precision and 5V is the Vref, then, 0 corresponds to 0V, 1023 (2^10 - 1) corresponds to 5V. Similarly, the intermediate voltages correspond to their corresponding ADC value. So, what exactly is the output that we get from ADC?

ADC value is nothing but, the corresponding digital value given by:

#### Registers

You need to declare certain registers before you initiate ADC specifying the conditions it needs to follow.

ADSC: ADC Start Conversion bit, this bit is set to 1 to start ADC conversion, as soon as conversion is completed this bit is set back to 0 by the hardware.
ADATE: ADC Auto Trigger Enable, this bit is set to 1 to enable auto triggering of ADC conversion.
ADIE: ADC Interrupt Enable, this bit is set to 1 if we want to activate the ADC conversion complete interrupt.

ADC clock frequency = XTAL frequency / Prescaler
The ADC clock frequency must lie somewhere between 50 kHz to 200 kHz to get maximum resolution. If ADC resolution of less than 10 bits required, then the ADC clock frequency can be higher than 200 kHz. At 1 MHz it is possible to achieve eight bits of maximum resolution.

In the microcontroller we’re discussing, prescaler values of 2, 4, 8, 16, 32, 64 & 128 are provided. A typical core clock speed is 16 MHz. So if you are running your AVR board at 16 Mhz, you can set the ADC clock to one of the following values:

Since the ADC clock needs to be between 50 kHz & 200 kHz for 10 bit accuracy, we can only use the 128 prescaler and achieve a 125 kHz ADC clock.