10 years, 1 month ago.

CanBus CANExtended read what am I doing wrong?

I am trying to get data from a J1939 Can Bus. The code is some what working.

The output I get with the MBED code is:

Message received: 8

Message2 received: 10000110

however using a Beaglebone Black configured to read the CAN bus at the same time I get:

DATA,0x18F00300,0x8,0xFF 0xFE 0x0A 0xFF 0xFF 0xFF 0xFF 0xFF,0x6FF9,ACK

I don't understand why my MBED code only reports back the first Byte of data and not the entire sentence.

My code is below.

Anyone able to provide some pointers?

/* Program Example 13.5: CAN data read – reads CAN messages from the CAN bus                    
                                                                            */
#include "mbed.h"
Serial pc(USBTX, USBRX);          // tx, rx for Tera Term output
DigitalOut led2(LED2);            // status LED
DigitalOut led4(LED4);            // status LED

CAN can1(p9, p10);                // CAN interface
int main() {
  pc.baud(115200);  
  can1.frequency(250000);
  
static CANMessage msg;


msg.type    = CANData;
msg.format  = CANExtended;
  //CANMessage msg;                 // create empty CAN message
  printf("read...\n");
  while(1) {
    if(can1.read(msg)) {
          if(msg.id ==0x18FEEF00){
    
          printf("Message received: %X\n", msg.len);   // display message length
          led4 = !led4;   
    }                                       // toggle status LED
    else if(msg.id ==0x18F00300){
    
          printf("Message2 received: %X\n", msg.data);  //display message data
          led2=!led2;
    
    } 

Please use <<code>> and <</code>> around your code, now it is very hard to read.

posted by Erik - 06 Mar 2014

2 Answers

10 years, 1 month ago.

msg.data is a pointer to where the data resides. So what you are now printing is the location where it is stored. So what you need to do is:

else if(msg.id ==0x18F00300){
    
          printf("Message2 received: ");
          for (int i = 0; i<msg.len; i++) 
              printf("0x%02X -", msg.data[i]);       
          printf("\n");
          led2=!led2;
    
    } 

Didn't test it myself (obviously), but that probably works. Not it first prints message2 received, then runs a loop to output all received data from the data array, and finally prints new line char. (In the loop your %X would have worked too, but this is nicer formatted).

Accepted Answer
Narrab
poster
10 years, 1 month ago.

Thanks so much for the help and also teaching me the <<code>> and <</code>> trick. Looks so much better that way.

Np, good luck with it

posted by Erik - 07 Mar 2014