Defining constructors for classes representing memory-mapped devices is a good idea, if only you could get those constructors to run automatically.
Slightly more than a year ago, I wrote a column explaining some common approaches to representing and manipulating memory-mapped devices in C.1 I followed that with another column explaining some better alternatives using classes in C++.2 The C++ alternatives are better in the sense that they yield
interfaces that are typically easier to use correctly and harder to use incorrectly than the C alternatives, and yet have much the same performance.
In C, structures often provide the best way to model the device registers of memory-mapped devices. For example:
typedef struct timer_type timer_type;
struct timer_type
{
device_register TMOD;
device_register TDATA;
device_register TCNT;
};
defines the layout for a timer that employs three device registers.
The header file that defines this structure might also define useful constants and types for manipulating the registers, such as:
#define TE 0x01
#define TICKS_PER_SEC 50000000
typedef uint32_t timer_count_type;along with functions that provide basic operations for programming a timer, such as:
void timer_disable(timer_type *t);
void timer_enable(timer_type *t);
void timer_set(timer_type *t, timer_count_type c);
timer_count_type timer_get(timer_type const *t);
To read the entire article, click here.