Bye Bye Moore

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

M5stack + COMMU ModuleでCAN通信する その3:複数構成での通信

実際のところ

送信側

#include <M5Stack.h>
#include <mcp_can.h>
#include <SPI.h>

const int SPI_CS_PIN = 12;
MCP_CAN CAN(SPI_CS_PIN);

void setup() {
  M5.begin();
  M5.Power.begin();
  M5.Lcd.println("M5Stack wake up!");
  
  if (CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_8MHZ) == CAN_OK) {  
    M5.Lcd.println("Init!");
  } else {
    M5.Lcd.println("Fail!");
  }
  CAN0.setMode(MCP_NORMAL); // Set operation mode to normal so the MCP2515 sends acks
  M5.Lcd.println("BtnA to 1, BtnB to 2, BtnC to Both");
}

void loop() {
  M5.update();

  if (M5.BtnA.wasPressed()) {
    sendMessage(0x001, "To Receiver 1");
  }
  if (M5.BtnB.wasPressed()) {
    sendMessage(0x002, "To Receiver 2");
  }
  if (M5.BtnC.wasPressed()) {
    sendMessage(0x003, "To Both Receivers");
  }
}

void sendMessage(unsigned long id, const char* message) {
  unsigned char len = strlen(message);
  unsigned char buf[8];
  strncpy((char*)buf, message, 8);
  
  CAN.sendMsgBuf(id, 0, len, buf);
  M5.Lcd.printf("Receive: ID 0x%lX, Msg: %s\n", id, message);
}

受信側

書き込み時にRECEIVER_IDを変更しておく

#include <M5Stack.h>
#include <mcp_can.h>
#include <SPI.h>

#define CAN0_INT 15  // 割り込みピンを設定

volatile bool messageReceived = false;

void CANInterrupt() {
  messageReceived = true;
}

const int SPI_CS_PIN = 12;
MCP_CAN CAN(SPI_CS_PIN);

// 受信機1の場合は0x001、受信機2の場合は0x002に設定
const unsigned long RECEIVER_ID = 0x001; // または 0x002

void setup() {
  M5.begin();
  M5.Power.begin();
  Serial2.begin(9600, SERIAL_8N1, 16, 17);
  delay(1000);

  pinMode(CAN0_INT, INPUT);
  attachInterrupt(digitalPinToInterrupt(CAN0_INT), CANInterrupt, FALLING);
  Serial2.begin(9600, SERIAL_8N1, 16, 17);
  delay(1000);
  
  
  if (CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_8MHZ) == CAN_OK) {  
    M5.Lcd.println("Init!");
  } else {
    M5.Lcd.println("Fail!");
  }
  CAN0.setMode(MCP_NORMAL); // Set operation mode to normal so the MCP2515 sends acks
  M5.Lcd.printf("Receive ID: 0x%lX\n", RECEIVER_ID);
}

void loop() {
  unsigned char len = 0;
  unsigned char buf[8];

  if (CAN_MSGAVAIL == CAN.checkReceive()) {
    CAN.readMsgBuf(&len, buf);
    unsigned long canId = CAN.getCanId();

    if (canId == RECEIVER_ID || canId == 0x003) {
      M5.Lcd.printf("Receive: ID: 0x%lX, msg: ", canId);
      for (int i = 0; i < len; i++) {
        M5.Lcd.write(buf[i]);
      }
      M5.Lcd.println();
    }
  }

  M5.Lcd.print(".");
  delay(200);
  M5.update();
}