Canbus message filtering

if (mcp2515_check_message()) 
  {
    if (mcp2515_get_message(&message)) 
     {
          if(message.id == 0x181 and 
     message.data[0] == 0x00 and
     message.data[1] == 0x23 and
     message.data[2] == 0x00 and
     message.data[3] == 0x01) 
             {
               Serial.println("Show green LED");
               digitalWrite(ledPin, HIGH); //Set LED on
             }
        else

        
             {
               digitalWrite(ledPin, LOW); //Set LED off
             }
      }
    
  }
}

How can I add additional message with 181 data: 00 23 00 00 and show RED led ?

  if (mcp2515_check_message())
  {
    if (mcp2515_get_message(&message))
    {
      if (message.id == 0x181 and
      message.data[0] == 0x00 and
      message.data[1] == 0x23 and
      message.data[2] == 0x00)
      {
        digitalWrite(GreenLEDPin, LOW); // Set LED off
        digitalWrite(RedLEDPin, LOW); //Set LED off

        if (message.data[3] == 0x01)
        {
          Serial.println("Show green LED");
          digitalWrite(GreenLEDPin, HIGH); //Set LED on
        }
        else if (message.data[3] == 0x00)
        {
          Serial.println("Show red LED");
          digitalWrite(RedLEDPin, HIGH); //Set LED on
        }
      }
    }
  }

If you compare the same value to more than two constants it is probably time to change to a switch/case statement:

      {
        digitalWrite(GreenLEDPin, LOW); // Set LED off
        digitalWrite(RedLEDPin, LOW); //Set LED off

        switch (message.data[3])
        {
          case 0x00:
            Serial.println("Show red LED");
            digitalWrite(RedLEDPin, HIGH); //Set LED on
            break;

          case 0x01:
            Serial.println("Show green LED");
            digitalWrite(GreenLEDPin, HIGH); //Set LED on
            break;
        }
      }

It's a shortcut for:

  if (intVariable == intConstantA)
  {
  }
  else if (intVariable == intConstantB)
  {
  }
  else if (intVariable == intConstantC)
  {
  }
  else if (intVariable == intConstantD)
  {
  }
  else
  {
    // Default if nothing else matched
  }

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