Issue with LCD Display of Time on Timer

you should use millis() to manage the time . For extra information and examples look at

you might benefit from studying state machines. Here is a small introduction to the topic: Yet another Finite State Machine introduction

I'd suggest you use one of the numerous button libraries such as Button in easyRun or OneButton or Toggle or EasyButton or Bounce2, ... to manage the float switch.

with all this, your code could become something like this (using Toggle to handle the float switch)

click to see the code
#include "Wire.h"               // Library for I2C communication
#include "LiquidCrystal_I2C.h"  // Library for LCD
#include <Toggle.h>  // https://github.com/Dlloydev/Toggle for handling buttons

LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4);  // Change to (0x27,20,4) for 20x4 LCD.
const byte floatSwitchPin = 7; //which pin the float switch is connected to
Toggle floatSwitch;

unsigned long onTime = 0; // in ms
unsigned long startTime = 0; // in ms

enum {PUMP_OFF, PUMP_ON} pumpState = PUMP_OFF;

void printTime(unsigned long t) {
  unsigned long h = t / 3600ul;
  unsigned long m = (t % 3600ul) / 60ul;
  unsigned long s = (t % 3600ul) % 60ul;
  if (h < 10) lcd.write('0');
  lcd.print(h);
  lcd.write(':');
  if (m < 10) lcd.write('0');
  lcd.print(m);
  lcd.write(':');
  if (s < 10) lcd.write('0');
  lcd.print(s);
}

void show() {
  lcd.setCursor(0, 1);
  printTime(onTime / 1000ul);

  lcd.setCursor(12, 1);
  if (pumpState == PUMP_OFF) printTime(0);
  else  printTime((millis() - startTime) / 1000ul);// get rid of the ms
}

void setup() {
  floatSwitch.begin(floatSwitchPin);
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("CUMULATED   ONGOING");
}

void loop() {
  show();
  floatSwitch.poll();
  switch (pumpState) {
    case PUMP_OFF: // check if the float switch is activated
      if (floatSwitch.onPress()) {
        startTime = millis();
        pumpState = PUMP_ON;
      }
      break;

    case PUMP_ON:
      if (floatSwitch.onRelease()) {
        onTime += (millis() - startTime);
        startTime = 0;
        pumpState = PUMP_OFF;
      }
      break;
  }
}


I did not include the 10th of the seconds, left as an exercise for you.

1 Like