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