Problem by Calling Specific CAN-ID to Control digital Output (Arduino Mega and CAN schield)

Hello, I'm Trying to read Specific CAN-ID from the CAN-Communication to control Digital Ouput.

The problem is:
I used IF-loop to turn on the relay only if CAN-ID 0X25 getting in and the rest IDs don't have to be part of this program. However the programm also take that IDs and deal with it as a part of my program.

Here is my Code:

in loop() you assign cId the ID of the received frame CAN.getCanId();

  unsigned long canId = CAN.getCanId();

then a few statements later compare cId with CAN.getCanId();

    if (CAN.getCanId() == cId ) {                               //Serial.println("CAN ID Korrekt!");

which will always be true as you just assigned it that value

do you have an CAN ID you are looking for?

Hello,

The ID that i want the program to run with is 0x25 as it defined in the beginning.

I misread the statement -

    if (CAN.getCanId() == cId ) {                               //Serial.println("CAN ID Korrekt!");

should check if the received frame ID is 25
try printing the value of CAN.getCanId() as a check

I tried to print it in different places in the Loop it is always getting 0x25 and the loop working as it is the right id to run the loop.

But as soon as i send anothed ID after that its also gona be read an coming into the loop.

it means that the loop working firstly with ID 0 25 then whatever us snd it gonna be read and be part of the loop. I have no idea why :smiley:

try printing

void loop() {
  SERIAL_PORT_MONITOR.println("In loop");
  unsigned char len = 0;
  unsigned char buf[8];
  unsigned long canId = CAN.getCanId();
  if (CAN_MSGAVAIL == CAN.checkReceive()) {                      // check if data coming   CAN_MSGAVAIL:Indicates there are data in FIFO buffer to be read.
    CAN.readMsgBuf(&len, buf);                                   // Daten von CAN-Bus auslesen mit [len: Daten Länge]und [buf: data buf]
    canId = CAN.getCanId();
    Serial.println(canId);
    if (canId == cId ) {                               //Serial.println("CAN ID Korrekt!");
       if  (bitRead(buf[0], 0) == 1) {                            // Offene Leitung Relais Kanal_1, Check die Daten von ID.[--] Byte N.0 Bit N.0
        digitalWrite(OFL1, 1);
      }
      else {
        digitalWrite(OFL1, 0);
      }
    }
    else {
      Serial.println("CAN ID is not for this programm");
      Serial.println();
    }
  }
  else Serial.println("CAN READ Communication Failed!!!");
  delay(50);

}
1 Like

thanks alot it works Now really appretiate it. :blush:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.