1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
5 `analogio` - Analog input control
6 =================================================
7 Read the SysFS ADC using IIO (Industrial Input/Output) and return the value
9 See `CircuitPython:analogio` in CircuitPython for more details.
10 * Author(s): Melissa LeBlanc-Williams
14 from adafruit_blinka import ContextManaged
17 from microcontroller.pin import analogIns
19 raise RuntimeError("No Analog Inputs defined for this board") from ImportError
22 class AnalogIn(ContextManaged):
23 """Analog Input Class"""
26 _sysfs_path = "/sys/bus/iio/devices/"
27 _device_path = "iio:device{}"
30 _channel_path = "in_voltage{}_raw"
31 _scale_path = "in_voltage_scale"
33 def __init__(self, adc_id):
34 """Instantiate an AnalogIn object and verify the sysfs IIO
35 corresponding to the specified channel and pin.
38 adc_id (int): Analog Input ID as defined in microcontroller.pin
41 AnalogIn: AnalogIn object.
44 TypeError: if `channel` or `pin` types are invalid.
45 ValueError: if AnalogIn channel does not exist.
57 def _open(self, adc_id):
59 for adcpair in analogIns:
60 if adcpair[0] == adc_id:
61 self._device = adcpair[1]
62 self._channel = adcpair[2]
64 if self._device is None:
65 raise RuntimeError("No AnalogIn device found for the given ID")
67 device_path = os.path.join(
68 self._sysfs_path, self._device_path.format(self._device)
71 if not os.path.isdir(device_path):
73 "AnalogIn device does not exist, check that the required modules are loaded."
78 """Read the ADC and return the value as an integer"""
81 self._device_path.format(self._device),
82 self._channel_path.format(self._channel),
85 with open(path, "r", encoding="utf-8") as analog_in:
86 return int(analog_in.read().strip())
88 # pylint: disable=no-self-use
90 def value(self, value):
91 # emulate what CircuitPython does
92 raise AttributeError("'AnalogIn' object has no attribute 'value'")
94 # pylint: enable=no-self-use