Example Code for Raspberry Pi-Analog Read
Last revision 2026/01/06
Read analog signal input from Analog P0 using the expansion board's on-board STM32 12-bit ADC.
Hardware Preparation
- 1x DFR0604 IO Expansion HAT for Raspberry Pi, Purchase Link
- 1x Analog Sensor
- 1x Raspberry Pi
Software Preparation
- To use the analog and PWM ports in the board, download the driver library first. Press Ctrl+Alt+T to open the terminal, input the following command and hit Enter.
git clone https://github.com/DFRobot/DFRobot_RaspberryPi_Expansion_Board.git - Download the library and unzip the file. Input the following command into the terminal:
tar -xvzf DFRobot_RaspberryPi_Expansion_Board - Enter the directory of the uncompressed files:
cd DFRobot_RaspberryPi_Expansion_Board/raspberry/ - Use nano editor to create and edit the code file.
Wiring Diagram
- Plug the IO expansion board into Raspberry Pi.
- Connect an analog sensor to Analog P0.
Other Preparation Work
Create a file for the analog test (e.g., using nano: sudo nano analogTest.py) and add the sample code.
Sample Code
analogTest.py
# -*- coding:utf-8 -*-
# analogTest.py
import time
from DFRobot_RaspberryPi_Expansion_Board import DFRobot_Expansion_Board_IIC as Board
board = Board(1, 0x10) # Select i2c bus 1, set address to 0x10
if __name__ == "__main__":
while board.begin() != board.STA_OK: # Board begin and check the board's status
print("Board begin faild.")
time.sleep(1)
print("Board begin success.")
board.set_adc_enable()
while True:
print("Read part of channels.")
val0 = board.get_adc_value(board.A0) # channel A0 is readed
'''
val1 = board.get_adc_value(board.A1) # channel A1 is readed
val2 = board.get_adc_value(board.A2) # channel A2 is readed
val3 = board.get_adc_value(board.A3) # channel A3 is readed
'''
print("channel:A0, value:%d" %val0)
'''
print("channel:A1, value:%d" %val1)
print("channel:A2, value:%d" %val2)
print("channel:A3, value:%d" %val3)
'''
print("")
time.sleep(1)
The function board.get_adc_value() in the example is used to get the value of analog port, the pin selection list is shown below:
| Analog Pin of IO expansion board | Value of the parameter |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| All Pins | board.ALL |
Result
The terminal will output the analog value read from channel A0 every 1 second, e.g.
- "channel:A0, value: 512".
Additional Information
The IO expansion board comes with an on-board MCU STM32 that provides 12 bit ADC. The voltage of analog sensor will be input into the 12-bit ADC sent to Raspberry Pi via IIC when the analog data is converted into digital data, by which to allow Raspberry Pi to read values of analog sensor.
Was this article helpful?
