Accessing Ports and Pins in 8051 Microcontroller

In this tutorial, we will learn how to access and write instructions for various ports and their specific pins through C programming using Keil? By Sudarshan Paul Last updated : May 13, 2023

How to access Ports and Pins in 8051 Microcontroller?

The 8051 microcontrollers have 8-bit ports. All the ports are bidirectional in nature, which means they can perform both input and output operations. In addition to performing some specific operations like controlling the access to external storage.

In order to control the ports, we need a function known as "Special Function Registers" (SFRs). There are four ports in an 8051 microcontroller and these are named as P0, P1, P2, P3 respectively. SFRs denotes the physical address of these ports in the internal RAM: P0 is at address 0x80, P1 is at address 0x90, P2 is at address 0xA0 and P3 is at address 0xB0.

Pins and ports of 8051

If you wish to access these ports, we need to write these addresses. These addresses of ports are predefined in the reg52 file which is inserted as the source file using the #include pre-directive. They are defined in the file as:

sfr P0 = 0x80;
sfr P1 = 0x90;
sfr P2 = 0xA0;
sfr P3 = 0xB0; 

Thus now we can straightforward access the ports to give appropriate instructions.

unsigned char Port_data;
Port_data = 0x0f;
P1 = Port_data;

Even though we are referring to an address in the above definition the use (*) or indirection operator is not necessary since the compiler understands them by itself as SFRs.

The above example is written to control the whole of port 1. But in case we wish to control only the specific pins in a particular port. Suppose if we wish to control 5th pin of PORT 1, we can use the following declarations:

sbitLED_pin = P1^5;

The use of sbit keyword allows us to define bit variable which is already a part of some predefined byte-sized variable. The ^ symbol that is used to specify the 5th pin in Port 1 is a Keil-specific operation i.e. this feature is exclusively available when you are working with Keil software.

Creating and using a bit variable

The 8051 microcontrollers have BDATA area which is around 16-bytes in size. This is used to store user-defined bit-sized variables. The variable can only take values 0 and 1.

For example, in "hello world" program that we discussed earlier:

We use the LED_state_G variable to store the current state of the LED either ON or OFF.

bit LED_state_G;

The variable was used in the LED_FLASH_Change_State function under if - else statement.

if (LED_state_G == 1)
{
	LED_state_G = 0;
	LED_pin = 0;
}



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.