Home / Learn Chip Programming / ADC and DAC: Reading Sensors and Making Analog Voltages

ADC and DAC: Reading Sensors and Making Analog Voltages

The real world is analog. An ADC turns a voltage into a number that the chip can use.

In shortAn ADC with n bits gives 2^n steps between 0 V and the reference voltage. Value = Vin / Vref x (2^n - 1). Use a voltage divider and filter noise.

Theory in plain words

Reading a sensorSensor voltageDivider / filterADC input pinSample and holdConversionNumber 0..1023
Reading a sensor

What it is

An ADC (analog to digital converter) measures a voltage and returns an integer. A DAC does the opposite: it turns an integer into a voltage.

Why we use it

Temperature, light, battery level, joysticks and microphones all produce voltages. To use them in code you must digitise them.

How it works

The ADC compares the input with the reference voltage Vref and finds the closest of 2^n levels (successive approximation takes n steps). A 10 bit ADC with 5 V has 1024 levels, each 4.88 mV.

Where it is used

  • Temperature, light and gas sensors
  • Battery monitoring
  • Audio capture, joysticks, potentiometers
  • DAC: audio output, waveform generators

Resolution

BitsLevelsStep at 3.3 V
825612.9 mV
10 (Arduino Uno)10243.22 mV
12 (STM32, ESP32)40960.806 mV
16 (precision ADC chips)655360.050 mV
24 (load cell chips)16,777,2160.0002 mV
ADC converterTry it Yourself

Compare 8 bit and 16 bit: more bits means smaller steps and less quantisation error.

Voltage divider and thermistor

The input must stay between 0 V and Vref. To measure a higher voltage, divide it: Vout = Vin x R2 / (R1 + R2). A thermistor and a fixed resistor form a divider whose output changes with temperature.

Battery voltage divider (12 V into a 3.3 V ADC)Try it Yourself

A 30k and 10k divider scales by 1/4, so 12 V becomes 3 V. Push the slider to 16 V and the pin goes over its limit: this is how pins get destroyed.

Reading the ADC in C (AVR)

Single conversion
uint16_t adc_read(uint8_t ch) {
    ADMUX  = (1 << REFS0) | (ch & 0x0F);                 // AVcc as reference, choose channel
    ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);  // enable, clock / 128
    ADCSRA |= (1 << ADSC);                               // start conversion
    while (ADCSRA & (1 << ADSC)) { }                     // wait until done
    return ADC;                                          // 0..1023
}
Careful:ADC readings are never perfectly steady. Do not compare with ==. Use ranges and hysteresis (turn on above 520, off below 480) to avoid flickering decisions.

Quick quiz

1. A 10 bit ADC has how many levels?

2. Why use a voltage divider before an ADC?

Common questions

A 10 bit ADC has how many levels?

1024. 2^10 = 1024.

Why use a voltage divider before an ADC?

To keep the voltage within 0 to Vref. The ADC pin must not exceed its reference or supply.