我一直在搞乱CAN-bus尝试学习基础知识,所以我可以在未来的项目中使用它。我有2个连接MCP2515芯片的arduinos,我之间正在发送消息。我已经能够连接芯片并在arduinos之间发送消息就好了,但是当我去修改代码以使LED闪烁时,如果第一个字节是0x00或0x01它就不会闪烁。我添加了print语句以检查它是否正在进入循环,并且使用串行监视器我可以看到它,但是数字引脚3保持在~0V。
这可能是一个比CAN总线问题更多的问题,但有人可以帮我理解为什么我的LED不会闪烁吗?代码进入循环,所以它应该处理命令,我初始化引脚作为输出,但我仍然没有得到任何闪烁。
注意,发送arduino正在发送交替的数据包,首先是一个包含0X01的数据包作为第一个数据字节,然后是0x00作为第一个数据字节。这些数据包间隔5000毫秒。
我目前正在使用这里提供的CAN库https://github.com/autowp/arduino-mcp2515
接收arduino的代码
#include <SPI.h>
#include <mcp2515.h>
struct can_frame canMsg;
MCP2515 mcp2515(10);
int LED_PIN = 3;
void setup() {
Serial.begin(115200);
SPI.begin();
pinMode(LED_PIN, OUTPUT);
mcp2515.reset();
mcp2515.setBitrate(CAN_125KBPS);
mcp2515.setNormalMode();
Serial.println("------- CAN Read ----------");
Serial.println("ID DLC DATA");
}
void loop() {
if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
Serial.print(canMsg.can_id, HEX); // print ID
Serial.print(" ");
Serial.print(canMsg.can_dlc, HEX); // print DLC
Serial.print(" ");
if(canMsg.data[0] == 0x00){
digitalWrite(LED_PIN,HIGH);
Serial.print("YEET");
}
if(canMsg.data[0] == 0x01){
digitalWrite(LED_PIN,LOW);
Serial.print("YOTE");
}
for (int i = 0; i<canMsg.can_dlc; i++) { // print the data
Serial.print(canMsg.data[i],HEX);
Serial.print(" ");
}
Serial.println();
}
}
和完整性传输arduino的代码
#include <SPI.h>
#include <mcp2515.h>
struct can_frame canMsg1;
struct can_frame canMsg2;
MCP2515 mcp2515(10);
void setup() {
canMsg1.can_id = 0x0F6;
canMsg1.can_dlc = 8;
canMsg1.data[0] = 0x01;
canMsg1.data[1] = 0x87;
canMsg1.data[2] = 0x32;
canMsg1.data[3] = 0xFA;
canMsg1.data[4] = 0x26;
canMsg1.data[5] = 0x8E;
canMsg1.data[6] = 0xBE;
canMsg1.data[7] = 0x86;
canMsg2.can_id = 0x036;
canMsg2.can_dlc = 8;
canMsg2.data[0] = 0x00;
canMsg2.data[1] = 0x00;
canMsg2.data[2] = 0x00;
canMsg2.data[3] = 0x08;
canMsg2.data[4] = 0x01;
canMsg2.data[5] = 0x00;
canMsg2.data[6] = 0x00;
canMsg2.data[7] = 0xA0;
while (!Serial);
Serial.begin(115200);
SPI.begin();
mcp2515.reset();
mcp2515.setBitrate(CAN_125KBPS);
mcp2515.setNormalMode();
Serial.println("Example: Write to CAN");
}
void loop() {
mcp2515.sendMessage(&canMsg1);
delay(5000);
mcp2515.sendMessage(&canMsg2);
Serial.println("Messages sent");
delay(5000);
}
对不起,我是个白痴。我忘记了面包板电源线没有一直连接到电路板上。我将Arduino连接到面包板的适当部分以接收电源和接地,但将LED连接到未连接的接地引脚。