Skip to content

Instantly share code, notes, and snippets.

@thankthemaker
Last active August 14, 2023 18:39
Show Gist options
  • Save thankthemaker/9b8565c904f6351cdba5d5f0c4c1aac6 to your computer and use it in GitHub Desktop.
Save thankthemaker/9b8565c904f6351cdba5d5f0c4c1aac6 to your computer and use it in GitHub Desktop.
#include "driver/twai.h"
twai_message_t rx_frame = {};
gpio_num_t tx = GPIO_NUM_1;
gpio_num_t rx = GPIO_NUM_2;
void setup() {
delay(2000);
gpio_reset_pin(rx);
gpio_reset_pin(tx);
//twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(tx, rx, TWAI_MODE_NORMAL);
twai_general_config_t g_config = {
.mode = TWAI_MODE_NORMAL,
.tx_io = (gpio_num_t)tx,
.rx_io = (gpio_num_t)rx,
.clkout_io = TWAI_IO_UNUSED,
.bus_off_io = TWAI_IO_UNUSED,
.tx_queue_len = 5,
.rx_queue_len = 5,
.alerts_enabled = TWAI_ALERT_ALL,
.clkout_divider = 0};
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
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) {
printf("Driver installed\n");
} else {
printf("Failed to install driver\n");
}
// Start TWAI driver
if (twai_start() == ESP_OK) {
printf("Driver started\n");
} else {
printf("Failed to start driver\n");
}
delay(100);
twai_status_info_t status;
twai_get_status_info(&status);
printf("TWAI state 0x%X\n", status.state);
}
uint32_t alerts_triggered;
esp_err_t status;
void loop() {
delay(1000);
twai_message_t tx_frame = {};
tx_frame.extd = 1;
tx_frame.identifier = (uint32_t(0x8000) << 16) + (uint16_t(0x01) << 8) + 25;
tx_frame.data_length_code = 0x03;
tx_frame.data[0] = 26;
tx_frame.data[1] = 0x00;
tx_frame.data[2] = 0x00; //
//Queue message for transmission
status = twai_transmit(&tx_frame, pdMS_TO_TICKS(10));
if (status != ESP_OK) {
twai_read_alerts(&alerts_triggered, pdMS_TO_TICKS(2000));
printf("Failed to queue message for transmission alert 0x%X, status 0x%X %S\n", alerts_triggered , status, esp_err_to_name(status));
}
status = twai_receive( &rx_frame, 3 * portTICK_PERIOD_MS);
while (status == ESP_OK) {
status = twai_receive( &rx_frame, 3 * portTICK_PERIOD_MS);
if((status == ESP_OK)) {
printf("Received package\n");
} else {
printf("Failed to receive messages, alert 0x%X, status 0x%X %S\n", alerts_triggered , status, esp_err_to_name(status));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment