
Arduino Quick Start
PowerHub CAN communication related APIs and example programs.
#include <Arduino.h>
#include "driver/twai.h"
const gpio_num_t MCU_CAN_TXD = GPIO_NUM_39;
const gpio_num_t MCU_CAN_RXD = GPIO_NUM_40;
void setup() {
Serial.begin(115200);
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(MCU_CAN_TXD, MCU_CAN_RXD, TWAI_MODE_NORMAL);
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 && twai_start() == ESP_OK) {
Serial.println("\nCAN ready. ");
} else {
Serial.println("\nCAN init failed. ");
while (1) delay(1000);
}
}
void loop() {
// transmit
twai_message_t tx_msg = {};
tx_msg.extd = 0; // 0 = standard frame, 1 = extended frame
tx_msg.identifier = 0x123; // 11-bit standard ID, change it on another device
tx_msg.data_length_code = 2;
tx_msg.data[0] = 0xAA; // change it on another device
tx_msg.data[1] = 0xBB; // change it on another device
if (twai_transmit(&tx_msg, pdMS_TO_TICKS(100)) == ESP_OK) {
Serial.println("TX OK");
} else {
Serial.println("TX failed");
}
// receive (non-blocking)
twai_message_t rx_msg;
if (twai_receive(&rx_msg, pdMS_TO_TICKS(10)) == ESP_OK) {
Serial.print("RX: ");
for (int i = 0; i < rx_msg.data_length_code; i++) Serial.printf("%02X ", rx_msg.data[i]);
Serial.printf("(ext=%d, id=0x%X, dlc=%d)", rx_msg.extd, rx_msg.identifier, rx_msg.data_length_code);
Serial.println();
}
delay(2000);
}Prepare two PowerHub devices and flash the above code onto both (you can modify the message ID and content to distinguish them). Set the 120 Ω terminal matching resistor switch of both devices to ON, then connect the CAN interfaces of the two devices using an XT30(2+2)-F connector cable (for example, PwrCAN Cable):
After connecting, the two PowerHub devices will send messages to each other via CAN communication. Connect one of them to your computer and observe the serial monitor output:
The CAN communication driver of PowerHub uses TWAI from ESP-IDF. For more related APIs, refer to the following documentation: