문제

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");
}

다른 팁

Presumably it means the same thing it means in standard C. !x evaluates to 1 if x==0, or to 0 otherwise. The result is of type int.

If you're looking for a bitwise complement that inverts all the bits, you want the ~ operator.

UPDATE :

There's more to it than that; see Clifford's answer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top