[136] | 1 | // demo: CAN-BUS Shield, receive data with check mode
|
---|
| 2 | // send data coming to fast, such as less than 10ms, you can use this way
|
---|
| 3 | // loovee, 2014-6-13
|
---|
| 4 |
|
---|
| 5 |
|
---|
| 6 | #include <SPI.h>
|
---|
| 7 | #include "mcp_can.h"
|
---|
| 8 |
|
---|
| 9 |
|
---|
| 10 | // the cs pin of the version after v1.1 is default to D9
|
---|
| 11 | // v0.9b and v1.0 is default D10
|
---|
| 12 | const int SPI_CS_PIN = 9;
|
---|
| 13 | const int LED=8;
|
---|
| 14 | boolean ledON=1;
|
---|
| 15 | MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
|
---|
| 16 |
|
---|
| 17 | void setup()
|
---|
| 18 | {
|
---|
| 19 | Serial.begin(115200);
|
---|
| 20 | pinMode(LED,OUTPUT);
|
---|
| 21 |
|
---|
| 22 | START_INIT:
|
---|
| 23 |
|
---|
| 24 | if(CAN_OK == CAN.begin(CAN_500KBPS)) // init can bus : baudrate = 500k
|
---|
| 25 | {
|
---|
| 26 | Serial.println("CAN BUS Shield init ok!");
|
---|
| 27 | }
|
---|
| 28 | else
|
---|
| 29 | {
|
---|
| 30 | Serial.println("CAN BUS Shield init fail");
|
---|
| 31 | Serial.println("Init CAN BUS Shield again");
|
---|
| 32 | delay(100);
|
---|
| 33 | goto START_INIT;
|
---|
| 34 | }
|
---|
| 35 | }
|
---|
| 36 |
|
---|
| 37 |
|
---|
| 38 | void loop()
|
---|
| 39 | {
|
---|
| 40 | unsigned char len = 0;
|
---|
| 41 | unsigned char buf[8];
|
---|
| 42 |
|
---|
| 43 | if(CAN_MSGAVAIL == CAN.checkReceive()) // check if data coming
|
---|
| 44 | {
|
---|
| 45 | CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
|
---|
| 46 |
|
---|
| 47 | unsigned char canId = CAN.getCanId();
|
---|
| 48 |
|
---|
| 49 | Serial.println("-----------------------------");
|
---|
| 50 | Serial.println("get data from ID: ");
|
---|
| 51 | Serial.println(canId);
|
---|
| 52 |
|
---|
| 53 | for(int i = 0; i<len; i++) // print the data
|
---|
| 54 | {
|
---|
| 55 | Serial.print(buf[i]);
|
---|
| 56 | Serial.print("\t");
|
---|
| 57 | if(ledON && i==0)
|
---|
| 58 | {
|
---|
| 59 |
|
---|
| 60 | digitalWrite(LED,buf[i]);
|
---|
| 61 | ledON=0;
|
---|
| 62 | delay(500);
|
---|
| 63 | }
|
---|
| 64 | else if((!(ledON)) && i==4){
|
---|
| 65 |
|
---|
| 66 | digitalWrite(LED,buf[i]);
|
---|
| 67 | ledON=1;
|
---|
| 68 | }
|
---|
| 69 |
|
---|
| 70 |
|
---|
| 71 | }
|
---|
| 72 | Serial.println();
|
---|
| 73 | }
|
---|
| 74 | }
|
---|
| 75 |
|
---|
| 76 | /*********************************************************************************************************
|
---|
| 77 | END FILE
|
---|
| 78 | *********************************************************************************************************/
|
---|