Sensing the world · Lesson 2 of 5· 20 min

A water tank that warns you

Why this matters

Many homes, schools and clinics store water in a tank on a stand. Nobody climbs up to look until the taps run dry.

Example

Teaching scenario (fictional)

Fatmata looks after the water tank at a primary school in Bo. The tank is 150 cm deep. She wants a buzzer to sound when the water drops below a quarter, so there is time to order more before the children have none.

From distance to level

Mount the sensor at the top of the tank, looking down. It measures the gap to the water. The water level is the tank depth minus the gap.

Try the maths here first. Press Run:

Python

On the board

Add a buzzer to your circuit from the last lesson: one pin to GP15, the other to GND. Then add this below your distance_cm function, replacing the old loop:

from machine import PWM

buzzer = PWM(Pin(15))
TANK = 150

while True:
    gap = distance_cm()
    if gap is not None:
        percent = (TANK - gap) / TANK * 100
        print(round(percent), "% full")
        if percent < 25:
            buzzer.freq(1000)
            buzzer.duty_u16(32768)   # sound on
        else:
            buzzer.duty_u16(0)       # sound off
    time.sleep(1)
You’re reading for free. Sign in to save your progress, ask questions on any lesson, and earn a certificate when you finish.Sign in to keep my progress →

Lesson 2 of 5