Acquired wisdom

I'm working on a second device driver today.

When the driver is supposed to poke or read certain memory mapped registers
(and I'd dare say that's quite common) the normal thing is to define a C
structure with the fields specified by the data sheet, and access the
registers through a volatile pointer to a structure of that type.

Needless to say, it is of paramount importance to nail the correct offset for
each register.  This is not itself tricky, except for those sneaky paddings,
that must correspond to appropriate unused fields in the defined struct.

So far I've always found that the datasheets report the registers offset from
the the address where the device is accessible.  Given how common it is to use
the C language in embedded sytems, I think it would be quite useful if data
sheets came already with the definition of a C struct.

Since the compiler won't protect you against accidental missing fields or
wrong paddings, it is wise to cross check the defined structure by copying it
into a little test program and printing out the offset of each field.


       #define ShowRegister(RegName) printf(#RegName ": %02x\n", \
               offsetof(struct quiddikey_registers, RegName)     \
       )

       // packed aligned...
       struct my_struct
       {
               uint32_t field_1;
               uint32_t field_2;
               uint32_t field_3;
               // ...
       };

       int main(int argc, char **argv)
       {
               ShowRegister(struct my_struct, field_1);
               ShowRegister(struct my_struct, field_2);
               ShowRegister(struct my_struct, field_3);
               // ...
       }