Hi all,
I have modified the code below to turn on a MOSFET when any CAN traffic is present. It works fine. I would like to now pick a specific CAN id (i.e 0x1B0) to turn on the MOSFET. Just need some guidance on doing this before filtering further depending on the data within the CAN frame.
#include <mcp_can.h>
#include <SPI.h>
long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];
char msgString[128]; // Array to store serial string
#define CAN0_INT 2 // Set INT to pin 2
MCP_CAN CAN0(10); // Set CS to pin 10
const int loadMosfet = 9; //Digital Pin 9
const int led = 8; //Green LED indicator showing CAN signa is active
const int powerMosfet = 4; //Digital output to instantly turn power mosfet on / off
unsigned long lastMessageTime;
unsigned long timeoutInterval = 10000; //10 seconds
void setup()
{
pinMode (powerMosfet, OUTPUT);
digitalWrite (powerMosfet, HIGH); // Immediatly turn on Mosfet to power up circuitry.
pinMode (loadMosfet, OUTPUT);
pinMode (led, OUTPUT);
Serial.begin(115200);
// Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
if (CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
Serial.println("MCP2515 Initialized Successfully!");
else
Serial.println("Error Initializing MCP2515...");
CAN0.setMode(MCP_NORMAL); // Set operation mode to normal so the MCP2515 sends acks to received data.
pinMode(CAN0_INT, INPUT); // Configuring pin for /INT input
}
void loop()
{
if (!digitalRead(CAN0_INT)) // If CAN0_INT pin is low, read receive buffer
{
digitalWrite (loadMosfet, HIGH); // Turn loadMosfet ON if CAN is present
digitalWrite (led, HIGH); //Turn on LED to indicate CAN signal is active
digitalWrite (powerMosfet, HIGH);
CAN0.readMsgBuf(&rxId, &len, rxBuf); // Read data: len = data length, buf = data byte(s)
Serial.println("CAN Bus Is Active");
lastMessageTime = millis(); //Start a 'timer' to track last time a successful message was recieved
}
else {
digitalWrite (led, LOW); //Turn off LED to show CAN signal is inactive
Serial.println("CAN Bus Is Asleep");
}
if (millis() - lastMessageTime >= timeoutInterval)
{
digitalWrite (powerMosfet, LOW); //Turn OFF power Mosfet to shutdown circuitry
digitalWrite (loadMosfet, LOW); //Turn OFF loadMosfet if CAN is not present
}
}
Thanks in advance!