-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,384
  • 3
  • 9
  • 23
  • 1
    The relay might not be suitable for use with the Pi. Does it switch on if you (CAREFULLY) connect a wire from a Pi 3V3 pin to the input? Does it switch off if you (CAREFULLY) connect a wire from a Pi ground pin to the input? – joan Apr 12 '21 at 20:42
  • 1
    yes it does. if i use a sipmple on/off switch code it turn on and off but when i try to intigrat it like in the code above it wont do anything. – Liron Aviv Apr 12 '21 at 23:11
  • 1
    Can you edit your question, and include the code that does work for you. – Chad G Apr 12 '21 at 23:38
  • 2
    Does this answer your question? [Can you use a 5V Relay Module with the Pi?](https://raspberrypi.stackexchange.com/questions/118116/can-you-use-a-5v-relay-module-with-the-pi) – Milliways Apr 12 '21 at 23:38
  • 1
    If it works the only conclusion is you have wired to the wrong GPIO. A clear photo may help. – joan Apr 13 '21 at 07:45
  • Does this answer your question? [4 relay board weird behavior](https://raspberrypi.stackexchange.com/questions/92299/4-relay-board-weird-behavior) – Dmitry Grigoryev Apr 15 '21 at 07:29

3 Answers3

3

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

Bra1n
  • 1,181
  • 6
  • 7
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
  • 440
  • 1
  • 6
  • 12
tlfong01
  • 4,384
  • 3
  • 9
  • 23
  • 2
    thank you for the story i really learn something today. so just to be clear the 3.3v from the R-pi in to the "IN" pin in the relay is not enough? this mean i need to use an analogue device like an amplifier of some sort? – Liron Aviv Apr 13 '21 at 11:50
  • 2
    Not necessarily, depends on your relay board. All of mine work fine at 3.3V. – CoderMike Apr 13 '21 at 12:38
  • @Liron Aviv, Ah, your idea of using an amplifier is no good. A better idea is buy a HIGH level trigger relay. Why: there are two kinds of relay, (1) Low level trigger, (2) High level trigger. High trigger relay has no problem. Low level trigger MIGHT have a problem. So a quick solution is throw away your low trig relay and buy a high trig relay. You might like to read my first post when I started learning relay as a newbie, some three years ago. (1) Re: Relay Module KY-019 5V Report this post 2018-Jun-02 Sat 10:10 pm https://www.raspberrypi.org/forums/viewtopic.php?f=37&t=77158#p1323061 – tlfong01 Apr 13 '21 at 14:13
  • @CoderMike, yes, as I said, all HIGH level trigger relays have not problem. – tlfong01 Apr 13 '21 at 14:15
  • @Liron Aviv, Instead of throwing away your always on relay, you can try other turarounds, but they have their own problems. For example, see ***Appendix C - How to turn off a always on (Low trig) relay*** of the following Q&A:(1) JD-Vcc Realy Q&A https://electronics.stackexchange.com/questions/505318/how-to-properly-use-a-relay-module-with-jd-vcc-from-arduino-raspberry.Cheers. – tlfong01 Apr 15 '21 at 03:35
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
  • 6,381
  • 1
  • 9
  • 15