]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/sysfs_pwmout.py
added support for I2C bus 0,1,2 that where missing for the OPI zero2W implementation
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / generic_linux / sysfs_pwmout.py
1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4 """
5 Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
6 Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
7 License: MIT
8 """
9
10 import os
11 from time import sleep
12 from errno import EACCES
13
14 try:
15     from microcontroller.pin import pwmOuts
16 except ImportError:
17     raise RuntimeError("No PWM outputs defined for this board") from ImportError
18
19
20 # pylint: disable=unnecessary-pass
21 class PWMError(IOError):
22     """Base class for PWM errors."""
23
24     pass
25
26
27 # pylint: enable=unnecessary-pass
28
29
30 class PWMOut:
31     """Pulse Width Modulation Output Class"""
32
33     # Number of retries to check for successful PWM export on open
34     PWM_STAT_RETRIES = 10
35     # Delay between check for scucessful PWM export on open (100ms)
36     PWM_STAT_DELAY = 0.1
37
38     # Sysfs paths
39     _sysfs_path = "/sys/class/pwm/"
40     _channel_path = "pwmchip{}"
41
42     # Channel paths
43     _export_path = "export"
44     _unexport_path = "unexport"
45     _pin_path = "pwm{}"
46
47     # Pin attribute paths
48     _pin_period_path = "period"
49     _pin_duty_cycle_path = "duty_cycle"
50     _pin_polarity_path = "polarity"
51     _pin_enable_path = "enable"
52
53     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
54         """Instantiate a PWM object and open the sysfs PWM corresponding to the
55         specified channel and pin.
56
57         Args:
58             pin (Pin): CircuitPython Pin object to output to
59             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
60             frequency (int) : target frequency in Hertz (32-bit)
61             variable_frequency (bool) : True if the frequency will change over time
62
63         Returns:
64             PWMOut: PWMOut object.
65
66         Raises:
67             PWMError: if an I/O or OS error occurs.
68             TypeError: if `channel` or `pin` types are invalid.
69             ValueError: if PWM channel does not exist.
70
71         """
72
73         self._pwmpin = None
74         self._channel = None
75         self._period = 0
76         self._open(pin, duty_cycle, frequency, variable_frequency)
77
78     def __del__(self):
79         self.deinit()
80
81     def __enter__(self):
82         return self
83
84     def __exit__(self, t, value, traceback):
85         self.deinit()
86
87     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
88         self._channel = None
89         for pwmpair in pwmOuts:
90             if pwmpair[1] == pin:
91                 self._channel = pwmpair[0][0]
92                 self._pwmpin = pwmpair[0][1]
93
94         self._pin = pin
95         if self._channel is None:
96             raise RuntimeError("No PWM channel found for this Pin")
97
98         if variable_frequency:
99             print("Variable Frequency is not supported, continuing without it...")
100
101         channel_path = os.path.join(
102             self._sysfs_path, self._channel_path.format(self._channel)
103         )
104         if not os.path.isdir(channel_path):
105             raise ValueError(
106                 "PWM channel does not exist, check that the required modules are loaded."
107             )
108
109         try:
110             with open(
111                 os.path.join(channel_path, self._unexport_path), "w", encoding="utf-8"
112             ) as f_unexport:
113                 f_unexport.write("%d\n" % self._pwmpin)
114         except IOError:
115             pass  # not unusual, it doesnt already exist
116         try:
117             with open(
118                 os.path.join(channel_path, self._export_path), "w", encoding="utf-8"
119             ) as f_export:
120                 f_export.write("%d\n" % self._pwmpin)
121         except IOError as e:
122             raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
123
124         # Loop until 'period' is writable, because application of udev rules
125         # after the above pin export is asynchronous.
126         # Without this loop, the following properties may not be writable yet.
127         for i in range(PWMOut.PWM_STAT_RETRIES):
128             try:
129                 with open(
130                     os.path.join(
131                         channel_path, self._pin_path.format(self._pwmpin), "period"
132                     ),
133                     "w",
134                     encoding="utf-8",
135                 ):
136                     break
137             except IOError as e:
138                 if e.errno != EACCES or (
139                     e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
140                 ):
141                     raise PWMError(e.errno, "Opening PWM period: " + e.strerror) from e
142             sleep(PWMOut.PWM_STAT_DELAY)
143
144         # self._set_enabled(False) # This line causes a write error when trying to enable
145
146         # Look up the period, for fast duty cycle updates
147         self._period = self._get_period()
148
149         # self.duty_cycle = 0  # This line causes a write error when trying to enable
150
151         # set frequency
152         self.frequency = freq
153         # set duty
154         self.duty_cycle = duty
155
156         self._set_enabled(True)
157
158     def deinit(self):
159         """Deinit the sysfs PWM."""
160         if self._channel is not None:
161             try:
162                 channel_path = os.path.join(
163                     self._sysfs_path, self._channel_path.format(self._channel)
164                 )
165                 with open(
166                     os.path.join(channel_path, self._unexport_path),
167                     "w",
168                     encoding="utf-8",
169                 ) as f_unexport:
170                     f_unexport.write("%d\n" % self._pwmpin)
171             except IOError as e:
172                 raise PWMError(
173                     e.errno, "Unexporting PWM pin: " + e.strerror
174                 ) from IOError
175
176         self._channel = None
177         self._pwmpin = None
178
179     def _is_deinited(self):
180         if self._pwmpin is None:
181             raise ValueError(
182                 "Object has been deinitialize and can no longer "
183                 "be used. Create a new object."
184             )
185
186     def _write_pin_attr(self, attr, value):
187         # Make sure the pin is active
188         self._is_deinited()
189
190         path = os.path.join(
191             self._sysfs_path,
192             self._channel_path.format(self._channel),
193             self._pin_path.format(self._pwmpin),
194             attr,
195         )
196
197         with open(path, "w", encoding="utf-8") as f_attr:
198             # print(value, path)
199             f_attr.write(value + "\n")
200
201     def _read_pin_attr(self, attr):
202         # Make sure the pin is active
203         self._is_deinited()
204
205         path = os.path.join(
206             self._sysfs_path,
207             self._channel_path.format(self._channel),
208             self._pin_path.format(self._pwmpin),
209             attr,
210         )
211
212         with open(path, "r", encoding="utf-8") as f_attr:
213             return f_attr.read().strip()
214
215     # Mutable properties
216
217     def _get_period(self):
218         period_ns = self._read_pin_attr(self._pin_period_path)
219         try:
220             period_ns = int(period_ns)
221         except ValueError:
222             raise PWMError(
223                 None, 'Unknown period value: "%s"' % period_ns
224             ) from ValueError
225
226         # Convert period from nanoseconds to seconds
227         period = period_ns / 1e9
228
229         # Update our cached period
230         self._period = period
231
232         return period
233
234     def _set_period(self, period):
235         if not isinstance(period, (int, float)):
236             raise TypeError("Invalid period type, should be int or float.")
237
238         # Convert period from seconds to integer nanoseconds
239         period_ns = int(period * 1e9)
240
241         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
242
243         # Update our cached period
244         self._period = float(period)
245
246     period = property(_get_period, _set_period)
247
248     """Get or set the PWM's output period in seconds.
249
250     Raises:
251         PWMError: if an I/O or OS error occurs.
252         TypeError: if value type is not int or float.
253
254     :type: int, float
255     """
256
257     def _get_duty_cycle(self):
258         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
259         try:
260             duty_cycle_ns = int(duty_cycle_ns)
261         except ValueError:
262             raise PWMError(
263                 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
264             ) from ValueError
265
266         # Convert duty cycle from nanoseconds to seconds
267         duty_cycle = duty_cycle_ns / 1e9
268
269         # Convert duty cycle to ratio from 0.0 to 1.0
270         duty_cycle = duty_cycle / self._period
271
272         # convert to 16-bit
273         duty_cycle = int(duty_cycle * 65535)
274         return duty_cycle
275
276     def _set_duty_cycle(self, duty_cycle):
277         if not isinstance(duty_cycle, (int, float)):
278             raise TypeError("Invalid duty cycle type, should be int or float.")
279
280         # convert from 16-bit
281         duty_cycle /= 65535.0
282         if not 0.0 <= duty_cycle <= 1.0:
283             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
284
285         # Convert duty cycle from ratio to seconds
286         duty_cycle = duty_cycle * self._period
287
288         # Convert duty cycle from seconds to integer nanoseconds
289         duty_cycle_ns = int(duty_cycle * 1e9)
290
291         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
292
293     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
294     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
295
296     Raises:
297         PWMError: if an I/O or OS error occurs.
298         TypeError: if value type is not int or float.
299         ValueError: if value is out of bounds of 0.0 to 1.0.
300
301     :type: int, float
302     """
303
304     def _get_frequency(self):
305         return 1.0 / self._get_period()
306
307     def _set_frequency(self, frequency):
308         if not isinstance(frequency, (int, float)):
309             raise TypeError("Invalid frequency type, should be int or float.")
310
311         self._set_period(1.0 / frequency)
312
313     frequency = property(_get_frequency, _set_frequency)
314     """Get or set the PWM's output frequency in Hertz.
315
316     Raises:
317         PWMError: if an I/O or OS error occurs.
318         TypeError: if value type is not int or float.
319
320     :type: int, float
321     """
322
323     def _get_enabled(self):
324         enabled = self._read_pin_attr(self._pin_enable_path)
325
326         if enabled == "1":
327             return True
328         if enabled == "0":
329             return False
330
331         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
332
333     def _set_enabled(self, value):
334         """Get or set the PWM's output enabled state.
335
336         Raises:
337             PWMError: if an I/O or OS error occurs.
338             TypeError: if value type is not bool.
339
340         :type: bool
341         """
342         if not isinstance(value, bool):
343             raise TypeError("Invalid enabled type, should be string.")
344
345         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
346
347     # String representation
348
349     def __str__(self):
350         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
351             self._channel,
352             self._pin,
353             self.frequency,
354             self.duty_cycle * 100,
355         )