Single channel ADC reading in Embedded C - Time & Space Complexity
We want to understand how the time to read from an ADC changes as we take more readings.
How does the number of readings affect the total time spent?
Analyze the time complexity of the following code snippet.
int readADC(int channel) {
// Start ADC conversion
ADC_START_CONVERSION(channel);
// Wait until conversion is done
while(!ADC_CONVERSION_COMPLETE());
// Return the ADC value
return ADC_GET_VALUE();
}
int readMultiple(int channel, int times) {
int sum = 0;
for(int i = 0; i < times; i++) {
sum += readADC(channel);
}
return sum / times;
}
This code reads an analog value from one ADC channel multiple times and averages the results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop in
readMultiplecallsreadADCrepeatedly. - How many times: Exactly
timestimes, which is the input size.
Each additional reading adds one full ADC read cycle, so time grows directly with the number of readings.
| Input Size (times) | Approx. Operations |
|---|---|
| 10 | 10 ADC reads |
| 100 | 100 ADC reads |
| 1000 | 1000 ADC reads |
Pattern observation: Doubling the number of readings doubles the total time.
Time Complexity: O(n)
This means the total time grows linearly with the number of ADC readings requested.
[X] Wrong: "Reading multiple times is just as fast as reading once because the ADC is fast."
[OK] Correct: Each ADC read takes time to start, convert, and finish, so multiple reads add up in time.
Understanding how repeated hardware reads affect time helps you write efficient embedded code and explain your reasoning clearly.
"What if we read from multiple ADC channels instead of one? How would the time complexity change?"