6 years, 3 months ago.

Share dynamic sensor data via CAN

Hello,

I have the following problem (Board used LPC1768):

I want to send the four distances, calculated with four ultrasonic sensor, via CAN. The data shall be sent in the CAN Message using Hex format (2 bytes for each distance) with respect to the following coding: 00 01 hex = 1mm The distance calculated with the four ultrasonic sensors can be send using one CAN message (8bytes), 2 bytes for each distance.

Code

int = mm1, mm2, mm3, mm4;
mm1 = Distance(Sensor1);    //  
mm2 = Distance(Sensor2);    //  
mm3 = Distance(Sensor3);    //  
mm4 = Distance(Sensor4);    //  

msg.id=0x500;
msg.len=8;

msg.data [0] =   ?????                          // Do i have to send the data as Hex or Int? 
msg.data [1] =   ?????                          //  How can i split the data on two bytes?
msg.data [2] =   ?????                          // 
msg.data [3] =   ?????                          //  
msg.data [4] =   ?????                          // 
msg.data [5] =   ?????                          //  
msg.data [6] =   ?????                          // 
msg.data [7] =   ?????                          //  

can1.write(CANMessage(msg));

Thanks in advance!

1 Answer

6 years, 3 months ago.

Hello Florian,

An uint16_t type variable is suitable for distances from 0 up to 2^16 - 1 = 65535 mm. If that suffices your needs and you do not mind to import the CANMsg library into your project then you can do the following to send your data:

#include "mbed.h"
#include "CanMsg.h"

...
uint16_t    mm1, mm2, mm3, mm4;
CANMsg      msg;
CAN         can1(...);

...

mm1 = Distance(Sensor1);
mm2 = Distance(Sensor2);
mm3 = Distance(Sensor3);
mm4 = Distance(Sensor4);

msg.clear();
msg.id=0x500;
msg << mm1;
msg << mm2;
msg << mm3;
msg << mm4;
 
can1.write(msg);

...

and the following to receive the data:

#include "mbed.h"
#include "CanMsg.h"

...
uint16_t    mm1, mm2, mm3, mm4;
CANMsg      msg;
CAN         can1(...);

...

if (can1.read(msg)) {    
    if (msg.id == 0x500) {
        msg >> mm1;
        msg >> mm2;
        msg >> mm3;
        msg >> mm4;
        ...
    }
    ...
}
...

You can have a look at the CAN_Hello demo for more details.

Accepted Answer

Hell Zoltan,

thank you for your detailed response, you helped a lot.

posted by Florian Schindler 03 Jan 2018