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)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.
{
...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.
unsigned char switch_value = 0; // a variable where port value will be stored.
value = P3 & 0x40;
if(value == 0x00)
{
..your code here;
}
Example Application :
if P3.6 is pressed , all LEDs connected to PORT2 will light, else LEDs will be off.
Demo of the above code:#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;
}
}
}
With the basic knowledge of writing and reading the ports is the basic building blocks in more advance projects.