Analog input with ADS1115 in Python

Python has the pretty good library “WiringPi-Python“, but it depends on WiringPi2 for Raspberry Pi and cannot be installed automatically through pip. Here is a solution.

In my project I want to control a battery voltage and a charging state for my LiPo battery. Therefore I’ve added the ADS1115 board.

I’ve installed WiringPi2 for BPi and tried to read analog inputs through the gpio command line utility.

1
$ gpio -x ads1115:200:0x48 aread 200

The main disadvantage of this method for me is the default analog reading settings: 128 samples per second and +/-4.096V range (my battery voltage is 4.2V). You cannot change these setting in the command line utility.

1
2
3
4
5
6
7
8
9
10
$ sudo apt install swig
$ cd ~/
$ mkdir BPI-WiringPi2
$ cd BPI-WiringPi2
$ git clone https://github.com/BPI-SINOVOIP/BPI-WiringPi2.git
$ mkdir WiringPi-Python
$ cd WiringPi-Python
$ git clone https://github.com/WiringPi/WiringPi-Python.git
$ mv /home/pi/WiringPi-Python/WiringPi /home/pi/WiringPi-Python/WiringPi_old
$ nano setup.py

; change the string (add a new include directory)

 include_dirs=['WiringPi/wiringPi','WiringPi/devLib'],

to

include_dirs=['WiringPi/wiringPi','WiringPi/devLib', 'WiringPi/wiringPi/board'],
1
2
$ sudo ln -s /home/pi/BPI-WiringPi2 /home/pi/WiringPi-Python/WiringPi
$ sudo python3 setup.py install

The corresponding Python script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python3

import wiringpi

pin_base = 0x200
i2c_addr = 0x48

wiringpi.wiringPiSetup()
wiringpi.ads1115Setup(pin_base, i2c_addr)

# 0 - +/-6.144V range = Gain 2/3 = 1 bit = 1.875mV
# 1 - +/-4.096V range = Gain 1 = 1 bit = 1.25mV
wiringpi.digitalWrite(pin_base +0, 0)
# 0 - 8 samples/s
# 1 - 16 samples/s
# 4 -128 samples/s
# look at wiringPi\ads1115.h for other constants
wiringpi.digitalWrite(pin_base +1, 0)
# read pin 0
value = wiringpi.analogRead(pin_base + 0)
print("CH0: {}".format(value))
value = wiringpi.analogRead(pin_base + 1)
print("CH1: {}".format(value))
value = wiringpi.analogRead(pin_base + 2)
print("CH2: {}".format(value))
value = wiringpi.analogRead(pin_base + 3)
print("CH3: {}".format(value))

There are no comments.

Leave a Reply

Navigation