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