Electronic – Getting garbage output in serial monitor while communicating with OBD using CAN interface (MCP2515) and nodemcu

#nodemcucanmicrocontrollerobd

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:

  1. 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)
  2. The baudrate which I am using maybe wrong
  3. 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:

  1. As mentioned by @Alexander von Wernherr in his comment, there is not one CAN ID related to your car, but a number of different CAN Frames with individual CAN ID. However, the loop part of your program already takes care to read all of them and prints them out. So this is not the Problem here.
  2. Do you see the printout Initialized successfully or Initializing is failed on your serial terminal? If not, your baudrate of 38400 is wrong. Please consult the documentation of the MCP2515 for the correct value.
  3. The frequency you set needs to fit to the Hardware you use. In the link you shared, they are talking about using 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.

Related Topic