CAN message container. Defines "<<" and ">>" operators to simplify adding/getting data to/from a CAN message.
Dependents: CAN_Hello EinlesenSensorabstand_digital_2 CAN_STABLE_EINSTEIN CAN_ex_STM32F103C8T6 ... more
CAN message container
In order to simplify adding/getting data to/from a CAN message the CANMsg class extends mbed's built-in CANMessage class by defining "<<" (append) and ">>" (extract) operators. Since it inherits everything from CANMessage, after importing the library into your project, you can use it instead of CANMessage without any additional modification or limitations. The usage of "<<" and ">>" operators is similar to the C++ io-streams operators.
- Before adding data to a CANMsg object it is recommended to clear it by calling its
clear()
member function. - Then set up all the other properties (ID, type, format) as needed.
- Finally append data one by one or combine them into a stream. The actual data length of a CAN message is automatically updated when using "<<" or ">>" operators. However, you have to make sure that the total length of data does not exceed eight bytes.
For an example of use have a look at this wiki page.
Import programCAN_Hello
Using CAN bus with (not just NUCLEO) mbed boards
Revision 4:5017a65ff423, committed 2019-02-05
- Comitter:
- hudakz
- Date:
- Tue Feb 05 14:50:19 2019 +0000
- Parent:
- 3:4e42fdc0459f
- Commit message:
- Modified.
Changed in this revision
CANMsg.h | Show annotated file Show diff for this revision Revisions of this file |
diff -r 4e42fdc0459f -r 5017a65ff423 CANMsg.h --- a/CANMsg.h Wed Apr 25 11:47:00 2018 +0000 +++ b/CANMsg.h Tue Feb 05 14:50:19 2019 +0000 @@ -12,7 +12,7 @@ #include "CAN.h" -class CANMsg : public CANMessage +class CANMsg : public mbed::CANMessage { public: /** Creates empty CAN message. @@ -45,7 +45,6 @@ template<class T> CANMsg &operator<<(const T val) { MBED_ASSERT(len + sizeof(T) <= 8); - //*reinterpret_cast<T*>(&data[len]) = val; // This used to work but now it hangs at run time. memcpy(&data[len], &val, sizeof(T)); len += sizeof(T); return *this; @@ -56,8 +55,14 @@ template<class T> CANMsg &operator>>(T& val) { MBED_ASSERT(sizeof(T) <= len); - val = *reinterpret_cast<T*>(&data[0]); - len -= sizeof(T); + if (sizeof(T) > len) { + memcpy(&val, data, len); + len = 0; + } + else { + memcpy(&val, data, sizeof(T)); + len -= sizeof(T); + } memcpy(data, data + sizeof(T), len); return *this; }