Back from holidays, back to other hobbies.
One thing that I hate when programming on MCUs is that you almost always access register directly through macros, masks and bit shifting operations; so, inspired by this talk on Youtube I decided to write my own code to access registers.
The result is a couple of templates that makes it possible to access registers in a clean way.
First is the Bitfield class: it allows to access some specific bits on a memory address; you can combine many Bitfields with an union. For example:
union SR1 { Bitfield<uint16_t, 0, 1> sb; Bitfield<uint16_t, 1, 1> addr; Bitfield<uint16_t, 2, 1> btf; Bitfield<uint16_t, 3, 1> add10; Bitfield<uint16_t, 4, 1> stopf; Bitfield<uint16_t, 6, 1> rxne; Bitfield<uint16_t, 7, 1> txne; Bitfield<uint16_t, 8, 1> berr; Bitfield<uint16_t, 9, 1> arlo; Bitfield<uint16_t, 10, 1> af; Bitfield<uint16_t, 11, 1> ovr; Bitfield<uint16_t, 12, 1> pec_err; Bitfield<uint16_t, 14, 1> timeout; Bitfield<uint16_t, 15, 1> smb_alert; }; SR1* const sr1; sr1->addr.get(); sr1->af.set(0);
With the BitfieldArray class you can access the bits of a register in an array-like manner:
using ODR=BitfieldArray<uint16_t, 0, 1, 1>; ODR* const odr; odr[3]=1; odr.set(3, 1);
This not only looks nice, but it also avoids possible errors in accessing a register bits. And it supports exceptions 😀
The code is on github.