PI-SPI-DIN-4KO Python Code Samples
4 Channel Relay Output Module
The PI-SPI-DIN-4KO is a 4 channel Relay Output Module that communicates with the Raspberry Pi via the SPI bus.
This module has 5 chip selects: CE0 thru CE4
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=vpe-2701c
Sample 1 - Basic Write Relay Output
In this code example:
1. We import the Widgetlords library
2. Initialize the library
3. Write 4 Relay Channels using Chip Select 3
from time import sleep
from widgetlords.pi_spi_din import *
init()
relays = Mod4KO(ChipEnable.CE3)
while True:
relays.write(0x05)
sleep(1)
relays.write(0x0A)
sleep(1)
Sample 2 - Write Single Relay Output
This code example will write a single relay output where 0 is K1 and 3 is K4
from time import sleep
from widgetlords.pi_spi_din import *
init()
relays = Mod4KO(ChipEnable.CE3)
while True:
relays.write_single(0,1)
sleep(1)
relays.write_single(1,1)
sleep(1)
relays.write_single(2,1)
sleep(1)
relays.write_single(3,1)
sleep(1)
Sample 3 - Write Relay Outputs from a Different Address
The PI-SPI-4KO uses the Microchip MCP23S08 GPIO expander, which has 4 different address selections. The default address is 0 where the jumpers labelled J3-A0 and J3-A1 are installed. Up to 4 modules or 16 relay outputs can be written simultaneously with 1 chip select.
The default is address 0:
relays = Mod4KO(ChipEnable.CE3)
To change the addressing to address 1 J3-A0 removed and J3-A1 installed, the address is selected as shown:
relays = Mod4KO(ChipEnable.CE3,1)
This code example will relays from Address = 1
from time import sleep
from widgetlords.pi_spi_din import *
init()
relays = Mod4KO(ChipEnable.CE3,1)
while True:
relays.write(0x0a)
sleep(1)
relays.write(0x05)
sleep(1)
Sample 4 - Write Relay Outputs from Alternate Chip Select
Every Pi-SPI-DIN module has 5 Chip Selects allowing up to 5 different modules to be used together.
This code example shows how to enable the alternate chip select. NOTE: this works for all code examples as well!
Each module type has the Chip Selects defaulted to the following GPIO Pins:
CE4 = GPIO18
CE3 = GPIO23
CE2 = GPIO24
CE0 = GPIO8
CE1 = GPIO7
Here is the complete sample code example using CE4 as the Chip Select
from time import sleep
from widgetlords.pi_spi_din import *
init()
relays = Mod4KO(ChipEnable.CE4)
while True:
relays.write(0x0a)
sleep(1)
relays.write(0x05)
sleep(1)