51 Microcontroller LED Control and Flowing LED Tutorial

1. Lightign All LEDs on P2 Port

Using an STC89C52-based development board (e.g., model A2), start by configuring Keil: enable "Create HEX File" in output settings. The microcontroller runs code in an infinite loop, so use while(1).

From the schematic, LEDs are common-anode (connected to P2). Setting P2 to 0x00 (low voltage) lights all LEDs. Code:

#include <REGX52.H>
void main() {
    P2 = 0x00; // Drive P2 low to light all LEDs
    while(1); // Infinite loop to keep code running
}

Compile, then download via STC programimng software. All 8 LEDs will illuminate.

2. Code Explanation

P2 is a port defined in REGX52.H (mapped to a hardware register). For common-anode LEDs, low voltage (0) activates them. The header also defines individual bits (e.g., P2_0P2_7), enabling single-LED control.

3. Lighting a Single LED

To light the LED at P2_0, modify the code:

#include <REGX52.H>
void main() {
    P2_0 = 0; // Drive P2.0 low (light the LED)
    while(1);
}

Downloading this lights only the LED connected to P2_0.

4. Flowing LED Effect

For a cyclic flowing effect, use bit shifting. Here’s the code with a custom delay:

#include <REGX52.H>
#include <intrins.h> // For _crol_()

void delay(unsigned int t) {
    unsigned int i, j;
    for(i = t; i > 0; i--)
        for(j = 110; j > 0; j--);
}

void main() {
    unsigned char ledMask = 0x01; // Start with bit 0 set
    while(1) {
        P2 = ~ledMask; // Invert for common-anode (low = on)
        delay(500); // Adjust speed
        ledMask = _crol_(ledMask, 1); // Shift left cyclically
    }
}
  • delay() creates a time delay using nested loops.
  • _crol_(ledMask, 1) shifts ledMask left (e.g., 0000000100000010).
  • P2 = ~ledMask inverts the value (comon-anode LEDs require low voltage to light).

This code makes LEDs light sequentially in a loop, creating a flowing effect. Adjust delay(500) to change the speed.

Tags: 51 Microcontroller LED Control Embedded System c programming Flowing LED

Posted on Fri, 08 May 2026 21:38:53 +0000 by Adika