0

I would like to define a single bit of a register or a variable. For example: #define Pin5 (5th bit of portA) //assuming porta is a 16 bit data type.

How can I define a single bit of a variable so that I can toggle that bit easily and make my code easier on my eyes. Please note that I want the bit value to become the RValue of the variable.

for example Pin5 = 1; //will result in the 5th bit of partA to be 1

Sam
  • 51
  • 1
  • 5
  • 1
    Possible duplicate of [How do you set, clear and toggle a single bit in C/C++?](http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c) – AShelly Nov 16 '15 at 18:29
  • 1
    See [this answer](http://stackoverflow.com/a/50691/10396) – AShelly Nov 16 '15 at 18:30
  • @AShelly Actually, Sam seems to be asking whether there is any way to define the bit as an lvalue, which is a more interesting question than just "how do I set it". – Jeff Y Nov 16 '15 at 19:48
  • Oh good point. The answer is unions of bitfields. – AShelly Nov 16 '15 at 19:54
  • Yes, I thought that too, but then I read the comments on the bitfield answer at your link, and realized any use of bitfields is going to be quite bad. – Jeff Y Nov 16 '15 at 20:02

1 Answers1

0

Given that bitfields are a bad idea, the cleanest I've been able to come up with for code "easy on the eyes" (i.e. wrapping as much syntax as possible into macros):

#define setbit(n) |=(1<<(n))
#define clrbit(n) &=~(1<<(n))

And then the code for your example would be:

portA setbit(5);
Jeff Y
  • 2,437
  • 1
  • 11
  • 18