I am trying to trigger/stop a water pump with the use of a 4-channel relay and a UC-SR04 distance sensor. I tried with some codes but I think I am missing something because although there was no error in the codes, the pump was not triggered.
The 12V water pump has a flow rate of 20l/min and works at max. 45W. The distance sensor works on its own, I am able to see data displaying on the monitor. The water pump can also work on its own with a relay and a 12V 5A power supply. I would like to incorporate the features from the distance sensor with that of the water pump.
Ideally, when the distance sensor detects that the water surface is < 10cm away from it, it gives signal to the pump to turn the pump on. When the sensor detects that the water surface is >10cm away from it, it turns the pump off.
Ideally the whole setup should be similar to what happens in this video, which I found on YouTube: https://www.youtube.com/watch?v=RTmbWMSiwiQ
The person in this video uses an Arduino though, I am using a Raspberry pi 3B.
These are my codes:
> import RPI.GPIO as GPIO
> import time
> import datetime
> init = False
> GPIO.setmode(GPIO.BOARD)
> GPIO.setwarnings(False)
> TRIG = 36
> ECHO = 38
>
> def get_status(pin = 38):
> GPIO.setup(pin, GPIO.IN)
> return GPIO.input(pin)
>
> def init_output(pin):
> GPIO.setup(pin, GPIO.OUT)
> GPIO.output(pin, GPIO.LOW)
> GPIO.output(pin, GPIO.HIGH)
>
> def auto_water(delay = 6, pump_pin = 7, water_sensor_pin = 8):
> distance_count = 0
> init_output(pump_pin)
> print("press CTRL+C to exit")
> try:
> while 1 and distance_count > 10:
> time.sleep(delay)
> shallow = get_status(pin = water_sensor_pin) == 0
> if not shallow:
> if distance_count < 10:
> pump_on(pump_pin, 1)
> distance_count += 1
> else:
> distance_count = 0
> except KeyboardInterrupt:
> GPIO.cleanup()
>
> def pump_on(pump_pin = 7, delay = 1):
> init_output(pump_pin)
> GPIO.output(pump_pin, GPIO.LOW)
> time.sleep(1)
> GPIO.output(pump_pin, GPIO.HIGH)
>
> print "Distance measurement in progress"
>
> GPIO.setup(TRIG,GPIO.OUT)
> GPIO.setup(ECHO,GPIO.IN)
>
>
> while True:
>
> GPIO.output(TRIG, False)
> print "Waiting For Sensor To Settle"
> time.sleep(2)
>
> GPIO.output(TRIG, True)
> time.sleep(0.00001)
> GPIO.output(TRIG, False)
>
> while GPIO.input(ECHO)==0:
> pulse_start = time.time()
>
> while GPIO.input(ECHO)==1:
> pulse_end = time.time()
>
> pulse_duration = pulse_end - pulse_start
>
> distance = pulse_duration * 17150
> distance = round(distance, 2)
>
> if distance > 0 and distance < 100:
> print ("Distance:"),distance - 0.5, ("cm")
> else:
> print ("Out Of Range")
>
> GPIO.cleanup()
Here is a graph of the circuit. The setup in this graph is similar to mine, the only difference is that I am using a distance sensor, not a moisture sensor. Additionally, I am using slightly different pins.
I think there is something missing in my code, as the pump cannot be triggered. Could you please help me out?
Thank you very much in advance.