I am currently trying to implement CAN on an ESP32. Here is my code:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/twai.h"
#include "esp_err.h"
#define TAG "CAN_TX"
// Define CAN pins
#define CAN_TX_PIN GPIO_NUM_5
#define CAN_RX_PIN GPIO_NUM_4
void app_main(void)
{
// Configurations
const twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(CAN_TX_PIN, CAN_RX_PIN, TWAI_MODE_NORMAL);
const twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
const twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
// Install and start driver
if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
printf("Failed to install TWAI driver: %s\n", esp_err_to_name(twai_driver_install(&g_config, &t_config, &f_config)));
return;
}
if (twai_start() != ESP_OK) {
printf("Failed to start TWAI driver: %s\n", esp_err_to_name(twai_start()));
return;
}
printf("TWAI driver started. Beginning transmission...\n");
// Create message
twai_message_t message = {
.identifier = 0x123,
.data_length_code = 8,
.data = {0, 1, 2, 3, 4, 5, 6, 7},
.flags = 0
};
while (1) {
esp_err_t result = twai_transmit(&message, pdMS_TO_TICKS(1000));
if (result == ESP_OK) {
//printf("Message sent\n"); // Remove or slow down this print.
} else {
printf("Failed to send message: %s\n", esp_err_to_name(result));
}
vTaskDelay(pdMS_TO_TICKS(1000)); // Send every 1 second
}
}
Here is what the terminal returns:
TWAI driver started. Beginning transmission...
Failed to send message: ESP_ERR_TIMEOUT
Failed to send message: ESP_ERR_TIMEOUT
Failed to send message: ESP_ERR_TIMEOUT
And it continues with this error, and I'm not sure what to do about it. If it’s a hardware issue or software issue. How can I fix it?