Links

Relay Toggle Sample

This sample demonstrates toggling the relays.

To run the sample:

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

Sample Code

Relay_Toggle.py
#!/usr/bin/env python3
#This sample demonstrates toggling the relays.
#Install Relay HAT 2 library with "pip3 install turta-relayhat2"
from time import sleep
from turta_relayhat2 import Turta_Relay
#Initialize
relay = Turta_Relay.RelayController()
try:
while 1:
#Toggle relays 1 to 5
for x in range(1, 6):
print("Toggling relay", x)
relay.toggle(x)
sleep(2.0)
#Toggle all relays
relay.toggle_all()
print("Toggling all relays")
sleep(2.0)
except KeyboardInterrupt:
print('Bye.')

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:
Toggling relay 1
Toggling relay 2
Toggling relay 3
Toggling relay 4
Toggling relay 5
Toggling all relays
To stop the Python script, just press CTRL + C.