Skip to content

Instantly share code, notes, and snippets.

@nook-scheel
Created October 23, 2016 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nook-scheel/2bf09898d12b1c4dc730ac2fd669bf3c to your computer and use it in GitHub Desktop.
Save nook-scheel/2bf09898d12b1c4dc730ac2fd669bf3c to your computer and use it in GitHub Desktop.
#include "mcp_can.h"
const int SPI_CS_PIN = 9;
const int LED=13;
boolean ledON=1;
MCP_CAN CAN(SPI_CS_PIN);
void setup()
{
Serial.begin(115200);
pinMode(LED, OUTPUT);
Serial.begin(9600);
//while (!Serial) {
// ;
//}
while (CAN_OK != CAN.begin(CAN_100KBPS_8MHZ))
{
Serial.println("CAN BUS Shield init fail");
Serial.println(" Init CAN BUS Shield again");
delay(100);
}
Serial.println("CAN BUS Shield init ok!");
}
void loop()
{
unsigned char len = 0;
unsigned char buf[8];
if(CAN_MSGAVAIL == CAN.checkReceive()) // check if data coming
{
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned char canId = CAN.getCanId();
Serial.print("[");
Serial.print(canId);
Serial.print("\t");
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i]);
Serial.print("\t");
if(ledON && i==0)
{
digitalWrite(LED,buf[i]);
ledON=0;
delay(500);
}
else if((!(ledON)) && i==4)
{
digitalWrite(LED,buf[i]);
ledON=1;
}
}
Serial.println("]");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment