Water Level Sensor

Water Level Sensor:

This script uses a HCSR04 Ultrasonic Sensor to measure the distance between the sensor and the water line. The code requires 8 consistent readings over the stated threshold before triggering an action.

This is helpful in case the triggered event is something like a refill pump that could cause a flood if activated too often by false-positives.

Repository on GitHub

# Distance Sensor with alarm
# Alarm requires x number of consecutive positive readings over threshold.  

from machine import Pin
import machine
import time
import utime

pump = machine.Pin(5, machine.Pin.OUT) # Builtin LED for testing. 
trig = Pin(18,Pin.OUT, pull=None)
echo = Pin(23, Pin.IN, pull=None)
trig.value(0)
echo.value(0)

pump.on() # for some reason on is off/off is on. This is just to ensure that the pin is indeed low. 

def send_pulse_and_wait(echo_timeout_us=500*2*30):
        trig.value(0) # Stabilize the sensor
        time.sleep_us(5)
        trig.value(1) # Send a 10us pulse.
        time.sleep_us(10)
        trig.value(0)
        try:
            pulse_time = machine.time_pulse_us(echo, 1, echo_timeout_us)
            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110: # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex

def distance_cm():
        pulse_time = send_pulse_and_wait()
        cms = (pulse_time / 2) / 29.1
        return cms
 
def main():
  threshold_count = 0
  threshold = 8 # Number of consecutive readings needed to trigger pump pin. 
  distance_threshold = 20 # distance in cm / adjust as needed.
  try:
    while True:
      utime.sleep_ms(1000)
      distance = distance_cm()
      print(distance)
      if distance > distance_threshold:
        threshold_count += 1
      else:
        threshold_count = 0
      if threshold_count >= threshold:
        pump.off()
        utime.sleep_ms(3000) #length of time to activate pin/relay/pump. 
        pump.on() 
        
  except KeyboardInterrupt:
            pass

main()