-
Notifications
You must be signed in to change notification settings - Fork 0
/
can_receive_LED.ino
67 lines (55 loc) · 1.88 KB
/
can_receive_LED.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <SPI.h>
#include "mcp2515_can.h"
/*SAMD core*/
#ifdef ARDUINO_SAMD_VARIANT_COMPLIANCE
#define SERIAL SerialUSB
#else
#define SERIAL Serial
#endif
const int SPI_CS_PIN = 9;
mcp2515_can CAN(SPI_CS_PIN); // Set CS pin
const unsigned char expectedBuf_Reg[8] = {6, 4, 6, 4, 0, 0, 0, 9};
void setup() {
SERIAL.begin(115200);
pinMode(10, OUTPUT);
while (!Serial) {};
while (CAN_OK != CAN.begin(CAN_500KBPS)) { // Init CAN bus: baudrate = 500k
SERIAL.println("CAN BUS Shield init fail");
SERIAL.println(" Init CAN BUS Shield again");
delay(100);
}
SERIAL.println("CAN BUS Shield init ok!");
}
void loop() {
unsigned char len = 0;
unsigned char buf[8];
if (CAN_MSGAVAIL == CAN.checkReceive()) { // Check if data is available
CAN.readMsgBuf(&len, buf); // Read data: len = data length, buf = data byte(s)
unsigned long canId = CAN.getCanId(); // Get CAN ID
SERIAL.print("CAN ID: ");
SERIAL.println(canId, HEX);
SERIAL.print("Data: ");
for (int i = 0; i < len; i++) { // Print each byte of the data
SERIAL.print(buf[i], HEX);
SERIAL.print(" ");
}
SERIAL.println();
// Check if the received message matches the expected buffer
bool match = true;
if (len == 8) {
for (int i = 0; i < 8; i++) {
if (buf[i] != expectedBuf_Reg[i]) {
match = false;
break;
}
}
if (match) {
// Blink the LED if the message matches
digitalWrite(10, HIGH); // turn the LED on (HIGH is the voltage level)
delay(200); // wait for 200ms
digitalWrite(10, LOW); // turn the LED off by making the voltage LOW
delay(200);
}
}
}
}