Reading and Writing Values in Microcontroller Ports

In this tutorial, we will learn how to read and write values (bytes, bits) in Microcontroller's ports? By Sudarshan Paul Last updated : May 13, 2023

Reading and Writing Bytes

In this example, we will see how we can read input from one port and copy it to the other port of an 8051 microcontroller.

A simple "Super Loop" application which copies the value from Port 1 (P1) to Port 2 (P2).

#include <Reg52.H>

void main(void) {
  unsigned char Port1_value;

  // Must set up P1 for reading
  P1 = 0xFF;

  while (1) {
    // Read the value of P1
    Port1_value = P1;
    // Copy the value to P2
    P2 = Port1_value;
  }
}

Reading and Writing Bits

In the previous example, we have seen how we can copy the value from one port of microcontroller to the other. In this example, we will refer how we can copy the value from one pin to another pin of the same port in an 8051 microcontroller. This is required in cases when the pins of a particular port are connected to the different input and output devices. Thus in such cases, the code to access the devices will be different as per the companies manufacturing them. So there comes the necessity to read from and write to a particular pin only, rather than the entire port of the microcontroller.

Let's see how this can be achieved,

#include <Reg52.H>

sbit Switch_pin = P1 ^ 0;
sbit LED_pin = P1 ^ 1;

void main(void) {
  bit x;

  // Set switch pin for reading
  Switch_pin = 1;

  while (1) {
    x = Switch_pin; // Read Pin 1.0
    LED_pin = x; // Write to Pin 1.1
  }
}



Comments and Discussions!

Load comments ↻





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