Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Last updated: Friday 13 November 2026 @ 17:29:40
Programming for Engineers

Analogue-to-Digital Conversion

In this practical you will configure the ATmega328P's 10-bit analogue-to-digital converter (ADC), inspect its registers, measure the chip's internal temperature sensor, and read an external analogue signal. You will transmit measurements to a serial terminal using the USART developed in the previous practical.

ATmega328PADCRegistersUSARTEmbedded C
Practical Checklist

{{%track-checklist}}

1. Understanding the ADC

The ADC converts an analogue input voltage into a digital number. In its usual 10-bit mode, the ATmega328P produces values from 0 to 1023 (1024 possible codes). The result depends on the selected reference voltage, \(V_{REF}\).

\[ ADC \approx \frac{V_{IN}}{V_{REF}} \times 1024 \]

The output is limited to the range 0–1023. For an ideal 5 V reference, one least-significant bit (LSB) represents approximately \(5/1024 = 4.88\text{ mV}\).

ADC registers at a glance

RegisterPurpose
ADMUXSelect the reference, result alignment and input channel
ADCSRAEnable the ADC, start a conversion and set the ADC clock prescaler
ADCL, ADCHHold the low and high bytes of the conversion result
ADCAVR C-library 16-bit access to the combined ADC result
DIDR0Optionally disable digital input buffers on analogue pins

ADMUX: reference and channel selection

Bit 7Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
REFS1REFS0ADLARReservedMUX3MUX2MUX1MUX0

For the external inputs used here, the channel is selected by MUX3:MUX0. The reference is selected by REFS1:REFS0:

REFS1:REFS0Reference source
00External reference on AREF (internal reference switched off)
01AVcc, with external capacitor at AREF
10Reserved
11Internal nominal 1.1 V reference, with external capacitor at AREF
ADMUX = (1 << REFS0); // AVcc reference, ADC0 (A0)

ADMUX is set to 0b01000000: REFS0=1, and MUX3:MUX0=0000.

ADMUX = (1 << REFS0) | (1 << MUX1) | (1 << MUX0);

ADMUX is set to 0b01000011: AVcc reference and channel 0011 (ADC3).

ADCSRA: enable, convert and select the clock

// Enable ADC and select a clock prescaler of 128.
ADCSRA = (1 << ADEN) | (1 << ADPS2) |
         (1 << ADPS1) | (1 << ADPS0);

// Start a single conversion.
ADCSRA |= (1 << ADSC);

// Wait while the ADC is converting.
while (ADCSRA & (1 << ADSC)) {
}

// Obtain the 10-bit result (ADCL and ADCH).
uint16_t reading = ADC;

The ADC clock is the CPU clock divided by the selected prescaler:

\[ f_{ADC} = \frac{f_{CPU}}{128} = \frac{16,000,000}{128} = 125,000\ \text{Hz} \]

2. Internal temperature sensing

The ATmega328P contains an internal temperature sensor connected to ADC channel 1000. To read it, select the internal 1.1 V reference rather than AVcc. Its output depends on the individual chip and should not be treated as a precise thermometer without calibration.

The datasheet gives these typical values:

TemperatureTypical ADC codeDecimal
−40°C0x010D269
+25°C0x0160352
+125°C0x01E0480

For a simple demonstration, we will use an approximate sensitivity of 1 ADC count per °C and a typical 25°C reading of 352:

\[ T_{estimated} (°C) \approx 25 + (ADC_{reading}-352) \]

  1. Create the project alongside the previous Blink and UART directories:

    mkdir -p ~/embeddedC/internalADCTemp
    cd ~/embeddedC/internalADCTemp
    touch internalADCTemp.c
  2. Enter the following internalADCTemp.c programme. It initialises USART, selects the temperature channel and repeatedly transmits its approximate reading.

    #define F_CPU 16000000UL
    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdlib.h>
    #include <stdint.h>
    
    #define USART_BAUDRATE 9600UL
    #define BAUD_PRESCALER ((F_CPU / (16UL * USART_BAUDRATE)) - 1UL)
    #define ADC_AT_25C 352
    
    static void USART_Init(void) {
        UBRR0H = (uint8_t)(BAUD_PRESCALER >> 8);
        UBRR0L = (uint8_t)BAUD_PRESCALER;
        UCSR0A = 0;  // Normal asynchronous speed (U2X0 = 0)
        UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8N1
        UCSR0B = (1 << TXEN0); // Only transmission is needed
    }
    
    static void USART_Transmit(uint8_t data) {
        while (!(UCSR0A & (1 << UDRE0))) {
        }
        UDR0 = data;
    }
    
    static void USART_SendString(const char *str) {
        while (*str) {
            USART_Transmit((uint8_t)*str++);
        }
    }
    
    static void ADC_Init(void) {
        // Internal 1.1 V reference, temperature channel (MUX3 = 1).
        ADMUX = (1 << REFS1) | (1 << REFS0) | (1 << MUX3);
        ADCSRA = (1 << ADEN) | (1 << ADPS2) |
                 (1 << ADPS1) | (1 << ADPS0);
        _delay_ms(2); // Allow the internal reference to settle.
        ADCSRA |= (1 << ADSC); // Discard initial conversion.
        while (ADCSRA & (1 << ADSC)) {
        }
        (void)ADC;
    }
    
    static uint16_t ADC_Read(void) {
        ADCSRA |= (1 << ADSC);
        while (ADCSRA & (1 << ADSC)) {
        }
        return ADC;
    }
    
    int main(void) {
        char buffer[12];
        USART_Init();
        ADC_Init();
    
        while (1) {
            uint16_t adc_value = ADC_Read();
            int16_t temperature = (int16_t)adc_value - ADC_AT_25C + 25;
            itoa(temperature, buffer, 10);
            USART_SendString("Estimated chip temperature: ");
            USART_SendString(buffer);
            USART_SendString(" C\r\n");
            _delay_ms(1000);
        }
    }
    What the programme does
    • USART_Init() configures serial transmission at 9600 baud.
    • ADC_Init() selects the internal temperature sensor and 1.1 V reference, enables the ADC and performs an initial conversion.
    • ADC_Read() starts and waits for each subsequent conversion.
    • The sample is converted to an approximate Celsius value, formatted using itoa() and sent to the terminal.
  3. Create a Makefile by copying the one from your UART practical, then replace the programme name with internalADCTemp.

    cp ../uart/Makefile .
    vim Makefile

    In Vim, press Esc and enter :%s/\<uart\>/internalADCTemp/g, then save with :wq. Verify the resulting rules reference internalADCTemp.c, .o, .elf and .hex. Keep the existing AVRDUDE configuration path, programmer and port appropriate to your board.

  4. Check the board's serial port, then build and upload the firmware:

    make clean
    make
    make upload

    Open PuTTY using a Serial connection at 9600 baud and inspect the readings.

    Temperature: 28 C
    Temperature: 29 C
    Temperature: 28 C

    The numbers above are illustrative and will differ on your hardware.

    Reference output of the internal ADC temperature experiment

3. Reading analogue pins A0–A5

We will now sample the external ADC0 channel, presented as A0 on an Arduino Uno, and transmit the raw 10-bit value over USART.

Selecting the channel

Arduino inputADC channelChannel-selection expression
A0ADC0ADMUX = (1 << REFS0);
A1ADC1ADMUX = (1 << REFS0) | (1 << MUX0);
A2ADC2ADMUX = (1 << REFS0) | (1 << MUX1);
A3ADC3ADMUX = (1 << REFS0) | (1 << MUX1) | (1 << MUX0);
A4ADC4ADMUX = (1 << REFS0) | (1 << MUX2);
A5ADC5ADMUX = (1 << REFS0) | (1 << MUX2) | (1 << MUX0);
  1. Create a new project and source file:

    mkdir -p ~/embeddedC/adcread
    cd ~/embeddedC/adcread
    touch adcread.c
  2. Enter the following code in adcread.c:

    #define F_CPU 16000000UL
    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdlib.h>
    #include <stdint.h>
    
    #define USART_BAUDRATE 9600UL
    #define BAUD_PRESCALER ((F_CPU / (16UL * USART_BAUDRATE)) - 1UL)
    
    static void USART_Init(void) {
        UBRR0H = (uint8_t)(BAUD_PRESCALER >> 8);
        UBRR0L = (uint8_t)BAUD_PRESCALER;
        UCSR0A = 0; // Normal asynchronous speed
        UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8N1
        UCSR0B = (1 << TXEN0);
    }
    
    static void USART_Transmit(uint8_t data) {
        while (!(UCSR0A & (1 << UDRE0))) {
        }
        UDR0 = data;
    }
    
    static void USART_SendString(const char *str) {
        while (*str) {
            USART_Transmit((uint8_t)*str++);
        }
    }
    
    static void ADC_Init(void) {
        ADMUX = (1 << REFS0); // AVcc reference, ADC0 (A0)
        ADCSRA = (1 << ADEN) | (1 << ADPS2) |
                 (1 << ADPS1) | (1 << ADPS0); // Prescaler = 128
        DIDR0 |= (1 << ADC0D); // Disable ADC0 digital input buffer
        ADCSRA |= (1 << ADSC); // Discard first conversion
        while (ADCSRA & (1 << ADSC)) {
        }
        (void)ADC;
    }
    
    static uint16_t ADC_Read(void) {
        ADCSRA |= (1 << ADSC);
        while (ADCSRA & (1 << ADSC)) {
        }
        return ADC;
    }
    
    int main(void) {
        char buffer[12];
        USART_Init();
        ADC_Init();
    
        while (1) {
            uint16_t adc_value = ADC_Read();
            utoa(adc_value, buffer, 10);
            USART_SendString("ADC Value: ");
            USART_SendString(buffer);
            USART_SendString("\r\n");
            _delay_ms(1000);
        }
    }
  3. Copy the Makefile from internalADCTemp and change its build target:

    cp ../internalADCTemp/Makefile .
    vim Makefile

    From Vim normal mode, use :%s/\<internalADCTemp\>/adcread/g and save. Check that PORT, AVRDUDECONFIG and the MCU are correct.

  4. Compile and upload to the board, then open PuTTY at 9600 baud:

    make clean
    make
    make upload
    ADC Value: 0
    ADC Value: 278
    ADC Value: 512
    ADC Value: 1023

    These are example values, not a guaranteed sequence. Turn the potentiometer and observe the reading change.

    Reading an external ADC signal in PuTTY

4. Investigate the ADC

  • What happens if the ADC input is left disconnected?
  • What does ADMUX control, and how does it differ from ADCSRA?
  • Why do we read a 10-bit result through the ADC macro rather than reading ADCH alone?
  • Why does the internal temperature example require a different reference?
  • Near GND the ADC code is close to zero.
  • Near half the reference it is close to the middle of the range.
  • Near AVcc it approaches the upper limit, 1023.
  • Electrical noise, component tolerance and an imprecisely known reference can affect the readings.