Skip to content

Instantly share code, notes, and snippets.

@kenny-macchina
Last active March 15, 2023 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenny-macchina/f87e4c39e29a39562e168b9869d64ef8 to your computer and use it in GitHub Desktop.
Save kenny-macchina/f87e4c39e29a39562e168b9869d64ef8 to your computer and use it in GitHub Desktop.
#include <esp32_can.h>
uint8_t codes[4] = {5, 0xB, 0xC, 0xD};
int idx = 0;
uint32_t tick = 0;
const int led_pin = 13;
char msg_buf[10];
int led_state = 0;
int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 1000; // interval at which to blink (milliseconds)
void setup()
{
pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, LOW);
// Start Serial port
Serial.begin(115200);
CAN0.setCANPins(GPIO_NUM_4, GPIO_NUM_5);
CAN0.begin(500000);
Serial.println("Ready ...!");
int filter;
//extended
for (filter = 0; filter < 3; filter++)
{
Can0.setRXFilter(filter, 0, 0, false);
}
}
void loop()
{
CAN_FRAME incoming;
if (Can0.available() > 0)
{
Can0.read(incoming);
if (incoming.id > 0x7DF && incoming.id < 0x7F0)
{
processPID(incoming);
}
}
static unsigned long l = 0;
unsigned long t = millis();
if ((t - l) > 50)
{
sendPIDRequest(0x7DF, 0xC);
sendPIDRequest(0x7DF, 0xD);
sendPIDRequest(0x7DF, 5);
l = t;
}
}
void sendPIDRequest(uint32_t id, uint8_t PID)
{
CAN_FRAME frame;
frame.id = id;
frame.extended = 0;
frame.length = 8;
for (int i = 0; i < 8; i++)
frame.data.bytes[i] = 0xAA;
frame.data.bytes[0] = 2; //2 more bytes to follow
frame.data.bytes[1] = 1;
frame.data.bytes[2] = PID;
Can0.sendFrame(frame);
}
int lastTemp=-1;
float lastpsi=-1;
int lastRPM=-1;
int lastMPH=-1;
void processPID(CAN_FRAME &frame)
{
int temperature;
float psi;
int RPM;
int MPH;
if (frame.data.bytes[1] != 0x41)
return; //not anything we're interested in then
switch (frame.data.bytes[2])
{
case 5:
temperature = frame.data.bytes[3] - 40;
if (temperature!=lastTemp)
{
Serial.print("Coolant temperature (C): ");
Serial.println(temperature);
lastTemp=temperature;
}
break;
case 0xB:
psi = frame.data.bytes[3] * 0.145038; //kPA to PSI
psi = psi - 14.8;
//psi = psi * 100;
if (psi!=lastpsi)
{
Serial.print("Manifold abs pressure (psi): ");
Serial.println(psi);
lastpsi=psi;
}
break;
case 0xC:
RPM = ((frame.data.bytes[3] * 256) + frame.data.bytes[4]) / 4;
if (RPM!=lastRPM)
{
Serial.print("Engine RPM: ");
Serial.println(RPM);
sprintf(msg_buf, "%d", RPM);
lastRPM=RPM;
}
break;
case 0xD:
MPH = frame.data.bytes[3] * 0.621371;
if (MPH!=lastMPH)
{
Serial.print("Vehicle Speed (MPH): ");
Serial.println(MPH);
lastMPH=MPH;
}
break;
}
}
@weeblebiker
Copy link

the two above sketches pretty much cover almost everything between the two of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment