Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

M5stampS3 と Grove Mini CANモジュールでCAN通信 その2:UbuntuからのパケットをM5stampで受信

実際のところ

#include <M5Unified.h>
#include <FastLED.h>
#include "driver/twai.h" //TWAI for CAN

// CAN Pins
#define TX_GPIO_NUM GPIO_NUM_13
#define RX_GPIO_NUM GPIO_NUM_15
#define CAN_BITRATE TWAI_TIMING_CONFIG_1MBITS()

#define BUTTON1_PIN 7

// LED Strip configuration
#define NUM_LEDS 27
#define LED_PIN 3
#define BRIGHTNESS 20

// Define the LED array
CRGB leds[NUM_LEDS];


// global variables
twai_message_t rx_msg;

void readCANMessage() {
  // read CAN messages
  if (twai_receive(&rx_msg, pdMS_TO_TICKS(100)) == ESP_OK) {
    if (rx_msg.data_length_code > 0) {
      leds[17] = CRGB::Yellow;
      FastLED.show();
      Serial.printf("Message received - ID: 0x%03X, Length: %d, Data: ", rx_msg.identifier, rx_msg.data_length_code);
      for (int i = 0; i < rx_msg.data_length_code; i++) {
        Serial.printf("%02X ", rx_msg.data[i]);
      }
      Serial.println();
    }
  } else {
    leds[17] = CRGB::Black;
    FastLED.show();
  }
}



void setup() {
  auto cfg = M5.config();
  M5.begin(cfg);
  Serial.begin(115200);
  while (!Serial) {
    delay(100);
  }
  Serial.println("Serial initialized");

  // TWAI CAN Setup
  twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(TX_GPIO_NUM, RX_GPIO_NUM, TWAI_MODE_NORMAL);
  twai_timing_config_t t_config = TWAI_TIMING_CONFIG_1MBITS();
  twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();

    // Initialize FastLED
  FastLED.addLeds<SK6812, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(BRIGHTNESS);  // Set brightness (0-255)

  
  // Install TWAI Driver
  if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
    // Success
    Serial.println("TWAI Driver installed");
    // Turn on LEDs
    leds[4] = CRGB::White;
    FastLED.show();
  } else {
    // Failed
    Serial.println("TWAI Driver installation failed");
    return;
  }

  // Start TWAI Driver
  if (twai_start() == ESP_OK) {
    // Success
    // Turn on LEDs
    leds[8] = CRGB::Yellow;
    FastLED.show();
    Serial.println("TWAI Driver started");
  } else {
    // Failed
    Serial.println("TWAI Driver start failed");
    return;
  }


  // Initialize buttons
  pinMode(BUTTON_BODY, INPUT);
  pinMode(BUTTON1_PIN, INPUT_PULLUP);
  pinMode(BUTTON2_PIN, INPUT_PULLUP);
  Serial.println("Buttons initialized");

}

void loop() {

  M5.update();
  
  // Check Button 1
  if (digitalRead(BUTTON1_PIN) == LOW) {
    fill_solid(leds, NUM_LEDS, CRGB::Black);
    FastLED.show();
    Serial.println("Button 1 pressed");
    delay(200);

  }

  readCANMessage();

  delay(200);
}

Ubuntu

予めbaudrateを1Mに設定した状態で

$ cansend can0 123#48656C6C6F43414E

参考もと