#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>
// Inisialisasi LCD dan RTC
LiquidCrystal_I2C lcd(0x27, 16, 2);
RTC_DS1307 rtc;
// Inisialisasi pin untuk flowmeter dan push button
const int flowmeterPin = 2; // Pin flowmeter
const int buttonPin = 3; // Pin push button
// Variabel untuk pengukuran flowmeter
volatile int pulseCount = 0;
float flowRate = 0;
float totalLiters = 0;
unsigned long oldTime = 0;
// Variabel untuk penyimpanan history
float history1 = 0;
float history2 = 0;
float history3 = 0;
// Variabel untuk tracking waktu
DateTime now;
int currentHistory = 1;
// Fungsi interrupt untuk menghitung pulsa flowmeter
void pulseCounter() {
pulseCount++;
}
void setup() {
// Setup LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Flowmeter");
// Setup RTC
if (!rtc.begin()) {
lcd.setCursor(0, 1);
lcd.print("RTC Gagal");
while (1);
}
if (!rtc.isrunning()) {
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
// Setup flowmeter
pinMode(flowmeterPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(flowmeterPin), pulseCounter, FALLING);
// Setup push button
pinMode(buttonPin, INPUT_PULLUP);
// Reset variabel waktu
oldTime = millis();
}
void loop() {
// Membaca waktu saat ini
now = rtc.now();
// Menghitung flowrate
if (millis() - oldTime > 1000) {
detachInterrupt(digitalPinToInterrupt(flowmeterPin));
float pulseRate = pulseCount;
pulseCount = 0;
flowRate = pulseRate / 7.5;
totalLiters += (flowRate / 60);
// Reset jika sudah 24 jam
if (now.hour() == 0 && now.minute() == 0 && now.second() == 0) {
totalLiters = 0;
history1 = 0;
history2 = 0;
history3 = 0;
}
// Simpan hasil ke history berdasarkan waktu
if (now.hour() >= 6 && now.hour() < 14) {
history1 = totalLiters;
} else if (now.hour() >= 14 && now.hour() < 22) {
history2 = totalLiters;
} else {
history3 = totalLiters;
}
// Tampilkan flowrate dan total liters
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Flow: ");
lcd.print(flowRate);
lcd.print(" L/min");
lcd.setCursor(0, 1);
lcd.print("Total: ");
lcd.print(totalLiters);
lcd.print(" L");
oldTime = millis();
attachInterrupt(digitalPinToInterrupt(flowmeterPin), pulseCounter, FALLING);
}
// Cek push button untuk menampilkan history
if (digitalRead(buttonPin) == LOW) {
delay(200); // Debouncing delay
currentHistory++;
if (currentHistory > 3) {
currentHistory = 1;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("History ");
lcd.print(currentHistory);
lcd.setCursor(0, 1);
if (currentHistory == 1) {
lcd.print(history1);
} else if (currentHistory == 2) {
lcd.print(history2);
} else {
lcd.print(history3);
}
lcd.print(" L");
delay(4000); // Delay to avoid bouncing effect
}
}