1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
5 `analogio` - Analog output control
6 =================================================
7 Write the SysFS DAC using IIO (Industrial Input/Output)
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 analogOuts
19 raise RuntimeError("No Analog Outputs defined for this board") from ImportError
22 class AnalogOut(ContextManaged):
23 """Analog Output Class"""
26 _sysfs_path = "/sys/bus/iio/devices/"
27 _device_path = "iio:device{}"
30 _channel_path = "out_voltage{}_raw"
31 _scale_path = "out_voltage_scale"
33 def __init__(self, dac_id):
34 """Instantiate an AnalogOut object and verify the sysfs IIO
35 corresponding to the specified channel and pin.
38 dac_id (int): Analog Output ID as defined in microcontroller.pin
41 AnalogOut: AnalogOut object.
44 TypeError: if `channel` or `pin` types are invalid.
45 ValueError: if AnalogOut channel does not exist.
57 def _open(self, dac_id):
59 for dacpair in analogOuts:
60 if dacpair[0] == dac_id:
61 self._device = dacpair[1]
62 self._channel = dacpair[2]
64 if self._device is None:
65 raise RuntimeError("No AnalogOut 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 "AnalogOut device does not exist, check that the required modules are loaded."
78 """Return an error. This is output only."""
79 # emulate what CircuitPython does
80 raise AttributeError("unreadable attribute")
83 def value(self, value):
84 """Write to the DAC"""
87 self._device_path.format(self._device),
88 self._channel_path.format(self._channel),
91 with open(path, "w", encoding="utf-8") as analog_out:
92 return analog_out.write(value + "\n")