User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Wed Jun 13, 2018 7:44 am

I am testing a module with opto isolation and High/Low level selectable. I found that for one sample I tested. the required input voltage levels are summarized below.

If Low Level Trigger is selected
Vin to turn on relay = 3.2V
Vin to turn off relay = 3.5V

Conclusion:
Arduino
No problem
Rpi
Problem - always on, cannot turn off relay, because Rpi's High signal is not high enough
Solution - use a logical level converter (BJT NPN, ULN2003/ULN2803 etc) to convert Rpi's High level signal from 3.0V to above 4V. Get around: set GPIO to input mode to turn off relay.

If High Level Trigger is selected
Vin to turn on relay = 1.8V
Vin to turn off relay = 1.5V

Conclusion:
Arduino
No problem
Rpi
No problem

Schematic
I used a multimeter to check open/shorts to figure out the schematic as below:
Attachments
FdenCZG[1].jpg
FdenCZG[1].jpg (127.78 KiB) Viewed 9178 times
Last edited by tlfong01 on Wed Jul 11, 2018 4:14 am, edited 2 times in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Wed Jun 13, 2018 9:22 am

davidcoton wrote:
Tue Jun 12, 2018 3:48 pm
... And what happens if someone takes you project and connects it to a circuit wherer there is no "earth leakage detector" (more correctly the RCD -- Residual Current Device), or where it has failed?
Safety with mains electricity is all about multiple layers of safety.
Earth wires must be able to carry enough current for long enough to blow the MCB or fuse, not the RCD.
Thanks a lot for pointing out my silly newbie mistake. That is very important. So if there is no RCD, and my earth wire is too thin, it might break and so all the current passes from the chassis to the human body then to ground. This current should be much more than RCD's threshold of 30mA, so should kill the human, that is, me!

Actually I know too little to understand the problem. I thought there is a RCD in my home, because once there was a heavy water leakage and some of the main wires got wet, and the circuit breaker activated. I wrongly though that current leaked to ground, so the RCD took action. Just now I looked closely at my MCB, actually it is MCB only, no expensive RCD connected with it.

Now I know that I was probably wrong, because even there is no RCD, the MCB should also activate. I need to study more to clear my mind.

Thanks for saving my life. :mrgreen:
Last edited by tlfong01 on Sat Oct 06, 2018 12:58 am, edited 1 time in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Thu Jun 14, 2018 4:42 am

tlfong01 wrote:
Wed Jun 13, 2018 7:44 am
I am testing a module with opto isolation and High/Low level selectable. I found that for one sample I tested. the required input voltage levels are summarized below.
I have also retested an old relay module I DIYed some weeks ago, when I first started playing with relays. Now I summarized the 4 types of relay module configurations in the piture attached below.
hmhjwP3[1].jpg
relay module types
hmhjwP3[1].jpg (202.86 KiB) Viewed 9152 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Thu Jun 14, 2018 5:43 am

Now I am using a python program to test KY-019 NPN HIgh Level trigger module. The program can control KY-019 Type 1 and 2 modules using Rpi GPIO pin 17 at 3.3V, without any logical level driver. However, Type 3 and Type 4 modules are not responding.

Code: Select all

# *** ky019test01.001 tlfong01 2018jun14hkt1315 ***

# Reference - https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=77158&p=1328075#p1328075

import RPi.GPIO as GPIO
from time import sleep

# *** Config ***

relayPin0      = 17

# *** GPIO Setp/Cleanup ***

def setGpioMode():
    GPIO.setwarnings(False) 
    GPIO.setmode(GPIO.BCM)
    return

def cleanupGpio(): 
    GPIO.cleanup()
    return

# *** Relay pin setup/set high/low ***

def setupRelayPin(relayPin):
    GPIO.setup(relayPin, GPIO.OUT)
    GPIO.output(relayPin, GPIO.LOW)  
    return

def setRelayPinHigh(relayPin):  
    GPIO.output(relayPin, GPIO.HIGH)
    return

def setRelayPinLow(relayPin): 
    GPIO.output(relayPin, GPIO.LOW)
    return

# *** Relay activate/deactivate/toggle ***

def activateRelay(relayPin, activateLevel):
    if activateLevel == 'High':
        setRelayPinHigh(relayPin)
    else:
        setRelayPinLow(relayPin)
    return

def deActivateRelay(relayPin, activateLevel):
    if activateLevel == 'High':
        setRelayPinLow(relayPin)
    else:
        setRelayPinHigh(relayPin)
    return

def toggleRelay(relayPin, activateLevel, activateMilliSeconds, deActivateMilliSeconds, toggleCount):
    for i in range(toggleCount):
        activateRelay(relayPin, activateLevel)
        sleep(activateMilliSeconds / 1000)
        deActivateRelay(relayPin, activateLevel)
        sleep(deActivateMilliSeconds / 1000)
    return

# *** Tests ***

# *** Toggle Relay ***

def test0():
    print('  Begin test0(), ...')
    toggleRelay(relayPin = relayPin0, activateLevel = 'High', \
                activateMilliSeconds = 1000, deActivateMilliSeconds = 1000, \
                toggleCount = 4)
    print('  End   test0().')
    return 

# *** Init/Cleanup/Test/Main ***

def init():
    setGpioMode()
    setupRelayPin(relayPin0)  
    return

def cleanup():
    cleanupGpio()
    return

def test():
    print('Begin test(), ...')
    init()
    test0()
    print('End   test().')
    cleanup()
    return

def main():
    test()
    return

# *** Main ***

if __name__ == '__main__':
    main()

# *** End ***

I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Thu Jun 14, 2018 6:47 am

tlfong01 wrote:
Thu Jun 14, 2018 5:43 am
Now I am using a python program to test KY-019 NPN HIgh Level trigger module. The program can control KY-019 Type 1 and 2 modules using Rpi GPIO pin 17 at 3.3V, without any logical level driver.

However, Type 3 and Type 4 modules are not responding.
I know the reason is that the modules are not responding to Rpi's 3.3V GPIO signal, because the modules are designed for Arduino's 5V GPIO signals. So I need a logical level converter to convert Rpi's 3.3V signal to Arduino compatible 5V signals. I remember there is a get around of setting Rpi GPIO to input to turn of the relay, but this get around has itself some problems. So I will not use it now.

Now I read one of my old forum posts to refresh my memory on level converter.

Notes on Logical Level Converters
...

There are many ways to do level shifting. I first learnt the idea from NXP

NXP I2c Logic Level Shifting Notes
https://www.nxp.com/docs/en/application ... N10441.pdf

Then I assembled a I2C bidirectional level shifter as suggested by NXP, using 2N7000. It was a good learning experience. But the soldering work is boraing. So I will not try it again.

Anyway, if you have an I2C level converter, then the next step is to try the MCP23017 IO expander, wtih 16 IO port to control 16 relay modules.

MCP23017 IO Expander
I tried the MCP23017 io expander, and mux 4 of them, so that I could control 64 relays at the same time.

i2c mcp23017 notes
https://electronics.stackexchange.com/q ... are-active

The above are a bit challenging and might take you weeks to catch up. If you are in a hurry, I would suggest you AdaFruit or SparkFun's MCP23017 tutorials for beginners. They also sell newbie friendly modules to help you jump start.

Logical level shifting using HCT125
I2C stuff is hard, an easier method is HCT125. Adafruit has a good tutorial, and rpi example. I have been using HCT125 in some of my projects, using 4 chips to up shift 16 rpi gpio pin signals. You can use OE to disable and mux to as many pins as you like. One good thing of HCT125 when comparing to other source or sink driver is that it can both drive and sink. One bad thing is that the HCT125 wiring and soldering is a bit messy.

74AHCT125 - Quad Level-Shifter (3V to 5V)
https://www.adafruit.com/product/1787

Logic Level Up Shifting using HC04
Different approaches have different pros and cons, and you need to make an engineering trade off, or cost benefit analysis. If you wish to control 128 relays placed far far away, I2C MCP23017 is good; if you want to Mux/OE (Output enable/disable) the relay modules, then HCT125 is good; if you wish to up shift to different levels (not just 3v3 to 5v0, but 3v3 or 5v0 to 12/24/36V, then HC04 Quad Open Drain NAND gate is good. I once tried HC04 for a 817c photocoupler driven relay module and found it working OK.

Up shifter using 2N2222
And if you want to entertain only one relay module, then the 4 shifters in 1 chip HCT125/HC04 is a waste or overkill. Then you may consider single transistors (such as BJT NPN 2N2222, MosFet 2N7000). I tried 2N2222 the other day and found it OK.

DIY your own module using 2N2222
If you are a DIYer or maker, and you want to build everything yourself, then you can start with a bare Songle relay and use 2N2222 to drive it.

Built Your Own 5V Relay Module [using 2N2222, driven by rpi] - Nick Momrik 2017jul05
https://nick.blog/2017/06/22/5v-relay-module/

.END
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Thu Jun 14, 2018 7:03 am

tlfong01 wrote:
Thu Jun 14, 2018 6:47 am
tlfong01 wrote:
Thu Jun 14, 2018 5:43 am

However, Type 3 and Type 4 modules are not responding.
Logical level shifting using HCT125
I have been using HCT125 in some of my projects, using 4 chips to up shift 16 rpi gpio pin signals. You can use OE to disable and mux to as many pins as you like. One good thing of HCT125 when comparing to other source or sink driver is that it can both drive and sink.

74AHCT125 - Quad Level-Shifter (3V to 5V)
https://www.adafruit.com/product/1787
Now I am trying to use HCT125 to shift up Rpi GPIO signal and see if the Type 3, 4 (opto coupler low trigger, an PNP driver low trigger).
Attachments
34gxEQp[1].jpg
34gxEQp[1].jpg (123.22 KiB) Viewed 9104 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Thu Jun 14, 2018 7:38 am

tlfong01 wrote:
Thu Jun 14, 2018 7:03 am
Now I am trying to use HCT125 to shift up Rpi GPIO signal and see if the Type 3, 4 (opto coupler low trigger, an PNP driver low trigger).
I found
GPIO pin 17 3V3 signal, after HCT125 shifted up to 5V, can control all 4 types of modules.

One problem is that the

noise level at the KY-0109 Normal Open connector with the LED + 1k loading, is high, about 1V pp.

Perhaps I should try another level converter.
Attachments
LnCKtMv[1].jpg
LnCKtMv[1].jpg (64.96 KiB) Viewed 9089 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Thu Jun 14, 2018 2:35 pm

tlfong01 wrote:
Thu Jun 14, 2018 7:38 am
tlfong01 wrote:
Thu Jun 14, 2018 7:03 am
Now I am trying to use HCT125 to shift up Rpi GPIO signal and see if the Type 3, 4 (opto coupler low trigger, an PNP driver low trigger).
I found
GPIO pin 17 3V3 signal, after HCT125 shifted up to 5V, can control all 4 types of modules.
I found things confusing because I have little idea the differences of levels of output logic signal between Arduino and Rpi. I made the following summary and see the cause of most of the confusion.

Relay modules designed for Ariduino expect High Level control signal which garrantees 4.2V,

but Rpi High Level output signal only garrrantees 2.4V!

References

Logic Level Tutorial - Sparkfun
https://learn.sparkfun.com/tutorials/logic-levels

Rpi GPIO Voltage and Current Spec
http://www.mosaic-industries.com/embedd ... ifications
Attachments
wFijP3T[1].jpg
wFijP3T[1].jpg (31.7 KiB) Viewed 9050 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 3:15 am

tlfong01 wrote:
Thu Jun 14, 2018 7:38 am
tlfong01 wrote:
Thu Jun 14, 2018 7:03 am
Now I am trying to use HCT125 to shift up Rpi GPIO signal and see if the Type 3, 4 (opto coupler low trigger, an PNP driver low trigger).
I found
GPIO pin 17 3V3 signal, after HCT125 shifted up to 5V, can control all 4 types of modules.

One problem is that the

noise level at the KY-0109 Normal Open connector with the LED + 1k loading, is high, about 1V pp.

Perhaps I should try another level converter.
Now I am trying 74HC03 Quad Open Drain NAND Gate as logic level converter to KY019 OPTO Low Level Input Relay Module.

Examples of Low Level Trigger NPN and High/Low Level Trigger Optocoupler relay modules

Note: Rpi 3.3V GPIO signals cannot directly drive these high level trigger modules. A logical level converter such as NPN BJT 2N2222, ULN2003/2803, 74HC03 etc, in open drain mode, can be used to convert Rpi's 3.3V GPIO signals to 5V.

A get around without using logical level converter is to turn off relay by setting GPIO pin from output mode to input mode.

5V Low Level Trigger One 1 Channel Relay Module DC AC 220V Interface Relay Board Shield LED Indicator for Arduino
https://www.aliexpress.com/item/5V-Low ... 27376.html

DZS Elec 12V 2 Channel High / Low Level Trigger with Optical Isolation Relay Module Fault Tolerant Design Load AC 0-250V/10A DC 0-30V/10A Circuit Switch Board
https://www.amazon.com/dp/B071K7ZLYL/re ... 3XH38?th=1
SXfCdjQ[1].jpg
HC03 logic level converter
SXfCdjQ[1].jpg (82.1 KiB) Viewed 9015 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 4:28 am

tlfong01 wrote:
Fri Jun 15, 2018 3:15 am
Now I am trying 74HC03 Quad Open Drain NAND Gate as logic level converter to KY019 OPTO Low Level Input Relay Module.
The results is not OK. HC03 converts Rpi GPIO signal from around 3V+ to 4V+ (image A), but very noisy. Converted signal is overloaded if used for non open drain mode (One get around is to use a HC04 hex inverter to buffer the open drain to totem pole/push/pull) (B). For open drain mode, the low level modules is working and HC03 output not loaded (C), but contact Normal Open (NO) with LED + 1K load if very noisy (not sure if because of contact bouncing) (D).
Attachments
sgMv5uX[1].jpg
sgMv5uX[1].jpg (145.5 KiB) Viewed 8996 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 6:43 am

tlfong01 wrote:
Fri Jun 15, 2018 4:28 am
The results is not OK. HC03 converts Rpi GPIO signal from around 3V+ to 4V+ (image A), but very noisy. Converted signal is overloaded if used for non open drain mode (One get around is to use a HC04 hex inverter to buffer the open drain to totem pole/push/pull) (B). For open drain mode, the low level modules is working and HC03 output not loaded (C), but contact Normal Open (NO) with LED + 1K load if very noisy (not sure if because of contact bouncing) (D).
Perhaps I should try the three diode logic level converter. I think the operation is like below. When Rpi wants to turn off relay, it outputs High, which is 2.4V+. But the module designed for Arduino epxects an Arduino High of 4.2V+. So to cheat EL534, three diodes in series, deopping 0.5 * 3 = 1.5V let The optocoupler at the IN connector things that there is a High of 3.3V + 1.5V = 4.7V, compatible to Arduino High.
Attachments
jRtAGkT[1].jpg
jRtAGkT[1].jpg (89.64 KiB) Viewed 8965 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 8:04 am

tlfong01 wrote:
Fri Jun 15, 2018 6:43 am
Perhaps I should try the three diode logic level converter. I think the operation is like below. When Rpi wants to turn off relay, it outputs High, which is 2.4V+. But the module designed for Arduino epxects an Arduino High of 4.2V+. So to cheat EL534, three diodes in series, deopping 0.5 * 3 = 1.5V let The optocoupler at the IN connector things that there is a High of 3.3V + 1.5V = 4.7V, compatible to Arduino High.
Logical Level Converter using 3 diodes and 2N2222
viewtopic.php?p=794834#p790643

There are three methods to connect the relay on the PI.

1 - Use three diodes in series. (1n4148 or 1n400X) cathode to the GPIO , Anode to the IN relay. This way the 3.3V won't conduct current.

2 - Use a low signal NPN transistor, like a 2n3904 or 2n2222, to activate the IN signal. A 10K ohm resistor from the GPIO and the transistor base. Emitter to gnd and collector to the relay IN pin.

3 - Use an 3.3V to 5V sparkfun, or adafruit, adapter level converter. https://www.sparkfun.com/products/12009


The 3 diode thing does not work. I used three 1N4148 but the relay did not toggle. I gave up for now and would come back later.

I then tried the 2N2222 to do the level shift up. This time no problem at all. The relay toggles happily, but the 2N2222 output signal is very noisy.
GFbzcwG[1].jpg
2n2222 3 diode
GFbzcwG[1].jpg (74.29 KiB) Viewed 8941 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 8:30 am

tlfong01 wrote:
Fri Jun 15, 2018 8:04 am
I then tried the 2N2222 to do the level shift up. This time no problem at all. The relay toggles happily, but the 2N2222 output signal is very noisy.
I also tried the HC03 + HC04 together as converter. HC03 open drain alone is not working well with KY019 NPN HIgh Level Trigger because it expect source driver, not not open drain (HC03) sink driver. HC03 + HC04 has little noise, so it seems a better alternative than HCT125.
PPxHNeZ[1].jpg
HC03 + HC04 converter
PPxHNeZ[1].jpg (93.66 KiB) Viewed 8926 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 9:06 am

tlfong01 wrote:
Fri Jun 15, 2018 8:30 am
I also tried the HC03 + HC04 together as converter.
I also tried ULN2803 sink driver and UDN2983 source driver. The outputs of these two drivers are not that noisy. ULN2803 works with Opto Low trigger (but not PNP Low trigger, should come back and check later), UDN2981 works with both NPN High trigger and Opto High Trigger.
GClsWxi[1].jpg
uln udn
GClsWxi[1].jpg (86.61 KiB) Viewed 8911 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 12:48 pm

tlfong01 wrote:
Fri Jun 15, 2018 8:04 am

Logical Level Converter using 3 diodes and 2N2222
viewtopic.php?p=794834#p790643

There are three methods to connect the relay on the PI.
...
3 - Use an 3.3V to 5V sparkfun, or adafruit, adapter level converter. https://www.sparkfun.com/products/12009
This time I tried the third method, TXS0104E level converter. I found that it works only with the two modules with High level trigger. Other two modules had no response. The signal level seems a bit low. TXS0104E is mainly for I2C type bidirectional up level shifter. So I would not study further.
LceQksZ[1].jpg
tsx0104e
LceQksZ[1].jpg (137.08 KiB) Viewed 8851 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 1:23 pm

After studying and experimenting relays for a couple of weeks, I guess now I understand about 80% of the basic things about relays. There are things I am not interested to dig deeper, such as the following.

Removing the jumper JDVcc and supply Rpi 3.3V to relay board.

5V Relay, Power through Pi or with separate source - 2017Feb09
viewtopic.php?p=1111661#p1111337

I've been trying to research this for some time, and found articles from 2013 to present day and everything seems to conflict, so now I am utterly confused. And I am not an electrical guy so I'm learning as I read. ...

However, I wouldn't do that, because with the jumper in place I think the relay board will pull the GPIO up to near 5V when the GPIO is not sinking the current, and the GPIO won't like that (ie, you're risking damage to your Pi). What you should do is remove the jumper, connect the RY-VCC to the 5V pin on the GPIO, connect the VCC pin to a 3.3V on the GPIO header, and the input to whatever GPIO you're using. The potential headache is that the optocoupler might not work at 3.3V (depending on its specs, and I'm not going hunting for data sheets on that just now)...


There is at least one thing I hope to understand:

Why we can set GPIO pin to input mode to turn off the relay?

Is it harmful to the Rpi?


/ to continue, ...
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Fri Jun 15, 2018 2:06 pm

tlfong01 wrote:
Fri Jun 15, 2018 1:23 pm
There is at least one thing I hope to understand:
Why we can set GPIO pin to input mode to turn off the relay?
Is it harmful to the Rpi?
Now I have written a basic python program to toggle the relay.
For now the program works in the following condition:

1. GPIO pin 13 3v3 signal - only the two High level trigger modules toggle. The two Low trigger modules have no response.

2. GPIO pin 17 level converted 5V signal. All 4 modules toggles. However, the two low trigger modules only toggle sluggishly, sometimes do not start.

Code: Select all

# *** ky019test01.003 tlfong01 2018jun15hkt2144 ***

import RPi.GPIO as GPIO
from time import sleep

# *** Config ***

relayPin0      = 17
#testNum        = 0 # slow toggle
testNum        = 1 # quick toggle

# *** GPIO Setp/Cleanup ***

def setGpioMode():
    GPIO.setwarnings(False) 
    GPIO.setmode(GPIO.BCM)
    return

def cleanupGpio(): 
    GPIO.cleanup()
    return

# *** Relay pin setup/set high/low ***

def setupRelayPin(relayPin):
    GPIO.setup(relayPin, GPIO.OUT)
    GPIO.output(relayPin, GPIO.LOW)  
    return

def setRelayPinHigh(relayPin):  
    GPIO.output(relayPin, GPIO.HIGH)
    return

def setRelayPinLow(relayPin): 
    GPIO.output(relayPin, GPIO.LOW)
    return

# *** Relay activate/deactivate/toggle ***

def activateRelay(relayPin, activateLevel):
    if activateLevel == 'High':
        setRelayPinHigh(relayPin)
    else:
        setRelayPinLow(relayPin)
    return

def deActivateRelay(relayPin, activateLevel):
    if activateLevel == 'High':
        setRelayPinLow(relayPin)
    else:
        setRelayPinHigh(relayPin)
    return

def toggleRelay(relayPin, activateLevel, activateMilliSeconds, deActivateMilliSeconds, toggleCount):
    for i in range(toggleCount):
        activateRelay(relayPin, activateLevel)
        sleep(activateMilliSeconds / 1000)
        deActivateRelay(relayPin, activateLevel)
        sleep(deActivateMilliSeconds / 1000)
    return

# *** Tests ***

# *** Toggle Relay ***

def slowToggleRelayFourTimes(): # slow toggle
    print('  Begin slowToggleRelayFourTimes(), ...')
    toggleRelay(relayPin = relayPin0, activateLevel = 'High', \
                activateMilliSeconds = 1000, deActivateMilliSeconds = 1000, \
                toggleCount = 4)
    print('  End   slowToggleRelayFourTimes().')
    return

def quickToggleRelay100000Times(): # quick toggle
    print('  Begin quickToggleRelay100000Times(), ...')
    toggleRelay(relayPin = relayPin0, activateLevel = 'High', \
                activateMilliSeconds = 20, deActivateMilliSeconds = 10, \
                toggleCount = 1000000)
    print('  End   quickToggleRelay100000Times().')

testDict =  { \
                '0': slowToggleRelayFourTimes,
                '1': quickToggleRelay100000Times,
            }

# *** Init/Cleanup/Test/Main ***

def setup():
    setGpioMode()
    setupRelayPin(relayPin0)  
    return

def cleanup():
    cleanupGpio()
    return

def test():
    print('Begin test(), ...')
    setup()
    test = testDict[str(testNum)]
    test()
    print('End   test().')
    cleanup()
    return

def main():
    test()
    return

# *** Main ***

if __name__ == '__main__':
    main()

# *** End ***



I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Sat Jun 16, 2018 3:23 am

tlfong01 wrote:
Fri Jun 15, 2018 1:23 pm
... There is at least one thing I hope to understand:
Why we can set GPIO pin to input mode to turn off the relay?
Is it harmful to the Rpi?
When I started playing relays this April, I googled around and found the popular, beginner friendly get around of "set GPIO pin to turn off relay". A typical dialog about this get around is as summarized below.

Issues with Sunfounder relay board - Raspberry Pi Stack Exchange 2016mar216
https://raspberrypi.stackexchange.com/q ... board?rq=1

Question by @timr 2016mar26
I recently purchased a Sunfounder single relay board https://www.amazon.ca/gp/product/B013GAGFOU and am attempting to use it with my Pi. ... and created a basic script to test ...

The expected result is the the relay turns on for half a second and then turns off. However, the relay is being turned on and not turned off at all, despite the pin being cycled.

Interestingly, the status LED on the board is always on. it is on but dim when the pin is high, and on and full brightness when the pin is low. I'm not sure what I'm doing wrong, so any input would be appreciated.

---

Answer by @joan 2016mar26
The relay is sold for a 5V Arduino.

The description says it is triggered low so it will be ON when you output 0 (0V) and OFF when you output 1 (5V). But the Pi can't output 5V from a GPIO as it is a 3V3 device.

The relay may switch off if you change the GPIO to be an input.

---

Comment by @Timr 2016mar26
... Your suggestion of making it an input worked. Are there any concerns about doing it this way?

---

Comment by @ joan 2016mar26
I don't know. Hopefully someone with electronics knowledge will comment.

---

The following post by mahjongg also talks about the set-gpio-to-input-mode to turn off a relay.

Common Pitfalls for Beginners, 25: PROBLEMS WITH RELAY MODULES - mahjongg 2017oct22
viewtopic.php?p=1250211#p1225448

... one could program the IN0 GPIO so that it becomes high-ohmic, and that would turn the relay off, but the downfall of that approach is that there might appear a voltage on the GPIO larger than 4V, and this might cause the dreaded "latch up" phenomenon as the GPIO's of a PI are NOT 5V TOLERANT!

See https://en.wikipedia.org/wiki/Latch-up for an explanation of what might happen. Just maybe the two diodes (LED's) might prevent latchup in practice, so it might work, but your mileage might vary! ...
I am an electronics and smart home hobbyist.

gordon77
Posts: 7738
Joined: Sun Aug 05, 2012 3:12 pm

Re: Relay Module KY-019 5V

Sat Jun 16, 2018 5:43 pm

Some of the relay boards designed for the Arduino don't always work for the Pi.

I have modified a couple of models to make them work for me.

viewtopic.php?f=45&t=186210&p=1176810#p1176810

viewtopic.php?t=63659

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Sun Jun 17, 2018 5:23 am

gordon77 wrote:
Sat Jun 16, 2018 5:43 pm
Some of the relay boards designed for the Arduino don't always work for the Pi.

I have modified a couple of models to make them work for me.

viewtopic.php?f=45&t=186210&p=1176810#p1176810

viewtopic.php?t=63659
I am a bit confused of your modification. You seem to short pin 1 of the optocoupler to ground. I need to draw the schematic to see what is going on.
Attachments
FKRCERU[1].jpg
FKRCERU[1].jpg (218.26 KiB) Viewed 8599 times
Last edited by tlfong01 on Mon Jun 18, 2018 12:56 am, edited 1 time in total.
I am an electronics and smart home hobbyist.

gordon77
Posts: 7738
Joined: Sun Aug 05, 2012 3:12 pm

Re: Relay Module KY-019 5V

Sun Jun 17, 2018 7:41 am

It's not a short, it's a 4.7k resistor. I'll try and find the schematic again.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Sun Jun 17, 2018 8:31 am

gordon77 wrote:
Sun Jun 17, 2018 7:41 am
It's not a short, it's a 4.7k resistor. I'll try and find the schematic again.
Ah, it was my laughably careless mistake. My apologies.

My eyes did see the 4k7 resistor but my brain translated it to a short circuit. I think it is some sort of physical or mental "blind spot" where the human brain makes a short cut in processing information, with the objective to complete the job as soon as possible, usually in a desperate case, like my ancestors being chased by a tiger etc.

In my case, these days I have been googling too often, and brain washed about get arounds of short circuiting a LED, or a current limiting resistor, so the Rpi's 2.4V+ GPIO pin can drive as much current as the Arduino's 4.2V+ signal.

Don't worry about the schematic for now, because these few weeks I am playing with a couple of various configuration of relay modules, to try to find a "Unified Relay Theory", sort of Einstein's "Unified Relativity Theory". I hope my unified relay theory will bring joy to all the miserable Rpi relay newbies still weeping in the dark, ...

One other thing is that I started learning the CircuitLab schematic tool some weeks ago. I am feeling the same joy many years ago, learning tools like Word, Excel, and PhotoShop, creating text, crunching numbers, and cutting and pasting images. I guess my joy is similar to my cave dwelling stone age ancestors discovering how to use stone to build houses.

So let me first make a schematic and you can check if my guess is correct.
Last edited by tlfong01 on Sun Jun 17, 2018 1:08 pm, edited 1 time in total.
I am an electronics and smart home hobbyist.

gordon77
Posts: 7738
Joined: Sun Aug 05, 2012 3:12 pm

Re: Relay Module KY-019 5V

Sun Jun 17, 2018 11:49 am

The 4.7k resistor is simply in parallel with the 1k resistor, which is in series with the diode in the opto coupler. This lowers the resistance and the volts so it will work with 3.3v.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Mon Jun 18, 2018 3:46 am

gordon77 wrote:
Sun Jun 17, 2018 11:49 am
The 4.7k resistor is simply in parallel with the 1k resistor, which is in series with the diode in the opto coupler. This lowers the resistance and the volts so it will work with 3.3v.
OK. Now I see what is going on. Earlier I lost my sense of current direction and orientation of the photocoupler. So I drew the following schematic to clear my mind.

There is still one confusing thing.

The relay seller Amazon Xsource says the module is High Level Trigger, but your picture's PCB marking says it is Low Level Trigger! Perhaps I again missed something.

Update 2018jun18hkt1321: I found many bugs in my schematic. Please ignore this schematic. I am making another version.
Attachments
W3hQi2L[1].jpg
W3hQi2L[1].jpg (125.61 KiB) Viewed 8593 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: Relay Module KY-019 5V

Mon Jun 18, 2018 7:06 am

tlfong01 wrote:
Mon Jun 18, 2018 3:46 am
There is still one confusing thing.
The Amazon Xsource says the module is High Level Trigger, but your picture's PCB marking says it is Low Level Trigger!
On second thought, your Xsource relay board should be high level trigger, and the PCB marking is a typo. Last week I bought some 20 different models of relay boards from ShenZhen, for experimentation. I found one model similar to the Xsource one. So I am going to check it out.

This cheap relay broad cost me only 4 Chinese Yuen. So I don't worry frying it by careless mistake.
Attachments
XWtW6Bj[1].jpg
XWtW6Bj[1].jpg (136.68 KiB) Viewed 8573 times
I am an electronics and smart home hobbyist.

Return to “Automation, sensing and robotics”