Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
8 years, 7 months ago.
Concatenate 2 bytes from a CANMessage
Hey folks
I am currently working on a project where I am trying to communicate with a device via CAN using an Nucleo-F767Zi board and mbed CAN library.
The problem I am facing is that one of the parameters that this device is sending is divided in 2 bytes, how can I concatenate this two bytes?
I tried shifting 8 bits and using bitwise OR but it did not work.
Thanks!
2 Answers
8 years, 7 months ago.
If you don't want to add an extra library then it should be as simple as:
uint16_t value;
CANMessage dataRx;
main() {
if(can.read(dataRx)) {
value = dataRx.data[0] | ((uint16_t)dataRx.data[1] << 8);
}
}
My guess is that your code didn't work because you shifted the data without first casting it to something larger than 8 bits. value = dataRx.data[0] + dataRx.data[1] * 256; should also work fine.
8 years, 7 months ago.
Hello,
If the parameter is of a known data type then you can try to use the ">>" (extract) operator defined in the CANMsg library.
Let's assume your parameter is of uint16_t type and it's the only data carried by the CANMessage. Then you can extract it from the CAN message as follows:
#include "mbed.h"
#include "CANMsg.h"
uint16_t parameter; // your two bytes long parameter
CANMsg rxMsg; // storage for the received CAN message
main() {
...
if(can.read(rxMsg)) {
...
rxMsg >> parameter; // extracts the parameter from the CAN message and casts it into uint16_t
}
...
}
Have a look also at the CAN_Hello demo.