itaki
itaki

Reputation: 39

How do you use a variable for pin number on an ADS1115 or other chips in python

I'm trying to understand how I can use a variable for specifying the pin number on an ADS1115. Generally one would read from the analog input by specifying something like this

import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

chan0 = AnalogIn(ADS.ADS1115(i2c, address = 0x48), ADS.P0)

What I want to do is use a variable for the "P0" part of it.

I can make it into an object like

p_object = ADS.P0
chan0 = AnalogIn(ADS.ADS1115(i2c, address = 0x48), p_object)

But I this doesn't help when I'm init ing my class.

Here is the full code I'm working with. I'm wanting to swap out the P0 with 'pin_number', which I understand is probably not a number, but is it a string?

class Voltage_sensor:
    '''
    Given an ADS1115 address and a corresponding pin number 
    will read voltage values from an AC715
    '''
    def __init__(self, address, pin_number) -> None:
        self.address = int(address)
        self.pin_number = pin_number
        try:
            self.chan = AnalogIn(ADS.ADS1115(i2c, address = self.address), ADS.P0) #<- wanting to replace this with the pin number.
            self.chan = AnalogIn(ADS.ADS1115(i2c, address = self.address), ADS.self.pin_number) # something like this, but this doesn't work
            print(f"Adding ADS1115 at address {hex(self.address)}")

        except:
            print(f"Voltage Sensor not found at {hex(self.address)}")

Upvotes: 1

Views: 506

Answers (1)

itaki
itaki

Reputation: 39

I ended up creating a dictionary of pins

self.pins = {'0' : ADS.P0, '1' : ADS.P1, '2' : ADS.P2, '3' : ADS.P3}

Then I just used an integer to call the corresponding pin.

Upvotes: 1

Related Questions