I tried CAN communication between two arduino unos using the CAN SPI MCP2515 modules but its seemingly very unreliable as it only worked once
This was the code i used, any idea what could be wrong?
thanks!!
transmitter:
#include<SPI.h>
#include <can.h>
#include <mcp2515.h>
struct can_frame canMsg1;
MCP2515 mcp2515(10);
void setup(){
canMsg1.can_id = 0x037;
canMsg1.can_dlc = 8;
canMsg1.data[0] = 1;
canMsg1.data[1] = 2;
canMsg1.data[2] = 3;
canMsg1.data[3] = 4;
canMsg1.data[4] = 5;
canMsg1.data[5] = 6;
canMsg1.data[6] = 7;
canMsg1.data[7] = 8;
Serial.begin(9600);
mcp2515.reset();
mcp2515.setBitrate(CAN_125KBPS, MCP_8MHZ);
mcp2515.setNormalMode();
Serial.println("Example: Write to CAN");
}
void loop(){
mcp2515.sendMessage(&canMsg1);
Serial.println("Messages sent");
delay(1000);
}
receiver:
#include<SPI.h>
#include <can.h>
#include <mcp2515.h>
struct can_frame canMsg1;
MCP2515 mcp2515(10);
void setup() {
Serial.begin(9600);
mcp2515.reset();
mcp2515.setBitrate(CAN_125KBPS, MCP_8MHZ);
mcp2515.setNormalMode();
Serial.println("-----CAN Read-----");
}
void loop() {
// put your main code here, to run repeatedly:
if(mcp2515.readMessage(&canMsg1) == MCP2515::ERROR_OK){
Serial.print("ID: ");
Serial.print(canMsg1.can_id, HEX);
Serial.println(" ");
Serial.print("DLC: ");
Serial.print(canMsg1.can_dlc);
Serial.println(" ");
Serial.print("DATA: ");
for(int i =0; i< canMsg1.can_dlc; i++){
Serial.print(canMsg1.data[i]);
Serial.print(" ");
}
Serial.println();
}
}