Home » Embedded Systems

Reading and Writing values in Microcontroller Ports

In this article, we are going to learn - how to read and write values (bytes, bits) in Microcontroller’s ports?
Submitted by Sudarshan Paul, on July 01, 2018

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;

		// 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;

		x = Switch_pin; // Read Pin 1.0
		LED_pin = x; // Write to Pin 1.1

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.