]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/sysfs_pwmout.py
3ce2ee3a195f2f1f3b26fb35b2af5976c9905bf6
[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.deinit()
59
60     def __enter__(self):
61         return self
62
63     def __exit__(self, t, value, traceback):
64         self.deinit()
65
66     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
67         self._channel = None
68         for pwmpair in pwmOuts:
69             if pwmpair[1] == pin:
70                 self._channel = pwmpair[0][0]
71                 self._pwmpin = pwmpair[0][1]
72
73         self._pin = pin
74         if self._channel is None:
75             raise RuntimeError("No PWM channel found for this Pin")
76
77         channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
78         if not os.path.isdir(channel_path):
79             raise ValueError("PWM channel does not exist, check that the required modules are loaded.")
80
81         pin_path = os.path.join(channel_path, self._pin_path.format(self._pwmpin))
82         try:
83             with open(os.path.join(channel_path, self._unexport_path), "w") as f_unexport:
84                 f_unexport.write("%d\n" % self._pwmpin)
85         except IOError as e:
86             pass # not unusual, it doesnt already exist
87         try:
88             with open(os.path.join(channel_path, self._export_path), "w") as f_export:
89                 f_export.write("%d\n" % self._pwmpin)
90         except IOError as e:
91             raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror)
92
93         #self._set_enabled(False) # This line causes a write error when trying to enable
94
95         # Look up the period, for fast duty cycle updates
96         self._period = self._get_period()
97
98         #self.duty_cycle = 0  # This line causes a write error when trying to enable
99
100         # set frequency
101         self.frequency = freq
102         # set duty
103         self.duty_cycle = duty
104
105         self._set_enabled(True)
106
107     def deinit(self):
108         """Deinit the sysfs PWM."""
109         if self._channel is not None:
110             self.duty_cycle = 0
111             try:
112                 channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
113                 with open(os.path.join(channel_path, self._unexport_path), "w") as f_unexport:
114                     f_unexport.write("%d\n" % self._pwmpin)
115             except IOError as e:
116                 raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
117
118         self._channel = None
119         self._pwmpin = None
120
121     def _is_deinited(self):
122         if self._pwmpin is None:
123             raise ValueError("Object has been deinitialize and can no longer "
124                              "be used. Create a new object.")
125
126     def _write_pin_attr(self, attr, value):
127         # Make sure the pin is active
128         self._is_deinited()
129
130         path = os.path.join(
131             self._sysfs_path,
132             self._channel_path.format(self._channel),
133             self._pin_path.format(self._pwmpin),
134             attr)
135
136         with open(path, 'w') as f_attr:
137             #print(value, path)
138             f_attr.write(value + "\n")
139
140     def _read_pin_attr(self, attr):
141         # Make sure the pin is active
142         self._is_deinited()
143
144         path = os.path.join(
145             self._sysfs_path,
146             self._channel_path.format(self._channel),
147             self._pin_path.format(self._pwmpin),
148             attr)
149
150         with open(path, 'r') as f_attr:
151             return f_attr.read().strip()
152
153     # Mutable properties
154
155     def _get_period(self):
156         try:
157             period_ns = int(self._read_pin_attr(self._pin_period_path))
158         except ValueError:
159             raise PWMError(None, "Unknown period value: \"%s\"" % period_ns)
160
161         # Convert period from nanoseconds to seconds
162         period = period_ns / 1e9
163
164         # Update our cached period
165         self._period = period
166
167         return period
168
169     def _set_period(self, period):
170         if not isinstance(period, (int, float)):
171             raise TypeError("Invalid period type, should be int or float.")
172
173         # Convert period from seconds to integer nanoseconds
174         period_ns = int(period * 1e9)
175
176         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
177
178         # Update our cached period
179         self._period = float(period)
180
181     """Get or set the PWM's output period in seconds.
182
183     Raises:
184         PWMError: if an I/O or OS error occurs.
185         TypeError: if value type is not int or float.
186
187     :type: int, float
188     """
189
190     def _get_duty_cycle(self):
191         try:
192             duty_cycle_ns = int(self._read_pin_attr(self._pin_duty_cycle_path))
193         except ValueError:
194             raise PWMError(None, "Unknown duty cycle value: \"%s\"" % duty_cycle_ns)
195
196         # Convert duty cycle from nanoseconds to seconds
197         duty_cycle = duty_cycle_ns / 1e9
198
199         # Convert duty cycle to ratio from 0.0 to 1.0
200         duty_cycle = duty_cycle / self._period
201
202         # convert to 16-bit
203         duty_cycle = int(duty_cycle * 65535)
204         return duty_cycle
205
206     def _set_duty_cycle(self, duty_cycle):
207         if not isinstance(duty_cycle, (int, float)):
208             raise TypeError("Invalid duty cycle type, should be int or float.")
209
210         # convert from 16-bit
211         duty_cycle /= 65535.0
212         if not 0.0 <= duty_cycle <= 1.0:
213             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
214
215         # Convert duty cycle from ratio to seconds
216         duty_cycle = duty_cycle * self._period
217
218         # Convert duty cycle from seconds to integer nanoseconds
219         duty_cycle_ns = int(duty_cycle * 1e9)
220
221         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
222
223     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
224     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
225
226     Raises:
227         PWMError: if an I/O or OS error occurs.
228         TypeError: if value type is not int or float.
229         ValueError: if value is out of bounds of 0.0 to 1.0.
230
231     :type: int, float
232     """
233
234     def _get_frequency(self):
235         return 1.0 / self._get_period()
236
237     def _set_frequency(self, frequency):
238         if not isinstance(frequency, (int, float)):
239             raise TypeError("Invalid frequency type, should be int or float.")
240
241         self._set_period(1.0 / frequency)
242
243     frequency = property(_get_frequency, _set_frequency)
244     """Get or set the PWM's output frequency in Hertz.
245
246     Raises:
247         PWMError: if an I/O or OS error occurs.
248         TypeError: if value type is not int or float.
249
250     :type: int, float
251     """
252
253     def _get_enabled(self):
254         enabled = self._read_pin_attr(self._pin_enable_path)
255
256         if enabled == "1":
257             return True
258         elif enabled == "0":
259             return False
260
261         raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
262
263     def _set_enabled(self, value):
264         if not isinstance(value, bool):
265             raise TypeError("Invalid enabled type, should be string.")
266
267         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
268
269     """Get or set the PWM's output enabled state.
270
271     Raises:
272         PWMError: if an I/O or OS error occurs.
273         TypeError: if value type is not bool.
274
275     :type: bool
276     """
277
278     # String representation
279
280     def __str__(self):
281         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
282             (self._channel, self._pin, self.frequency, self.duty_cycle * 100,)