Friday, May 25, 2012

Reading Port Status

From the previous examples, we seen how easy to output values to the ports of the 8051. Now we will learn how to read port status. For the following examples, beside from the LEDs connected at Port2, we will connect two switches on P3.6 and P3.7 as seen on the diagram below.



 In SDCC, ports can directly read. For instance if we want to read the status of the switch connected at P3.6, we can detect the if it was pressed using the following line of codes.

if(!P3_6)
{
  ...your code here;
}
The if statement above will test the value of P3.6 if it is  zero since we have the port pulled to VCC, so when the switch is pressed, it will be pulled to ground, so the value of P3.6 becomes zero. The value of P3.6 can also be read by reading whole 8 bits of P3 and masking its value to separate P3.6 from others. It can be done by the following line of codes.

unsigned char switch_value = 0; // a variable where port value will be stored.

value = P3 & 0x40;

if(value == 0x00)
  {
      ..your code here;
  }
We mask the value of the port such that other bits are read as zero, and the bit position of P3.6 is 1 so that we can detect the change if its status changes from 1 to 0.

Example Application :
 if P3.6 is pressed , all LEDs connected to PORT2 will light, else LEDs will be off.

#include <at89x52.h>

void main (void)
{
   unsigned char sw_value = 0;
   P2 = 0;

      while(1)
         {
            sw_value = P3 & 0x40;
           
            if(sw_value == 0){
                P2 = 0xFF;
             }
            else{
               P2 = 0x00;
             }
         }
}
Demo of the above code:


With the basic knowledge of writing and reading the ports is the basic building blocks in more advance projects.



















 

No comments:

Post a Comment