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