I was playing with a simple demo that sets up the clock on an STM32F4 board, I got the demo working.
But I didn't like the look of the code, for example
If that's not clear to you, join the club. It's actually setting the MC01 clock output pin to be driven by the PLL and the MC01PRE (the divider) to 7 (divide by 5).
But by defining a simple bit field typedef and a macro, that code can be rewritten:
Not only is this much more readable, it leads to less generated machine instructions too:

all of a sudden this "low level" code started to look less low level.
Why on earth didn't ST do something like that, if they'd just defined a bitfield typedef for each of these various registers, and an associated simple macro, it would so much easier to follow examples and samples and so on. Furthermore, by making the typedef contain a union where the entire datum is just an int32, we can use that member to zeroize the entire register:
Here's the typedef and macro:
But I didn't like the look of the code, for example
C:
RCC->CFGR &= ~0x07E00000;
RCC->CFGR |= 0x07600000;
But by defining a simple bit field typedef and a macro, that code can be rewritten:
C:
RCC_CFGR->MCO1 = 3;
RCC_CFGR->MCO1_PRE = 7;

all of a sudden this "low level" code started to look less low level.
Why on earth didn't ST do something like that, if they'd just defined a bitfield typedef for each of these various registers, and an associated simple macro, it would so much easier to follow examples and samples and so on. Furthermore, by making the typedef contain a union where the entire datum is just an int32, we can use that member to zeroize the entire register:
C:
RCC_CFGR->ALLBITS = 0;
C:
#define RCC_CFGR ((CFGR_Type_ptr)&(RCC->CFGR))
typedef union
{
struct
{
__IO BIT SW : 2;
__IO BIT SWS : 2;
__IO BIT HPRE : 4;
__IO BIT UNUSED2 : 2;
__IO BIT PPRE1 : 3;
__IO BIT PPRE2 : 3;
__IO BIT RTCPRE : 5;
__IO BIT MCO1 : 2;
__IO BIT UNUSED1 : 1;
__IO BIT MCO1_PRE : 3;
__IO BIT MCO2_PRE : 3;
__IO BIT MCO2 : 2;
};
uint32_t ALLBITS;
} CFGR_Type, * CFGR_Type_ptr;
Last edited:



