Relay Toggle Sample
This sample demonstrates toggling the 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 relays.
4
#Install Relay HAT 2 library with "pip3 install turta-relayhat2"
5
6
from time import sleep
7
from turta_relayhat2 import Turta_Relay
8
9
#Initialize
10
relay = Turta_Relay.RelayController()
11
12
try:
13
while 1:
14
#Toggle relays 1 to 5
15
for x in range(1, 6):
16
print("Toggling relay", x)
17
relay.toggle(x)
18
sleep(2.0)
19
20
#Toggle all relays
21
relay.toggle_all()
22
print("Toggling all relays")
23
sleep(2.0)
24
25
except KeyboardInterrupt:
26
print('Bye.')
Copied!

Result

When you run the sample, the relays invert their states sequentially. The application also writes the relay states to the terminal. The example output should be like this:
1
Toggling relay 1
2
Toggling relay 2
3
Toggling relay 3
4
Toggling relay 4
5
Toggling relay 5
6
Toggling all relays
Copied!
To stop the Python script, just press CTRL + C.
Last modified 2yr ago
Copy link