I am getting an encoder Angle information via a CAN message. The first two bytes hold the information. I am using the following code to extract same :
unsigned int axle1_RawAngle = (rxBuf[1] << 8) | rxBuf[0];
float aX1G = (axle1_RawAngle / 256) - 125;
Serial.println(axle1_RawAngle, HEX);
Serial.println(aX1G);
With the above conversion I expect to read as below :
0x5F00 should read -30 Deg
0X7D00 should read 0 Deg
0x9B00 should read +30 Deg
Values above 0X7D00 work as expected . But values below 0x7D00 result in 65535. Possibly there is a error in the bit shift operation and storing in INT … the rXBuf[8] is declared as char.
Where is this going wrong ?
===>
float aX1G = (axle1_RawAngle / 256.0) - 125.0;
horace
January 21, 2026, 9:50am
3
what microcontroller are you using?
with problems like this it is a good idea to implement a simple program to test the algorithm, e.g.
void decode(uint8_t* rxBuf) {
int axle1_RawAngle = (rxBuf[1] << 8) | rxBuf[0]; // << change to signed int
float aX1G = (axle1_RawAngle / 256) - 125;
Serial.println(axle1_RawAngle, HEX);
Serial.println(aX1G);
}
void setup() {
Serial.begin(115200);
delay(2000);
uint8_t d[] = { 0x00, 0x7d };
decode(d);
uint8_t d1[] = { 0x00, 0x5f };
decode(d1);
uint8_t d2[] = { 0x00, 0x9b };
decode(d2);
}
void loop() {}
when run on an ESP32 displays
7D00
0.00
5F00
-30.00
9B00
30.00
1 Like
Ardubit
January 21, 2026, 10:31am
5
Perfect …. the data type definition was the issue. The moment I changed from Char to uint8_t all things fell in place !! I am using a Mega 2560 mcu
unsigned int axle1_RawAngle = (rxBuf[1] << 8) | rxBuf[0]; // Axle 1 Angle
aX1G = (float(axle1_RawAngle) / 256) - 125;
Thanks for the quick help !!
1 Like