So my CANBUS code works perfectly when I have one master and one slave but when I attach two slaves, the master receives data for 60-70 seconds then just stops. It of course starts working again when I restart the serial monitor. I am guessing something is being overloaded but I am not experienced enough to know what the exact problem is.
Here is my code for the two slaves. There are identical except for the address where one is 0x00 and the other is 0x10 (so 0 and 16).
// demo: CAN-BUS Shield, send data
#include <mcp_can.h>
#include <SPI.h>
void setup()
{
Serial.begin(115200);
// init can bus, baudrate: 500k
if(CAN.begin(CAN_500KBPS) ==CAN_OK) Serial.print("can init ok!!\r\n");
else Serial.print("Can init fail!!\r\n");
}
void loop()
{
int sensor1 = analogRead(A1);
sensor1 = map(sensor1, 0, 1023,0,255);
int sensor2 = analogRead(A2);
sensor2 = map(sensor2, 0, 1023,0,255);
int sensor3 = analogRead(A3);
sensor3 = map(sensor3, 0, 1023,0,255);
unsigned char sensor1array[3]= {sensor1,sensor2,sensor3};
Serial.println(sensor1,DEC);
// send data: id = 0x00, standrad flame, data len = 3, stmp: data buf
CAN.sendMsgBuf(0x10, 0, 3, sensor1array);
// CAN.sendMsgBuf(0x10, 0, 1, sensor2array);
delay(100); // send data per 100ms
}
And here is my receiving code:
// demo: CAN-BUS Shield, receive data
#include <mcp_can.h>
#include <SPI.h>
unsigned char Flag_Recv = 0;
unsigned char len = 0;
unsigned char buf[3];
char str[20];
void setup()
{
CAN.begin(CAN_500KBPS); // init can bus : baudrate = 500k
attachInterrupt(0, MCP2515_ISR, FALLING); // start interrupt
Serial.begin(115200);
}
void MCP2515_ISR()
{
Flag_Recv = 1;
}
void loop()
{
if(Flag_Recv) // check if get data
{
Flag_Recv = 0; // clear flag
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
int address = CAN.getCanId();
Serial.println(address);
if (address == 0 )
{
Serial.print("Voltage at pin 1 is ");
float voltage1 = buf[0] * (5.1/ 255.0);
Serial.println(voltage1);
Serial.print("Voltage at pin 2 is ");
float voltage2 = buf[1] * (5.1/ 255.0);
Serial.println(voltage2);
/* Serial.print("Arduino 2 value is ");
float voltage3 = buf[3]* (5.1/ 255.0) ;
Serial.println(voltage3);*/
}
else if (address ==1)
{
Serial.println(buf[0]);
Serial.print("Slave 2 going throug");
}
Serial.println();
}
}
I am using the MCP2551 and MCP2515 for the Canbus system and the line is terminated by 120 ohms on both sides. Thanks