FlexCAN can only send globally defined CAN_message_t

Status
Not open for further replies.

cgc

Member
I'm running into an issue where FlexCAN can only send globally defined can message. Specifically, If I try to Can0.write() a CAN_message_t that is inside of a class, Can0 writes all 0's to the bus. This can be resolved by making the CAN_message_t a global variable.

Can anyone tell me why this is happening?

The only difference below is the location of "CAN_message_t msg;"

(EXAMPLE1) This code works:
Cansender.cpp

Code:
#include <Arduino.h>
#include <FlexCAN.h>

CAN_message_t msg;

void hexDump(uint8_t dumpLen, uint8_t *bytePtr)
{
  uint8_t working;
  while( dumpLen-- ) {
    working = *bytePtr++;
    Serial.write( hex[ working>>4 ] );
    Serial.write( hex[ working&15 ] );
  }
  Serial.write('\r');
  Serial.write('\n');
}

Cansender::Cansender()
{
  Can0.begin(500000);

  msg.ext = 0;
  msg.id = 0x100; // 0
  msg.len = 8;
  msg.buf[0] = 100;
  msg.buf[1] = 0;
  msg.buf[2] = 0;
  msg.buf[3] = 0;
  msg.buf[4] = 0;
  msg.buf[5] = 0;
  msg.buf[6] = 0;
  msg.buf[7] = 0;
}

void Cansender::sendmsg()
{
  Can0.write(msg);
  Serial.print("out: "); hexDump(8,msg.buf);
}

(EXAMPLE2) This code doesn't work:
Cansender.cpp

Code:
#include <Arduino.h>
#include <FlexCAN.h>

void hexDump(uint8_t dumpLen, uint8_t *bytePtr)
{
  uint8_t working;
  while( dumpLen-- ) {
    working = *bytePtr++;
    Serial.write( hex[ working>>4 ] );
    Serial.write( hex[ working&15 ] );
  }
  Serial.write('\r');
  Serial.write('\n');
}

Cansender::Cansender()
{
  Can0.begin(500000);

  CAN_message_t msg;

  msg.ext = 0;
  msg.id = 0x100; // 0
  msg.len = 8;
  msg.buf[0] = 100;
  msg.buf[1] = 0;
  msg.buf[2] = 0;
  msg.buf[3] = 0;
  msg.buf[4] = 0;
  msg.buf[5] = 0;
  msg.buf[6] = 0;
  msg.buf[7] = 0;
}

void Cansender::sendmsg()
{
  Can0.write(msg);
  Serial.print("out: "); hexDump(8,msg.buf);
}

Cansender.h
Code:
#ifndef Cansender_h
#define Cansender_h

#include <Arduino.h>
#include <FlexCAN.h>

class Cansender
{
  public:
    Cansender();
    void sendmsg();
    CAN_message_t msg;
};

#endif

Usage as follows:
Code:
#include <Arduino.h>
#include <Cansender.h>

void setup() {
  Cansender sender = Cansender();
}

void loop() {
  delay(1000);
  sender.sendmsg();
  sender.msg.buf[0]++;
}
 
You have "CAN_message_t msg" declared twice. Once in the header file and another in the Cansender constructor. Remove the "CAN_message_t msg" from the constructor and it should work.
 
You have "CAN_message_t msg" declared twice. Once in the header file and another in the Cansender constructor. Remove the "CAN_message_t msg" from the constructor and it should work.

Thanks, this fixed it! I haven't noticed this issue with other types of class variables. I understand the mistake now, should have read this first.
 
Status
Not open for further replies.
Back
Top