First embedded program (LED blink) in Embedded C - Time & Space 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.
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 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.
Here, the program runs the same steps over and over without changing based on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 cycles | About 10 on-off steps |
| 100 cycles | About 100 on-off steps |
| 1000 cycles | About 1000 on-off steps |
Pattern observation: The time grows linearly with the number of blink cycles you want.
Time Complexity: O(n)
This means the time to run grows directly with how many times the LED blinks.
[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.
Understanding how loops affect time helps you explain how embedded programs behave over time, a key skill for real devices.
"What if we changed the delay from 500 ms to 1000 ms? How would the time complexity change?"