red = values for capacity
black = values for voltage
green = values for power
The values in buf are in luittle endian. I just need the values for the voltage buf[4] and buf[5].
The above value => 0xCF90 => d53136
I have following method to calulate that:
unsigned long byteArrayToInt(byte *data, int startIndex, int byteCount) {
switch (byteCount) {
case 2:
return (data[startIndex + 1] << 8)
| data[startIndex];
break;
case 4:
return (data[startIndex + 3] << 24)
| (data[startIndex + 2] << 16)
| (data[startIndex + 1] << 8)
| data[startIndex];
break;
}
}
and I call the method like
unsigned long actualVoltage = byteArrayToInt(buf,4,2);
but the result for actualVoltage is = 429495286. Looks for me like an overflow.
I tryed also following method. This method is more flexible.
unsigned long byteArrayToInt(byte *data, int startIndex, int byteCount) {
unsigned long value = 0;
for (int i = 0; i < byteCount; i++) {
int shift = i * 8;
value += data[startIndex + i] << shift;
}
return value;
}
wg0z:
unsigned longs are 4 bytes each, so you're actually going past the end of buf with 'power'
you'd presumably see that if you ever tried to use it.
(Ab)using a union like that is most definitely processor and compiler dependent. It may work with the Arduino IDE and the particular board you're programming, but it's not guaranteed to be portable.