I am doing a project which involves getting vehicle speed from a car's OBD port and storing it in my database using nodemcu.
I am programming nodemcu using the Arduino IDE and using this library for working with CAN.
Here is a simple example program which I am trying to test, but I am getting garbage output on the serial monitor:
#include <SPI.h>
#include "mcp_can.h"
INT32U canId = 0x000;
unsigned char buf[8];
char str[20];
MCP_CAN CAN0(10);
void setup()
{
Serial.begin(38400);
START_INIT:
if(CAN_OK == CAN0.begin(MCP_ANY, CAN_125KBPS, MCP_80MHZ))
{
Serial.println("Initialized successfully");
}
else
{
Serial.println("Initializing is failed");
Serial.println("Reloading...");
delay(100);
goto START_INIT;
}
}
void loop()
{
INT8U len=8;
if(CAN_MSGAVAIL == CAN0.checkReceive())
{
CAN0.readMsgBuf(&canId,&len, buf);
Serial.print("<");Serial.print(canId);Serial.print(",");
for(int i = 0; i<len; i++)
{
Serial.print(buf[i]);Serial.print(",");
}
Serial.print(">");
Serial.println();
}
}
My speculations:
- A CAN ID can differ from car to car. If so how do I know CAN ID of my car? (It is Maruti Suzuki Ertiga)
- The baudrate which I am using maybe wrong
- The frequency or the kbps I am using in the function call CAN0.begin(MCP_ANY, CAN_125KBPS, MCP_80MHZ) maybe wrong.
If any of the above mentioned points are wrong, then how do I know/what are the correct values?
Best Answer
Regarding your speculations:
Initialized successfully
orInitializing is failed
on your serial terminal? If not, your baudrate of38400
is wrong. Please consult the documentation of the MCP2515 for the correct value.MCP_16MHZ
for the MCP2515. So maybe this is the issue. Again, please check the documentation of the MCP2515.The bitrate of the CAN interface is determined by the car manufacturer. Either you have to get this number from some documentation or you simply try the most common bitrate values , e.g.
CAN_125KBPS
,CAN_250KBPS
,CAN_500KBPS
.Finally, if all of those are set correctly, you will see the individual bytes of each CAN frame. However, then you still need to reverse engineer yourself, which CAN frame contains what information and how is it encoded inside the data bytes.