0
0
Embedded Cprogramming~5 mins

LED control patterns in Embedded C

Choose your learning style9 modes available
Introduction
LED control patterns help make lights blink or change in fun and useful ways, like showing alerts or decorations.
To show a blinking light when a device is working.
To create a running light effect for decoration.
To signal errors or warnings with different blink patterns.
To indicate different modes or states of a device.
To make a simple light show for fun or testing.
Syntax
Embedded C
void pattern_name() {
    // turn LEDs on or off in a sequence
    // use delay to control timing
}
Each pattern is a function that controls LEDs step by step.
Use delay functions to create visible blinking or movement.
Examples
This pattern turns the LED on for half a second, then off for half a second.
Embedded C
void blink_led() {
    LED_ON();
    delay(500);
    LED_OFF();
    delay(500);
}
This pattern lights each LED one by one, creating a running effect.
Embedded C
void running_light() {
    for (int i = 0; i < NUM_LEDS; i++) {
        turn_on_led(i);
        delay(200);
        turn_off_led(i);
    }
}
Sample Program
This program simulates turning 3 LEDs on and off together, then lighting them one by one. It prints the LED states to the console.
Embedded C
#include <stdio.h>
#include <unistd.h> // for usleep

#define NUM_LEDS 3

void LED_ON(int led) {
    printf("LED %d ON\n", led);
}

void LED_OFF(int led) {
    printf("LED %d OFF\n", led);
}

void delay_ms(int ms) {
    usleep(ms * 1000); // sleep in microseconds
}

void blink_all_leds() {
    for (int i = 0; i < NUM_LEDS; i++) {
        LED_ON(i);
    }
    delay_ms(500);
    for (int i = 0; i < NUM_LEDS; i++) {
        LED_OFF(i);
    }
    delay_ms(500);
}

void running_light() {
    for (int i = 0; i < NUM_LEDS; i++) {
        LED_ON(i);
        delay_ms(300);
        LED_OFF(i);
    }
}

int main() {
    printf("Start LED patterns\n");
    blink_all_leds();
    running_light();
    printf("End LED patterns\n");
    return 0;
}
OutputSuccess
Important Notes
Use small delays so the blinking is visible but not too slow.
Make sure to turn off LEDs after turning them on to avoid leaving them lit.
You can combine patterns to create more complex light shows.
Summary
LED control patterns are small programs to turn lights on and off in fun ways.
Use functions and delays to create blinking or running effects.
Patterns help show device status or make decorations.