Embedded C Program for LED Binary Counter
for(count=0; count<16; count++) { PORT = count; delay(); } where PORT controls LEDs.Examples
How to Think About It
Algorithm
Code
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB = 0xFF; // Set PORTB as output for LEDs unsigned char count = 0; while(1) { PORTB = count; // Output count to LEDs _delay_ms(500); // Wait 500 ms count++; } return 0; }
Dry Run
Let's trace the counter from 0 to 3 through the code
Initialize
PORTB set as output, count = 0
Output count
PORTB = 0 (binary 00000000), LEDs all off
Delay
Wait 500 ms
Increment count
count = 1
Output count
PORTB = 1 (binary 00000001), LED0 on
Delay
Wait 500 ms
Increment count
count = 2
Output count
PORTB = 2 (binary 00000010), LED1 on
Delay
Wait 500 ms
Increment count
count = 3
| Count | PORTB (binary) | LEDs |
|---|---|---|
| 0 | 00000000 | All off |
| 1 | 00000001 | LED0 on |
| 2 | 00000010 | LED1 on |
| 3 | 00000011 | LED0 and LED1 on |
Why This Works
Step 1: Set PORT as output
We use DDRB = 0xFF to make all pins of PORTB output pins so they can control LEDs.
Step 2: Output count to LEDs
The variable count holds the number to display. Writing it to PORTB sets LEDs on/off in binary.
Step 3: Delay to see LEDs
A delay like _delay_ms(500) lets us see the LED pattern before changing to the next count.
Step 4: Increment and repeat
Increasing count by one each loop cycles through binary numbers, showing a counting effect on LEDs.
Alternative Approaches
#include <avr/io.h> #include <avr/interrupt.h> volatile unsigned char count = 0; ISR(TIMER0_OVF_vect) { PORTB = count++; } int main(void) { DDRB = 0xFF; TCCR0 = (1 << CS02) | (1 << CS00); // Prescaler 1024 TIMSK = (1 << TOIE0); // Enable overflow interrupt sei(); // Enable global interrupts while(1) {} return 0; }
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB = 0xFF; for(unsigned char count=0; ; count++) { PORTB = count; _delay_ms(500); } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program runs an infinite loop incrementing the count, so time complexity is O(n) where n is the number of counts displayed.
Space Complexity
Uses only a few variables and fixed port registers, so space complexity is O(1).
Which Approach is Fastest?
Using timer interrupts is more efficient for multitasking, while simple loops are easier but block CPU during delay.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop with delay | O(n) | O(1) | Easy implementation, blocking |
| Timer interrupt | O(n) | O(1) | Efficient multitasking, precise timing |