This demo shows how to read from the ADC input channels on the Expander Pi
With your Raspberry Pi switched off, install the Expander Pi on the Raspberry Pi GPIO port and insert a CR2032 coin battery into the battery holder. Using the Expander Pi without a battery installed may damage the Expander Pi and will stop it from appearing on the I2C bus.
We will use the AB Electronics Python library to talk to the Expander Pi. To download the library, visit our Python Library and Demos knowledge base article.
You must enable I2C and SPI on your Raspberry Pi; see our other tutorial on I2C: I2C, SMBus and Raspbian Linux and SPI: SPI and Raspbian Linux on a Raspberry Pi.
The AB Electronics Python library uses another library called python3-smbus; you can install it using apt-get with the following commands.
sudo apt-get update sudo apt-get install python3-smbus
With the libraries installed and the Raspberry Pi configured to use i2c, we can begin building our project.
We will create a new Python program file called demo-adcread.py for this tutorial. You can use your favourite text editor to write the program. You can find a complete example of demo-adcread.py in the ABElectronics_Python_Libraries/ExpanderPi/demos folder.
At the top of your program, you must import the ADC class from the ExpanderPi library and the time library.
from ExpanderPi import ADC import time
Now, we create an instance of the ADC class.
adc = ADC()
We need to set the reference voltage. This should be set to the exact voltage measured on the Expander Pi Vref pin.
adc.set_adc_refvoltage(4.096)
Now, we create a loop to read the voltage from channel 1 in single-ended mode and display it on the screen.
while True: # read the voltage from channel 1 in single ended mode and display on the screen print adc.read_adc_voltage(1,0) time.sleep(0.5)
To run the demo in a console window, enter the following:
python3 demo_adcread.py
The complete code for this demo is as follows:
#!/usr/bin/env python from ExpanderPi import ADC import time """ ================================================ ABElectronics Expander Pi | ADC Read Demo run with: python3 demo_adcread.py ================================================ this demo reads the voltage from channel 1 on the ADC inputs """ adc = ADC() # create an instance of the ADC # set the reference voltage. this should be set to the exact voltage # measured on the Expander Pi Vref pin. adc.set_adc_refvoltage(4.096) while True: # read the voltage from channel 1 in single ended mode and display on the screen print(adc.read_adc_voltage(1,0)) time.sleep(0.5)