View previous topic :: View next topic |
Author |
Message |
Sergeant82d
Joined: 01 Nov 2009 Posts: 55 Location: Central Oklahoma
|
Question about Union declaration/naming/using |
Posted: Fri Apr 01, 2011 11:47 am |
|
|
On an old board thread (link below), there is a post from RayJones, regarding Unions for the HMC6352 Compass Driver. I have a question about the line which says:
Is this line declaring a copy/iteration of the Val16 union type, named heading? And then the next few lines:
Code: |
heading.bytes.msb = i2c_read();
heading.bytes.lsb = i2c_read(0);
return heading.word;
|
call and store the compass data in the temporary union thus declared? I'm just trying to understand what is going on... I will be using this compass module (from Sparkfun) whenever it arrives next week and wanted to get a handle on the driver.
Thanks,
Brad
http://www.ccsinfo.com/forum/viewtopic.php?t=35913&highlight=hmc6352
Code: |
typedef union {
int16 word;
struct {
int8 lsb;
int8 msb;
} bytes;
} Val16 ;
int16 example1()
{
Val16 heading;
heading.bytes.msb = i2c_read();
heading.bytes.lsb = i2c_read(0);
return heading.word;
}
|
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Apr 01, 2011 12:21 pm |
|
|
Quote: |
Is this line declaring a copy/iteration of the Val16 union type, named heading?
Code:
Val16 heading;
|
Yes. The union is "typedef'ed". Then an instance of it is created in
the line above. The instance is called 'heading'. In other words,
RAM memory is allocated for it, and it exists in the program.
Quote: |
And then the next few lines:
Code:
heading.bytes.msb = i2c_read();
heading.bytes.lsb = i2c_read(0);
return heading.word;
call and store the compass data in the temporary union thus declared? I'm just trying to understand what is going on... |
Yes, the first two lines read the i2c data and put it into the 'msb' and 'lsb'
bytes of the union. Then, when that's completed, the function returns
the two bytes, but it returns them packed into a 16-bit word. |
|
|
Sergeant82d
Joined: 01 Nov 2009 Posts: 55 Location: Central Oklahoma
|
|
Posted: Fri Apr 01, 2011 7:59 pm |
|
|
Thank you |
|
|
|