I'm programming with Keil uVision 4.
I have some code like this:
sbit X = P3 ^ 3; // X is third bit of P3 register
...
while (1) {
X = !X; // X equals not X ?!
if (X == 0)
printf("0");
else
printf("1");
}
I can control `P3^3
generic input pin, because on this pin i've got a PIR (pulse infrared sensor). It gives me 1 on that line when it is blinking, 0 when it is sleeping.
when P3^3
is pulled-up to 1
,
output is (as expected) 10101010101010..
When it is still to 0,
output is (as not expected) 0000000000000..
The behaviour I'm obtaing is that I described above, considering that sbit X
is setted/unsetted by PIR..
So the question is, what is the meaning of the operator !
in the Keil C51 compiler?
In Keil C51, to quote the manual:
The sbit type defines a bit within a special function register (SFR)
So you are not declaring a variable X and reading it once before the loop, rather you are defining a reference to P3.3, and reading it's state on every iteration of the loop. That is to say that X is a reference to the hardware I/O pin register, not a variable.
Despite appearances sbit
is not a simple typedef
alias and the ^
is not a bitwise XOR operator. Rather it defines a reference to a bit addressable register. Assigning X
writes to the hardware register - the behaviour is then defined by the hardware in this case rather than the language. The ability to apparently change the value of X when it is externally pulled high, I am guessing is in the nature of the GPIO hardware rather than any strange behaviour of the !
operator. Check the hardware documentation for I/O pin behaviour, but I am guessing again that pulling it high makes the pin output-capable
To get the behaviour (I imagine) you expect you would code it thus:
sbit p = P3 ^ 3; // p is third bit of P3 register
...
int X = p ; // get p's current value
while (1) {
X = !X; // X equals not X ?!
if (X == 0)
printf("0");
else
printf("1");
}