Mateusz Tocha
Mateusz Tocha

Reputation: 15

C Union, Padding of array inside the struct

I have code as below:

  struct MODER_BITS
{   __IO uint32_t MODER0:2;
    __IO uint32_t MODER1:2;
    __IO uint32_t MODER2:2;
    __IO uint32_t MODER3:2;
    __IO uint32_t MODER4:2;
    __IO uint32_t MODER5:2;
    __IO uint32_t MODER6:2;
    __IO uint32_t MODER7:2;
    __IO uint32_t MODER8:2;
    __IO uint32_t MODER9:2;
    __IO uint32_t MODER10:2;
    __IO uint32_t MODER11:2;
    __IO uint32_t MODER12:2;
    __IO uint32_t MODER13:2;
    __IO uint32_t MODER14:2;
    __IO uint32_t MODER15:2;
};

typedef union {
    __IO uint32_t all;
    struct MODER_BITS bit;
}MODER_REG;

then I am able to use the GPIO struct

typedef struct
{
  MODER_REG MODER_REG;
  //__IO uint32_t MODER    ;/*!< GPIO port mode register,                  
  __IO uint32_t OTYPER;   /*!< GPIO port output type register,            */
  __IO uint32_t OSPEEDR;  /*!< GPIO port output speed register,          */
  __IO uint32_t PUPDR;    /*!< GPIO port pull-up/pull-down register,     */
  __IO uint32_t IDR;      /*!< GPIO port input data register,            */
  __IO uint32_t ODR;      /*!< GPIO port output data register,           */
  __IO uint32_t BSRR;     /*!< GPIO port bit set/reset register,          */
  __IO uint32_t LCKR;     /*!< GPIO port configuration lock register,     */
  __IO uint32_t AFR[2];   /*!< GPIO alternate function registers,     */
} GPIO_TypeDef;

Then I can use this definition like this:

GPIOA->MODER_REG.bit.MODER0=0x2;

Is there some way to use the array inside the struct MODER_REG? To used the GPIO like this:

GPIOA->MODER_REG.bit.MODER[0]=0x2;

How should looks like definition of

struct MODER_BITS{
 __IO uint32_t MODER[?]:? //options     
}

PS: __IO is just a macro of volatile

Please advice.

Upvotes: 0

Views: 326

Answers (1)

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18865

There is no way. C doesn't allow arrays of bits.

However, you can still access the original word by using bitmask:

GPIOA->MODER_REG.all = (GPIOA->MODER_REG.all)&(~3<<0)|(2<<0);

The first part resets the bits at position 0, the second part sets then to value 2.

Upvotes: 3

Related Questions