Setting bits in microcontroller registers without getting confused
Last updated: Oct 15, 2023
Flipping bits the easy way
Writing long binary numbers to set registers on microcontrollers is error prone. How can we make this easier?
Define preprocessor macros for setting, clearing and reading bits.
Preprocessor macros to manipulate bits
I learned most of how to flip bits using macros from issue 180 of Circuit Cellar, dated July 2005. I’ve had a subscription to this magazine for almost 20 years. I’ve written a handful of articles for the magazine. They pay cold, hard cash for anything they publish.
Here’s the good stuff:
#define bit(n) (1 << n) #define bit_set(var, mask) ((var) |= (mask)) #define bit_clear(var, mask) ((var) &= ~(mask)) #define bit_toggle(var, mask) ((var) ^= (mask)) #define bit_read(var, mask) ((var) & (mask))
Set bits 0, 3, 5 high in register DIR:
bit_set(DIR, bit(0) | bit(3), | bit(5));
You get the idea.