PI-SPI-2AO Python Code Samples

2 Channel Analog Output 4-20 mA Module

The Pi-SPI-2AO is a 2 channel Analog Output Module that communicates with the Raspberry Pi via the SPI bus.

This module has 2 chip selects:

Default Chip Select is GPIO4      (Errata: The Revision A PCB has this marked as GPIO7)
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 - Basic Write D/A Counts

In this code example:

1. We import the Widgetlords library
2. Initialize the library
3. Write Channel 0 and Channel 1 D/A Counts

The DAC used a 12 bit converter with a 3.3V Reference. The output circuit has been optimized to provide 4 mA at 745 D/A counts and 20 mA at 3723 D/A counts.(For the VDC outputs the circuit has been optiomized for 2 and 10 VDC output)

Please note the values are approximate and may vary from module to module and from channel to channel.

from time import sleep
from widgetlords.pi_spi import *

init()
outputs = Mod2AO()

while True:
    outputs.write_single(0, 745)
    outputs.write_single(1, 3723)
    sleep(2)
    
    outputs.write_single(0, 3733)
    outputs.write_single(1, 745)
    sleep(2)

 

Sample 2 - Write D/A Counts 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

outputs = Mod2AO()

OR

outputs = Mod2AO(False)

To use the alternate chip select:

outputs = Mod2Ao(True)

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

from time import sleep
from widgetlords.pi_spi import *

init()
outputs = Mod2AO(True)

while True:
    outputs.write_single(0, 745)
    outputs.write_single(1, 3723)
    sleep(2)
    
    outputs.write_single(0, 3733)
    outputs.write_single(1, 745)
    sleep(2)