Links

Relay LED Control Sample

This sample demonstrates turning relay indicator LEDs on and off.

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_LED_Control.py

Sample Code

Relay_LED_Control.py
#!/usr/bin/env python3
#This sample demonstrates turning relay indicator LEDs on and off.
#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(leds_state = True)
try:
while 1:
#Toggle relays 1 to 5
for x in range(1, 6):
print("Toggling relay", x)
relay.toggle(x)
sleep(0.5)
#Turn LEDs off
print("Setting LEDs off")
relay.set_leds(False)
sleep(2.0)
#Turn LEDs on
print("Setting LEDs on")
relay.set_leds(True)
sleep(1.0)
#Turn off all relays
relay.write_all(False)
print("Turn off all relays")
sleep(1.0)
except KeyboardInterrupt:
print('Bye.')

Result

When you run the sample, the relays invert their states sequentially. Then, it turns off all indicator LEDs, while relays are on. Then, the sample code turns indicator LEDs on and turns off all the relays. The example output should be like this:
Toggling relay 1
Toggling relay 2
Toggling relay 3
Toggling relay 4
Toggling relay 5
Setting LEDs off
Setting LEDs on
Turn off all relays
To stop the Python script, just press CTRL + C.