Skip to content

Instantly share code, notes, and snippets.

@tmkdev
Created October 7, 2017 18:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmkdev/c225d52212f6aea41cd0b073a622e254 to your computer and use it in GitHub Desktop.
Save tmkdev/c225d52212f6aea41cd0b073a622e254 to your computer and use it in GitHub Desktop.
SWCAN on the macchina M2.
#include <SPI.h>
#include <MCP2515_sw_can.h>
// Pin definitions specific to how the MCP2515 is wired up.
#define CS_PIN SPI0_CS3
#define INT_PIN SWC_INT
#define Serial SerialUSB
// Create CAN object with pins as defined
SWcan CAN(CS_PIN, INT_PIN);
void CANHandler() {
CAN.intHandler();
}
void setup() {
Serial.begin(115200);
while (!Serial);
pinMode(DS2, OUTPUT);
pinMode(DS6, OUTPUT);
Serial.println("Initializing ...");
digitalWrite(DS2, HIGH);
// Set up SPI Communication
// dataMode can be SPI_MODE0 or SPI_MODE3 only for MCP2515
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
SPI.begin();
// Initialize MCP2515 CAN controller at the specified speed and clock frequency
// (Note: This is the oscillator attached to the MCP2515, not the Arduino oscillator)
//speed in KHz, clock in MHz
CAN.setupSW(33333); //GMLAN
CAN.mode(3); // Normal on the SWCAN bus.
// 0 = Sleep
// 1 = High Speed
// 2 = High Voltage
// 3 = Normal
attachInterrupt(SWC_INT, CANHandler, FALLING);
//CAN.SetRXMask(MASK0, 0x7F0, 0); //match all but bottom four bits
//CAN.SetRXFilter(FILTER0, 0x100, 0); //allows 0x100 - 0x10F
//So, this code will only accept frames with ID of 0x100 - 0x10F. All other frames
//will be ignored.
Serial.println("Ready ...");
}
byte i=0;
// CAN message frame (actually just the parts that are exposed by the MCP2515 RX/TX buffers)
Frame message;
void loop() {
if (CAN.GetRXFrame(message)) {
digitalWrite(DS6, HIGH);
// Print message
Serial.print("ID: ");
Serial.println(message.id,HEX);
Serial.print("Extended: ");
if(message.extended) {
Serial.println("Yes");
} else {
Serial.println("No");
}
Serial.print("Length: ");
Serial.println(message.length,DEC);
for(i=0;i<message.length;i++) {
Serial.print(message.data.byte[i],HEX);
Serial.print(" ");
}
Serial.println();
Serial.println();
digitalWrite(DS6, LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment