# The MIT License (MIT)
#
# Copyright (c) 2018 Carter Nelson for Adafruit
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`analog_in`
==============================
AnalogIn for single-ended and
differential ADC readings.
* Author(s): Carter Nelson, adapted from MCP3xxx original by Brent Rubell
"""
# pylint: disable=bad-whitespace
_ADS1X15_DIFF_CHANNELS = {
(0, 1): 0,
(0, 3): 1,
(1, 3): 2,
(2, 3): 3
}
_ADS1X15_PGA_RANGE = {
2/3: 6.144,
1: 4.096,
2: 2.048,
4: 1.024,
8: 0.512,
16: 0.256
}
# pylint: enable=bad-whitespace
[docs]class AnalogIn():
"""AnalogIn Mock Implementation for ADC Reads."""
def __init__(self, ads, positive_pin, negative_pin=None):
"""AnalogIn
:param ads: The ads object.
:param ~digitalio.DigitalInOut positive_pin: Required pin for single-ended.
:param ~digitalio.DigitalInOut negative_pin: Optional pin for differential reads.
"""
self._ads = ads
self._pin_setting = positive_pin
self._negative_pin = negative_pin
self.is_differential = False
if negative_pin is not None:
pins = (self._pin_setting, self._negative_pin)
if pins not in _ADS1X15_DIFF_CHANNELS:
raise ValueError("Differential channels must be one of: {}"
.format(list(_ADS1X15_DIFF_CHANNELS.keys())))
self._pin_setting = _ADS1X15_DIFF_CHANNELS[pins]
self.is_differential = True
@property
def value(self):
"""Returns the value of an ADC pin as an integer."""
return self._ads.read(self._pin_setting, is_differential=self.is_differential)
@property
def voltage(self):
"""Returns the voltage from the ADC pin as a floating point value."""
raw = self.value
volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1))
return volts