Re: [Hampshire] [Slightly OT] Arduino coding help - pointers…

Top Page

Reply to this message
Author: James Courtier-Dutton
Date:  
To: paul, Hampshire LUG Discussion List
Subject: Re: [Hampshire] [Slightly OT] Arduino coding help - pointers to structs
On 3 August 2010 15:12, <paul@???> wrote:
>
> 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?


Try looking at the source code to libdvdread.
If uses bitmapping structures and casts in just the same way you wish
to use them.
You have to be careful of the target platform. Is it big or little endian.
Bitmap structs work find when using the gcc compiler, but other
compilers might not work so well.

Kind Regards

James