I need help with setting up mcp_can communication for esp32 on arduino

I an unable to send packets to my mcp buffer as my code returns "Failed to send chunck". Can someone help me to fix this? I have the code below

Main ino file:

#include "mastercommodule_parameters.h"
#include <mcp_can.h>
#include <SPI.h>


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  // Initialize CAN bus at 500 kbps
  if (CAN.begin(MCP_ANY, CAN_500KBPS, MCP_8MHZ) == CAN_OK) {
    Serial.println("CAN Bus Initialized Successfully!");
  } else {
    Serial.println("Error Initializing CAN Bus.");
    while (1);
  }
  CAN.setMode(MCP_NORMAL); // Set MCP2515 to Normal mode
}

void loop() {
  // put your main code here, to run repeatedly:
  pulses = 4;
  desiredFlowMass = 0.03;

  buildMessage();
  receiveMessage();

}


header file:

#ifndef MASTERCOMMODULE_PARAMETERS_H
#define MASTERCOMMODULE_PARAMETERS_H

#include <mcp_can.h>
#include <SPI.h>

//MCP CAN Communication Parameters
const uint32_t MY_ADDRESS = 0x00000001;       // Address of this board
const uint32_t BROADCAST_ADDRESS = 0xFFFFFFFF; // All-cast address
const uint32_t SLAVE1_ADDRESS = 0x00000002; // All-cast address

#define csPin 5                         //CS pin ID
#define intPin 4                        //interrupt pin D
#define MAX_CAN_FRAME_SIZE 7
extern int pulses;
extern float desiredFlowMass;
extern int pulsesR;
extern float desiredFlowMassR;
extern bool CAN_UP;
extern int packetSize;
extern MCP_CAN CAN;
extern bool MSG_ACK;
extern int failMessageCount;

//Seedmeter functions
void processMessage(char* message); 
void acknowledgeData();
void receiveMessage();
void sendMessage(char* message);
void buildMessage();
   
#endif

cpp file:

#include "mastercommodule_parameters.h"

#include <mcp_can.h>
#include <SPI.h>

extern int pulses = 0;
extern float desiredFlowMass = 0;
extern int pulsesR = 0;
extern float desiredFlowMassR = 0;
extern bool CAN_UP = false;
extern int packetSize = 0;
extern MCP_CAN CAN(csPin);
extern bool MSG_ACK = false;
extern int failMessageCount = 0;

void buildMessage(){
  char message[64];
  snprintf(message, sizeof(message), "A1:%d;B1:%.2f;", pulses, desiredFlowMass);
  sendMessage(message);
}

void sendMessage(char* message){
  int messageLength = strlen(message);
  int numChunks = (messageLength / MAX_CAN_FRAME_SIZE) + (messageLength % MAX_CAN_FRAME_SIZE != 0); // Number of chunks required
  int chunkIndex = 0;

  while (chunkIndex < numChunks) {
    uint8_t chunkStart = chunkIndex * MAX_CAN_FRAME_SIZE;
    uint8_t chunkEnd = min(chunkStart + MAX_CAN_FRAME_SIZE, messageLength);

    // Prepare a chunk of the message
    //char chunk[MAX_CAN_FRAME_SIZE + 1];  // +1 for null terminator
    char chunk[MAX_CAN_FRAME_SIZE + 1];  // +1 for null terminator
    strncpy(chunk, message + chunkStart, chunkEnd - chunkStart);
    chunk[chunkEnd - chunkStart] = '\0';  // Ensure null termination

    uint8_t gesa = CAN.sendMsgBuf(SLAVE1_ADDRESS,0, 8, (uint8_t*)chunk);
    Serial.println(gesa );

    // Send the chunk as a CAN message
    if (CAN.sendMsgBuf(SLAVE1_ADDRESS,0, 8, (uint8_t*)chunk) == CAN_OK) {
      Serial.print("Sent Chunk: ");
      Serial.println(chunk);
    } else {
      Serial.println("Failed to send chunk");
    }

    chunkIndex++;
    delay(500);  // Small delay to prevent flooding the bus
  }

}

void processMessage(char* message) {
  // Parse the key-value pairs in the message
  char buffer[64];
  strncpy(buffer, message, sizeof(buffer)-1); // Copy message to buffer
  buffer[sizeof(buffer) - 1] = '\0';        // Ensure null-termination

  char* pair = strtok(buffer, ";"); // Split by semicolon
  while (pair != NULL) {
    char* key = strtok(pair, ":"); // Split key and value
    char* value = strtok(NULL, ":");

    if (key && value) {
      if (strcmp(key, "A1") == 0) {
        pulsesR = atoi(value); // Convert string to integer
      } else if (strcmp(key, "B1") == 0) {
        desiredFlowMassR = atof(value); // Convert string to float
      }
    }
    pair = strtok(NULL, ";"); // Move to the next pair
  }

  // Debug print the updated variables
  Serial.print("Updated Pulses: ");
  Serial.println(pulses);
  Serial.print("Updated Desired Flow Mass: ");
  Serial.println(desiredFlowMass);

}


// Function to send acknowledgment
void acknowledgeData() {
  failMessageCount = 0;
  if (!(pulses == pulsesR)){
    failMessageCount = failMessageCount + 1;
  }

  if (!(desiredFlowMass == desiredFlowMassR)){
    failMessageCount = failMessageCount + 1;
  }

  if (failMessageCount == 0){
    MSG_ACK = true;
    Serial.println("Acknowledgment transmission complete");
  } else {
    MSG_ACK = false;
    Serial.println("Acknowledgment transmission failed");
  }
  
}

void receiveMessage() {
  uint32_t canId;     // Variable to store the CAN ID
  uint8_t senderAddress;  // Read sender address
  uint8_t len = 0;           // Variable to store the length of the message
  uint8_t buf[8];            // Buffer for the message data (up to 8 bytes)

  if (CAN.checkReceive() == CAN_MSGAVAIL) {

    if (CAN.readMsgBuf(&canId, &len, buf) == CAN_OK) {
      senderAddress = (uint8_t)(canId & 0xFF); // Keep only the least significant byte

      if (senderAddress == MY_ADDRESS || senderAddress == BROADCAST_ADDRESS) {
        CAN_UP = true;

        char message[64] = {'\0'};
        static int messageIndex = 0; // Keeps track of reassembly

        for (int i = 0; i < len; i++) {
          message[i] = (char)buf[i];  // Convert data to char
        }
        message[len] = '\0';  // Null-terminate the string

        if (CAN_UP) {
          processMessage(message);
          acknowledgeData();
        }
      }

    }

  }
  
}

That could be a hardware problem, post an annotated schematic showing exactly how it is wired. Show all power, ground, extra components etc. With the power off what is the resistance of the CAN bus?

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