Copy the sample code to a folder on the Raspberry Pi.
Open terminal, and then go to the folder you copied the sample.
Run the sample with the following command:
python3 Relay_Control.py
Sample Code
Relay_Control.py
#!/usr/bin/env python3#This sample demonstrates turning relays on and off.#Install Relay HAT 2 library with "pip3 install turta-relayhat2"from time import sleepfrom turta_relayhat2 import Turta_Relay#Initializerelay = Turta_Relay.RelayController()try:while1:#Turn on relay 1 relay.write(1, True)print("Relay 1 state: "+ ("On"if relay.read(1) else"Off"))sleep(1.0)#Turn on relay 2 relay.write(2, True)print("Relay 2 state: "+ ("On"if relay.read(2) else"Off"))sleep(1.0)#Turn on relay 3 relay.write(3, True)print("Relay 3 state: "+ ("On"if relay.read(3) else"Off"))sleep(1.0)#Turn on relay 4 relay.write(4, True)print("Relay 4 state: "+ ("On"if relay.read(4) else"Off"))sleep(1.0)#Turn on relay 5 relay.write(5, True)print("Relay 5 state: "+ ("On"if relay.read(5) else"Off"))sleep(1.0)#Turn off relay 1 relay.write(1, False)print("Relay 1 state: "+ ("On"if relay.read(1) else"Off"))sleep(1.0)#Turn off relay 2 relay.write(2, False)print("Relay 2 state: "+ ("On"if relay.read(2) else"Off"))sleep(1.0)#Turn off relay 3 relay.write(3, False)print("Relay 3 state: "+ ("On"if relay.read(3) else"Off"))sleep(1.0)#Turn off relay 4 relay.write(4, False)print("Relay 4 state: "+ ("On"if relay.read(4) else"Off"))sleep(1.0)#Turn off relay 5 relay.write(5, False)print("Relay 5 state: "+ ("On"if relay.read(5) else"Off"))sleep(1.0)#Turn on all relays relay.write_all(True)print("Turn on all relays")sleep(1.0)#Turn off all relays relay.write_all(False)print("Turn off all relays")sleep(1.0)exceptKeyboardInterrupt:print('Bye.')
Result
When you run the sample, the relays turn on one after another and then turn off in the same order. The application also writes the relay states to the terminal. The example output should be like this:
Relay 1 state: On
Relay 2 state: On
Relay 3 state: On
Relay 4 state: On
Relay 5 state: On
Relay 1 state: Off
Relay 2 state: Off
Relay 3 state: Off
Relay 4 state: Off
Relay 5 state: Off
Turn on all relays
Turn off all relays