I wrote this code, but it is not working..
#include <EEPROM.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 9, 8);
const int rstPin = 7;
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.5; //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
void setup()
{
lcd.begin(16,2);
// Initialise wheel revs from value stored in EEPROM
wheelRevs = 0UL;
for (int i = odometerEepromLocation + 3; i >= odometerEepromLocation; --i)
{
wheelRevs <<= 8;
wheelRevs |= (unsigned long)EEPROM.read(i);
}
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, FALLING);
}
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)
for (int i = odometerEepromLocation; i < odometerEepromLocation + 4; ++i)
{
EEPROM.write(i, (unsigned char)savedWheelRevs);
savedWheelRevs >>= 8;
}
// 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
}
rstState = digitalRead(rstPin);
if (rstState == HIGH){
EEPROM.write(9, wheelRevs);
}
Trip = (savedWheelRevs - EEPROM.read (9)) * wheelCircumference;
lcd.setCursor(0, 1);
lcd.print (Trip, 1);
lcd.print(" ");
}