Relay Controller

This documentation includes installation guidelines and sample code for your hardware.

Python Library

Turta_RelayController library is responsible for controlling onboard relays.

To install the library from the (PyPI) Python Package Index, enter the following command to the console.

pip install turta-iothat

Add the following statement to the top of your Python code.

from turta_iothat import Turta_RelayController

Then, create an instance of the Turta_RelayController class.

rc = Turta_RelayController.RelayController()

Now you're ready to access the library by calling the rc instance.

Initialization

The library automatically initializes the required components when its instance is being created, so there is no need to do a manual initialization.

Basic Members

Set Relay

Turns the desired relay on or off.

set_relay(ch, st)
  • Parameters

    • Int ch: Relay channel. 1 or 2.

    • Bool st: Relay state. True or False.

  • Returns

    • None

Read Relay State

Reads the desired relay state.

read_relay_state(ch)
  • Parameters

    • Int ch: Relay channel. 1 or 2.

  • Returns

    • Bool: Relay state. True or False.

Samples

You can copy the example code from https://github.com/Turta-io/IoTHAT/tree/master/Samples/Raspbian/Python address, and then copy it to the Raspberry Pi. There is one example of this library.

Relay Controller Sample App

This application demonstrates relay functions. It turns relays on and off in a loop.

To run the example:

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

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

  3. Run the sample with the following command:

python RelayControllerSampleApp.py

Sample Code

RelayControllerSampleApp.py
import time
from turta_iothat import Turta_RelayController
#Install IoT HAT library with "pip install turta-iothat"

#Initialize
rc = Turta_RelayController.RelayController()

try:
    while 1:
        #Toggle relay 1
        rc.set_relay(1, not rc.read_relay_state(1))
        print("Relay 1 state: " + ("On" if rc.read_relay_state(1) else "Off"))
        time.sleep(5.0)

        #Toggle relay 2
        rc.set_relay(2, not rc.read_relay_state(2))
        print("Relay 2 state: " + ("On" if rc.read_relay_state(2) else "Off"))
        time.sleep(5.0)

except KeyboardInterrupt:
    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 1 state: Off
Relay 2 state: Off

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

Last updated