]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/am335x/sysfs_pwmout.py
reformatted with black
[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")
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)
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(e.errno, "Unexporting PWM pin: " + e.strerror)
139         except Exception as e:
140             # due to a race condition for which I have not yet been
141             # able to find the root cause, deinit() often fails
142             # but it does not effect future usage of the pwm pin
143             print(
144                 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
145                     self._channel, self._pwmpin, type(e).__name__
146                 )
147             )
148         finally:
149             self._channel = None
150             self._pwmpin = None
151         # pylint: enable=broad-except
152
153     def _is_deinited(self):
154         if self._pwmpin is None:
155             raise ValueError(
156                 "Object has been deinitialize and can no longer "
157                 "be used. Create a new object."
158             )
159
160     def _write_pin_attr(self, attr, value):
161         # Make sure the pin is active
162         self._is_deinited()
163
164         path = os.path.join(
165             self._sysfs_path,
166             self._channel_path.format(self._channel),
167             self._pin_path.format(self._channel, self._pwmpin),
168             attr,
169         )
170
171         with open(path, "w") as f_attr:
172             f_attr.write(value + "\n")
173
174     def _read_pin_attr(self, attr):
175         # Make sure the pin is active
176         self._is_deinited()
177
178         path = os.path.join(
179             self._sysfs_path,
180             self._channel_path.format(self._channel),
181             self._pin_path.format(self._channel, self._pwmpin),
182             attr,
183         )
184
185         with open(path, "r") as f_attr:
186             return f_attr.read().strip()
187
188     # Mutable properties
189
190     def _get_period(self):
191         period_ns = self._read_pin_attr(self._pin_period_path)
192         try:
193             period_ns = int(period_ns)
194         except ValueError:
195             raise PWMError(None, 'Unknown period value: "%s"' % period_ns)
196
197         # Convert period from nanoseconds to seconds
198         period = period_ns / 1e9
199
200         # Update our cached period
201         self._period = period
202
203         return period
204
205     def _set_period(self, period):
206         if not isinstance(period, (int, float)):
207             raise TypeError("Invalid period type, should be int or float.")
208
209         # Convert period from seconds to integer nanoseconds
210         period_ns = int(period * 1e9)
211
212         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
213
214         # Update our cached period
215         self._period = float(period)
216
217     period = property(_get_period, _set_period)
218
219     """Get or set the PWM's output period in seconds.
220
221     Raises:
222         PWMError: if an I/O or OS error occurs.
223         TypeError: if value type is not int or float.
224
225     :type: int, float
226     """
227
228     def _get_duty_cycle(self):
229         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
230         try:
231             duty_cycle_ns = int(duty_cycle_ns)
232         except ValueError:
233             raise PWMError(None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns)
234
235         # Convert duty cycle from nanoseconds to seconds
236         duty_cycle = duty_cycle_ns / 1e9
237
238         # Convert duty cycle to ratio from 0.0 to 1.0
239         duty_cycle = duty_cycle / self._period
240
241         # convert to 16-bit
242         duty_cycle = int(duty_cycle * 65535)
243         return duty_cycle
244
245     def _set_duty_cycle(self, duty_cycle):
246         if not isinstance(duty_cycle, (int, float)):
247             raise TypeError("Invalid duty cycle type, should be int or float.")
248
249         # convert from 16-bit
250         duty_cycle /= 65535.0
251         if not 0.0 <= duty_cycle <= 1.0:
252             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
253
254         # Convert duty cycle from ratio to seconds
255         duty_cycle = duty_cycle * self._period
256
257         # Convert duty cycle from seconds to integer nanoseconds
258         duty_cycle_ns = int(duty_cycle * 1e9)
259
260         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
261
262     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
263     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
264
265     Raises:
266         PWMError: if an I/O or OS error occurs.
267         TypeError: if value type is not int or float.
268         ValueError: if value is out of bounds of 0.0 to 1.0.
269
270     :type: int, float
271     """
272
273     def _get_frequency(self):
274         return 1.0 / self._get_period()
275
276     def _set_frequency(self, frequency):
277         if not isinstance(frequency, (int, float)):
278             raise TypeError("Invalid frequency type, should be int or float.")
279
280         self._set_period(1.0 / frequency)
281
282     frequency = property(_get_frequency, _set_frequency)
283     """Get or set the PWM's output frequency in Hertz.
284
285     Raises:
286         PWMError: if an I/O or OS error occurs.
287         TypeError: if value type is not int or float.
288
289     :type: int, float
290     """
291
292     def _get_enabled(self):
293         enabled = self._read_pin_attr(self._pin_enable_path)
294
295         if enabled == "1":
296             return True
297         if enabled == "0":
298             return False
299
300         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
301
302     def _set_enabled(self, value):
303         """Get or set the PWM's output enabled state.
304
305         Raises:
306             PWMError: if an I/O or OS error occurs.
307             TypeError: if value type is not bool.
308
309         :type: bool
310         """
311         if not isinstance(value, bool):
312             raise TypeError("Invalid enabled type, should be string.")
313
314         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
315
316     # String representation
317
318     def __str__(self):
319         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
320             self._channel,
321             self._pin,
322             self.frequency,
323             self.duty_cycle * 100,
324         )