]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/sysfs_pwmout.py
Merge pull request #299 from caternuson/iss295
[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")
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         channel_path = os.path.join(
89             self._sysfs_path, self._channel_path.format(self._channel)
90         )
91         if not os.path.isdir(channel_path):
92             raise ValueError(
93                 "PWM channel does not exist, check that the required modules are loaded."
94             )
95
96         pin_path = os.path.join(channel_path, self._pin_path.format(self._pwmpin))
97         try:
98             with open(
99                 os.path.join(channel_path, self._unexport_path), "w"
100             ) as f_unexport:
101                 f_unexport.write("%d\n" % self._pwmpin)
102         except IOError as e:
103             pass  # not unusual, it doesnt already exist
104         try:
105             with open(os.path.join(channel_path, self._export_path), "w") 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         # self._set_enabled(False) # This line causes a write error when trying to enable
111
112         # Look up the period, for fast duty cycle updates
113         self._period = self._get_period()
114
115         # self.duty_cycle = 0  # This line causes a write error when trying to enable
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         if self._channel is not None:
127             self.duty_cycle = 0
128             try:
129                 channel_path = os.path.join(
130                     self._sysfs_path, self._channel_path.format(self._channel)
131                 )
132                 with open(
133                     os.path.join(channel_path, self._unexport_path), "w"
134                 ) as f_unexport:
135                     f_unexport.write("%d\n" % self._pwmpin)
136             except IOError as e:
137                 raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
138
139         self._channel = None
140         self._pwmpin = None
141
142     def _is_deinited(self):
143         if self._pwmpin is None:
144             raise ValueError(
145                 "Object has been deinitialize and can no longer "
146                 "be used. Create a new object."
147             )
148
149     def _write_pin_attr(self, attr, value):
150         # Make sure the pin is active
151         self._is_deinited()
152
153         path = os.path.join(
154             self._sysfs_path,
155             self._channel_path.format(self._channel),
156             self._pin_path.format(self._pwmpin),
157             attr,
158         )
159
160         with open(path, "w") as f_attr:
161             # print(value, path)
162             f_attr.write(value + "\n")
163
164     def _read_pin_attr(self, attr):
165         # Make sure the pin is active
166         self._is_deinited()
167
168         path = os.path.join(
169             self._sysfs_path,
170             self._channel_path.format(self._channel),
171             self._pin_path.format(self._pwmpin),
172             attr,
173         )
174
175         with open(path, "r") as f_attr:
176             return f_attr.read().strip()
177
178     # Mutable properties
179
180     def _get_period(self):
181         period_ns = self._read_pin_attr(self._pin_period_path)
182         try:
183             period_ns = int(period_ns)
184         except ValueError:
185             raise PWMError(None, 'Unknown period value: "%s"' % period_ns)
186
187         # Convert period from nanoseconds to seconds
188         period = period_ns / 1e9
189
190         # Update our cached period
191         self._period = period
192
193         return period
194
195     def _set_period(self, period):
196         if not isinstance(period, (int, float)):
197             raise TypeError("Invalid period type, should be int or float.")
198
199         # Convert period from seconds to integer nanoseconds
200         period_ns = int(period * 1e9)
201
202         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
203
204         # Update our cached period
205         self._period = float(period)
206
207     period = property(_get_period, _set_period)
208
209     """Get or set the PWM's output period in seconds.
210
211     Raises:
212         PWMError: if an I/O or OS error occurs.
213         TypeError: if value type is not int or float.
214
215     :type: int, float
216     """
217
218     def _get_duty_cycle(self):
219         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
220         try:
221             duty_cycle_ns = int(duty_cycle_ns)
222         except ValueError:
223             raise PWMError(None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns)
224
225         # Convert duty cycle from nanoseconds to seconds
226         duty_cycle = duty_cycle_ns / 1e9
227
228         # Convert duty cycle to ratio from 0.0 to 1.0
229         duty_cycle = duty_cycle / self._period
230
231         # convert to 16-bit
232         duty_cycle = int(duty_cycle * 65535)
233         return duty_cycle
234
235     def _set_duty_cycle(self, duty_cycle):
236         if not isinstance(duty_cycle, (int, float)):
237             raise TypeError("Invalid duty cycle type, should be int or float.")
238
239         # convert from 16-bit
240         duty_cycle /= 65535.0
241         if not 0.0 <= duty_cycle <= 1.0:
242             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
243
244         # Convert duty cycle from ratio to seconds
245         duty_cycle = duty_cycle * self._period
246
247         # Convert duty cycle from seconds to integer nanoseconds
248         duty_cycle_ns = int(duty_cycle * 1e9)
249
250         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
251
252     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
253     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
254
255     Raises:
256         PWMError: if an I/O or OS error occurs.
257         TypeError: if value type is not int or float.
258         ValueError: if value is out of bounds of 0.0 to 1.0.
259
260     :type: int, float
261     """
262
263     def _get_frequency(self):
264         return 1.0 / self._get_period()
265
266     def _set_frequency(self, frequency):
267         if not isinstance(frequency, (int, float)):
268             raise TypeError("Invalid frequency type, should be int or float.")
269
270         self._set_period(1.0 / frequency)
271
272     frequency = property(_get_frequency, _set_frequency)
273     """Get or set the PWM's output frequency in Hertz.
274
275     Raises:
276         PWMError: if an I/O or OS error occurs.
277         TypeError: if value type is not int or float.
278
279     :type: int, float
280     """
281
282     def _get_enabled(self):
283         enabled = self._read_pin_attr(self._pin_enable_path)
284
285         if enabled == "1":
286             return True
287         if enabled == "0":
288             return False
289
290         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
291
292     def _set_enabled(self, value):
293         """Get or set the PWM's output enabled state.
294
295         Raises:
296             PWMError: if an I/O or OS error occurs.
297             TypeError: if value type is not bool.
298
299         :type: bool
300         """
301         if not isinstance(value, bool):
302             raise TypeError("Invalid enabled type, should be string.")
303
304         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
305
306     # String representation
307
308     def __str__(self):
309         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
310             self._channel,
311             self._pin,
312             self.frequency,
313             self.duty_cycle * 100,
314         )