fiddled a bit with your code:
- use #define for those vars that are not changeable
- made 2 different IRQ's one for counting the IN pulses and one for counting the out pulses
- changed some var names to reflect what they meant like litersperminute
- use a copy of millis() in the if block as millis() might change during the block (accuracy)
- probably screwed up the math but you should be able to fix that relative easily
- made some vars local instead of global (reduce scope)
have a look and give it a try (not tested as I don't have an I2CLCD nearby ![]()
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16, 2);
// as these are const one better use #defines
#define IRQ_A 0
#define IRQ_B 1
#define PIN_A 2
#define PIN_B 3
// a separate counter per channel
volatile unsigned long countIN = 0;
volatile unsigned long countOUT = 0;
unsigned long oldTime = 0;
void setup()
{
lcd.begin(16, 2);
Serial.begin(9600);
pinMode(PIN_A, INPUT);
pinMode(PIN_B, INPUT);
digitalWrite(PIN_A, HIGH);
digitalWrite(PIN_B, HIGH);
attachInterrupt(IRQ_A, CounterIN, FALLING);
attachInterrupt(IRQ_B, CounterOUT, FALLING);
}
void loop()
{
// use a var for value of millis, as it might change in the if .... block
// due to slow serial prints
unsigned long now = millis();
if((now - oldTime > 1000))
{
unsigned long duration = now - oldTime;
oldTime = now;
// use names that indicate the unit!
// don't know if all math is correct anymore
// 8500 pulses per liter?
float liters = (countIN - countOUT) * 0.000117647; // faster than divide by 8500.0
float litersPerMinute = (1000 * liters)/duration / 60; // optimized 16.66667*liters/duration
Serial.print(duration);
Serial.print(","); // separate by comma's so you can copy output to Excel easily.
Serial.println(litersPerMinute, 3); // print a float with three decimals
int LPM = litersPerMinute; // implicit conversion to int
int frac = (litersPerMinute-LPM)*10;
lcd.setCursor(0, 0);
lcd.print("Flow L/min: ");
lcd.print(LPM);
lcd.print(".");
lcd.print(frac);
lcd.print(" ");
}
}
void CounterIN()
{
countIN++;
}
void CounterOUT()
{
countOUT++;
}