Huh...
I am jumbling up things
#include <EEPROM.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 9, 8);
int rstState = 0;
int Trip;
const int odometerPin = 3;
const int odometerInterrupt = 1;
const int odometerEepromLocation = 0; // address of the first of 4 bytes in which the total wheel revs is stored
const int powerPin = A0; // analog pin used to sense impending loss of power
const float wheelCircumference = 0.002035; // wheel circumference in km
const int minPowerOkReading = 700; // minimum reading on the power sense analog input that indicates good power
const int minPowerRestoredReading = 750; // minimum reading on the power sense analog input that indicates we have powered back up
volatile unsigned long wheelRevs; // total wheel revolutions counted, will overflow after 85 million km
unsigned long lastDisplayedMs = 0UL; // time when we last refreshed the display
unsigned long readEepromLong(unsigned int address)
{
unsigned long ret = 0UL;
for (int i = address + 3; i >= address; --i)
{
ret <<= 8;
ret |= (unsigned long)EEPROM.read(i);
}
return(ret);
}
void writeEepromLong(unsigned int address, unsigned long val)
{
for (int i = odometerEepromLocation; i < odometerEepromLocation + 4; ++i)
{
EEPROM.write(i, (unsigned char)val);
val >>= 8;
}
}
void setup()
{
lcd.begin(16,2);
// Initialise wheel revs from value stored in EEPROM
wheelRevs = readEepromLong(odometerEepromLocation);
if (wheelRevs == 0xFFFFFFFFUL)
{
// must be the first time we have run
wheelRevs = 0UL;
}
// Set up the odometer sensor pin and interrupt
pinMode(odometerPin, INPUT);
attachInterrupt(odometerInterrupt, odometerIsr, RISING);
}
void odometerIsr()
{
++wheelRevs;
}
void loop()
{
// Capture the wheel revs with interrupts disabled in case it changes while we read it
noInterrupts();
unsigned long savedWheelRevs = wheelRevs;
interrupts();
if (analogRead(powerPin) < minPowerOkReading)
{
// Looks like power is going down, so write wheel revs to EEPROM (takes 13.2ms to write 4 bytes)
writeEepromLong(odometerEepromLocation, savedWheelRevs);
// Wait until either we die or the power comes back up
while (analogRead(powerPin) < minPowerRestoredReading)
{
delay(200);
}
}
else
{
unsigned long now = millis();
if (now - lastDisplayedMs >= 200) // update display every 200ms
{
lastDisplayedMs = now;
float km = wheelCircumference * savedWheelRevs;
lcd.setCursor(0, 0);
lcd.print(km, 1);
lcd.print("Km");
}
delay(5); // repeat after 5ms so that we check for power down often enough
}
if (rstState == HIGH){
writeEepromLong(TripMeterEepromLocation, wheelRevs);
}
Trip = (savedWheelRevs - readEepromLong(TripMeterEepromLocation)) * wheelCircumference;
}