01-15-2010 03:03 PM
Hello. I seem to be having a problem with interpreting data placed into a char array that is overlayed with a structure. It seems to be related to bit ordering. The overall scope of my application is to take a data packet, send it over a serial communication port, then another application decodes the data packet, and places the data into a table. I built two seperate LabWindows applications that perform the tasks on both sides of the serial port, and they work properly. Each application makes use of the same header file containing structures defining the data packets. When I remove the LabWindows application on one side and replace it with my actual hardware, I start running into problems decoding the data sent over the serial port with the remaining LabWindows application.
The structure is as follows:
typedef struct
{
unsigned int lcu_status_id:4;
unsigned int fan_id: 1;
unsigned int dimv_id: 1;
unsigned int thunderstorm_id: 1;
unsigned int nvis_mode_id: 1;
unsigned int temp_id: 1;
unsigned int power_id: 1;
unsigned int fan_status_id: 1;
unsigned int lcu_fault: 1;
unsigned int undefined_bits: 4;
} LCU_STATUS_DEF;
typedef union
{
LCU_STATUS_DEF lcu_status_data;
unsigned char lcu_status_str[2];
}
When receiving data from the serial port (COM1), I use the following commands:
read_status = ComRd(1, buf, 1)
packets.lcu_status.lcu_status_str[0] = buf[0]; //packets is another structure not mentioned in above code containing LCU_STATUS and others
... Later in the code I fill data tables by assigning each table the value that is stored in the packets.lcu_status.lcu_status_data.lcu_status_id (or whichever of the variables in the structure I need)
I'm finding that the actual hardware sends the data across the serial port correctly, so that packets.lcu_status.lcu_status_str[0] (and subsequent words) is filled correctly. For example, if I send across a word containing 27 (decimal) then packets.lcu_status.lcu_status_str[0] is filled with 27 when I read it in debug mode. The next word I send is 16 and packets.lcu_status.lcu_status_str[1] is filled with 16. However,
I would expect the structure to then be filled like so:
lcu_status_id = 3
fan_id = 1
dimv_id = 0
thunderstorm_id = 1
nvis_mode_id = 1
temp_id = 0
power_id = 0
fan_status_id = 0
lcu_fault = 1
undefined_bits = 0
But instead, I get:
lcu_status_id = 0
fan_id = 1
dimv_id = 0
thunderstorm_id = 0
nvis_mode_id = 0
temp_id = 1
power_id = 1
fan_status_id = 0
lcu_fault = 1
undefined_bits = 3
I do not understand why this bit order occurs. Would anyone be able to explain?
Thank you,
Jason
01-19-2010 08:21 PM
Jason,
Seems to me that your hardware communicates in "big endian" (as many embedded systems do). This means that you will need to rearrange the bytes in the numeric data you receive before using the values. The same will apply to any numeric data you send.
Have a look at Roberto's reply in this thread. Also, here is an informative article discussing endianness.
Cheers,
Colin.