我试图从VGM CAN message
中获取Reachstacker 42-45 tonnes
我在哪里使用arduino MEGA 2560
和CAN-BUS shield
这是我目前的代码:
#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;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
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;
}
}
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 char canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.println("get data from ID: ");
Serial.println(canId);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i]);
Serial.print("\t");
}
Serial.println();
}
}
如果有人需要更多信息或不了解我在寻找什么,您可以请求您需要帮助我
发送数据:
// demo: CAN-BUS Shield, send data
#include <mcp_can.h>
#include <SPI.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;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
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;
}
}
unsigned char stmp[8] = {0, 1, 2, 3, 4, 5, 6, 7};
void loop()
{
// send data: id = 0x00, standrad frame, data len = 8, stmp: data buf
CAN.sendMsgBuf(0x00, 0, 8, stmp);
delay(100); // send data per 100ms
}
您有两个不适合您的文档和正在生成的输出的部分:
对于数据有效负载,它只是格式化的问题。您将每个字节打印为整数值,而在文档中,它打印为十六进制值。使用
Serial.print(buf[i], HEX)
将有效负载打印为十六进制字符。
对于CAN帧的ID,您可以从文档中看到它们不适合未签名的char,正如@Guille在评论中已经提到的那样。实际上这些是29位标识符,您应该理想地存储在适当大小的变量中。理想情况下使用unsigned long
:
unsigned long canId = CAN.getCanId();
在文档中,CAN ID也以十六进制打印,因此这里使用:
Serial.println(canId, HEX);