Try Embedded

Pico in MicroPython: a water meter that counts pulses in PIO

A four-instruction PIO program, written in MicroPython with rp2.asmpio, counts a flow sensor's pulses on its own; the CPU takes a snapshot of the count with…

Sensors · Advanced

In a real product: Smart water meter (Smart home): A meter on a home's water pipe reports the flow and the litres used, and lights a lamp while water is running.

A YF-S201 flow sensor has a small turbine in the pipe with a magnet on it. A hall sensor sends one pulse each time the magnet passes: 7.5 pulses a second for each litre a minute, and 450 pulses for each litre. At 30 L/min that is 225 pulses a second. Counting them one interrupt at a time costs the CPU work all the time. The RP2040 has PIO (programmable I/O): small state machines that run their own programs on the pins. Here one of them counts every rising edge on GP16, and the CPU only reads the total once a second.

What you'll learn

  • Writing a PIO program in Python with @rp2.asm_pio and running it with rp2.StateMachine
  • wait, jmp(x_dec, ...) and mov with invert: counting in a PIO scratch register
  • StateMachine.exec(): running one instruction in a state machine from the CPU, to take a snapshot
  • Turning a count into a rate: pulses per second, then litres a minute

How it works

The PIO program has four instructions. It first sets the scratch register X to 0xFFFFFFFF (all ones, "not zero"), then loops: wait(0, pin, 0) waits until the pin is low, wait(1, pin, 0) until it is high again, which is one rising edge. jmp(x_dec, "loop") takes 1 away from X and goes back to the start of the loop. PIO has no "add" instruction, so it counts down: after n edges X is 0xFFFFFFFF - n. The CPU reads it with all its bits inverted, invert(x), which is exactly n.

in_base=Pin(16) tells the state machine that its pin 0 is GP16. freq=2_000_000 runs it at 2 MHz, fast enough to see pulses much shorter than the sensor's.

To read the count, the CPU does not wait for the PIO. sm.exec("mov(isr, invert(x))") makes the state machine copy the inverted X into its input shift register, and sm.exec("push()") puts that into its RX FIFO, where sm.get() reads it. exec runs an instruction straight away, even while the program is stalled in a wait, and the program then goes on where it was. No edge is lost.

Once a second the program takes the difference between two counts. It divides by the time between them, from time.ticks_ms(), to get pulses per second, then divides by 7.5 for litres a minute. The total is count / 450 litres. The LED on GP15 lights while water flows.

The diagram's sensor is set to 8 L/min, which is 60 pulses a second. The Serial Monitor shows:

PIO flow meter on GP16
8.0 L/min, 0.14 L in total

This sensor is sold as a 5 V part. Its output follows its supply, so the diagram powers it from 3V3. If yours needs 5 V, power it from VBUS and bring OUT down to 3.3 V with a divider (for example 10 kΩ and 20 kΩ): the RP2040's pins are not 5 V tolerant.

Try this

  • Click the sensor and change the flow: the litres a minute follow, and at 0 the LED goes out.
  • Add a second state machine, rp2.StateMachine(1, pulse_counter, ..., in_base=Pin(17)), for a second meter on GP17. The same program runs on both, and each has its own X.
  • Close a valve after 2 litres: add a relay on another pin and switch it off once now_count / PULSES_PER_LITRE >= 2.

main.py

# A water meter: a YF-S201 flow sensor on GP16, its pulses counted by a PIO state machine. The LED on GP15 lights
# while water is flowing.
from machine import Pin
import rp2
import time

PULSES_PER_LITRE = 450       # the YF-S201's datasheet: 7.5 Hz per L/min = 450 pulses a litre
flowing = Pin(15, Pin.OUT)


@rp2.asm_pio()
def pulse_counter():
    mov(x, invert(null))     # X = 0xFFFFFFFF
    wrap_target()
    label("loop")
    wait(0, pin, 0)          # wait for the pin to be low...
    wait(1, pin, 0)          # ...then high: one rising edge
    jmp(x_dec, "loop")       # X = X - 1, and back to the loop (the wrap goes there too)
    wrap()


sm = rp2.StateMachine(0, pulse_counter, freq=2_000_000, in_base=Pin(16, Pin.IN))
sm.active(1)


def count():
    # A snapshot of the PIO's count: X inverted is the number of edges so far.
    sm.exec("mov(isr, invert(x))")
    sm.exec("push()")
    return sm.get()


print("PIO flow meter on GP16")
last_count = count()
last_ms = time.ticks_ms()
while True:
    time.sleep_ms(1000)
    now_count = count()
    now_ms = time.ticks_ms()
    pulses = now_count - last_count
    seconds = time.ticks_diff(now_ms, last_ms) / 1000
    litres_a_minute = pulses / seconds / 7.5
    flowing.value(pulses > 0)
    print("{:.1f} L/min, {:.2f} L in total".format(litres_a_minute, now_count / PULSES_PER_LITRE))
    last_count, last_ms = now_count, now_ms

Lessons behind it