Skip to content

TWAI CAN Recieve not working properly.  #9170

@samuelatceon

Description

@samuelatceon

Board

ESP32-WROOM-32D

Device Description

This is a custom board developed by myself for work applications
It has a SN65HVD230DR CAN Transciever chip for CAN communication.

Hardware Configuration

Have attached a PEAK CAN lead to the board to listen to CAN Messages and send its own messages for test.

Version

latest master (checkout manually)

IDE Name

Arduino IDE

Operating System

Windows 10

Flash frequency

40MHz

PSRAM enabled

no

Upload speed

115200

Description

Having some werd behaviour on the RX side of the CAN, I can send out a CAN message no problem, i can see it come through on the PCAN, However when trying to receive messages being sent from the PEAK, im unable to receive them on the ESP end.
Hardware appears to be fine, as ive used this board with the CAN.h alternative, however i know that header isnt compatible with the newer chips. Hence why im trying to use this alternative.

Sketch

#include "driver/twai.h"

// Function declarations
void sendTwaiMessage(uint32_t id, uint8_t* data, uint8_t len);
void checkAndRecoverBusOff();
void twaiCheckAndPrintAlerts();

const gpio_num_t CAN_TX_PIN = GPIO_NUM_5;
const gpio_num_t CAN_RX_PIN = GPIO_NUM_4;

void setup() {
    Serial.begin(115200);
  
    // TWAI (CAN) General Configuration
    //twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_5, GPIO_NUM_4, TWAI_MODE_NORMAL);
      twai_general_config_t g_config = {.mode = TWAI_MODE_NORMAL,
                                        .tx_io = CAN_TX_PIN,
                                        .rx_io = CAN_RX_PIN,
                                        .clkout_io = TWAI_IO_UNUSED,
                                        .bus_off_io = TWAI_IO_UNUSED,
                                        .tx_queue_len = 21,
                                        .rx_queue_len = 0,
                                        .alerts_enabled = TWAI_ALERT_NONE,
                                        .clkout_divider = 0
                                            };
    twai_timing_config_t t_config = TWAI_TIMING_CONFIG_250KBITS();
    // Setup filter for extended frame with ID 0xAACA
    // Use unsigned long for shift operations
    /*twai_filter_config_t f_config = {
        .acceptance_code = ((uint32_t)0xAACA << 18),
        .acceptance_mask = ((uint32_t)0x1FFFFFFF << 18),
        .single_filter = true
    };*/
    twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();

    // Install TWAI driver
    if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
        Serial.println("Failed to install driver");
        return;
    }
    Serial.println("Driver installed");

    // Start the TWAI driver
    if (twai_start() != ESP_OK) {
        Serial.println("Failed to start driver");
        return;
    }
    Serial.println("Driver started");

    g_config.intr_flags = 0;




}


void loop() {
    // Check and recover from bus-off state if necessary
    checkAndRecoverBusOff();
 twaiCheckAndPrintAlerts();



    // Attempt to send a message
 //  uint8_t data[8] = {0, 1, 2, 3, 4, 5, 6, 7}; // Replace with actual data to send
   //sendTwaiMessage(0x1234, data, 8); // Replace 0xAAAA with the actual ID to send
twai_message_t message;
    message.identifier = 0x1234;
    message.extd = 1; // Assuming extended identifier
    message.rtr = 0;
    message.data_length_code = 8;
  for (int i = 0; i < 8; i++) {
    message.data[i] = i + 1 ;
    Serial.println(message.data[i],HEX);
      }

    if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
        Serial.println("Message queued for transmission");
    } else {
        Serial.println("Failed to queue message for transmission");
    }
    

twai_message_t Recieve_CAN;
Serial.println("Check if new message");
  if (twai_receive(&Recieve_CAN, pdMS_TO_TICKS(1000))) {
    // Check if it's an extended frame

    Serial.print("Message recived : ");
    Serial.print(Recieve_CAN.identifier);
    Serial.print("   Length : ");
    Serial.print(Recieve_CAN.data_length_code);
    Serial.print("   Data : ");
    for (int i = 0; i < sizeof(Recieve_CAN.data)/sizeof(Recieve_CAN.data[0]); i++) {
    Serial.print(Recieve_CAN.data[i]);
    Serial.print("  ");
    }
    Serial.println(" ");
    if (!Recieve_CAN.extd && (Recieve_CAN.identifier == 0x1234)) {
      Serial.print("Received extended message with ID : ");
      // Process the message data
      for (int i = 0; i < Recieve_CAN.data_length_code; i++) {
        Serial.print(Recieve_CAN.data[i], HEX);
        Serial.print(" ");
      }
      Serial.println();
    }
  }
    // Add a small delay to avoid overwhelming the serial output
    delay(100);

}
/*
void sendTwaiMessage(uint32_t id, uint8_t* data, uint8_t len) {
    twai_message_t message;
    message.identifier = id;
    message.extd = 1; // Assuming extended identifier
    message.rtr = 0;
    message.data_length_code = len;
    memcpy(message.data, data, len);

    if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
        Serial.println("Message queued for transmission");
    } else {
        Serial.println("Failed to queue message for transmission");
    }

  return 
}
*/
void checkAndRecoverBusOff() {
    twai_status_info_t status_info;
    if (twai_get_status_info(&status_info) == ESP_OK) {
      Serial.println("TWAI is Running");
        if (status_info.state == TWAI_STATE_BUS_OFF) {
            Serial.println("TWAI controller is in bus-off state, attempting recovery.");
            if (twai_initiate_recovery() == ESP_OK) {
                // The controller will automatically start recovery.
                // Wait for bus recovery - according to the standard, this should be at least 128 * 11 bit times.
                vTaskDelay(pdMS_TO_TICKS(128 * 11));
                // After the delay, restart the TWAI driver
                if (twai_start() != ESP_OK) {
                    Serial.println("Failed to restart TWAI driver after recovery.");
                }
            } else {
                Serial.println("Failed to initiate TWAI recovery.");
            }
        } else if (status_info.state == TWAI_STATE_RECOVERING) {
            // You may want to skip sending messages if recovery is in progress
            Serial.println("TWAI controller recovery in progress.");
        }
    } else {
        Serial.println("Failed to get TWAI status info.");
    }
}
void twaiCheckAndPrintAlerts() {
    uint32_t alerts;
    if (twai_read_alerts(&alerts, pdMS_TO_TICKS(100)) == ESP_OK) {
        if (alerts != 0) {
            Serial.print("TWAI alerts: ");
            Serial.println(alerts, HEX);
        }
    }
}

Debug Message

Check if new message
Message recived : 21   Length : 0   Data : 0  0  0  224  81  252  63  200   
Failed to get TWAI status info.
1
2
3
4
5
6
7
8
Failed to queue message for transmissio

Other Steps to Reproduce

No response

I have checked existing issues, online documentation and the Troubleshooting Guide

  • I confirm I have checked existing issues, online documentation and Troubleshooting guide.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions