0
0
Embedded Cprogramming~5 mins

Single channel ADC reading in Embedded C

Choose your learning style9 modes available
Introduction
We use single channel ADC reading to convert one analog signal into a digital number so the microcontroller can understand it.
Reading temperature from a single sensor.
Measuring light intensity with one photoresistor.
Checking battery voltage level.
Reading a single joystick position.
Syntax
Embedded C
void ADC_Init(void);
uint16_t ADC_Read(void);
ADC_Init() sets up the ADC hardware before use.
ADC_Read() starts a conversion and returns the digital value.
Examples
Initialize ADC and read one value from the single channel.
Embedded C
ADC_Init();
uint16_t value = ADC_Read();
Continuously read the ADC value in a loop.
Embedded C
ADC_Init();
while(1) {
  uint16_t sensorValue = ADC_Read();
  // use sensorValue
}
Sample Program
This program initializes the ADC, simulates an analog input value, reads it, and prints the digital result.
Embedded C
#include <stdint.h>
#include <stdio.h>

// Simulated ADC hardware registers
volatile uint16_t ADC_DATA = 0;

void ADC_Init(void) {
    // Normally hardware setup code here
    // For simulation, do nothing
}

uint16_t ADC_Read(void) {
    // Simulate starting ADC conversion
    // Wait for conversion complete (simulated)
    // Return ADC data
    return ADC_DATA;
}

int main(void) {
    ADC_Init();
    ADC_DATA = 512; // Simulate analog input value
    uint16_t adcValue = ADC_Read();
    printf("ADC Reading: %u\n", adcValue);
    return 0;
}
OutputSuccess
Important Notes
ADC values depend on the reference voltage and resolution (e.g., 10-bit ADC gives values 0-1023).
Make sure to initialize the ADC before reading values.
Reading ADC may take some time; wait for conversion to finish if needed.
Summary
Single channel ADC reads one analog input and converts it to a digital number.
Initialize ADC hardware before reading values.
Use ADC_Read() to get the current analog value as a number.