Skip to main content

Read switches at port 1, show on port 2

Short answer

Set P1 as input (all 1s), read a switch into A, and output to P2 in a loop. Code: MOV P1,#0FFH; LOOP: MOV A,P1; MOV P2,A; SJMP LOOP. For active-low LEDs, complement A before the output.

Write an assembly language programming for 8051 microcontroller to read the data from switches connected at port 1 and send it to port 2 for display in LED.

Port 1 is configured as an input by writing 1s to it; the switch value is read into A and written to Port 2 where the LEDs are connected (active high).

        ORG 0000H
        MOV P1,#0FFH      ; make Port 1 an input port
LOOP:   MOV A,P1          ; read the switches into A
        MOV P2,A          ; send to LEDs on Port 2
        SJMP LOOP         ; repeat forever
        END

Explanation:

  • MOV P1,#0FFH writes 1 to every pin so that external switches can pull the pins down (input mode).
  • MOV A,P1 reads the pin levels; a closed switch to ground reads 0.
  • MOV P2,A copies the pattern, so the LED pattern follows the switch settings. For LEDs wired active-low (anode to VCC) use CPL A before the output.
  • The program was assembled and tested in an 8051 simulator: P1 = 5AH gives P2 = 5AH.

Same program in C:

#include <reg51.h>
void main(void)
{
    P1 = 0xFF;              /* input port */
    while (1)
        P2 = P1;            /* copy switches to LEDs */
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 9 questions →