The connection is as follows An infrared sensor circuit which yields 0 or 5v depending on closed or open circuit output line to port 2_0 pin of microcontroller 8051 philips.Problem is when i do this the circuit value are overridden by the current value on port 2_0 led always goes on.Here is my 开发者_JAVA技巧code(in keil c) i guess i have not configured P 2_0 as input properly
void MSDelay(unsigned int);
sbit led=P1^0;
void main()
{
unsigned int var;
P2=0xFF;
TMOD=0x20;
TH1=0xFD;
SCON =0x50;
TR1=1;
while(1)
{
var=P2^0;
if(var==0)
{
led=1;
SBUF='0';
while(TI==0);
TI=0;
MSDelay(250);
}
else
{
led=0;
SBUF='9';
while(TI==0);
TI=0;
MSDelay(100);
}
}
}
EDIT : I was facing a problem since the 8086 processor i was using had a fault in it. Would recommend anyone trying this to get a few spares when programming.
jschmier has a good point. Also the port may not be configured correctly, or is there something in the circuit that is causing the led to toggle off and on very quickly so it looks like it is on all the time.
You typically use the sbit data type for P2_0 to define a bit within a special function register (SFR).
From C51: READING FROM AN INPUT PORT (modified)
sfr P2 = 0xA0;
sbit P2_0 = P2^0;
...
P2_0 = 1; /* set port for input */
var = P2_0; /* read P2_0 into var */
It is important to note that sbit variables may not be declared inside a function. They must be declared outside of the function body.
Another option may be to read all 8 pins of P2 and then mask off the unwanted bits.
char var; /* define 8 bit variable */
P2 = 0xFF; /* set P2 for input */
var = P2; /* read P2 into var */
var &= 0x01; /* mask off unwanted bits */
Rather than read P2 or the P2_0 pin into an unsigned int (16 bits), you could use a char (8 bits) or single bit to save on memory.
char var;
...
var = P2;
or
bit var;
...
var = P2_0;
Another option may be to make the char bit-addressable.
char bdata var; /* bit-addressable char */
sbit var_0 = var^0; /* bit 0 of var */
...
var = P2; /* read P2 into var */
if(var_0 == 0) /* test var_0 (bit 0 of var char) */
{
...
}
You can find additional useful information in the Keil Cx51 Compiler User's Guide and related links.
Note: Most of my 8051 experience is in assembly. The C examples above may not be 100% correct.
Thank you so much... my coding works
And I learn how to define input port and read the data
#include<reg51.h>
#define opp P1
#define ipp P0
sbit op =P1^0;
sbit ip =P0^0;
main()
{
unsigned int value;
P0=0xFF;
value=P0;
value &=0x01;
if(value==0)
{
P1=0x01;
}
else
{
P1=0x00;
}
}
精彩评论