Tag Archives: C

Pointers and the const keyword

One thing I remember from my early days as a C-programmer as all too easy to mess up is the usage of the const keyword in the context of pointers.

Given the following lines of code, which pointer is a pointer to a constant value, and which is a constant pointer to a value?

int v1, v2;
const int * p1 = &v1;
int * const p2 = &v2;

The simple rule of thumb to decipher this type of declaration, I soon learned, was to read the declaration from the very end.

So, p1 is a pointer to an int that is constant, and p2 is a constant pointer to an int.

Thus, neither of the two expressions would be allowed:

*p1 = 2;
p2 = &v1;

But both these would:

p1 = &v2;
*p2 = 1;

A simple CRC implementation

Every now and then I find myself worrying about data transmitted over a media now showing up correctly on the other side. The best way to make sure this is the case is to add a CRC calculation to the data being transmitted.

While the web is swamped with implementations of CRC calculations, I still find it useful to have one reliable piece of software doing this type of calculation conveniently at hand, enter this zip archive.

The linked to CRC code was provided by Michael Barr at http://www.barrgroup.com/.

Memory Access through a structure

One of the more common things you do as an Embedded Systems programmer is accessing registers of different peripherals.

Rather than hardcoding the address to each and every register in a peripheral, I find it convenient to typedef a C-struct for easy access of these registers. Setup the struct with a layout identical to that of your hardware registers, assign a pointer to the structure to point at the (base)address of the hardware registers in question, and voila! Access each register as a regular element of the structure for read/write operations.

typedef struct {
volatile uint8_t STATUS;
volatile uint8_t TX_REG;
volatile uint8_t RX_REG;
} hw_device_t;

hw_device_t * const ptr = (hw_device_t *) 0xFF000000;

hw_device->RX_REG = 0x10;
hw_device->TX_REF = 0x03;
uint8_t current_status = hw_device->STATUS;

Note: all elements of structure should be made volatile to avoid compiler optimizations.