1

Using winAVR for the following code.

I got an 8-bit PIN here that I need to OR it with 00000010 or 0x02 to set the 7th bit.

Now what I have to do is the following :

  • Set Port B bit 7
  • Wait for 1ms
  • Clear port B bit 7
  • wait 19ms

BUT, I shouldn't change the other bits in these steps.

So I have to :

  • Read port B
  • Set bit needed
  • write the modified value back to the port
  • Clear bits
  • Write back to Port B

So my test code is :

B=PINB|0x02
Loop delay for 1ms
BP=PINB&0x00
Loop for 19ms

But I think that the other bits are going to be altered in this process, my question is, HOW am I supposed to manipulate one bit of an 8 bit port without changing the other bits ?

Thanks alot !!

NLed
  • 1,845
  • 14
  • 39
  • 68

3 Answers3

4

You need BP=PINB & ~0x02 The ~ operator is logical NOT. The and operator keeps only the bits other than 2.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
1

You use the bitwise negation of the setting mask, and AND that:

B = PINB & ~0x02

For the selected bit, the bitwise negation sets that bit to zero; all the others are one. The ones do not change the value in PINB when ANDed.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

This page has a good summary of several tricks with bitwise operators. http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know

rogue780
  • 155
  • 1
  • 1
  • 9