#define on HIGH
#define off LOW
#define ledTimeout 16
#define ledFlow 17
#define pinOutput 2
#define switchMain 5
#define switchFlow 4
#define modePowerTunggal false
int tWait = 20 * 1000;
bool timeOut = false, pumpState = false;
unsigned long lastMil = 0, difMil;
void setup()
{
Serial.begin(115200);
pinMode(ledTimeout, OUTPUT);
pinMode(pinOutput, OUTPUT);
pinMode(ledFlow, OUTPUT);
pinMode(switchMain, INPUT_PULLUP);
pinMode(switchFlow, INPUT_PULLUP);
Serial.println("Auto turn off pump if water source is empty (no water flow)");
delay(1000);
digitalWrite(ledTimeout, off);
if (modePowerTunggal)
{
delay(2000);
digitalWrite(pinOutput, on);
digitalWrite(ledTimeout, on);
pumpState = true;
timeOut = false;
Serial.println("pump on");
}
}
void loop()
{
if (modePowerTunggal == false)
{
if (digitalRead(switchMain) == LOW && pumpState == false)
{
// turn on pump / connect power
delay(500);
digitalWrite(pinOutput, on);
digitalWrite(ledTimeout, on);
digitalWrite(ledFlow, off);
pumpState = true;
timeOut = false;
lastMil = millis();
Serial.println("pump on");
}
else if (digitalRead(switchMain) && pumpState == true)
{
delay(100);
digitalWrite(pinOutput, off);
digitalWrite(ledTimeout, off);
digitalWrite(ledFlow, off);
pumpState = false;
Serial.println("pump off");
}
}
if (pumpState && timeOut == false)
{
// read water flow switch. if no flow
if (digitalRead(switchFlow) == true)
{
// if no flow until 1 minute
difMil = millis() - lastMil;
digitalWrite(ledFlow, LOW);
// Serial.print("timer second ");
// Serial.println(difMil / 1000);
if (difMil > tWait)
{
// turn off pump / disconnect power
digitalWrite(pinOutput, off);
// digitalWrite(ledTimeout, on);
timeOut = true;
// pumpState = false;
Serial.println("no water flow. pump turn off for safety");
// give notification no water from source
}
}
else
{
lastMil = millis();
digitalWrite(ledFlow, HIGH);
delay(100);
}
}
// delay(1000);
if (timeOut)
{
blinkLed();
}
}
unsigned long prevMillis = 0;
bool ledState = LOW;
void blinkLed()
{
unsigned long currMillis = millis();
if (currMillis - prevMillis >= 600)
{
// if the LED is off turn it on and vice-versa:
ledState = (ledState == LOW) ? HIGH : LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledTimeout, ledState);
// save the last time you blinked the LED
prevMillis = currMillis;
}
}
/*
pump on -> get water flow ? 0 -> wait 1 minute -> get water flow ? 0 -> turn off pump
*/