-1
    #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.

  1. why the relay turn on in GPIO.setup(GPIO_IN, GPIO.OUT) line? this is a line to define GPIO pin
  2. 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.

tlfong01
  • 4,847
  • 3
  • 12
  • 24

3 Answers3

3

Most relay modules are active LOW and you need to set the pin HIGH to turn the relay off

Bra1n
  • 1,261
  • 7
  • 8
1

Ah, so you have the relay always on problem, which is the Rpi relay newbies' constant (well, 12 years) sorrow.


The very sad story began in the good old happy days, when we hobbyists played with only 5V Arduino and all logical levels are sort of 5V TTL, life was easy.

It is only when 3V3 Raspberry Pi came along, and later also 3V3 Arduino (Pro Mini 328 3V3 8MHz), life has become confusing, especially for the oldies/newbies who only know about Arduino/TTL 5V logic.

To understand why all (well, almost) newbies get confused, we need to look closely the following logical level chart, showing the root cause of newbie 3V/5V sorrows.


logical chart


Let us focus on the left most two columns, TTL and Arduino. In those were the days, my Arduino friends thought the imperial Arudino empire would live happily ever after, never imagined that some big guys like Rpi would soon appear. So the story goes than the Arduino engineers devised a new logical level standard/specification:


(Arduino) High level means at least 4.2V

Low level means at most 0.8V

The result is that most devices, say actuators, including relays, solenoids, buzzers, you name it, meet this spec, with (the latter Rpi guys scary) requirement that to do something using High level, you need to give 4.2V or higher (But how can 3V3 Rpi do that!).

Of course this makes the life of Rpi, born later, very miserable, because they are weak 3V3 guys, and their High level is usually 2.4V to at most 3.2V.

This is what I usually refer as

The (Arduino compatible only) Low Trig Relay is always on, because Rpi's High is Not High Enough Problem.

Of course there are solutions and workarounds. You can search for a couple of my suggestions in this Rpi SS and EE SE forums. EG. Appendix C of this Q&A (1) How to properly use a relay module with JD-VCC from Arduino/Raspberry? EESE, Asked 10 months ago Active 3 months ago Viewed 7k times.

You can use a Logic Level Converter Bi-Directional too, if you want.


Glorfindel
  • 620
  • 1
  • 9
  • 16
tlfong01
  • 4,847
  • 3
  • 12
  • 24
1

In one of your comments you said:

if i use a simple on/off switch code it turn on and off

Did your code include corresponding print statements when switching?

Does the following work for you?

import RPi.GPIO as GPIO
import time

GPIO_IN = 21

GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(GPIO_IN, GPIO.OUT)

while True: print('relay off') GPIO.output(GPIO_IN, GPIO.HIGH) time.sleep(2)

print('relay on')
GPIO.output(GPIO_IN, GPIO.LOW)
time.sleep(2)

If the above worked, change your original code to:

if dist >= 5:
    time.sleep(2)
    GPIO.output(GPIO_IN, GPIO.LOW) #turm pump on
    print("water pump is on")

if dist <= 6: GPIO.output(GPIO_IN, GPIO.HIGH) #turn pump off print("water pump off")

CoderMike
  • 7,102
  • 1
  • 11
  • 16