C and small microcontrollers

When wring code for small microcontrollers often single bits need to be read, written and checked. Often there are registers (e.g. 8 bit wide) where every bit has its meaning.

C would offer a very nice way to access single bit by using structure with the data type unsigned where even number of bits could be grouped. Unfortunately this has a big disadvantage if it comes to portable code and C compiler issues. First depending on little or big endians, all structures would have to be flipped or two versions would have to be maintained. Second the C compiler might move the bits around in the memory as it desires resulting in empty spaces between the bits (paddings,,trailers and so on).

An other approach (that avr-gcc uses) is assigning numbers to bit names and using left shift functions.

reg = (1<<D7) // shifts 1 as defined by D7, so it results in 0x80

To look a bit nicer avr-gcc has the _BV macro that hides the shift operation, however it uses the same amount of characters.

reg = _BV(D7)

Those shift commands can be put in brackets and logically + or | to get a byte constant.

Since most registers can be read back individual bits can be set as:

reg |= (1<<D7);  // set D7

To clear individual bits:

reg &= ~((1<<D7) | (1<<D6)); // clear D7 and D6

To toggle a bit

reg ^= (1<<D7);  // toggles D7

To test bits

Linurs Hosttech startpage