1 | // demo: CAN-BUS Shield, receive data with interrupt mode
|
---|
2 | // when in interrupt mode, the data coming can't be too fast, must >20ms, or else you can use check mode
|
---|
3 | // loovee, 2014-6-13
|
---|
4 |
|
---|
5 | #include <SPI.h>
|
---|
6 | #include "mcp_can.h"
|
---|
7 |
|
---|
8 | // the cs pin of the version after v1.1 is default to D9
|
---|
9 | // v0.9b and v1.0 is default D10
|
---|
10 | const int SPI_CS_PIN = 9;
|
---|
11 |
|
---|
12 | MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
|
---|
13 |
|
---|
14 |
|
---|
15 | unsigned char flagRecv = 0;
|
---|
16 | unsigned char len = 0;
|
---|
17 | unsigned char buf[8];
|
---|
18 | char str[20];
|
---|
19 |
|
---|
20 | void setup()
|
---|
21 | {
|
---|
22 | Serial.begin(115200);
|
---|
23 |
|
---|
24 | START_INIT:
|
---|
25 |
|
---|
26 | if(CAN_OK == CAN.begin(CAN_500KBPS)) // init can bus : baudrate = 500k
|
---|
27 | {
|
---|
28 | Serial.println("CAN BUS Shield init ok!");
|
---|
29 | }
|
---|
30 | else
|
---|
31 | {
|
---|
32 | Serial.println("CAN BUS Shield init fail");
|
---|
33 | Serial.println("Init CAN BUS Shield again");
|
---|
34 | delay(100);
|
---|
35 | goto START_INIT;
|
---|
36 | }
|
---|
37 |
|
---|
38 | attachInterrupt(0, MCP2515_ISR, FALLING); // start interrupt
|
---|
39 | }
|
---|
40 |
|
---|
41 | void MCP2515_ISR()
|
---|
42 | {
|
---|
43 | flagRecv = 1;
|
---|
44 | }
|
---|
45 |
|
---|
46 | void loop()
|
---|
47 | {
|
---|
48 | if(flagRecv)
|
---|
49 | { // check if get data
|
---|
50 |
|
---|
51 | flagRecv = 0; // clear flag
|
---|
52 |
|
---|
53 | // iterate over all pending messages
|
---|
54 | // If either the bus is saturated or the MCU is busy,
|
---|
55 | // both RX buffers may be in use and reading a single
|
---|
56 | // message does not clear the IRQ conditon.
|
---|
57 | while (CAN_MSGAVAIL == CAN.checkReceive())
|
---|
58 | {
|
---|
59 | // read data, len: data length, buf: data buf
|
---|
60 | CAN.readMsgBuf(&len, buf);
|
---|
61 |
|
---|
62 | // print the data
|
---|
63 | for(int i = 0; i<len; i++)
|
---|
64 | {
|
---|
65 | Serial.print(buf[i]);Serial.print("\t");
|
---|
66 | }
|
---|
67 | Serial.println();
|
---|
68 | }
|
---|
69 | }
|
---|
70 | }
|
---|
71 |
|
---|
72 | /*********************************************************************************************************
|
---|
73 | END FILE
|
---|
74 | *********************************************************************************************************/
|
---|