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