Multiple LEDs controlling though Switch

A momentary switch is connected to P2.5 and four LEDs are connected to the lower nibble of port 0. Your program should behave as follows :

  • Depending on the number of times the SW pressed –
  • the 1st time, LED 0 should be ON only,
  • the 2nd time, LED 1 should be ON only,
  • the 3rd time, LED 2 should be ON only,
  • the 4th time, LED 3 should be ON only,
  • If pressed hereafter none should be ON until the system reset.

Required components

  • 8051 MCU
  • 4 LEDs
  • 4 Registers 330 ohm
  • Push to on switch
  • Jumpers

Circuit diagram

Multiple LEDs controlling though Switch circuit diagram

RED LEDs are connected to the lower nibble of port 0(P0-P3). The cathode of each LED is connected to the Ground. Anode of LED is connected to port0.  The resistor is needed to limit the flow of current.

As the cathode of LED is connected to the Ground terminal, we just need to provide a positive voltage to LED`s Anode terminal. So in order to turn on the LED we just need to give HIGH logic (1) to port pins.

Push Button switch is connected to P2.5.

Code

Header files required:- delay.h

Download it from here

Code description

To turn on the LED when the switch is pressed, we just need to read the switch status, and based on switch status just have to turn on LEDs one by one.

Initially, Port2 is initialized with 0xff. so when the switch is pressed and as another terminal of the switch is connected to the ground Port2.5 will receive logic 0.

Once the switch is pressed, it will give high logic to LEDs, which in turn will glow the LED.

For the first Iteration, the count will be 0.

P0 = (1 << count);

P0 = (1 << 0);

0000 0001; will turn on LED 0.

Now count is incremented by 1.

so when next time switch is pressed.

P0 = (1 << count);

P0 = (1 << 1);

0000 0010; will turn on LED 1.

Now count is incremented by 1.(count is 2 now).

so when next time switch is pressed.

P0 = (1 << count);

P0 = (1 << 2);

0000 0100; will turn on LED 2.

Now count is incremented by 1.(count is 3 now).

so when next time switch is pressed.

P0 = (1 << count);

P0 = (1 << 3);

0000 1000; will turn on LED 3.

Now count is incremented by 1.(the count is 4 now).

Since first we are checking the condition(<4), from now when even if the switch is pressed it will not satisfy if condition and will go in else part. so nothing will happen till we reboot the board.

Download Proteus Circuit and Hex File

Video

Thank you for reading…

Leave a Comment

Your email address will not be published. Required fields are marked *