/*
  Flow Sensor Counter Meter FS300A G3/4
  Flow rate :   1-60L/min
  Flow Pulse:   508 pulse / Liter
  Description: This code interfaces with the FS300A flow sensor to measure flow rate and frequency. It handles interrupt-driven pulse counting and calculates the corresponding flow rate based on the sensor specifications.
*/

#define  FS300A_PULSE     508         // Number of pulses per liter
#define  FS300A_FLOW_RATE 60          // Maximum flow rate in liters per minute
const float factor = 60.0F / 508.0F;  // Conversion factor from pulses to flow rate (FS300A_FLOW_RATE / FS300A_PULSE)

#define interruptPin 2  // Define interrupt pin for flow sensor

uint16_t pulse;         // Variable to store pulse count
uint16_t count;         // Variable to store pulse count for calculation

float frequency;        // Variable to store frequency
float flowRate;         // Variable to store flow rate

bool busy;              // Flag to indicate interrupt handling status

void setup() {
  Serial.begin(115200);  // Initialize serial communication at 115200 baud

  pinMode(interruptPin, INPUT_PULLUP);  // Set interrupt pin as input with internal pull-up resistor
  attachInterrupt(digitalPinToInterrupt(interruptPin), FlowInterrupt, CHANGE);  // Attach interrupt handler to the interrupt pin
}

void loop() {
  Frequency();  // Call frequency measurement function
}

void FlowInterrupt() {
  busy = true;  // Set busy flag to indicate interrupt handling
  pulse++;      // Increment pulse count
  busy = false; // Clear busy flag after interrupt handling
}

void Frequency() {
  static unsigned long startTime;
  if (micros() - startTime < 1000000UL ) return;   // Check if 1000 milliseconds interval has passed
  startTime = micros();

  while (busy) {};  // Wait for interrupt handling to complete

  uint8_t sreg = SREG;  // Save status register
  cli();                // Disable interrupts
  count = pulse;        // Save pulse count for calculation
  pulse = 0;            // Reset pulse count
  SREG = sreg;          // Restore status register

  frequency = count / 2.0f;       // Calculate frequency
  flowRate = frequency * factor;  // Calculate flow rate

  PlotInfo();  // Display information
}

void PlotInfo() {
  Serial.print("Freq.:= " + String(frequency, 2) + " Hz");        // Print frequency with 2 decimal places
  Serial.println(", FLow:= " + String(flowRate, 3) + " L/min");   // Print flow rate with 3 decimal places
}
Pulse GeneratorBreakout