I'm fairly new to type union for combining bytes into a float/integer. This issue is anyways well covered on the internet. Now, my question is is there a way of combining bytes into multiple integers without creating a for loop?
My sensor data looks like so:
D0 D1 D2 D3 D4 D5 D6 D7
16 128 63 126 110 120
Every pair D0-D1 consists of 1 byte. I want to assign each byte to an int.
if (i==0){* Fx = (((combined - 32768)*scale_factor)/32768)+0;
}*
if (i==2){* Fy = (((combined - 32768)*scale_factor)/32768)+21;
}*
if (i==4){* Fz = (((combined - 32768)*scale_factor)/32768)+46;
}*
}*
i=i+2;* } Serial.print(Fx) Serial.print(", ") Serial.print(Fy) Serial.print(", ") Serial.print(Fz) but it seems what I read is wrong. I wanted to use a union like this: union{
byte dataBytes[3];*
int value;*
} SensorData;* void loop(){ SensorData.dataBytes[0]=message.data[0] SensorData.dataBytes[1]=message.data[1] SensorData.dataBytes[2]=message.data[2] Serial.println(SensorData.value) But I think this will just combine the 3 bytes into a single int. Do I need to use 3 unions to solve this?
Please use code tags (</> button on the toolbar) when you post code or warning/error messages. The reason is that the forum software can interpret parts of your code as markup (for example, the italics in your code above), leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier to read your code and to copy it to the IDE or editor. If your browser doesn't show the posting toolbar then you can just manually add the code tags: [code]``[color=blue]// your code is here[/color]``[/code]
Using code tags and other important information is explained in the How to use this forum post. Please read it.
Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.
Something worth noting from K&R 2nd Edition regarding unions:
“the results are implementation-dependent if something is stored as one type and extracted as another”
It says “implementation-dependent”, not “undefined”. So, I assume this means that if what you did works for a given processor and given version of the compiler, then it will always work for that combination. But, if the compiler changes over time ……
What you showed in your original code is a more portable solution: