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

Top Page

Reply to this message
Author: Chris Liddell
Date:  
To: paul, Hampshire LUG Discussion List
Subject: Re: [Hampshire] [Slightly OT] Arduino coding help - pointers to structs

Declarations like your code don't declare variables comprising that
number of bits, they still are still the size of the base type (in this
case unsigned int). All the bit length option does (if supported by the
compiler) is restrict the maximum value of the field (and sometimes not
even that - many compilers ignore it completely).

So your structure is not 16 bits long, it's 192 bits long.

You'll have to decode the message "manually" using shifts and masks.

HTH,

Chris


On 03/08/2010 14: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?
>
> Thanks,
> Paul.
>
> --
> Please post to: Hampshire@???
> Web Interface: https://mailman.lug.org.uk/mailman/listinfo/hampshire
> LUG URL: http://www.hantslug.org.uk
> --------------------------------------------------------------
>
>
>
>
> No virus found in this incoming message.
> Checked by AVG - www.avg.com
> Version: 9.0.851 / Virus Database: 271.1.1/3046 - Release Date: 08/02/10 18:59:00
>