/ adafruit_pcf8591 / analog_in.py
analog_in.py
1 # SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 # Permission is hereby granted, free of charge, to any person obtaining a copy 6 # of this software and associated documentation files (the "Software"), to deal 7 # in the Software without restriction, including without limitation the rights 8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 # copies of the Software, and to permit persons to whom the Software is 10 # furnished to do so, subject to the following conditions: 11 # 12 # The above copyright notice and this permission notice shall be included in 13 # all copies or substantial portions of the Software. 14 # 15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 # THE SOFTWARE. 22 """ 23 `analog_in` 24 ============================== 25 AnalogIn for ADC readings. 26 27 * Author(s): Bryan Siepert, adpted from ADS1x15 by Carter Nelson 28 """ 29 30 31 class AnalogIn: 32 """AnalogIn Mock Implementation for ADC Reads.""" 33 34 def __init__(self, pcf, pin): 35 """AnalogIn 36 37 :param ads: The PCF8591 object. 38 :param ~digitalio.DigitalInOut pin: Required ADC channel pin. 39 40 """ 41 self._pcf = pcf 42 self._channel_number = pin 43 44 @property 45 def voltage(self): 46 """Returns the value of an ADC channel in volts as compared to the reference voltage.""" 47 48 if not self._pcf: 49 raise RuntimeError( 50 "Underlying ADC does not exist, likely due to callint `deinit`" 51 ) 52 raw_reading = self._pcf.read(self._channel_number) 53 return ((raw_reading << 8) / 65535) * self._pcf.reference_voltage 54 55 @property 56 def value(self): 57 """Returns the value of an ADC channel. 58 The value is scaled to a 16-bit integer from the native 8-bit value.""" 59 60 if not self._pcf: 61 raise RuntimeError( 62 "Underlying ADC does not exist, likely due to callint `deinit`" 63 ) 64 65 return self._pcf.read(self._channel_number) << 8 66 67 @property 68 def reference_voltage(self): 69 """The maximum voltage measurable (also known as the reference voltage) as a float in 70 Volts. Assumed to be 3.3V but can be overridden using the `PCF8591` constructor""" 71 if not self._pcf: 72 raise RuntimeError( 73 "Underlying ADC does not exist, likely due to callint `deinit`" 74 ) 75 return self._pcf.reference_voltage 76 77 def deinit(self): 78 """Release the reference to the PCF8591. Create a new AnalogIn to use it again.""" 79 self._pcf = None