/*
Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

Measure the liquid/water flow rate using this code. 
Connect Vcc and Gnd of sensor to arduino, and the 
signal line to arduino digital pin 2.
 
 */


#include <TM1637Display.h>

byte statusLed    = 11;

#define CLK 5
#define DIO 4

// Initialize TM1637 display object
TM1637Display display(CLK, DIO);

// Interval for updating display (milliseconds)
const unsigned long DISPLAY_UPDATE_INTERVAL = 1000; // Update every second

//Water flow sensor pins 
byte sensorInterruptA = 0;  // 0 = digital pin 2
byte sensorInterruptB = 1; 
byte sensorPinA       = 2;
byte sensorPinB       = 3;


// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;
volatile byte pulseCount;  

float flowRate;
float thresholdFlowRate = 2; // flow rate limit 
unsigned long oldTime;

void setup()
{
  
  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);
   
  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  display.setBrightness(7); // Set brightness level (0 to 7)

  pinMode(sensorPinA, INPUT);
  pinMode(sensorPinB, INPUT);
  digitalWrite(sensorPinA, HIGH);
  digitalWrite(sensorPinB, HIGH);

  pulseCount        = 0;
  flowRate          = 0.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(sensorInterruptA, pulseCounter, FALLING);
  attachInterrupt(sensorInterruptB, pulseCounter, FALLING);
}

/**
 * Main program loop
 */
void loop()
{
   
   if((millis() - oldTime) > 1000)    // Only process counters once per second
  { 
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterruptA);
    detachInterrupt(sensorInterruptB);
        
    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    
    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

 
    unsigned int frac;
    
    // Print the flow rate for this second in litres / minute
    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


    // Display flow rate on all 4 digits
    int flowRateInt=int(flowRate);
    display.showNumberDec(flowRateInt, true);

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;
    
    // Enable the interrupt again now that we've finished sending output
      attachInterrupt(sensorInterruptA, pulseCounter, FALLING);
      attachInterrupt(sensorInterruptB, pulseCounter, FALLING);

      if (flowRate > thresholdFlowRate) {
      digitalWrite(statusLed, HIGH); // Turn on buzzer
      delay(500); // Buzzer on for 500ms
      digitalWrite(statusLed, LOW);  // Turn off buzzer
    }

    
  }
}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}