Hello,
I am working on a project that involves using an Arduino Uno and an MCP2515 CAN shield to send messages on a CAN bus at a speed of 1 Mbps. I am using the MCP2515 library available on Github at this address GitHub - autowp/arduino-mcp2515: Arduino MCP2515 CAN interface library.
My problem is that when I try to send two different messages, one every 100ms and the other every 200ms, the MCP2515 module sends the messages continuously with no delay between them.
Here is the code I use:
#include <SPI.h>
#include <mcp2515.h>
struct can_frame canMsg1;
struct can_frame canMsg2;
MCP2515 mcp2515(10);
unsigned long lastTimeMsg1 = 0;
unsigned long lastTimeMsg2 = 0;
void setup() {
canMsg1.can_id = 0x0F6;
canMsg1.can_dlc = 8;
canMsg1.data[0] = 0x8E;
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] = 0x0E;
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);
mcp2515.reset();
mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ);
mcp2515.setNormalMode();
Serial.println("Example: Write to CAN");
}
void loop() {
if (millis() - lastTimeMsg1 >= 100) {
mcp2515.sendMessage(&canMsg1);
lastTimeMsg1 = millis();
while (mcp2515.sendMessage(&canMsg1) != MCP2515::ERROR_OK) {
// wait
}
}
if (millis() - lastTimeMsg2 >= 200) {
mcp2515.sendMessage(&canMsg2);
lastTimeMsg2 = millis();
while (mcp2515.sendMessage(&canMsg2) != MCP2515::ERROR_OK) {
// wait
}
}
delay(100);
}
I tried to solve this problem by adding a while loop to wait for the TXREQ bit to reset, but that did not solve the problem. When I use this loop, the program crashes after the second pass through the while loop.
If anyone has encountered a similar problem or has any ideas on how to solve this problem, I would love to hear your suggestions.
I thank you in advance for your help.
time between 2 messages = 58µs
Only message 1 is sent = 0xF6