#include #include const int SPI_CS_PIN = 10; // MCP2515 CS pin MCP_CAN CAN(SPI_CS_PIN); // CAN object const byte i1 = 5; const byte i2 = 8; void setup() { Serial.begin(115200); pinMode(i1, INPUT_PULLUP); pinMode(i2, INPUT_PULLUP); if (CAN.begin(MCP_ANY, CAN_125KBPS, MCP_8MHZ) == CAN_OK) { Serial.println("CAN BUS Init OK!"); } else { Serial.println("CAN BUS Init Failed"); while (1); } CAN.setMode(MCP_NORMAL); // ตั้งให้ส่ง-รับได้ delay(1000); } void loop() { if (digitalRead(i1)==0) // กด sw 1 { byte dataToSend[8] = { 0x00, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; byte sendResult = CAN.sendMsgBuf(0x4f, 0, 8, dataToSend); byte dataToSend1[8] = { 0x00, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; byte sendResult2 = CAN.sendMsgBuf(0x6f, 0, 8, dataToSend1); byte dataToSend2[8] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; byte sendResult3 = CAN.sendMsgBuf(0x50, 0, 8, dataToSend2); } if (digitalRead(i2)==0) // กด sw 2 { byte dataToSend[8] = { 0xff, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; byte sendResult = CAN.sendMsgBuf(0x4f, 0, 8, dataToSend); byte dataToSend1[8] = { 0xff, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; byte sendResult2 = CAN.sendMsgBuf(0x6f, 0, 8, dataToSend1); byte dataToSend2[8] = { 0xff, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; byte sendResult3 = CAN.sendMsgBuf(0x50, 0, 8, dataToSend2); while (digitalRead(i2)==0) delay(10); // ตรวจว่ายก sw2 ขืันแล้ว } read_data(); //อ่านข้อมูลจาก canbus } void read_data() { if (CAN_MSGAVAIL == CAN.checkReceive()) //ถ้ามีข้อมูลมา { long unsigned int rxId; byte len = 0; byte rxBuf[8]; CAN.readMsgBuf(&rxId, &len, rxBuf); // อ่านข้อมูล id , จำนวน, array if (rxId==0x51) // ถ้า id ที่รับมา =0x51 ให้แสดงออกมา { Serial.print("Received ID: 0x"); Serial.println(rxId, HEX); Serial.print("Data: "); for (int i = 0; i < len; i++) //แสดงข้อมูลทั้งหมด { if (rxBuf[i] < 0x10) Serial.print("0"); Serial.print(rxBuf[i], HEX); Serial.print(" "); } Serial.println("data array[0]="); //แสดงข้อเฉพาะ array[0] เป็นเลขฐาน 10 Serial.println(rxBuf[0]); } if (rxId==0x21) run_prog_01(); // ถ้า id ที่รับมา =0x21 ให้run โปรแกรมย่อย run_prog_01() if (rxId==0x22) run_prog_02(); // ถ้า id ที่รับมา =0x21 ให้run โปรแกรมย่อย run_prog_02() if (rxId==0x23) run_prog_03(); // ถ้า id ที่รับมา =0x21 ให้run โปรแกรมย่อย run_prog_03() } } void run_prog_01() { // ชุดคำสั่ง.... } void run_prog_02() { // ชุดคำสั่ง.... } void run_prog_03() { // ชุดคำสั่ง.... }