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