#include "driver/twai.h"
// Define the GPIO pins connected to the CAN G-Mod TX and RX pins
#define CAN_TX_PIN 5 // Connected to CAN G-Mod TX
#define CAN_RX_PIN 4 // Connected to CAN G-Mod RX
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("Starting CAN Bus Transceiver Example...");
// Configure TWAI (CAN) controller at 500 kbps
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(
(gpio_num_t)CAN_TX_PIN,
(gpio_num_t)CAN_RX_PIN,
TWAI_MODE_NORMAL
);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
// Install and start TWAI driver
if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
Serial.println("Failed to install TWAI driver!");
return;
}
if (twai_start() != ESP_OK) {
Serial.println("Failed to start TWAI driver!");
return;
}
Serial.println("CAN Driver successfully initialized at 500 kbps.");
}
void loop() {
// --- 1. Transmit a CAN Message ---
twai_message_t tx_msg;
tx_msg.identifier = 0x123; // Standard 11-bit CAN ID
tx_msg.flags = TWAI_MSG_FLAG_NONE;
tx_msg.data_length_code = 4;
tx_msg.data[0] = 0x10;
tx_msg.data[1] = 0x20;
tx_msg.data[2] = 0x30;
tx_msg.data[3] = 0x40;
if (twai_transmit(&tx_msg, pdMS_TO_TICKS(100)) == ESP_OK) {
Serial.println("Sent CAN frame ID: 0x123");
} else {
Serial.println("Transmit timed out or bus busy");
}
// --- 2. Check for Incoming CAN Messages ---
twai_message_t rx_msg;
if (twai_receive(&rx_msg, pdMS_TO_TICKS(500)) == ESP_OK) {
Serial.printf("Received Frame from 0x%03X [DLC %d]: ", rx_msg.identifier, rx_msg.data_length_code);
for (int i = 0; i < rx_msg.data_length_code; i++) {
Serial.printf("0x%02X ", rx_msg.data[i]);
}
Serial.println();
}
delay(1000);
}