ArduinoESP32 DevKit V1Lab virtual

ESP32 TWAI and Uno MCP2515 on CAN

The ESP32’s own CAN controller (TWAI, driver/twai.h) through an SN65HVD230 transceiver, and an Uno with an MCP2515, on one pair at 500 kbit/s. The ESP32 sends its knob; the Uno dims its LED to it and answers how many it has had.

ESP32 TWAI and Uno MCP2515 on CAN in Argynix Lab

The code

sketch.inoC++
// ESP32: its own CAN controller (TWAI) on GPIO 5 (TX) and GPIO 4 (RX), through the
// SN65HVD230. Sends its knob (GPIO 34) as id 0x100 ten times a second, and prints what
// the Uno answers (id 0x200).
#include "driver/twai.h"

void setup() {
  Serial.begin(115200);
  twai_general_config_t g = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_5, GPIO_NUM_4, TWAI_MODE_NORMAL);
  twai_timing_config_t t = TWAI_TIMING_CONFIG_500KBITS();
  twai_filter_config_t f = TWAI_FILTER_CONFIG_ACCEPT_ALL();
  if (twai_driver_install(&g, &t, &f) == ESP_OK && twai_start() == ESP_OK) {
    Serial.println("TWAI started at 500 kbit/s");
  } else {
    Serial.println("TWAI did not start");
  }
}

void loop() {
  int knob = analogRead(34);  // 0..4095
  twai_message_t out = {};
  out.identifier = 0x100;
  out.data_length_code = 2;
  out.data[0] = knob >> 8;
  out.data[1] = knob & 0xff;
  if (twai_transmit(&out, pdMS_TO_TICKS(50)) != ESP_OK) Serial.println("Not sent: is the Uno there?");

  twai_message_t in;
  if (twai_receive(&in, pdMS_TO_TICKS(100)) == ESP_OK && in.identifier == 0x200) {
    Serial.printf("Knob %d, the Uno has had %d\n", knob, in.data[0] | (in.data[1] << 8));
  }
}