5 #include <driver/twai.h> 10 #define CAN_IO_UNUSED ((gpio_num_t) -1) 15 static const char *
const TAG =
"esp32_can";
17 static bool get_bitrate(
canbus::CanSpeed bitrate, twai_timing_config_t *t_config) {
19 #if defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32C3) || \ 20 defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32H6) 22 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_1KBITS();
25 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_5KBITS();
28 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_10KBITS();
31 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_12_5KBITS();
34 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_16KBITS();
37 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_20KBITS();
41 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_25KBITS();
44 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_50KBITS();
47 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_100KBITS();
50 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_125KBITS();
53 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_250KBITS();
56 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_500KBITS();
59 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_800KBITS();
62 *t_config = (twai_timing_config_t) TWAI_TIMING_CONFIG_1MBITS();
70 twai_general_config_t g_config =
71 TWAI_GENERAL_CONFIG_DEFAULT((gpio_num_t) this->
tx_, (gpio_num_t) this->
rx_, TWAI_MODE_NORMAL);
72 twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
73 twai_timing_config_t t_config;
75 if (!get_bitrate(this->
bit_rate_, &t_config)) {
82 if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
89 if (twai_start() != ESP_OK) {
102 uint32_t
flags = TWAI_MSG_FLAG_NONE;
104 flags |= TWAI_MSG_FLAG_EXTD;
107 flags |= TWAI_MSG_FLAG_RTR;
110 twai_message_t message = {
112 .identifier = frame->
can_id,
119 if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
127 twai_message_t message;
129 if (twai_receive(&message, 0) != ESP_OK) {
133 frame->
can_id = message.identifier;
140 message.data_length_code < canbus::CAN_MAX_DATA_LENGTH ? message.data_length_code : canbus::CAN_MAX_DATA_LENGTH;
141 memcpy(frame->data, message.data, dlc);
bool setup_internal() override
uint8_t can_data_length_code
bool remote_transmission_request
canbus::Error read_message(struct canbus::CanFrame *frame) override
virtual void mark_failed()
Mark this component as failed.
Implementation of SPI Controller mode.
canbus::Error send_message(struct canbus::CanFrame *frame) override