5 years, 7 months ago.

Issue with CAN.write() and CANMessage class

In my send a can frame function, I am doing the following:

void canTX(vector<char> &rxBuf ) {
    unsigned int CANid = rxBuf[0];
    for (int i = 1; i < 4; i++) {
        CANid = CANid << 8 + rxBuf[i];
    }
    char CANlen = rxBuf.size() - 4;

    if (CAN_Ext == 0) { 
        CANMessage canMsgToSend(CANid, &rxBuf[3], CANlen);
    } else {                
        CANMessage canMsgToSend(CANid, &rxBuf[3], CANlen, CANData, CANExtended);
    }
 
     if (can1.write( canMsgToSend )) {
          pc.printf("OK");
    } else if {
          pc.printf("NOK");
    }
}
   

I am confused as to why it doesn't work. It tells me that 'canMsgToSend' is undefined. While I could create the message within the write, I find it much more readable if I create the CANMessage first, to avoid can1.write in both if cases, and then on top of that having my debug (if write is successful/unsuccessful) with it inside both ifs. I define can1 as CAN can1(p30,p29,500000) as normal ahead of all of this. Read works like it should.

1 Answer

5 years, 7 months ago.

A variable defined inside a set of {}'s is only valid with those {}.

As soon as you leave your if (CAN_Ext == 0) statement the variable canMsgToSend no longer exists.

This is nothing to do with CAN, it's standard variable scoping for c, c++ and just about every other programming language.

Accepted Answer