#include <Arduino.h>
#define FLOW_POT_PIN 34
#define TRIG_PIN 5
#define ECHO_PIN 18
#define LED_PIN 2
const float TANK_AREA_M2 = 0.5;
const float ADC_MAX = 4095.0;
const float VREF = 3.3;
const float MAX_FLOW_LPM = 30.0;
unsigned long lastMillis = 0;
float accumulatedVolumeL = 0.0;
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
lastMillis = millis();
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (duration == 0) return -1.0;
return (duration * 0.0343) / 2.0;
}
float readFlowLPerMin() {
int raw = analogRead(FLOW_POT_PIN);
float v = (raw / ADC_MAX) * VREF;
return (v / VREF) * MAX_FLOW_LPM;
}
void loop() {
unsigned long now = millis();
float dt = (now - lastMillis) / 1000.0;
if (dt <= 0) dt = 0.001;
lastMillis = now;
float flowLpm = readFlowLPerMin();
float flowLps = flowLpm / 60.0;
accumulatedVolumeL += flowLps * dt;
float distCM = readDistanceCM();
float heightM = 0.0, tankVolumeL = 0.0;
if (distCM > 0) {
float sensorToBottomM = 2.00;
float distM = distCM / 100.0;
heightM = sensorToBottomM - distM;
if (heightM < 0) heightM = 0;
tankVolumeL = heightM * TANK_AREA_M2 * 1000.0;
}
bool lowVolume = (tankVolumeL > 0) ? (tankVolumeL < 20.0) : false;
digitalWrite(LED_PIN, lowVolume ? HIGH : LOW);
Serial.print("Flow (L/min): "); Serial.print(flowLpm, 2);
Serial.print(" | Volume Total (L): "); Serial.print(accumulatedVolumeL, 2);
Serial.print(" | Tinggi Air (m): "); Serial.print(heightM, 3);
Serial.print(" | Volume Tangki (L): "); Serial.println(tankVolumeL, 2);
delay(500);
}