Embedded C Program for LED Chaser with Delay
PORTB = 1 << i; with a delay between shifts to create a moving light effect.Examples
How to Think About It
Algorithm
Code
#include <xc.h> #define _XTAL_FREQ 4000000 void delay_ms(unsigned int ms) { while(ms--) { __delay_ms(1); } } void main() { TRISB = 0x00; // Set PORTB as output PORTB = 0x00; // Clear PORTB while(1) { for(unsigned char i = 0; i < 8; i++) { PORTB = 1 << i; // Light one LED at a time delay_ms(200); // Delay 200 ms } } }
Dry Run
Let's trace lighting LEDs one by one on PORTB with delay
Initialize PORTB
TRISB = 0x00 (all output), PORTB = 0x00 (all LEDs off)
First loop iteration i=0
PORTB = 1 << 0 = 0x01 (only first LED on), delay 200 ms
Second loop iteration i=1
PORTB = 1 << 1 = 0x02 (second LED on), delay 200 ms
Continue for i=2 to 7
PORTB lights LEDs 3rd to 8th one by one with delay
Repeat loop
Cycle repeats from first LED again
| Iteration i | PORTB Value (Hex) | LED On |
|---|---|---|
| 0 | 0x01 | First LED |
| 1 | 0x02 | Second LED |
| 2 | 0x04 | Third LED |
| 3 | 0x08 | Fourth LED |
| 4 | 0x10 | Fifth LED |
| 5 | 0x20 | Sixth LED |
| 6 | 0x40 | Seventh LED |
| 7 | 0x80 | Eighth LED |
Why This Works
Step 1: Setting PORTB as output
We use TRISB = 0x00; to make all PORTB pins outputs so we can control LEDs.
Step 2: Lighting one LED at a time
Using PORTB = 1 << i; shifts a 1 bit to the position of the LED to turn it on alone.
Step 3: Delay for visibility
The delay function pauses the program so the LED stays lit long enough to see before moving on.
Alternative Approaches
#include <xc.h> #define _XTAL_FREQ 4000000 void delay_ms(unsigned int ms) { while(ms--) { __delay_ms(1); } } void main() { TRISB = 0x00; PORTB = 0x01; while(1) { PORTB <<= 1; if(PORTB == 0) PORTB = 0x01; delay_ms(200); } }
#include <xc.h> #define _XTAL_FREQ 4000000 void delay_ms(unsigned int ms) { while(ms--) { __delay_ms(1); } } void main() { unsigned char leds[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; TRISB = 0x00; while(1) { for(int i=0; i<8; i++) { PORTB = leds[i]; delay_ms(200); } } }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each LED once per cycle, so time complexity is O(n) where n is number of LEDs.
Space Complexity
Uses constant extra space for variables and delay, so space complexity is O(1).
Which Approach is Fastest?
Bit shifting is fastest and simplest; using arrays adds memory overhead but allows flexible patterns.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bit shifting loop | O(n) | O(1) | Simple, fast LED chaser |
| Rotating bit mask | O(n) | O(1) | Compact code, continuous shift |
| Array pattern | O(n) | O(n) | Custom LED sequences |