Relay Preserve State Sample

This sample demonstrates state preserve functionality of the Relay HAT.

To run the sample:

  1. Copy the sample code to a folder on the Raspberry Pi.

  2. Open terminal, and then go to the folder you copied the sample.

  3. Run the sample with the following command:

python3 Relay_Preserve_State.py

Sample Code

Relay_Preserve_State.py
#!/usr/bin/env python3

#This sample demonstrates state preserve functionality of the Relay HAT.
#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(preserve_state = True)

#Read and increment the current relay state
state = relay.read_all() + 1
if (state == 32):
    state = 0

#Set the new relay state
relay.write_once(state)
print("Relay state is set")

Result

When you run the sample, the relay states are changed every two seconds. The example output should be like this:

Relay state is set

To stop the Python script, just press CTRL + C.

Last updated