Bird
0
0
Arduinoprogramming~5 mins

Humidity and temperature (DHT11/DHT22) in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Humidity and temperature (DHT11/DHT22)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
1010 sensor reads
100100 sensor reads
10001000 sensor reads

Pattern observation: The time grows linearly as we increase the number of readings.

Final Time Complexity

Time Complexity: O(n)

This means the total time to read data grows directly in proportion to how many times we read the sensor.

Common Mistake

[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.

Interview Connect

Understanding how sensor reading time adds up helps you design efficient programs that handle data smoothly without delays piling up.

Self-Check

"What if we read from multiple DHT sensors in the same loop? How would the time complexity change?"