-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCanbus
79 lines (62 loc) · 1.84 KB
/
Canbus
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
67
68
69
70
71
72
73
74
75
76
77
78
79
// canbus connection
// connecting two arduinos
#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include <mcp_can.h>
#include <mcp_can_dfs.h>
// demo: CAN-BUS Shield, receive data with check mode
// send data coming to fast, such as less than 10ms, you can use this way
// loovee, 2014-6-13
#include <SPI.h>
#include "mcp_can.h"
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;
const int LED = 8;
boolean ledON = 1;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
void setup()
{
Serial.begin(115200);
pinMode(LED,OUTPUT);
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 coming
{
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned long canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.println("get data from ID: 0x");
Serial.println(canId, HEX);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i]);
Serial.print("\t");
if(ledON && i==0)
{
digitalWrite(LED, buf[i]);
ledON = 0;
delay(500);
}
else if((!(ledON)) && i==4)
{
digitalWrite(LED, buf[i]);
ledON = 1;
}
}
Serial.println();
}
}
//END FILE