//ok
//edit 8 11 2024
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // Alamat I2C dan ukuran layar LCD

byte indikator = 13;

byte sensorInt = 0; 
byte flowsensor = 2;

float konstanta = 4.5; //konstanta flow meter

volatile byte pulseCount;

float debit;
unsigned int flowmlt;
unsigned long totalmlt;

unsigned long oldTime;

void setup()
{
  lcd.init();           // Inisialisasi LCD
  lcd.backlight();      // Nyalakan backlight.

  pinMode(flowsensor, INPUT);
  digitalWrite(flowsensor, HIGH);

  pulseCount = 0;
  debit = 0.0;
  flowmlt = 0;
  totalmlt = 0;
  oldTime = 0;
  attachInterrupt(sensorInt, pulseCounter, FALLING);
}

void loop()
{
  if((millis() - oldTime) > 1000) 
  { 
    detachInterrupt(sensorInt);
    debit = ((1000.0 / (millis() - oldTime)) * pulseCount) / konstanta;
    oldTime = millis();
    flowmlt = (debit / 60) * 1000;
    totalmlt += flowmlt;

    unsigned int frac;

    lcd.print("Flow  =");
    lcd.setCursor(8,0);
    lcd.print(debit,2);
    lcd.setCursor(13,0);
    lcd.print("L/min");

    lcd.setCursor(0, 1);
    lcd.print("Volume=");
    lcd.setCursor(8,1);
    lcd.print(totalmlt);
    lcd.setCursor(13,1);
    lcd.print("mL");

    pulseCount = 0;
    attachInterrupt(sensorInt, pulseCounter, FALLING);
   }
}

void pulseCounter()
{
  pulseCount++;
}