byte statusLed =13; byte sensorInterrupt = 0; // 0 = digital pin 2 byte sensorPin = 2; byte buttonPin = 12; long capacity = 10000; // enter capacity in milliliters // The hall-effect flow sensor outputs approximately 4.5 pulses per second per // litre/minute of flow. float calibrationFactor = 61.164; volatile byte pulseCount; float flowRate; unsigned int flowMilliLitres; unsigned long totalMilliLitres; unsigned long oldTime; void setup() { Serial.begin(115200); pinMode(sensorPin, INPUT); pinMode(buttonPin, INPUT); pinMode(statusLed, OUTPUT); digitalWrite(buttonPin, HIGH); digitalWrite(statusLed, LOW); digitalWrite(sensorPin, HIGH); pulseCount = 0; flowRate = 0.0; flowMilliLitres = 0; totalMilliLitres = 0; oldTime = 0; // The Hall-effect sensor is connected to pin 2 which uses interrupt 0. // Configured to trigger on a FALLING state change (transition from HIGH // state to LOW state) attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } void loop() { if (digitalRead(12)==LOW){ digitalWrite(statusLed,HIGH); //indicated motor is on while(capacity>totalMilliLitres){ if((millis() - oldTime) > 100) // Only process counters once per 0.1 second { // Disable the interrupt while calculating flow rate and sending the value to // the host detachInterrupt(sensorInterrupt); flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor; oldTime = millis(); flowMilliLitres = (flowRate / 60) * 1000; totalMilliLitres += flowMilliLitres; unsigned int frac; Serial.print(" Output Liquid Quantity: "); // Output separator Serial.print(totalMilliLitres); Serial.println("mL"); pulseCount = 0; // Enable the interrupt again now that we've finished sending output attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } } digitalWrite(statusLed,LOW); } } /* Insterrupt Service Routine */ void pulseCounter() { // Increment the pulse counter pulseCount++; }