Search code examples
carduinomicrocontrollerbitbit-fields

C - How do I receive a bit from a bit field as a parameter in a function?


I have a bit field defined like that (it is from a microcontroller library, so it looks a bit different):

typedef union {
    byte Byte;
    struct {
        byte PTAD0       :1;
        byte PTAD1       :1;                                       
        byte PTAD2       :1;
        byte PTAD3       :1;
        byte PTAD4       :1;
        byte PTAD5       :1;
        byte             :1;
        byte             :1;
    } Bits;
} PTADSTR;
extern volatile PTADSTR _PTAD @0x00000000;
#define PTAD                            _PTAD.Byte
#define PTAD_PTAD0                      _PTAD.Bits.PTAD0
#define PTAD_PTAD1                      _PTAD.Bits.PTAD1
#define PTAD_PTAD2                      _PTAD.Bits.PTAD2
#define PTAD_PTAD3                      _PTAD.Bits.PTAD3
#define PTAD_PTAD4                      _PTAD.Bits.PTAD4
#define PTAD_PTAD5                      _PTAD.Bits.PTAD5

So. Let's say that i want a function that sets a bit, like that:

void setbit(bit Bit) {
     Bit = 1;
}

Of course, the "bit" declaration doesn't work. I would like a declaration that I could use

setbit(PTAD_PTAD5)

and it would set this bit. I could do

void setbit(byte Byte, byte number) {
     Byte |= 1<<(number);
}

and send

setbit(PTAD,5);

That works perfectly, but... that's not what I want, cause I want to do something like Arduino's libraries. Anyone has any idea how to do that in the way I prefered?


Solution

    1. C is a pass-by-value language, so even if you could do:

      void setbit(bit Bit) {
           Bit = 1;
      }
      

      it would be a no-op.

    2. You can do what you're trying with a function-like-macro:

      #define setbit(x) do { (x) = 1; } while(0)
      

      If you call this macro with PTAD_PTAD5, it should work like you expect.