Embedded C Program to Blink LED - Simple Example
while(1) { PORTB ^= (1 << PB0); _delay_ms(500); } to create the blinking effect.Examples
How to Think About It
Algorithm
Code
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= (1 << PB0); // Set PORTB0 as output while(1) { PORTB ^= (1 << PB0); // Toggle PORTB0 _delay_ms(500); // Wait 500 ms } return 0; }
Dry Run
Let's trace blinking LED connected to PORTB0 through the code
Set PORTB0 as output
DDRB = 0b00000001 (PORTB0 pin set to output)
Toggle PORTB0 first time
PORTB = 0b00000001 (LED ON)
Wait 500 ms
Delay function pauses execution
Toggle PORTB0 second time
PORTB = 0b00000000 (LED OFF)
Wait 500 ms
Delay function pauses execution
Repeat toggling
PORTB toggles between 0b00000001 and 0b00000000 repeatedly
| Iteration | PORTB Value | LED State |
|---|---|---|
| 1 | 0b00000001 | ON |
| 2 | 0b00000000 | OFF |
| 3 | 0b00000001 | ON |
| 4 | 0b00000000 | OFF |
Why This Works
Step 1: Configure pin as output
Using DDRB |= (1 << PB0); sets the pin connected to the LED as output so it can drive the LED.
Step 2: Toggle LED pin
The PORTB ^= (1 << PB0); flips the pin state from HIGH to LOW or LOW to HIGH, turning the LED on or off.
Step 3: Delay creates visible blink
The _delay_ms(500); pauses the program so the LED stays on or off long enough for human eyes to see the blink.
Alternative Approaches
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= (1 << PB0); while(1) { PORTB |= (1 << PB0); // LED ON _delay_ms(500); PORTB &= ~(1 << PB0); // LED OFF _delay_ms(500); } return 0; }
// Timer interrupt code is more complex and hardware-specific // It allows blinking without blocking delay, better for multitasking
Complexity: O(1) time, O(1) space
Time Complexity
The blinking loop runs infinitely but each iteration takes constant time due to fixed delay; no loops depend on input size.
Space Complexity
Uses only a few registers and no extra memory; constant space usage.
Which Approach is Fastest?
Toggling the pin with XOR is slightly faster than separate ON/OFF commands, but difference is minimal for blinking.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Toggle with XOR | O(1) | O(1) | Simple and fast blinking |
| Separate ON/OFF commands | O(1) | O(1) | Clearer code, easy to understand |
| Timer interrupt | O(1) | O(1) | Non-blocking blinking in complex apps |
DDRx to set pin direction and PORTx to control pin output for blinking LEDs.