Try Embedded

Water meter with shut-off (YF-S201)

Count a flow sensor's pulses to measure litres a minute and the total, and close the valve (a relay) once two litres have run.

Sensors · Intermediate

In a real product: Smart water meter (Energy): Counts flow pulses for billing and closes a valve on a leak.

A YF-S201 has a turbine inside: water spins it, and a Hall sensor gives one pulse per blade passing, 7.5 pulses a second for each litre a minute. Count them and you have a water meter. Here a relay stands in for a valve that shuts once two litres have been dispensed.

What you'll learn

  • Measuring a frequency by counting pulses for a fixed time
  • Keeping a running total from the same pulses: 450 of them make a litre
  • Switching a relay coil through a transistor, with its flyback diode

How it works

Each rising edge on pin 2 runs onPulse(). Once a second the loop takes the count (with interrupts off for the copy), so the flow is pulses / 7.5 litres a minute and the volume pulses / 450 litres. The valve opens at the start (the relay, driven through an NPN transistor from pin 7, is energised); once the total reaches 2 L the sketch drops it.

Try this

  • Click the sensor and set the flow to 10 L/min: two litres take 12 seconds.
  • Change the target to 0.5 L and make the button on pin 3 start another fill.
  • Real sensors read a few percent off: add a calibration factor and correct it against a measuring jug.

sketch.ino

// A water meter: a YF-S201 on pin 2 (7.5 Hz per L/min, 450 pulses a litre), a valve relay switched through a
// transistor on pin 7. The valve closes once 2 litres have flowed.
const float PULSES_PER_LITRE = 450.0, TARGET_LITRES = 2.0;
const int VALVE = 7;

volatile unsigned long pulses = 0;
unsigned long total = 0;
bool valveOpen = true;

void onPulse() { pulses++; }

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  pinMode(VALVE, OUTPUT);
  digitalWrite(VALVE, HIGH);
  attachInterrupt(digitalPinToInterrupt(2), onPulse, RISING);
  Serial.println("Valve open");
}

void loop() {
  static unsigned long lastReport = 0;
  if (millis() - lastReport < 1000) return;
  lastReport = millis();
  noInterrupts();
  unsigned long counted = pulses;
  pulses = 0;
  interrupts();
  total += counted;
  float litres = total / PULSES_PER_LITRE;
  Serial.print(counted / 7.5, 1);
  Serial.print(" L/min, ");
  Serial.print(litres, 3);
  Serial.println(" L");
  if (valveOpen && litres >= TARGET_LITRES) {
    valveOpen = false;
    digitalWrite(VALVE, LOW);
    Serial.println("Target reached: valve closed");
  }
}

Lessons behind it