View Single Post
Old 01-05-2017, 06:25 PM   #1 (permalink)
t vago
MPGuino Supporter
t vago's Avatar
Join Date: Oct 2010
Location: Hungary
Posts: 1,807

iNXS - '10 Opel Zafira 111 Anniversary

Suzi - '02 Suzuki Swift GL
Thanks: 828
Thanked 708 Times in 456 Posts
t vago's MPGuino workspace thread, continued

This code is now being maintained on GitHub at tvago1972/MPGuino. It is too large to be attached to this post any more, even with maximum compression.

In the course of modifying the original MPGuino 0.86 code to incorporate the fuel injection correction factor for Chrysler vehicles with returnless fuel systems, I've been fiddling with the code, doing this and that and the other thing.

Since that other thread is really only meant for addressing that issue with Chrysler returnless fuel systems, it became increasingly apparent that a separate thread was needed to describe the other things I have done with the code. So, here it is. (All CPU workload figures assume a 20 MHz processor)

UPDATE: After a period of several years, I have dusted off this project and have performed an almost complete refactoring of my code, quashing many bugs in the process (and doubtlessly introducing different ones). Code readability has been addressed, and more comments have been added.

Known Issues (as of 18 March 2023):
  • On the AtMega2560 platform, MPGuino does not always wake up from deep sleep when the engine is started. MPGuino reacts correctly otherwise. Investigation on-going.
  • With the Adafruit RGB LCD module, there is no way to wake up MPGuino from a deep sleep by pressing the 5 input buttons - not without modifying the RGB LCD module itself. The Reset button can still be pressed to wake up MPGuino, if desired. MPGuino still wakes up normally if the engine is started or if it senses the vehicle starting to move.
  • AtMega2560 sometimes freezes up when attempting to upload MPGuino code to it. Issue is with buggy AtMega2560 bootloader, and reflashing the bootloader with Arduino IDE 1.0.4 or later will fix the issue. No workarounds within the MPGuino code itself.

Hardware Support added (as of 18 March 2023):
  • Support for the Adafruit RGB LCD module with 5-button input. (h/t meelis11)
  • Support for just about any generic 2x16 LCD module that uses a Two Wire Interface (TWI) interface. Tested with a SainSmart IIC/I2C/TWI 1602 Serial LCD Module Display.
  • Support for the Arduino Mega as a hardware platform. (via josemapiro)
  • Support for 5 different buttons via a single wire, while freeing up the TWI (Two-Wire Interface) pins for use for other functionality. (via nickdigger)
  • Support for the Parallax 5-position switch.
  • Support for the Parallax serial UART LCD module. (Minor changes had to be made to the spiffy big number font to enable it to work with the Parallax LCD module - these changes do not appear if the legacy MPGuino LCD display is used).
  • Chrysler returnless fuel injector correction factor, based off of intake manifold pressure. Utilizes existing manifold pressure (MAP) sensor built into the existing engine control system. An optional additional barometric sensor (in other words, a spare/extra MAP sensor), may be added to further increase accuracy.
  • Support for the TinkerKit! LCD hardware as a commercially-produced MPGuino module, with enhanced 5-button functionality (see above).

Implemented features undergoing testing (as of 18 March 2023):
  • Reduced-power sleep (via meelis11). Deep sleep mode implemented and appears to be working well on JBD board, AtMega2560, and TinkerKit! module. Still need to test on Meelis MPGuino (have to rig up a power circuit for it)

Program Features built into the base MPGuino code (as of 18 March 2023):
  • Low-level (bingo) fuel quantity added, which works in conjunction with total fuel quantity. Basically supports a "fuel low level warning", such as is found on later model cars with the fuel warning lamp.
    • A "reserve" fuel quantity is computed from entered total and bingo fuel quantity values. This value is defined as total - bingo.
      • If, for example, 18 gallons is defined for total and 3 gallons is defined for bingo, then a 15 gallon reserve is defined from these two values.
    • If consumed fuel quantity is less than this "reserve", then there will be a reserve fuel amount remaining calculated. Otherwise, reserve fuel quantity remaining will be 0. For instance,
      • Using the above example for total and bingo fuel, if 14 gallons of fuel is consumed, then there will be 4 gallons total remaining, 1 gallon reserve remaining, and 3 gallons bingo remaining.
      • However, if 17 gallons is then consumed, there will be 1 gallon total remaining, 0 gallons reserve remaining, and 1 gallon bingo remaining.
  • On-The-Fly support for Metric vs SAE (or Imperial) readouts. Metric/US functionality has been more tightly integrated into the display coding. Selected stored parameters and parameter labels also reflect the metric parameter setting.
  • Fuel economy can be displayed as either dist/quantity (MPG or L/K) or quantity/distance (L/100km or G/100mi).
  • Dedicated timeouts
    • EOC - if this timeout is reached, MPGuino will assume that Engine-Off Coasting is in progress, and will automatically display an EOC screen in place of whatever main screen was being displayed
    • Idle - if this timeout is reached, MPGuino will assume that the vehicle is parked with the engine running, and will automatically display an Idle screen in place of whatever main screen was being displayed
    • Park - if MPGuino detects both engine-off and vehicle stopped conditions, and this timeout is reached, MPGuino will assume that the vehicle is parked. If compiled in from the below listed optional compile-time features, MPGuino will also auto-save the Current and Tank trip readings
    • Button press - Independent of the above timeouts, but tracked
    • Activity timeout - if the all of the above timeouts have elapsed, MPGuino will then start an inactivity timeout. Once this inactivity timeout elapses, MPGuino will then either blank the screen or use one of the below described compiled-in options (system clock or deep sleep).
  • Menu display system that provides access to added features or to system stored parameters.
  • The settings interface has been enhanced to allow stepping back and forth between different stored parameters, without having to go through editing all of them in sequence. Separate screens have been defined for different setting groups.
    • Display settings - metric/SAE mode, output fuel economy in either qty/dist or dist/qty, LCD contrast, and other related settings
    • Fuel injector settings - number of cylinders, microseconds per gallon, and other related settings
    • Vehicle Speed sensor settings - VSS pulse/distance, VSS debounce, and other related settings
    • Tank Quantity settings - fuel tank quantity, bingo low-level fuel quantity, and other related settings
    • Timeout settings - Engine-off, vehicle stopped, park, button-press, and inactivity timeout settings
    • Miscellaneous settings - scratchpad (odo?) setting
  • Reduction of power consumption. MPGuino now consumes between 5 to 20 percent less power during normal operation.
  • 2-second temporary Status Line, with real-time updating of lower LCD data display.
  • Debounced buttons, with a "long-press" feature that effectively doubles the number of addressable button presses.
  • Button shortcuts are also possible. "Long-press" of the right button can now cause the main display to go directly to the next screen (like large Fuel Economy, FE vs. Time, FE vs. Speed, Large Distance to Empty, large Time To Empty, or System Clock)
  • Interface routines now take advantage of the above button enhancement to provide safeguards, such as requiring "long-press" button combinations to reset current and tank trip. Parameter editing has been enhanced with the addition of individual parameter reversion to initial settings, and the ability to cancel settings changes instead of saving them to EEPROM.
  • Leading spaces instead of zeros (of course).
  • Time values now show hhmmss, where they used to show
  • Inactivity timeout that shuts off LCD backlight when this timout is reached.
  • Ability to display the following calculations for Instant Trip, Current Trip, and Tank Trip.
    • Fuel Economy (MPG or L/K) - instant FE will swap over to fuel consumption rate when vehicle idles
    • Speed (MPH or kph)
    • Distance (miles or km)
    • Fuel Consumption Rate (gal/hr or L/hr)
    • Engine Speed (RPMs)
    • Engine Run Time (hhmmss)
    • Time spent moving (hhmmss)
    • Fuel Consumed (gallons or liters)
      • Total
      • Reserve (total - bingo)
      • Bingo
    • Fuel Remaining (gallons or liters)
      • Total
      • Reserve (total - bingo)
      • Bingo
    • Distance To Empty (miles or km)
      • Total
      • Reserve (total - bingo)
      • Bingo
    • Time To Empty (hhmmss)
      • Total
      • Reserve (total - bingo)
      • Bingo

Optional Compile-Tile Program Features added (as of 24 June 2023):
  • Spiffy Display Labels - Display labels have been changed to be more descriptive, a la OBDuino.
  • Vehicle Battery Voltage Display (via meelis11). Using a simple resistor bridge with an input protection diode, vehicle battery voltage can now be displayed.
  • Expansion Pin Support - User-definable support for two separate output pins, that can either drive LEDs (as described in the MPGuino Code Hacks), or be used as a variable voltage source for external gauges. Gauges can be programmed to show either remaining fuel quantity or fuel quantity used.
  • Idle/EOC Tracking - Tracks idle/EOC using separate Instant Idle/EOC Trip, Current Idle/EOC Trip, and Tank Idle/EOC Trip. Current and Tank Idle/EOC Trips are treated identically to Current and Tank Trip (auto-saved/auto-restored/auto-reset) with regard to the base MPGuino code and the other optional features here.
  • Deep Sleep Mode - Reduced-power sleep (via meelis11), which is entered once inactivity timeout has been reached. Not compatible with system clock function.
  • Software Clock - System clock, which is used as a "screen saver" once inactivity timeout has been reached. Not compatible with reduced-power sleep mode.
  • Editable Main Display pages - Each of the 9 or 12 main display pages may be edited to show any supported function.
  • Programmable Current Trip Auto-Reset - Ability to select current trip reset upon wakeup due to engine start and/or vehicle movement detection, if desired. This feature may also be turned off.
  • Trip Save - Saving of complete current trip or tank trip data. Current Trip and Tank Trip are auto-saved into EEPROM once park timeout has been reached. Current Trip and Tank Trip are auto-restored from EEPROM, if MPGuino is then switched off and switched back on at some later time.
  • Imperial Gallons - Support for Imperial gallons vs US gallons.
  • Spiffy large numbers have been added from the MPGuino Code Hacks wiki page.
  • Large Fuel Economy - Instant Trip Fuel Economy, Current Trip Fuel Economy, and Tank Trip Fuel Economy large number displays.
  • Large Distance-To-Empty - Instant Trip Distance-To-Empty, Current Trip Distance-To-Empty, and Tank Trip Distance-To-Empty large number displays.
  • Large Time-To-Empty - Instant Trip Time-To-Empty, Current Trip Time-To-Empty, and Tank Trip Time-To-Empty large number displays.
  • INST vs CURR, INST vs TANK - Displays a graphical status bar showing the relative comparison between Instant FE and one of either Tank FE or Current Trip FE.
    • If INST FE is equal to CURR/TANK FE, then the status bar will display 2/3s full
    • If INST FE is less than CURR/TANK FE, the status bar will be less than 2/3s full
    • If INST FE is greater than CURR/TANK FE, the status bar will be more than 2/3s full
    • If INST FE is at an overflow condition (EOC for MPG or KPL, IDLE for 100km/L or 100mi/G), then the status bar will show that, too.
  • Partial Refuel - For Partial Refuel, Tank Trip Reset has been replaced with a smaller sub-menu that allows temporary increases in Tank Size by a Partial Refuel amount. Each Partial Refuel amount is additive; the total Partial Refuel amount increases with each partial refuel value entered. It is also possible to reset just the Partial Refuel value by itself, or to reset the Tank Trip and Partial Refuel value together.
  • Easy Fuel Calibration - Eliminated requirement to know or look up microseconds/(gallons or liters) from somewhere on the web. Ability to calculate microseconds/(gallons or liters). # of injectors, reference injector flow rate in cc/min, reference fuel pressure for reference flow rate, and system fuel pressure are used to determine microseconds per unit volume figure. This figure can then be tweaked as necessary, as before.
  • Fuel Cost - Addition of below calculations for Instant Trip, Current Trip, Tank Trip (and Instant Idle/EOC Trip, Current EOC/Trip, Tank Idle/EOC Trip). Fuel Cost per (gallon or liter) is a stored parameter accessible through the Settings screen.
    • Fuel Consumed Cost
    • Remaining Fuel Cost
    • Fuel Cost per distance (money/mile or money/km) - example 0.12 dollars per mile
    • Distance per Fuel Cost (mile/money or km/money) - example 8.33 miles per dollar
    • Fuel Cost per hour (money/hr)
  • Tank and Current trip save/load menu now adds shortcuts to their respective pages for easy pen-and-paper logging.
  • CPU Monitoring - "Long-press" of the center button briefly (~2 seconds) shows the CPU loading for that page. System display mode added which shows CPU loading, time since power-up, and free RAM
  • Fuel Economy vs. Time - Bar graph for fuel economy vs. time. Bar graph for differential fuel economy vs. time (a la ScanGauge E)
  • Fuel Economy vs. Speed - Bar graphs for fuel economy vs. speed, total (tank) time travelled vs. speed, total (tank) distance travelled vs. speed, and total (tank) fuel used vs. speed. Bar graphs are plotted graphically on-the-fly, vs. using a clunky custom font. 15 elements are supported. FE vs. time and dFE vs. time periods are selectable via a single EEPROM parameter. FE vs. speed, fuel rate vs. speed, distance traveled vs. speed, and time spent travelling vs. speed have two EEPROM parameters (lower speed cutoff which is set at a default of 25 MPH, and speed bar length which is set at a default of 5 MPH).
  • JSON Output Logging - JSON output capability to show a more capable output screen via Raspberry PI or similar (via skybolt). Sample output looks like this:

    Not compatible with serial data logging on Legacy MPGuino hardware.
  • Serial Data Logging - MPGuino spits out 5 parameters to the serial output port while active, 2 times a second. A user-programmable stored parameter allows enabling or disabling of serial data logging. Not compatible with JSON output logging on Legacy MPGuino hardware.

Technical Features added (as of 24 June 2023):
  • Code is now more tightly integrated into the avr compile toolchain, including that used with the Arduino IDE.
  • A true input signal simulator can be compiled into MPGuino, enabling robust testing of input VSS/fuel injector display routines.
  • A serial debugging monitor terminal allows real-time monitoring and changing of trip variables, EEPROM parameters, volatile and main program registers. Button presses can be injected.
    Here is a summary list of what the debug monitor is capable of:
        [y].[x]P - list stored parameters, optionally between [y] and [x]
        [y].[x]V - list volatile variables, optionally between [y] and [x]
        [y].[x]M - list main program variables, optionally between [y] and [x]
        [y].[x]T - list terminal trip variable values, optionally between [y] and [x]
        [y].[x]O - list program constants, optionally between [y] and [x]
    [z]<[y].[x]L - list terminal trip variable function outputs, optionally between [y] and [x]
                    [z] - decimal window length (optional)
    [z]<[y].[x]U - list decimal number sample for output
                    [z] - decimal window length (optional)
                    [y] - decimal digit count (optional)
                    [x] - decimal processing flag (optional)
       [z]<[y].x - enters a number x into the 64-bit math accumulator
                    [z] - decimal window length (optional)
                    [y] - decimal digit count (optional)
              +x - adds x to math accumulator
              -x - subtracts x from math accumulator
              *x - multiplies math accumulator by x
              |  - finds square root of math accumulator
              /x - divides math accumulator by x
              =x - enters a number x into the 64-bit math accumulator
      x:Py [y] [y]... - store one or more y values, starting at stored parameter x
      x:Vy [y] [y]... - store one or more y values, starting at volatile variable x
      x:My [y] [y]... - store one or more y values, starting at main program variable x
      x:Ty [y] [y]... - store one or more y values, starting at terminal trip variable x
        [y]<[x]R - read trip variable x into trip variable y
                    default for x and y is terminal trip variable
                    if no x or y specified, lists available trip variables
               I - inject button press
                    short (l, c, r, u, d)
                     long (L, C, R, U, D)
               ? - displays this help
  • Selected SWEET64 routines can be traced as they execute, showing how various registers change values during routine execution.
  • MPGuino now consumes less power to operate, taking advantage of the built-in ability to turn on/off various hardware modules within the AVR chip that MPGuino runs on.
  • Interrupts for injector capture and VSS capture have been optimized for speed. This code can now easily handle VSS pulse-trains that come from an ABS wheel speed sensor, which typically outputs pulses at 10 times the frequency of ordinary vehicle speed sensors.
  • Fuel injector pulse measurement has been made more robust. Two separate rationality checks have been added.
  • The acceleration test (drag race) function operates completely independently of the display routines.
  • The primary tick timer that drives button and VSS debouncing, fuel injector monitoring, and various activity timeout functions, has been moved from timer2 to timer0. This enables MPGuino to run on platforms using the AtMega32U4 processor.
  • Interrupt driven, buffered LCD character output. The LCD buffer is processed through a secondary timer, which now causes LCD character processing to be transparent to the display update loop.
  • Interrupt driven, buffered serial character output. Serial output is now transparent to the display update loop. Serial output can be enabled or disabled via a dedicated parameter, if desired.
  • Interface coding has been re-written so that any display mode (primary display, clock set, settings edit, parameter edit, or trip save/retrieval) will reliably allow fuel readings to be collected and updated, and JSON/serial logging data to be output (if selected), regardless of mode. The various activity timeout functions also work, regardless of mode.
  • Parameters can now have variable byte length, whereas before they were all 32-bit numbers. Parameters may be sized from 1 bit to 32 bits in length. The parameter entry/editing routine enforces this specified length. The EEPROM routines have been modified to read and write these variable length parameters along byte boundaries.
  • Display routines were re-written to separate low-level LCD hardware support from higher-level character output. A common text streaming module handles string and character output, and can output to multiple output devices. This should make it easier to modify the code to support alternate display devices.
  • A TWI interface library was added, based off the twi.c library for Arduino. MPGuino is configured as a TWI master device. The TWI interface plays nicely with the rest of the MPGuino interrupt infrastructure, and allows for TWI input button pressing and output interfacing in a manner transparent to the main loop.

Technical 64-bit math specific features added (as of 24 June 2023):
  • 64-bit math routines are all written in bytecode that is interpreted by a 64-bit pseudoprocessor that I've named SWEET64. All of the 64-bit math routines have been shrunk by about 70%, compared to the original code.
  • Engine-off stationary vehicle CPU workload per display update loop is now between 1.15% and 11.3%. Simulated engine speeds of 12000 RPM and simulated vehicle speeds of 250 MPH give a CPU workload of around 60%.
  • Portions of the SWEET64 64-bit pseudoprocessor have been re-written in assembly language, to speed up 64-bit multiply, divide, shift, add, and condition test operations. Minor portions of the rest of the code have also been re-written in assembly language.
  • 64-bit mutiplication and division routines have been re-written to gain speed, which is about an 80% improvement for mult64, and a 98% improvement for div64.
  • Time-to-empty, distance-to-empty, and idle-time-to-empty values have been added. Engine speed (RPM) value has also been added. Time-to-Empty is accurate to the second, and Distance-to-Empty is accurate to 1/10th of a mile/kilometer.
  • The decimal number output function now uses SWEET64 to perform conversions from 64-bit numbers into strings. The function can output 0 through 3 decimal places (dependent on the value to be output). Output values can be of up to 9999999999, can be constrained to any window size between 2 and 10 characters, and properly handles decimal rounding.

    Example debug monitor "display decimal output" command for a window size of 10 with 3 decimal places:
    00: 00 0A 03
        0000000000000005 -      0.005 -
    01: 0000000000000037 -      0.055 -
    02: 000000000000022B -      0.555 -
    03: 00000000000015B3 -      5.555 -
    04: 000000000000D903 -     55.555 -
    05: 0000000000087A23 -    555.555 -
    06: 000000000054C563 -   5555.555 -
    07: 00000000034FB5E3 -  55555.555 -
    08: 00000000211D1AE3 - 555555.555 -
    09: 000000014B230CE3 - 5555555.56 -
    0A: 0000000CEF5E80E3 - 55555555.6 -
    0B: 0000008159B108E3 -  555555556 -
    0C: 0000050D80EA58E3 - 5555555556 -
    0D: 00003287092778E3 - ---------- -

Features in progress (as of 24 June 2023):
  • Add support for abbalooga's MPGuino Colour Touch.
  • Add support for calculating that microseconds per gallon feature from performing just two fill-ups. The idea is to drive normally for two tanks of fuel, top off the tank for these two tanks, and enter the amount of fuel for these two top-offs. MPGuino will then calculate the microseconds per gallon and the fuel injector open delay time from this data.
  • Drag Race Mode - (via meelis11), Enables recording 0-30 MPH, 0-60 MPH, and 1/4 mile time. Also records fuel consumption and distance travelled. This feature is slowly being refactored.
  • Coastdown variable determination. Underlying data capture mechanism in place, which is slowly being refactored. Currently working on adding matrix math support into SWEET64.
  • Add USB support to AtMega32U4 devices.
  • Add alert displays for up to 4 different programmable monitored variables. Currently modifying display code to support this feature.

Features to be added (as of 18 March 2023):
  • Matrix math capability.
  • Addition of SPI communications.
  • Replacement of 2x16 LCD display with TFT or other graphics
  • Easy method for performing VSS and fuel calibration
  • Addition of RTC support
  • System date setting, in conjunction with system time. Possibly limited just to adding day of week.
  • A-B comparison mode for saved trip/tank data, based off of fuel rate vs. speed graphs.
  • ?

This code is meant to be downloaded from GitHub, and compiled with the Arduino IDE. Currently using IDE 1.8.9.

If you use the AVR command-line tools, use these settings for setting the programmable fuses to ensure that your MPGuino will work:
Originally Posted by Ettore_M View Post
lfuse:0xf7 hfuse:0xd9 efuse:0x07
This code is now being maintained on GitHub at tvago1972/MPGuino. It is too large to be attached to this post any more, even with maximum compression.

Last edited by t vago; 06-24-2023 at 05:20 AM.. Reason: dust off thread and restart development
  Reply With Quote
The Following 10 Users Say Thank You to t vago For This Useful Post:
alvin_wj (04-30-2017), California98Civic (05-15-2017), CMOLIVEIRA (05-03-2017), ecoTex (04-23-2021), Felar (02-17-2017), josemapiro (01-06-2017), Lomotor (04-24-2017), MetroMPG (02-23-2017), skyking (01-08-2017), tf4624 (03-27-2024)