SWITCH INTERFACING WITH 8051

Photo of author

By Jackson Taylor

Home » Electronics Topics » 8051 Microcontroller » SWITCH INTERFACING WITH 8051

As an Amazon Associate we earn from qualifying purchases.

A switch is the simplest input you can connect to a microcontroller, and it is the usual first step before moving on to keypads, sensors and displays. This tutorial shows how to read a push button with an AT89S52 (8051 family) microcontroller, write the program in MikroC and test everything in a Proteus simulation.

The example is small. When you press the switch connected to pin P2.1, the microcontroller changes the output on pin P2.0, which drives an LED. The same idea works for any digital input, such as a limit switch, a door contact or a mode button.

Project details

  • MICROCONTROLLER – AT89S52
  • COMPILER – MIKROC
  • SIMULATION – PROTEUS 8.1
  • CRYSTAL – 4MHz

You can get the Proteus simulation files from the link below and open them to follow along.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
DOWNLOAD SIMULATION FILES

Video demonstration

The video below shows the circuit working in simulation.

How a switch works with an 8051 pin

A microcontroller pin cannot read a “open” or “closed” contact directly. It reads a voltage and decides whether it is a logic 1 (high) or a logic 0 (low). The switch therefore has to produce one of those two levels.

The most common way is to connect one side of the switch to the pin and the other side to ground. When the switch is open, the pin must be held high by a pull-up. When the switch is closed, the pin is pulled to ground and reads 0.

This means the logic is active low: pressed reads 0, released reads 1.

Pull-up on the AT89S52 ports

Ports P1, P2 and P3 on the 8051 family have internal pull-ups, so no external resistor is needed for a simple switch on those pins. Port P0 is different. It has no internal pull-ups, so it needs external resistors if you use it as an input or for logic-high outputs.

See also
HOME AUTOMATION (DEVICE CONTROLLING ) USING MSP430G2553 , IR REMOTE AND RELAY

The 8051 pins are quasi-bidirectional. To use a pin as an input you first write a 1 to it, which releases the pin so that the outside world (your switch) can pull it low. That is why the program below starts by writing 1 to the switch pin.

Components needed

CIRCUIT

The switch is connected to pin P2.1 and the LED to pin P2.0. The crystal sits across the XTAL1 and XTAL2 pins, and the reset pin is wired as usual. Check the diagram below for the exact connections used in the simulation.

Proteus circuit of a push button switch and LED connected to an AT89S52 microcontroller

PROGRAM


/*
MICROCONTROLLER -AT89S51/52
COMPILER ---MIKROC
BY---EMERGING TECHNOLOGIES --WWW.EMERGINGTECHS.ORG
*/
void main()
{
    P2.f1=1;   //pull up
    while(1)
    {
        if( P2.f1==0)
        {
            P2.f0=0;
        }
        else
        {
            P2.f0=1;
        }
    }
}

How the code works

  1. P2.f1=1 writes a 1 to the switch pin so it behaves as an input with its pull-up active.
  2. while(1) keeps the program running forever, checking the switch again and again.
  3. if(P2.f1==0) is true while the switch is pressed, because pressing pulls the pin to ground. In that case P2.0 is set to 0.
  4. Otherwise, when the switch is released, P2.0 is set to 1.

In other words, the output pin simply follows the state of the switch. Whether the LED lights when pressed or when released depends on how it is wired: an LED connected between the supply and the pin turns on when the pin is low, while one connected between the pin and ground turns on when the pin is high.

Running the simulation in Proteus

  1. Open the downloaded design file in Proteus 8.1.
  2. Double-click the AT89S52 and load the compiled HEX file produced by MikroC.
  3. Set the clock frequency of the microcontroller to 4 MHz to match the crystal.
  4. Press the play button and click the switch to see the LED respond.
See also
LCD INTERFACING WITH 8051 (AT89S52) -SIMULATION IN PROTEUS

Switch bounce and how to deal with it

A mechanical switch does not change state cleanly. For a few milliseconds after you press or release it, the contacts bounce and the pin may read a rapid series of 0s and 1s. In the example above this does not matter, because the LED simply follows the pin.

It does matter when you count presses or toggle something on each press. In those cases the microcontroller may see one press as several. A simple software fix is to wait a short time after detecting a change, then check the pin again. Delays of around 10 to 20 ms are commonly used.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

A toggle example using the MikroC delay function could look like this:


void main()
{
    P2.f1=1;   //pull up
    P2.f0=1;
    while(1)
    {
        if( P2.f1==0)
        {
            Delay_ms(20);          // wait for bounce to settle
            if( P2.f1==0)
            {
                P2.f0 = ~P2.f0;    // toggle the LED
                while(P2.f1==0);   // wait until released
            }
        }
    }
}

Treat this as a starting point and test it in the simulator before using it on hardware.

Common mistakes

  • Forgetting to write 1 to the input pin. The pin may not read the switch correctly.
  • Using port P0 without pull-up resistors. The pin will float when the switch is open.
  • Mismatched clock settings. If the crystal in the design and the clock set in Proteus differ, timing and delays will be off.
  • No current-limiting resistor on the LED. This can damage the LED or the pin.
  • Ignoring bounce in programs that count or toggle.

What to try next

Once a single switch works, you can read several switches on one port, or use a matrix to save pins. Our guide on keypad interfacing with 8051 shows how to scan rows and columns. If you want to show the result on a display, see LCD interfacing with 8051. To learn more about driving pins, read about 8051 digital output.

The same idea carries over to other chips. If you work with PIC-style controllers, there is a similar dsPIC30F2010 push button example in MikroC.

See also
UART - 8051

FAQ

Do I need an external pull-up resistor for a switch on the 8051?

Not on ports P1, P2 and P3, which have internal pull-ups. You do need one on port P0, which has none.

Why does the pin read 0 when the switch is pressed?

The switch connects the pin to ground, so pressing it pulls the pin low. This is called active-low wiring and is the most common way to connect a switch.

Can I use the same code for AT89S51?

Yes. The two chips share the same basic port structure, and the program header in this article lists both AT89S51 and AT89S52. Check the pin and port names in your compiler settings.

Why does my LED flicker or toggle more than once per press?

This is usually switch bounce. Add a short delay and re-check the pin, as shown in the toggle example above, or use a hardware debounce circuit.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works