Humidity and temperature (DHT11/DHT22) in Arduino - Time & Space Complexity
When reading humidity and temperature from sensors like DHT11 or DHT22, it's important to understand how the time to get data changes as we read more times or handle more sensors.
We want to know how the program's running time grows when we increase the number of readings.
Analyze the time complexity of the following code snippet.
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
delay(2000);
}
This code reads humidity and temperature once every 2 seconds from a single DHT11 sensor.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading humidity and temperature from the sensor.
- How many times: Once every 2 seconds, repeated indefinitely in the loop.
Each reading takes roughly the same time, so if we take more readings, the total time grows directly with the number of readings.
| Input Size (n readings) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads |
| 100 | 100 sensor reads |
| 1000 | 1000 sensor reads |
Pattern observation: The time grows linearly as we increase the number of readings.
Time Complexity: O(n)
This means the total time to read data grows directly in proportion to how many times we read the sensor.
[X] Wrong: "Reading from the sensor is instant and does not affect program time."
[OK] Correct: Each sensor read takes a fixed amount of time (usually around 250 milliseconds to 1 second), so reading many times adds up and affects total running time.
Understanding how sensor reading time adds up helps you design efficient programs that handle data smoothly without delays piling up.
"What if we read from multiple DHT sensors in the same loop? How would the time complexity change?"
