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