0
0
Embedded Cprogramming~5 mins

First embedded program (LED blink) in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: First embedded program (LED blink)
O(n)
Understanding Time Complexity

When we write a program to blink an LED, it runs some instructions repeatedly to turn the light on and off.

We want to know how the time the program takes changes as we change how long it blinks or how many times it blinks.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRB |= (1 << PB0); // Set pin as output
    while(1) {
        PORTB |= (1 << PB0);  // LED ON
        _delay_ms(500);          // Wait 500 ms
        PORTB &= ~(1 << PB0); // LED OFF
        _delay_ms(500);          // Wait 500 ms
    }
}
    

This code turns an LED on and off repeatedly with a delay in between.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The infinite while(1) loop that repeats turning the LED on and off.
  • How many times: It runs forever, repeating the on-off cycle endlessly.
How Execution Grows With Input

Here, the program runs the same steps over and over without changing based on input size.

Input Size (n)Approx. Operations
10 cyclesAbout 10 on-off steps
100 cyclesAbout 100 on-off steps
1000 cyclesAbout 1000 on-off steps

Pattern observation: The time grows linearly with the number of blink cycles you want.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with how many times the LED blinks.

Common Mistake

[X] Wrong: "The program runs in constant time because it just blinks the LED."

[OK] Correct: Even though the code loops forever, the total time depends on how many blink cycles you count. More cycles mean more time.

Interview Connect

Understanding how loops affect time helps you explain how embedded programs behave over time, a key skill for real devices.

Self-Check

"What if we changed the delay from 500 ms to 1000 ms? How would the time complexity change?"