PI-SPI-8KO Python Code Samples

8 Channel Relay Output Module

The Pi-SPI-8KO is an 8 channel Relay Output Module that communicates with the Raspberry Pi via the SPI bus. Outputs 1 and 2 have an Omron 10A SPDT relay, outputs 3 thru 8 are logic level outputs (0V and 3.3V) to drive relay switches.

 

This module has 2 chip selects:

Default Chip Select is GPIO8
Alternate Chip Select is GPIO22

The chip select operation during SPI communication is handled directly by the libwidgetlords library and kernel.

To run the sample Python code examples, please install the Widgetlords libwidgetlords libraries as explained in:

Getting Started with PI-SPI Libraries

NOTE: All of the sample code examples are for Python 3.

Please ensure you have the dtoverlay set correctly in the /boot/config.txt file:

dtoverlay=pi-spi

Sample 1 - Write 8 Channels Relay Status

In this code example:

1. We import the Widgetlords library
2. Initialize the library
3. Write 8 channels of relay information as a single byte - LSB is relay 1, MSB is relay 8.

from time import sleep
from widgetlords.pi_spi import *

init()
relays = Mod8KO()

while True:
    relays.write(0xaa)
    sleep(1)
    relays.write(0x55)
    sleep(1)

 

Sample 2 - Write 8 Channels Relay Status from Alternate Chip Select

Every Pi-SPI module has a dedicated GPIO pin for it's SPI Chip Select and an Alternate chip select to allow two modules of the same type to be used together.

This code example shows how to enable the alternate chip select. NOTE: this works for all following code examples as well!

Each module type has the Chip Select defaulted to it's unique GPIO Pin as follows:

PI-SPI-8AI = GPIO7 
PI-SPI-8KO = GPIO8
PI-SPI-8DI = GPIO17
PI-SPI-2AO = GPIO4

For each module, the alternate Chip Select is GPIO22

The module initialization line for the default Chip Select is

relays = Mod8KO()

OR

relays = Mod8KO(False)

To use the alternate chip select:

relays = Mod8KO(True)

Here is the complete sample code example using the alternate chip select:

from time import sleep
from widgetlords.pi_spi import *

init()
relays = Mod8KO(True)

while True:
    relays.write(0xaa)
    sleep(1)
    relays.write(0x55)
    sleep(1)

 

Sample 3 - Write Single Channel Relay Status

In this code example, a single relay status is written without affecting the other relays. Please note: during the start of the program and initialization, all relay status values are set to OFF (0).

from time import sleep
from widgetlords.pi_spi import *

init()
relays = Mod8KO()

while True:
    relays.write_single(0,1)
    sleep(1)
    relays.write_single(1,1)
    sleep(1)