Class 2 - Input Handling – LED Control with Button

April 28, 2025

Hello buddies! 👋
In the previous tutorial, we explored what a port is and learned about bit and byte addressable ports. We even saw how to control output using a basic LED blinking example.

In this post, let’s see how input works with the 8051 microcontroller, especially how to use a button to control an LED.

🔍 Checking the Status of a Pin

To check if a particular pin is ON (HIGH) or OFF (LOW), it’s quite simple.

For example, if we want to check pin P1.2:

Or directly use it in an if condition:

You can also access the bit using byte operations:

🔘 Connecting a Button to the 8051

Let’s connect a push button to pin P1.2 to control an LED.

We pull up the pin using a 10k resistor connected to 5V, and the other terminal of the button goes to ground.

So, when the button is not pressed, P1.2 receives 5V.
When the button is pressed, it gets grounded, and P1.2 becomes 0V.

To trigger an action when the button is pressed:

⚠️ Problem: LED Keeps Toggling Randomly

If you check the button in a loop like this:

Then the LED might toggle multiple times during a single press. That’s because the condition remains true as long as the button is held down.

🛠 Solution 1: Wait for Button Release

Modify the code to wait until the button is released:

🛠 Solution 2: Debouncing

Older buttons may introduce noise due to mechanical bouncing of the spring inside the button. This can trigger multiple toggles.

Debounce Fix:

After detecting a button press, wait for a short time (e.g., 1 ms), and check again.

This ensures a clean and single toggle per press.

📌 Summary

  • Read pin values using direct or byte-wise methods.
  • Use pull-up resistors for input pins.
  • Use !P1_2 to detect button press.
  • Prevent multiple toggles using button release logic or debounce delay.

In the next post, we’ll explore interrupt-based input handling for even better efficiency!

Thanks for reading! 😊

Leave a reply
Class 1 – Blinking an LEDClass 3 – 7-Segment Display Counter

Leave Your Reply