Skip to main content

LED blink rate controlled by two switches

Short answer

The LED at P1.1 toggles with half-period R2×10 ms. Switches active low: pressing P2.1 decrements R2 (min 1) for faster blink, pressing P2.2 increments R2 (max 255) for slower blink.

Using 8051 instructions, control rate of blink of LED at pin P1.1 by two switches at P2.1 and P2.2. (One switch to increase the rate of blink, another to decrease the rate of blink)

Idea

The LED at P1.1 is toggled forever. The half-period is R2 x 10 ms. Switch S1 (P2.1) decreases R2 (faster blink) and switch S2 (P2.2) increases R2 (slower blink). Switches are active low (pressed = 0, with pull-ups). Limits keep R2 within 1 to 255.

 Start --> R2 = 20 --> toggle P1.1 --> wait R2 x 10 ms
            ^                              |
            |   S2 pressed & R2<255: R2++ |
            +--  S1 pressed & R2>1 : R2-- <+

Program

        ORG 0000H
        MOV P2,#0FFH       ; P2 as input (write 1s), switches active low
        MOV R2,#20         ; half-period = 20 x 10 ms = 200 ms
MAIN:   CPL P1.1           ; toggle LED
        MOV A,R2
        MOV R3,A           ; R3 = number of 10 ms units
WAIT:   ACALL DELAY10      ; 10 ms
        DJNZ R3,WAIT
        JB P2.1,CHK2       ; P2.1 = 1 -> "faster" switch not pressed
        CJNE R2,#1,DECR    ; already at minimum (fastest)?
        SJMP CHK2
DECR:   DEC R2             ; shorter delay = faster blinking
CHK2:   JB P2.2,MAIN       ; P2.2 = 1 -> "slower" switch not pressed
        CJNE R2,#0FFH,INCR ; already at maximum (slowest)?
        SJMP MAIN
INCR:   INC R2             ; longer delay = slower blinking
        SJMP MAIN

DELAY10: MOV R6,#20        ; about 10 ms at 12 MHz
L1:     MOV R7,#248
L2:     DJNZ R7,L2
        DJNZ R6,L1
        RET
        END

Explanation:

  • MOV P2,#0FFH makes P2 an input port.
  • CPL P1.1 toggles the LED; the delay is R2 repetitions of DELAY10 (10 ms), so the half-period is R2 x 10 ms (200 ms initially, 2.5 Hz blinking).
  • JB P2.1,CHK2 skips if S1 is not pressed; if pressed and R2 is not yet 1, DEC R2 makes the delay shorter, so the blink is faster.
  • JB P2.2,MAIN skips if S2 is not pressed; if pressed and R2 is not yet 255, INC R2 makes the blink slower.
  • In simulation, holding S1 reduced the half-period 0.20 s to 0.19 s to 0.18 s per toggle and S2 raised it again.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 9 questions →