I am working on a project to implement CAN bus using the MCP2515. This is the first time I have used SPI and I am having a difficult time getting it to work.
First I tried several of the libraries on the internet. Bottom line is couldn’t get any of them working, so to enhance my understanding of how this all works I decided to try and write my own functions (eventually it will be turned into a library for my application). The problem is it appears the only thing the SPI.transfer function will return is “0”. At this point I am at a loss as to the next things to try. So what should I try next? How can I test this to see what is going wrong?
#include <SPI.h>
#define CAN_cs 10
void setup(){
pinMode(CAN_cs, OUTPUT);
digitalWrite(CAN_cs, HIGH);
Serial.begin(9600);
SPI.begin();
CAN_RESET();
delay(100);
CAN_WRITE(0xF, B00001010);
//write to enable loopback mode
delay(100);
byte stat;
stat=CAN_READ(0xE);
Serial.print(stat);
}
void loop(){
}
void CAN_WRITE(byte reg, byte value){
digitalWrite(CAN_cs, LOW);
SPI.transfer(B00000010);
SPI.transfer(reg);
SPI.transfer(value);
digitalWrite(CAN_cs, HIGH);
}
void CAN_RESET(){
digitalWrite(CAN_cs, LOW);
SPI.transfer(B11000000);
digitalWrite(CAN_cs, HIGH);
}
byte CAN_READ(byte reg){
byte data;
digitalWrite(CAN_cs, LOW);
SPI.transfer(B00000011);
SPI.transfer(reg);
data=SPI.transfer(0);
digitalWrite(CAN_cs, HIGH);
return(data);
}
Thanks