Tips and tricks (6)

PreviousT&T

Mapping a structure to an array of bytes, the lazy,the  clean and the smart way.

What for? While designing a data logger application, I decided to use a custom variable in order to store individual records and declared it the academic way

typedef struct varRecord {  
		double time;
		uint8_t temperature;
		uint16_t pressure;
} newRecord;

In order to be used this way for exemple

void createRecord() {
	newRecord record;
	record.time = 1;
	record.temperature = 20;
	record.pressure = 1013;
}

So far so good. But what to do now, I want to transfer this information in a vector of bytes? What for? i.e. for transfering data over a serial communication port or a memory chip.

The key word is: union. While struct is concatenating variables, union is overlapping them! The size of the resulting variable is corresponds tothe size of the largest variable from the union declaration. So that we will declare two variables: one, using the struct statement containing the variables as before, and the second shall simply be an array of bytes.

typedef union varRecord { 
	struct {  
		double time;
		uint8_t temperature;
		uint16_t pressure;
	}; 
	uint8_t vBytes[]; 
} newRecord;

And this is an illustration of the use you can make of the array of bytes.

void createRecord() {
	newRecord record;
	record.time = 1;
	record.temperature = 20;
	record.pressure = 1015;
	// Print record content as a stream of bytes
	for (uint8_t i = 0; i < sizeof(record); i++) 
		Serial.println(record.vBytes[i], HEX);
}

It is also a very elegant way for converting any data type in an array of bytes:

typedef union varData { 
	double anyData;
	uint8_t vBytes[sizeof(double)]; 
} newData;

Next T&T

Leave a Reply

You must be logged in to post a comment.