Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created July 7, 2025 03:22
Show Gist options
  • Save maxpromer/c74c87b1a8ab4e0ee1bfc05a7e917aab to your computer and use it in GitHub Desktop.
Save maxpromer/c74c87b1a8ab4e0ee1bfc05a7e917aab to your computer and use it in GitHub Desktop.
#include "driver/gpio.h"
#include "driver/twai.h"
void setup() {
Serial.begin(115200);
twai_general_config_t g_config = { // สร้างต้วแปร g_config ใช้กำหนดค่าเกี่ยวกับบัส CAN
.mode = TWAI_MODE_NORMAL,
.tx_io = GPIO_NUM_26, // กำหนดขา TX ต่อกับ 26
.rx_io = GPIO_NUM_27, // กำหนดขา TX ต่อกับ 27
.clkout_io = ((gpio_num_t) - 1),
.bus_off_io = ((gpio_num_t) - 1),
.tx_queue_len = 5,
.rx_queue_len = 5,
.alerts_enabled = TWAI_ALERT_NONE,
.clkout_divider = 0
};
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
Serial.println("Failed to install driver");
return;
}
if (twai_start() != ESP_OK) {
Serial.println("Failed to start driver");
return;
}
}
void loop() {
twai_message_t message;
if (twai_receive(&message, pdMS_TO_TICKS(10000)) != ESP_OK) {
return;
}
String payload = "";
for (int i=0;i<message.data_length_code;i++) {
if (i != 0) {
payload += " ";
}
payload += "0x";
if (message.data[i] < 0x10) {
payload += "0";
}
payload += String(message.data[i], HEX);
}
Serial.printf("Received ID 0x%02x: %s\n", message.identifier, payload.c_str());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment