#Libraries
import RPi.GPIO as GPIO
import time
#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24
GPIO_IN = 21
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False) # To avoid same PIN use warning
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.setup(GPIO_IN, GPIO.OUT)
def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
time.sleep(1) #the time befor it moves forward tothe next step
if dist >= 5:
time.sleep(2)
GPIO.output(GPIO_IN, GPIO.HIGH) #turm pump on
print("water pump is on")
if dist <= 6:
GPIO.output(GPIO_IN, GPIO.LOW) #turn pump off
print("water pump off")
except KeyboardInterrupt: # Reset by pressing CTRL + C
print("Measurement stopped by User")
GPIO.cleanup() #clean up all the porta i"v used
hi guys im connecting to the R-pi an ultrasonic sensor to mesure distanse and a relay to control a motor but the 5v relay doesnt seems to work.
- why the relay turn on in GPIO.setup(GPIO_IN, GPIO.OUT) line? this is a line to define GPIO pin
- why the reraly allways "on"? GPIO.output(GPIO_IN, GPIO.LOW) line does nothing, this line supos to turn the relay off but nothing happans
thank you.