#include <mcp_can.h> // Include MCP_CAN library to interface with the CAN bus
#include <SPI.h> // Include SPI library for communication with the MCP2515 module
MCP_CAN CAN0(10); // Initialize an instance of the MCP_CAN class for the CAN module (CS pin on 10)
unsigned long time_since_start; // Variable to store time since Arduino started
void setup()
{
Serial.begin(115200); // Initialize serial communication at 115200 baud rate
// Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
if(CAN0.begin(MCP_ANY, CAN_250KBPS, MCP_8MHZ) == CAN_OK)
Serial.println("MCP2515 Initialized Successfully!");
else
Serial.println("Error Initializing MCP2515...");
CAN0.setMode(MCP_NORMAL); // Set MCP2515 to normal mode to enable message transmission
}
byte data[8] = {0x0E, 0x88, 0x00, 0xB2, 0x00, 0x00, 0x00, 0x00}; // Data array to be sent over CAN bus
void loop()
{
// Send data over CAN bus: ID = 0x1806E5F4, Standard frame, data length = 8 bytes
byte sndStat = CAN0.sendMsgBuf(0x1806E5F4, 0, 8, data);
if(sndStat == CAN_OK){
// If message sent successfully, print the data and other details
printByteArrayAsString(data, 8);
Serial.print("Message Sent Successfully! ID: 0x1806E5F4, Length: 8 bytes, Time: ");
time_since_start = millis(); // Get the current time since Arduino started
Serial.print(time_since_start);
Serial.println(" ms");
} else { // If there was an error in sending, print an error message
Serial.println("Error Sending Message...");
}
delay(900); // Delay of 900 milliseconds before next send
}
void printByteArrayAsString(byte byteArray[], int length) {
// Converts the byte array to a string of hexadecimal values and prints it
char str[length * 2 + 1]; // Allocate space for the string
for (int i = 0; i < length; i++) {
sprintf(&str[i * 2], "%02X", byteArray[i]); // Convert each byte to hexadecimal
}
str[length * 2] = '\0'; // Null-terminate the string
Serial.println(str); // Print the hexadecimal string to the serial monitor
}