Ignition simulation with canbus
Posted: 20 Apr 2019, 08:14
Hi can any one help me please I'm having trouble getting this to work I want it to switch the relay on when it receives the canbus id and data and off when it no longer receives the canbus id and data, this is to simulate an ignition live so I can power up/down a DVD multi media system I have put in my car for my kids, if I leave it plugged in the battery will go flat and that's not good when we are out, and help would be much appreciated thanks
Code: Select all
#include <SPI.h>
#include "mcp_can.h"
#define INT32U unsigned long int
INT32U canId = 0x00;
unsigned char len = 0;
unsigned char buf[8];
char str[20];
String CanMessage="";
int IgnitionDetected=0;
int RelayCHN01=4;
const int SPI_CS_PIN = 17;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
void setup()
{
//INIT RELAY PIN
pinMode(RelayCHN01, OUTPUT);
//TEST RELAY PIN
TESTRElay();
Serial.begin(115200);
START_INIT:
if(CAN_OK == CAN.begin(CAN_125KBPS))
{
Serial.println("CAN BUS Shield init ok!");
}
else
{
Serial.println("CAN BUS Shield init fail");
Serial.println("Init CAN BUS Shield again");
delay(100);
//goto START_INIT;
}
}
void loop()
{
if(CAN_MSGAVAIL == CAN.checkReceive())
{
CAN.readMsgBuf(&len, buf);
CanMessage="";
canId = CAN.getCanId();
//Detect Ignition
if (canId==0x0048)
{
//Build Complete Message Without CAN ID From BUS
for(int i = 0; i<len; i++) // print the data
{
CanMessage = CanMessage + buf;
}
if (CanMessage=="0XFF, 0x07, 0x6C, 0x09, 0x27, 0x02, 0xE0"){IgnitionDetected=1;}else{IgnitionDetected=0;}
if (IgnitionDetected==1)
{
//PUT CODE HERE To TURN ON Relay
Serial.println("Relay turned on!!!!!");
digitalWrite(RelayCHN01, HIGH);
}
else
{
digitalWrite(RelayCHN01, LOW);
}
}
}
}
void TESTRElay()
{
digitalWrite(RelayCHN01, HIGH);
delay(200);
digitalWrite(RelayCHN01, LOW);
delay(200);
digitalWrite(RelayCHN01, HIGH);
delay(200);
digitalWrite(RelayCHN01, LOW);
delay(200);
}