CAN Bus Examples

Hello All,
I am working on a project where a CAN-BUS Shield v2.0 read the messages on a specific CAN ID, and if the first bit on that CAN ID = X, the arduino begins one code, and if its Y, it begins another.

I can't find any sort of examples where this is done.... Can anyone help by posting or linking a project, where the CAN Message VALUE is used as a variable for an IF/Then statement?

A good example would be engine speed... If the engine speed is over 1000, turn on an LED, if its under 1000 keep LED off... I can't find anything of this nature and I am hoping someone can help.
Everything I have found, just prints the CAN msgs to the serial port, no examples of using the value as an input to another line of code.
Thank you!

To follow up… basically all I am looking for is some code which defines bit 0/8 of a CAN ID (0x201) as a variable, and sets its current value coming over the CAN Bus as its value… so I can use If/Then based on the value of that bit at any time.

Welcome to the forum

Please read the How to get the best out of this forum

It sounds like you already have some code but need a small modification. Please post the code you have (use code tags) and provide a link to the library you are using e.g. on GitHub.

Your example code should look like this

To test a single bit you can uses boolean logic.

  • Create a variable with the same size (8,16,32 bit) and give it the value 1.
  • Shift the bit with the shift operator to the left (<<) depending the bit position. This is your mask.
  • Now use bitwise AND (single &) with the mask and the test variable to clear all other bits.
  • If the bit was a zero the whole value will now be zero otherwise it will be non-zero.

You can also do this in one line of code, once you know how it works.

tjbhunter:
Hello All,
I am working on a project where a CAN-BUS Shield v2.0 read the messages on a specific CAN ID, and if the first bit on that CAN ID = X, the arduino begins one code, and if its Y, it begins another.

I can't find any sort of examples where this is done.... Can anyone help by posting or linking a project, where the CAN

use bitRead()
depending on the library you are using, usually the CAN ID is stored in a struc.
so now to do what you requested it would be something as simple as this:

if(bitRead(msg.id, 1)){
   //do something if bit 1 of the CAN ID is set
}
else if(bitRead(msg.id, 2)){
 //do something if bit 2 of the CAN ID is set
}
//else if ... and so on

hope that helps....

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