Relay Toggle Sample
This sample demonstrates toggling the solid state relays.

To run the sample:

    2.
    Copy the sample code to a folder on the Raspberry Pi.
    3.
    Open terminal, and then go to the folder you copied the sample.
    4.
    Run the sample with the following command:
1
python3 Relay_Toggle.py
Copied!

Sample Code

Relay_Toggle.py
1
#!/usr/bin/env python3
2
3
#This sample demonstrates toggling the solid state relays.
4
#Do not toggle dc motors or solenoids frequently.
5
#Install IoT HAT 3 library with "pip3 install turta-iothat3"
6
7
from time import sleep
8
from turta_iothat3 import Turta_Relay
9
10
#Initialize
11
relay = Turta_Relay.RelayController()
12
13
try:
14
while True:
15
#Option one: Toggle the relays with 'write' method
16
17
#Turn relay 1 on
18
relay.write(1, True)
19
20
#Print relay 1 state
21
print("Relay 1 State...: " + ("On." if relay.read(1) else "Off."))
22
23
#Wait
24
sleep(2.0)
25
26
#Turn relay 1 off
27
relay.write(1, False)
28
29
#Print relay 1 state
30
print("Relay 1 State...: " + ("On." if relay.read(1) else "Off."))
31
32
#Wait
33
sleep(2.0)
34
35
#Option two: Toggle the relays with 'toggle' method
36
#Each method call inverts the relay's state
37
38
#Toggle relay 2
39
relay.toggle(2)
40
41
#Print relay 2 state
42
print("Relay 2 State...: " + ("On." if relay.read(2) else "Off."))
43
44
#Wait
45
sleep(2.0)
46
47
#Exit on CTRL+C
48
except KeyboardInterrupt:
49
print('Bye.')
Copied!

Result

When you run the sample, it switches the relays and prints their states. The example output should be like this:
1
Relay 1 State...: On.
2
Relay 1 State...: Off.
3
Relay 2 State...: On.
4
Relay 1 State...: On.
5
Relay 1 State...: Off.
6
Relay 2 State...: Off.
Copied!
To stop the Python script, just press CTRL + C.
Last modified 2yr ago
Copy link