Please help me with the code to communicate MCP2515 with Arduino MEGA

I copied the code from SEED studio and it is comunicating CAN msgs from my battery but it is repeating the same output. please help me out as i am new to all this.
i am attaching the code for your reference.

my code:

// demo: CAN-BUS Shield, receive data with check mode
// send data coming to fast, such as less than 10ms, you can use this way
// loovee, 2014-6-13

#include <SPI.h>

#define CAN_2515
// #define CAN_2518FD

// Set SPI CS Pin according to your hardware

#if defined(SEEED_WIO_TERMINAL) && defined(CAN_2518FD)
// For Wio Terminal w/ MCP2518FD RPi Hat:
// Channel 0 SPI_CS Pin: BCM 8
// Channel 1 SPI_CS Pin: BCM 7
// Interupt Pin: BCM25
const int SPI_CS_PIN = 12;
const int CAN_INT_PIN = 2;

// For Arduino MCP2515 Hat:
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 12;
const int CAN_INT_PIN = 2;

#ifdef CAN_2518FD
#include "mcp2518fd_can.h"
mcp2518fd CAN(SPI_CS_PIN); // Set CS pin

#ifdef CAN_2515
#include "mcp2515_can.h"
mcp2515_can CAN(SPI_CS_PIN); // Set CS pin

const int LED = 8;
boolean ledON = 1;

void setup() {
pinMode(LED, OUTPUT);

while (CAN_OK != CAN.begin(CAN_500KBPS)) {             // init can bus : baudrate = 500k
    SERIAL_PORT_MONITOR.println("CAN init fail, retry...");
SERIAL_PORT_MONITOR.println("CAN init ok!");


void loop() {
unsigned char len = 0;
unsigned char buf[8];

if (CAN_MSGAVAIL == CAN.checkReceive()) {         // check if data coming
    CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf

    unsigned long canId = CAN.getCanId();

    SERIAL_PORT_MONITOR.println("get data from ID: 0x");
    SERIAL_PORT_MONITOR.println(canId, HEX);

    for (int i = 0; i < len; i++) { // print the data
        if (ledON && i == 0) {

            digitalWrite(LED, buf[i]);
            ledON = 0;
        } else if ((!(ledON)) && i == 4) {

            digitalWrite(LED, buf[i]);
            ledON = 1;



and this is the output it is giving:

Welcome to the forum.

Can you please modify your original post to ensure the source code is in a single box? It should look like this.

// Your example source code

You need three ' at the beginning and end of the source code in the edit window? When you click on this icon </> you get.

type or paste code here

This ensures we can get all the source code.

Please also provide a link to all non-Arduino libraries e.g., on GitHub.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.