Soil moisture sensor in Arduino - Time & Space Complexity
When working with a soil moisture sensor on Arduino, it is important to understand how the program's running time changes as it reads sensor data repeatedly.
We want to know how the time to complete the program grows as the number of sensor readings increases.
Analyze the time complexity of the following code snippet.
const int sensorPin = A0;
int sensorValue;
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(1000);
}
This code reads the soil moisture sensor value once every second and prints it to the serial monitor.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
loop()function runs repeatedly, reading the sensor and printing the value. - How many times: It runs indefinitely, once every second.
Each sensor reading and print takes roughly the same time, so the total time grows directly with the number of readings.
| Input Size (n readings) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads and prints |
| 100 | 100 sensor reads and prints |
| 1000 | 1000 sensor reads and prints |
Pattern observation: The operations increase one-to-one with the number of readings.
Time Complexity: O(n)
This means the time to run grows directly in proportion to how many times the sensor is read.
[X] Wrong: "The sensor reading happens instantly and does not affect time growth."
[OK] Correct: Each sensor read and print takes time, so more readings mean more total time.
Understanding how repeated sensor readings affect program time helps you explain how embedded systems handle real-time data efficiently.
"What if we added a nested loop to read multiple sensors each cycle? How would the time complexity change?"
