// Add the Liquid Crystal I2C library
#include <LiquidCrystal_I2C.h>
// Add the lcd
LiquidCrystal_I2C lcd(0x27, 16, 2);
volatile int NumPulses; //variable for the number of pulses received
int PinSensor = 3; //Sensor connected to pin 2
float factor_conversion=7.11; //to convert from frequency to flow rate
float volume=0;
long dt=0; //time variation for each loop
long t0=0; //millis() from the previous loop
//---Function executed on interrupt----
void CountPulse ()
{
NumPulses++; //increment the pulse variable
}
//---Function to obtain pulse frequency----------
int ObtenerNumPulses()
{
int frequency;
NumPulses = 0; //We set the number of pulses to 0
interrupts(); //Enable interrupts
delay(1000); //sample 1 second
noInterrupts(); // Disable interrupts
frequency=NumPulses;//Hz(pulses per second)
return frequency;
}
void setup()
{
Serial.begin(9600);
pinMode(PinSensor, INPUT);
attachInterrupt(1,CountPulse,RISING);//(Interrupt 0(Pin2),function,Rising Edge)
Serial.println ("Send 'S' to reset volume to 0 Liters");
t0=millis();
// Initalise the LCD
lcd.init();
// Turn on the LCD backlight
lcd.backlight();
// Put text on the LCD
//lcd.print("Hello World!");
}
void loop ()
{
if (Serial.available()) {
if(Serial.read()=='S')volume=0;//reset the volume if we receive 'r'
}
float frequency=ObtenerNumPulses(); // get the frequency of the pulses in Hz
float flow_L_m=frequency/factor_conversion; //calculate the flow in L/m
dt=millis()-t0; ////calculate the time variation
t0=millis();
volume=volume+(flow_L_m/60)*(dt/1000); // volume(L)=flow(L/s)*time(s)
//-----Send through the serial port---------------
Serial.print ("flow: ");
Serial.print (flow_L_m,3);
Serial.print ("L/min\tvolume: ");
Serial.print (volume,3);
Serial.println ("L");
//lcd.setCursor(0,1);
//lcd.print(volume);
}