Search code examples
c++embeddedbit-manipulationmicrocontrollervolatile

How to define universal function for bit setting in C++?


I have got following problem in C++. I have a variable which is a pointer to a mcu peripheral register

uint32_t volatile * ctrl_reg;

I have defined a function for bit setting in given 32 bits word. This function is intended to be used not only for setting bits in peripheral registers but also in common 32 bits variables.

uint32_t bitMask(uint8_t bitPos)
{
    return 1UL << bitPos;
}

void setBit(uint32_t *word, uint8_t bitPos)
{
    *word = *word | bitMask(bitPos);
}

My problem is that as soon as I call

setBit(ctrl_reg, enable_bit);

the compiler warns me that pointer to volatile uint32_t is not compatible with pointer to uint32_t. I see but I don't know how to resolve my issue in clean manner i.e. how to use common function for bits setting in registers and also in common variables. Can anybody help? Thanks in advance.


Solution

  • Simply don't write bloatware for to hide away simple and readable bit manipulations.

    ctrl_reg |= 1u << n; is already super-fast and super-readable. This code cannot be improved. Every C programmer can see what it does with a quick glance, it's as canonical as code gets.

    The only kind of improvement possible is to use named bit masks, such as:

    #define CTRL_FOO (1u << 5)
    #define CRTL_BAR (1u << 6)
    ...
    ctrl_reg = CRTL_FOO | CTRL_BAR;
    

    More info about how to access/declare hardware registers here:
    How to access a hardware register from firmware?