byte sensorInterrupt = 0; byte statusLed = 13; byte sensorPin = 2; const int threshold = 15000; // threshold float calibrationFactor = 4.5; volatile byte pulseCount; float flowRate; unsigned int flowMilliLitres; unsigned long totalMilliLitres; unsigned long oldTime; unsigned int countstart = 0; unsigned long starttime; unsigned long endtime; unsigned long elapsedtime; void setup() { Serial.begin(9600); pinMode(statusLed, OUTPUT); digitalWrite(statusLed, HIGH); // We have an active-low LED attached pinMode(sensorPin, INPUT); digitalWrite(sensorPin, HIGH); pinMode(7, OUTPUT);// connected to relay pulseCount = 0; flowRate = 0.0; flowMilliLitres = 0; totalMilliLitres = 0; oldTime = 0; attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } void loop() { while (1){ if((millis() - oldTime) > 1000) // Only process counters once per second { detachInterrupt(sensorInterrupt); flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor; oldTime = millis(); flowMilliLitres = (flowRate / 60) * 1000; totalMilliLitres += flowMilliLitres; unsigned int frac; Serial.print("Flow rate: "); Serial.print(int(flowRate)); // Print the integer part of the variable Serial.print("L/min"); Serial.print("\t"); // Print tab space Serial.print("Output Liquid Quantity: "); Serial.print(totalMilliLitres); Serial.println("mL"); Serial.print("\t"); // Print tab space Serial.print(totalMilliLitres/1000); Serial.print("L"); pulseCount = 0; attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } if( totalMilliLitres > 0 && countstart == 0) { starttime = millis(); countstart = 1; } if ( totalMilliLitres > 0 ) { endtime = millis(); elapsedtime = endtime - starttime; } if (elapsedtime >= threshold){ digitalWrite(7,HIGH); // Activate relay to turn on motor delay(10000); digitalWrite(7,LOW); // Deactivate relay to turn on motor totalMilliLitres = 0; countstart = 0; elapsedtime = 0; break; } else{ digitalWrite(statusLed, LOW); // Turn the LED off digitalWrite(7, LOW);// turn relay OFF } } } void pulseCounter() { // Increment the pulse counter pulseCount++; }