0
0
Power-electronicsHow-ToBeginner · 4 min read

How to Configure ADC Channel in Embedded C: Simple Guide

To configure an ADC channel in embedded C, you typically set the ADC control registers to select the channel, configure the ADC clock, and enable the ADC module. This involves writing to specific registers like ADMUX for channel selection and ADCSRA for enabling and starting the conversion.
📐

Syntax

Configuring an ADC channel usually involves these steps:

  • Select ADC channel: Set bits in the ADMUX register to choose the input channel.
  • Configure ADC settings: Set reference voltage and data alignment in ADMUX.
  • Enable ADC: Set the enable bit in ADCSRA.
  • Start conversion: Set the start bit in ADCSRA.
c
ADMUX = (reference_voltage_bits) | (channel_selection_bits);
ADCSRA = (enable_bit) | (prescaler_bits);
ADCSRA |= (start_conversion_bit);
💻

Example

This example shows how to configure ADC channel 2 on an AVR microcontroller, start a conversion, and read the result.

c
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    // Select AVcc as reference, select ADC2 channel (binary 010)
    ADMUX = (1 << REFS0) | (2 & 0x07);

    // Enable ADC and set prescaler to 128 for 125kHz ADC clock
    ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

    while (1) {
        // Start conversion
        ADCSRA |= (1 << ADSC);

        // Wait for conversion to finish
        while (ADCSRA & (1 << ADSC));

        // Read ADC value
        uint16_t adc_value = ADC;

        // Use adc_value as needed
        _delay_ms(500);
    }
    return 0;
}
⚠️

Common Pitfalls

Common mistakes when configuring ADC channels include:

  • Not enabling the ADC before starting conversion.
  • Incorrectly setting the channel bits in ADMUX, causing wrong input selection.
  • Forgetting to wait for the conversion to complete before reading the result.
  • Using wrong prescaler values leading to ADC clock outside recommended range.
c
/* Wrong: Not enabling ADC */
ADMUX = (1 << REFS0) | (2 & 0x07); // Select channel 2
ADCSRA = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Missing ADEN bit
ADCSRA |= (1 << ADSC); // Start conversion

/* Right: Enable ADC */
ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
📊

Quick Reference

RegisterPurposeKey Bits
ADMUXSelect ADC channel and reference voltageREFS1:0 (reference), MUX3:0 (channel)
ADCSRAControl ADC enable, start, and prescalerADEN (enable), ADSC (start), ADPS2:0 (prescaler)
ADCADC data register (result)ADCL (low byte), ADCH (high byte)

Key Takeaways

Set the ADC channel by configuring the MUX bits in the ADMUX register.
Always enable the ADC by setting the ADEN bit before starting conversion.
Wait for the ADSC bit to clear before reading the ADC result.
Choose the correct prescaler to keep ADC clock within recommended frequency.
Use the ADC data register (ADC) to read the conversion result after completion.