3 from errno import EACCES
6 from microcontroller.pin import pwmOuts
8 raise RuntimeError("No PWM outputs defined for this board.") from ImportError
11 class PWMError(IOError):
12 """Base class for PWM errors."""
18 """Pulse Width Modulation Output Class"""
20 # Number of retries to check for successful PWM export on open
22 # Delay between check for successful PWM export on open (100ms)
26 _sysfs_path = "/sys/class/pwm"
27 _chip_path = "pwmchip{}"
28 _channel_path = "pwm{}"
32 _unexport = "unexport"
35 _pin_period = "period"
36 _pin_duty_cycle = "duty_cycle"
37 _pin_polarity = "polarity"
38 _pin_enable = "enable"
40 def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
41 """Instantiate a PWM object and open the sysfs PWM corresponding to the
42 specified chip and channel.
45 frequency (int, float): target frequency in Hertz (32-bit).
46 duty_cycle (int, float): The fraction of each pulse which is high (16-bit).
47 variable_frequency (bool): True if the frequency will change over time.
51 PWMError: if an I/O or OS error occurs.
52 TypeError: if `chip` or `channel` types are invalid.
53 LookupError: if PWM chip does not exist.
54 TimeoutError: if waiting for PWM export times out.
60 self._open(pwm, frequency, duty_cycle, variable_frequency)
68 def __exit__(self, exc_type, exc_val, exc_tb):
71 def _open(self, pwm, frequency, duty_cycle, variable_frequency):
72 for pwmout in pwmOuts:
74 self._chip = pwmout[0][0]
75 self._channel = pwmout[0][1]
79 self._chip_path = os.path.join(self._sysfs_path, self._chip_path.format(self._chip))
80 self._channel_path = os.path.join(self._chip_path, self._channel_path.format(self._channel))
82 if not os.path.isdir(self._chip_path):
83 raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
85 if not os.path.isdir(self._channel_path):
88 with open(os.path.join(self._chip_path, self._export), "w") as f_export:
89 f_export.write("{:d}\n".format(self._channel))
91 raise PWMError(e.errno, "Exporting PWM channel: " + e.strerror)
93 # Loop until PWM is exported
95 for i in range(PWMOut.PWM_STAT_RETRIES):
96 if os.path.isdir(self._channel_path):
100 sleep(PWMOut.PWM_STAT_DELAY)
103 raise TimeoutError("Exporting PWM: waiting for \"{:s}\" timed out.".format(self._channel_path))
105 # Loop until 'period' is writable, This could take some time after
106 # export as application of the udev rules after export is asynchronous.
107 # Without this loop, the following properties may not be writable yet.
108 for i in range(PWMOut.PWM_STAT_RETRIES):
110 with open(os.path.join(self._channel_path, "period"), "w",):
113 if e.errno != EACCES or (e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1):
114 raise PWMError(e.errno, "Opening PWM period: " + e.strerror) from IOError
116 sleep(PWMOut.PWM_STAT_DELAY)
118 self.frequency = frequency
119 self.duty_cycle = duty_cycle
121 # Cache the period for fast duty cycle updates
122 self._period_ns = self._get_period_ns()
126 if self._channel is not None:
127 # Unexporting the PWM channel
129 unexport_fd = os.open(os.path.join(self._chip_path, self._unexport), os.O_WRONLY)
130 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
131 os.close(unexport_fd)
133 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror)
138 def _write_channel_attr(self, attr, value):
139 with open(os.path.join(self._channel_path, attr), 'w') as f_attr:
140 f_attr.write(value + "\n")
142 def _read_channel_attr(self, attr):
143 with open(os.path.join(self._channel_path, attr), 'r') as f_attr:
144 return f_attr.read().strip()
149 """Enable the PWM outout."""
153 """Diable the PWM output."""
158 def _get_period(self):
159 return float(self.period_ms) / 1000
161 def _set_period(self, period):
162 if not isinstance(period, (int, float)):
163 raise TypeError("Invalid period type, should be int.")
165 self.period_ms = int(period * 1000)
167 period = property(_get_period, _set_period)
168 """Get or set the PWM's output period in seconds.
171 PWMError: if an I/O or OS error occurs.
172 TypeError: if value type is not int.
177 def _get_period_ms(self):
178 return self.period_us / 1000
180 def _set_period_ms(self, period_ms):
181 if not isinstance(period_ms, int):
182 raise TypeError("Invalid period type, should be int.")
183 self.period_us = int(period_ms * 1000)
185 period_ms = property(_get_period_ms, _set_period_ms)
186 """Get or set the PWM's output period in milliseconds.
189 PWMError: if an I/O or OS error occurs.
190 TypeError: if value type is not int.
195 def _get_period_us(self):
196 return self.period_ns / 1000
198 def _set_period_us(self, period_us):
199 if not isinstance(period_us, int):
200 raise TypeError("Invalid period type, should be int.")
202 self.period_ns = int(period_us * 1000)
204 period_us = property(_get_period_us, _set_period_us)
205 """Get or set the PWM's output period in microseconds.
208 PWMError: if an I/O or OS error occurs.
209 TypeError: if value type is not int.
214 def _get_period_ns(self):
215 period_ns = self._read_channel_attr(self._pin_period)
217 period_ns = int(period_ns)
219 raise PWMError(None, "Unknown period value: \"%s\"." % period_ns) from ValueError
221 self._period_ns = period_ns
225 def _set_period_ns(self, period_ns):
226 if not isinstance(period_ns, int):
227 raise TypeError("Invalid period type, should be int.")
229 self._write_channel_attr("period", str(period_ns))
231 # Update our cached period
232 self._period_ns = period_ns
234 period_ns = property(_get_period_ns, _set_period_ns)
235 """Get or set the PWM's output period in nanoseconds.
238 PWMError: if an I/O or OS error occurs.
239 TypeError: if value type is not int.
244 def _get_duty_cycle_ns(self):
245 duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
248 duty_cycle_ns = int(duty_cycle_ns_str)
250 raise PWMError(None, "Unknown duty cycle value: \"{:s}\"".format(duty_cycle_ns_str))
254 def _set_duty_cycle_ns(self, duty_cycle_ns):
255 if not isinstance(duty_cycle_ns, int):
256 raise TypeError("Invalid duty cycle type, should be int.")
258 self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
260 duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
261 """Get or set the PWM's output duty cycle in nanoseconds.
264 PWMError: if an I/O or OS error occurs.
265 TypeError: if value type is not int.
270 def _get_duty_cycle(self):
271 return float(self.duty_cycle_ns) / self._period_ns
273 def _set_duty_cycle(self, duty_cycle):
274 if not isinstance(duty_cycle, (int, float)):
275 raise TypeError("Invalid duty cycle type, should be int or float.")
276 elif not 0.0 <= duty_cycle <= 1.0:
277 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
279 # Convert duty cycle from ratio to nanoseconds
280 self.duty_cycle_ns = int(duty_cycle * self._period_ns)
282 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
283 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
285 PWMError: if an I/O or OS error occurs.
286 TypeError: if value type is not int or float.
287 ValueError: if value is out of bounds of 0.0 to 1.0.
291 def _get_frequency(self):
292 return 1.0 / self.period
294 def _set_frequency(self, frequency):
295 if not isinstance(frequency, (int, float)):
296 raise TypeError("Invalid frequency type, should be int or float.")
298 self.period = 1.0 / frequency
300 frequency = property(_get_frequency, _set_frequency)
301 """Get or set the PWM's output frequency in Hertz.
303 PWMError: if an I/O or OS error occurs.
304 TypeError: if value type is not int or float.
308 def _get_polarity(self):
309 return self._read_channel_attr("polarity")
311 def _set_polarity(self, polarity):
312 if not isinstance(polarity, str):
313 raise TypeError("Invalid polarity type, should be str.")
314 elif polarity.lower() not in ["normal", "inversed"]:
315 raise ValueError("Invalid polarity, can be: \"normal\" or \"inversed\".")
317 self._write_channel_attr("polarity", polarity.lower())
319 polarity = property(_get_polarity, _set_polarity)
320 """Get or set the PWM's output polarity. Can be "normal" or "inversed".
322 PWMError: if an I/O or OS error occurs.
323 TypeError: if value type is not str.
324 ValueError: if value is invalid.
328 def _get_enabled(self):
329 enabled = self._read_channel_attr("enable")
336 raise PWMError(None, "Unknown enabled value: \"{:s}\"".format(enabled))
338 def _set_enabled(self, value):
339 if not isinstance(value, bool):
340 raise TypeError("Invalid enabled type, should be bool.")
342 self._write_channel_attr("enable", "1" if value else "0")
344 enabled = property(_get_enabled, _set_enabled)
345 """Get or set the PWM's output enabled state.
347 PWMError: if an I/O or OS error occurs.
348 TypeError: if value type is not bool.
352 # String representation
355 return "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%, polarity={:s}, enabled={:s})" \
356 .format(self._channel, self._chip, self.period, self.duty_cycle * 100, self.polarity, str(self.enabled))