samedi 18 octobre 2014

Arduino Uno / CAN-Bus Shield

Le programme Arduino utilisé :
// 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
// some code added by reunisoft ntic974
#include <SPI.h>
#include "mcp_can.h"

unsigned char Flag_Recv = 0;
unsigned char len = 0;
unsigned char buf[8];
char str[20];

MCP_CAN CAN(10);                                            // Set CS to pin 10

void setup()
{
    Serial.begin(115200);

START_INIT:

    if(CAN_OK == CAN.begin(CAN_500KBPS))                   // init can bus : baudrate = 500k
    {
        Serial.println("CAN BUS Shield init ok!");
    }
    else
    {
        Serial.println("CAN BUS Shield init fail");
        Serial.println("Init CAN BUS Shield again");
        delay(100);
        goto START_INIT;
    }
}

INT32U canId = 0x000;

void loop()
{
    if(CAN_MSGAVAIL == CAN.checkReceive())            // check if data coming
    {
        CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf
      
        canId = CAN.getCanId();
        if(canId<16)
        {
          Serial.print('0');
        }
        Serial.print(canId, HEX); Serial.print('>');
      
        for(int i = 0; i<len; i++)    // print the data
        {
          if (buf[i]<16)
          {
            Serial.print('0');
          }
        
          Serial.print(buf[i],HEX);
        
          if (i<len-1)
          {
            Serial.print(":");
          }
        }
      
        Serial.println();
    }
}

/*********************************************************************************************************
  END FILE
*********************************************************************************************************/


Exemple de sortie sur le moniteur série (PORT COM5: sur mon poste), à l'arrêt du module :
50005>00:00:00:00:00:00:C0:00:00:05:00:05:00:05:00
00>E7:E0:00:00
00>
00>
17>
17>
1E30F0>
1E30F0>
30F00005>FF:FF:FF:FF:FF:FF:FF|F:FF:FF:FF:01:05:00:F0:30:1E:00