Bird
0
0
Arduinoprogramming~5 mins

Ultrasonic distance sensor (HC-SR04) in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Ultrasonic distance sensor (HC-SR04)
O(n)
Understanding Time Complexity

We want to understand how the time taken by the ultrasonic sensor code changes as we measure distances repeatedly.

How does the program's running time grow when we take more distance readings?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  Serial.println(distance);
  delay(500);
}
    

This code sends an ultrasonic pulse, waits for the echo, calculates the distance, and prints it every half second.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop() function runs repeatedly, sending pulses and measuring echoes.
  • How many times: It runs indefinitely, repeating the distance measurement every 500 milliseconds.
How Execution Grows With Input

Each distance measurement takes roughly the same time regardless of the distance value.

Input Size (n)Approx. Operations
10 readingsAbout 10 times the measurement steps
100 readingsAbout 100 times the measurement steps
1000 readingsAbout 1000 times the measurement steps

Pattern observation: The total time grows linearly with the number of readings taken.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete n distance measurements grows directly in proportion to n.

Common Mistake

[X] Wrong: "The time to measure distance depends on how far the object is."

[OK] Correct: The sensor waits for the echo pulse, and the code timing depends on the echo time, so time per reading varies slightly with distance but is mostly fixed per measurement cycle.

Interview Connect

Understanding how sensor reading loops scale helps you write efficient embedded programs that handle repeated tasks smoothly.

Self-Check

"What if we added a loop inside loop() to take multiple readings before printing? How would the time complexity change?"