[Hampshire] [Slightly OT] Arduino coding help - pointers to …

Top Page

Reply to this message
Author: paul
Date:  
To: hampshire
Subject: [Hampshire] [Slightly OT] Arduino coding help - pointers to structs

Hi,

Sorry this is a bit OT but I believe there is Arduino expertise here :)

I'm writing a piece of code for an Arduino to process short data blocks received
over a serial link.

I've made a struct to hold the input data block which is something like:

struct received_data {
    unsigned int start:1;
    unsigned int address:4;
    unsigned int command:5;
    unsigned int flags:4;
    unsigned int padding:1;
    unsigned int parity:1;
    }


The data arives as 2 characters on a serial port and lands in my processing
function as a pointer to a 2-element array-of-char. The struct is 16 bits long
and maps to the bits of these 2 characters.

So I've got a function: void processthis(char *message)

I've printed out the received message characters from within the function and am
sure that the character array pointed to contains the correct data.

In the function I define a pointer to the struct: struct received_data *messagedata;

I do a type-cast on the pointer to char: messagedata=(struct received_data*)message;

I want to be able to do something like: decodedaddress=messagedata.address; but I
can't seem to make it work. Every possible version of this I try either throws a
compile error or the first test I need to perform says that the first bit of the
struct (which must be 1) is 0.

I've not written C for a long time and would appreciate it if someone could show
me the correct way to do this. Am I barking up the wrong tree by trying to be
elegant and cast rather than writing statements to bit-slice the chars up?

Thanks,
Paul.