Skip to main content

Blink 8 LEDs at port 2

Short answer

Apply 0FFH to P2 (A-L LEDs ON), call a software delay, then 00H (OF-F), and repeat. Delay uses nested loops: outer 4, middle 250, inner 250 creating ~0.5 s at 12 MHz. Code: MOV P2,#0FFH; ACALL DEAY; MOV P2,#00H; ACALL DEAY; SJMP MAI.

Write an assembly language program to blink the 8 LEDs connected at Port 2 of the 8051 microcontroller.

The LEDs on Port 2 are turned all on, a delay is generated, they are turned all off, and the cycle repeats. The delay routine uses three nested loops (about 0.5 s at 12 MHz).

        ORG 0000H
MAIN:   MOV P2,#0FFH      ; all LEDs ON (active-high)
        ACALL DELAY
        MOV P2,#00H       ; all LEDs OFF
        ACALL DELAY
        SJMP MAIN
DELAY:  MOV R5,#4         ; about 0.5 s at 12 MHz
D1:     MOV R6,#250
D2:     MOV R7,#250
D3:     DJNZ R7,D3
        DJNZ R6,D2
        DJNZ R5,D1
        RET
        END

Explanation:

  • MOV P2,#0FFH / MOV P2,#00H switch all eight LEDs on and off (active-high LEDs).
  • DELAY: R5 x R6 x R7 loop = 4 x 250 x (250 x 2 + 3) us, which is about 0.50 s at a 12 MHz crystal (machine cycle 1 us). In simulation the delay measured 0.503 s.
  • To blink alternately, use patterns 0AAH and 55H instead.

In C:

#include <reg51.h>
void delay(unsigned int ms) { unsigned int i, j; for (i = 0; i < ms; i++) for (j = 0; j < 120; j++); }
void main(void)
{
    while (1) {
        P2 = 0xFF;  delay(500);
        P2 = 0x00;  delay(500);
    }
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 9 questions →