Reading analog sensors through ADC in Raspberry Pi - Time & Space Complexity
When reading analog sensors through an ADC on a Raspberry Pi, it's important to understand how the time taken grows as we read more sensor values.
We want to know how the program's running time changes when we increase the number of sensor readings.
Analyze the time complexity of the following code snippet.
import spidev
import time
def read_adc(channel, spi):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data
spi = spidev.SpiDev()
spi.open(0, 0)
for i in range(100):
value = read_adc(0, spi)
time.sleep(0.01)
This code reads analog values from channel 0 of an ADC 100 times, pausing briefly between each read.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calls
read_adc100 times. - How many times: Exactly 100 times in this example, but this number can change based on input.
Each sensor reading takes roughly the same time, so if we double the number of readings, the total time roughly doubles too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads |
| 100 | 100 sensor reads |
| 1000 | 1000 sensor reads |
Pattern observation: The total work grows directly with the number of readings.
Time Complexity: O(n)
This means the time to complete the readings grows in a straight line as you increase the number of sensor reads.
[X] Wrong: "Reading multiple sensors at once will take the same time as reading one sensor."
[OK] Correct: Each sensor read requires communication with the ADC, so reading more sensors means more time spent overall.
Understanding how sensor reading time grows helps you write efficient code for real devices, showing you can think about performance in practical situations.
"What if we changed the code to read from 4 different channels inside the loop? How would the time complexity change?"
