Skip to content

Instantly share code, notes, and snippets.

@kenny-macchina
Last active July 6, 2020 16:59
Show Gist options
  • Save kenny-macchina/5a39add47c97a8fcd16d0d45d8794679 to your computer and use it in GitHub Desktop.
Save kenny-macchina/5a39add47c97a8fcd16d0d45d8794679 to your computer and use it in GitHub Desktop.
#include "esp32_can.h"
void setup()
{
Serial.begin(115200);
CAN0.setCANPins((gpio_num_t)4,(gpio_num_t)5);
Serial.println("Initializing ...");
// Initialize CAN controller at the specified speed
if(CAN0.begin(500000))
{
Serial.println("Init OK ...");
}
else
{
Serial.println("Init Failed ...");
}
CAN0.watchFor(); //allow anything through
Serial.println("Ready ...!");
CAN_FRAME txFrame;
txFrame.rtr = 0;
txFrame.id = 0x123;
txFrame.extended = false;
txFrame.length = 4;
txFrame.data.byte[0] = 0x10;
txFrame.data.byte[1] = 0x1A;
txFrame.data.byte[2] = 0xFF;
txFrame.data.byte[3] = 0x5D;
CAN0.sendFrame(txFrame);
}
byte i=0;
// CAN message frame
CAN_FRAME message;
void loop()
{
if (CAN0.read(message))
{
// Print message
Serial.print("ID: ");
Serial.println(message.id,HEX);
Serial.print("Extended: ");
if(message.extended)
{
Serial.println("Yes");
}
else
{
Serial.println("No");
}
Serial.print("Length: ");
Serial.println(message.length,DEC);
for(i = 0;i < message.length; i++)
{
Serial.print(message.data.byte[i],HEX);
Serial.print(" ");
}
Serial.println();
Serial.println();
// Send out a return message for each one received
// Simply increment message id and data bytes to show proper transmission
// Note: this will double the traffic on the network (provided it passes the filter above)
message.id++;
for(i = 0;i < message.length; i++)
{
message.data.byte[i]++;
}
CAN0.sendFrame(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment