Tips for overriding the register bit field in C

I am struggling to come up with a clean way to override some registry bit fields that can be used on the chip I'm working with.

For example, it is that one of the CAN configuration registers is defined as:

extern volatile near unsigned char       BRGCON1;
extern volatile near struct {
  unsigned BRP0:1;
  unsigned BRP1:1;
  unsigned BRP2:1;
  unsigned BRP3:1;
  unsigned BRP4:1;
  unsigned BRP5:1;
  unsigned SJW0:1;
  unsigned SJW1:1;
} BRGCON1bits;

None of these definitions are useful, as I need to assign BRP and SJW as follows:

struct
{
    unsigned BRP:6;
    unsigned SJW:2;
} GoodBRGbits;

Here are two attempts I made:

Attempt # 1:

union
{
    byte Value;
    struct
    {
        unsigned Prescaler:6;
        unsigned SynchronizedJumpWidth:2;
    };    
} BaudRateConfig1 = {NULL};
BaudRateConfig1.Prescaler = 5;
BRGCON1 = BaudRateConfig1.Value;

Attempt number 2:

static volatile near struct
{
    unsigned Prescaler:6;
    unsigned SynchronizedJumpWidth:2;
} *BaudRateConfig1 = (volatile near void*)&BRGCON1;
BaudRateConfig1->Prescaler = 5;

Are there any “cleaner” ways to accomplish what I'm trying to do? In addition, I am a bit unhappy about the unstable close casting in attempt No. 2. Do I need to specify a variable next to it?

+3
source share
2 answers

. -, , .

(, )...

#define BRP0  0x80
#define BRP1  0x40
#define BRP2  0x20
#define BRP3  0x10
#define BRP4  0x08
#define BRP5  0x04
#define SJW0  0x02
#define SJW1  0x01

, . .

, .

+2

.

union/struct , , ​​.

// foo.h
// Declare struct, declare pointer to hw reg

struct com_setup_t {
  unsigned BRP:6;
  unsigned SJW:2;
};

extern volatile near struct com_setup_t *BaudRateConfig1;

// foo.c
// Initialise pointer

volatile near struct com_setup_t *BaudRateConfig1 = 
(volatile near struct com_setup_t *)0xfff...;

// access hw reg
foo() {
  ...
  BaudRateConfig1->BRP = 3;
  ...
}

/ , , , , .

+1

Source: https://habr.com/ru/post/1740007/


All Articles