Hello all, First post here.
I am building a digital dashboard for my car project. I am using a Teensy4.0 to read in CAN Bus signals and send them to a Nextion Display.
I have run into a small issue when calculating fuel consumption MPG etc..
I have one loop that reads the CAN bus. If CAN ID is = 1559 It finds the Fuel Tank Level in L converts to Gallons and keeps it as a 3 place Int. For example int 123 displays on screen as a float of 12.3 Gal. Then if CAN ID is =720 it Calculates instant MPG using Speed and Fuel consumption in gal per hour.
I am using the moving avg library https://github.com/JChristensen/movingAvg
First issue how can I get the GalA integer from the first IF statement down into the second IF statement. I use GalA (Fuel Tank Gallons) * Avg MPG to calculate Range in the bottom of the second loop.
Second, in the Second IF statement I only want to add instant MPG values to the rolling Avg if the speed if over 5Mph. This code works as long as the vehicle is going 5Mpg. When slower it doesn't print an Avg Mpg value.
CAN_message_t msg;
movingAvg FuelAvg(1000);
movingAvg GalAvg(1000);
void setup(void) {
can1.begin();
can1.setBaudRate(500000);
Serial1.begin(38400);
FuelAvg.begin();
GalAvg.begin();
}
void loop() {
if ( can1.read(msg) ) {
//-------FUEL CAPACITY (GAL)-------------------------------------------------------------------------------------------------------
if(msg.id == 1559){ //If Can ID 617 Hex Fuel Tank
Gal = (msg.buf[4] << 8) | msg.buf[5]; //Combine Bytes 4,5
Gal = Gal*0.264172; //Converstion to from L to G (Still X10)
int GalA = GalAvg.reading(Gal); //Creates Array GalAvg of 100 Gal and returns avg GalA
Serial1.print("Gal.val="); //Print to Display (float) Var Gal*10 to Gal.val
Serial1.print(GalA);
Serial1.write(0xff);
Serial1.write(0xff);
Serial1.write(0xff);
}
//-------FUEL USE (MPG)-------------------------------------------------------------------------------------------------------
if(msg.id == 720){ //If Can ID 2D0 Hex Fuel Use
FuelUse = (msg.buf[0] << 8) | msg.buf[1]; //Combine Bytes Fuel Use MicroL per Sec
Mpgi = (Speed*1100)/FuelUse; //Conversion to Instant MPG
Mpgis = Mpgi*10; //Conversion *10 to Display as Float
Serial1.print("Mpgi.val="); //Print to Display Var Mpgis*10
Serial1.print(Mpgis);
Serial1.write(0xff);
Serial1.write(0xff);
Serial1.write(0xff);
if (SpeedOut > 5){ //If Speed > 5Mph Add Mpg instant to rolling avg
int Mpga = FuelAvg.reading(Mpgis); //Creates Array FuelAvg of 100 Mpgis returns avg Mpga
Serial1.print("Mpga.val=");
Serial1.print(Mpga);
Serial1.write(0xff);
Serial1.write(0xff);
Serial1.write(0xff);
Range = Mpga * (GalA/10); //Range = Avg Mpg * Fuel Gal
Serial1.print("Range.val=");
Serial1.print(Range);
Serial1.write(0xff);
Serial1.write(0xff);
Serial1.write(0xff);
}
}
}