// https://wokwi.com/projects/409384416604568577
// https://forum.arduino.cc/t/using-2-flow-meters/1302833

const byte flowPinA = 2;
const byte flowPinB = 3;

double flowRateA;
double flowRateB;

volatile unsigned int countA;
volatile unsigned int countB;

const byte signalA = 8;
const byte aControl = A0;

const byte signalB = 9;
const byte bControl = A1;

void setup() {
  Serial.begin(115200);
  Serial.println("\nWake up!\n");

  pinMode(flowPinA, INPUT);      //Sets the pin as input
  pinMode(flowPinB, INPUT);      //Sets the pin as input
  attachInterrupt(digitalPinToInterrupt(flowPinA), FlowA, RISING);
  attachInterrupt(digitalPinToInterrupt(flowPinB), FlowB, RISING);

  pinMode(signalA, OUTPUT);
  pinMode(signalB, OUTPUT);
}

bool measuring;
bool calculate;

unsigned int countAStart;
unsigned int countBStart;
unsigned int aTotal;
unsigned int bTotal;

unsigned long startTime;

void loop() {

  generateFakeSignals();

  if (!measuring) {
    noInterrupts();
    countAStart = countA;
    countBStart = countB;
    interrupts();
    measuring = true;
    calculate = false;
    startTime = millis();
  }
  else {  // measuring
    if (millis() - startTime > 1000) {
      noInterrupts();
      aTotal = countA - countAStart;
      bTotal = countB - countBStart;
      interrupts();

      calculate = true;
      measuring = false;
    }
  }

// time to report?
  if (!calculate)
    return; // nope. We outta here

// calculate and report
  //math for useful readings
  flowRateA = (aTotal * 2.25);    //Count pulses in last second and multiply by 2.25mL
  flowRateA = flowRateA * 60;     //Convert seconds to minutes, giving mL / minute
  flowRateA = flowRateA / 1000;   //Convert mL to Liters, giving L / minute
  Serial.print("flow A : ");
  Serial.print(flowRateA);     //Print the variable flowRate to Serial

  flowRateB = (bTotal * 2.25);
  flowRateB = flowRateB * 60;
  flowRateB = flowRateB / 1000;
  Serial.print("    flow B : ");
  Serial.println(flowRateB);
}

void FlowA() {
  countA++;    //every time function runs, increase count by 1
}

void FlowB() {
  countB++;    //every time function runs, increase count by 1
}

void generateFakeSignals()
{
  static unsigned long aLastEdge;
  static unsigned long bLastEdge;
  unsigned long now = micros();


  int periodHalf = analogRead(aControl);
  periodHalf = map(periodHalf, 0, 1023, 5000, 833);
  if (now - aLastEdge > periodHalf) {
    digitalWrite(signalA, digitalRead(signalA) == LOW ? HIGH : LOW);

    aLastEdge = now;
  }

  periodHalf = analogRead(bControl);
  periodHalf = map(periodHalf, 0, 1023, 5000, 833);
  if (now - bLastEdge > periodHalf) {
    digitalWrite(signalB, digitalRead(signalB) == LOW ? HIGH : LOW);

    bLastEdge = now;
  }
}

/*
Serial.print("aTotal : "); Serial.println(aTotal);
Serial.print("aTotal : "); Serial.println(flowRateA);
*/