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(
80 self._sysfs_path, self._chip_path.format(self._chip)
82 self._channel_path = os.path.join(
83 self._chip_path, self._channel_path.format(self._channel)
86 if not os.path.isdir(self._chip_path):
87 raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
89 if not os.path.isdir(self._channel_path):
92 with open(os.path.join(self._chip_path, self._export), "w") as f_export:
93 f_export.write("{:d}\n".format(self._channel))
95 raise PWMError(e.errno, "Exporting PWM channel: " + e.strerror)
97 # Loop until PWM is exported
99 for i in range(PWMOut.PWM_STAT_RETRIES):
100 if os.path.isdir(self._channel_path):
104 sleep(PWMOut.PWM_STAT_DELAY)
108 'Exporting PWM: waiting for "{:s}" timed out.'.format(
113 # Loop until 'period' is writable, This could take some time after
114 # export as application of the udev rules after export is asynchronous.
115 # Without this loop, the following properties may not be writable yet.
116 for i in range(PWMOut.PWM_STAT_RETRIES):
119 os.path.join(self._channel_path, "period"),
124 if e.errno != EACCES or (
125 e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
128 e.errno, "Opening PWM period: " + e.strerror
131 sleep(PWMOut.PWM_STAT_DELAY)
133 self.frequency = frequency
134 self.duty_cycle = duty_cycle
136 # Cache the period for fast duty cycle updates
137 self._period_ns = self._get_period_ns()
141 if self._channel is not None:
142 # Unexporting the PWM channel
144 unexport_fd = os.open(
145 os.path.join(self._chip_path, self._unexport), os.O_WRONLY
147 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
148 os.close(unexport_fd)
150 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror)
155 def _write_channel_attr(self, attr, value):
156 with open(os.path.join(self._channel_path, attr), "w") as f_attr:
157 f_attr.write(value + "\n")
159 def _read_channel_attr(self, attr):
160 with open(os.path.join(self._channel_path, attr), "r") as f_attr:
161 return f_attr.read().strip()
166 """Enable the PWM outout."""
170 """Diable the PWM output."""
175 def _get_period(self):
176 return float(self.period_ms) / 1000
178 def _set_period(self, period):
179 if not isinstance(period, (int, float)):
180 raise TypeError("Invalid period type, should be int.")
182 self.period_ms = int(period * 1000)
184 period = property(_get_period, _set_period)
185 """Get or set the PWM's output period in seconds.
188 PWMError: if an I/O or OS error occurs.
189 TypeError: if value type is not int.
194 def _get_period_ms(self):
195 return self.period_us / 1000
197 def _set_period_ms(self, period_ms):
198 if not isinstance(period_ms, (int, float)):
199 raise TypeError("Invalid period type, should be int or float.")
200 self.period_us = int(period_ms * 1000)
202 period_ms = property(_get_period_ms, _set_period_ms)
203 """Get or set the PWM's output period in milliseconds.
206 PWMError: if an I/O or OS error occurs.
207 TypeError: if value type is not int.
212 def _get_period_us(self):
213 return self.period_ns / 1000
215 def _set_period_us(self, period_us):
216 if not isinstance(period_us, int):
217 raise TypeError("Invalid period type, should be int.")
219 self.period_ns = int(period_us * 1000)
221 period_us = property(_get_period_us, _set_period_us)
222 """Get or set the PWM's output period in microseconds.
225 PWMError: if an I/O or OS error occurs.
226 TypeError: if value type is not int.
231 def _get_period_ns(self):
232 period_ns = self._read_channel_attr(self._pin_period)
234 period_ns = int(period_ns)
237 None, 'Unknown period value: "%s".' % period_ns
240 self._period_ns = period_ns
244 def _set_period_ns(self, period_ns):
245 if not isinstance(period_ns, int):
246 raise TypeError("Invalid period type, should be int.")
248 self._write_channel_attr("period", str(period_ns))
250 # Update our cached period
251 self._period_ns = period_ns
253 period_ns = property(_get_period_ns, _set_period_ns)
254 """Get or set the PWM's output period in nanoseconds.
257 PWMError: if an I/O or OS error occurs.
258 TypeError: if value type is not int.
263 def _get_duty_cycle_ns(self):
264 duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
267 duty_cycle_ns = int(duty_cycle_ns_str)
270 None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
275 def _set_duty_cycle_ns(self, duty_cycle_ns):
276 if not isinstance(duty_cycle_ns, int):
277 raise TypeError("Invalid duty cycle type, should be int.")
279 self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
281 duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
282 """Get or set the PWM's output duty cycle in nanoseconds.
285 PWMError: if an I/O or OS error occurs.
286 TypeError: if value type is not int.
291 def _get_duty_cycle(self):
292 return float(self.duty_cycle_ns) / self._period_ns
294 def _set_duty_cycle(self, duty_cycle):
295 if not isinstance(duty_cycle, (int, float)):
296 raise TypeError("Invalid duty cycle type, should be int or float.")
297 elif not 0.0 <= duty_cycle <= 1.0:
298 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
300 # Convert duty cycle from ratio to nanoseconds
301 self.duty_cycle_ns = int(duty_cycle * self._period_ns)
303 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
304 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
306 PWMError: if an I/O or OS error occurs.
307 TypeError: if value type is not int or float.
308 ValueError: if value is out of bounds of 0.0 to 1.0.
312 def _get_frequency(self):
313 return 1.0 / self.period
315 def _set_frequency(self, frequency):
316 if not isinstance(frequency, (int, float)):
317 raise TypeError("Invalid frequency type, should be int or float.")
319 self.period = 1.0 / frequency
321 frequency = property(_get_frequency, _set_frequency)
322 """Get or set the PWM's output frequency in Hertz.
324 PWMError: if an I/O or OS error occurs.
325 TypeError: if value type is not int or float.
329 def _get_polarity(self):
330 return self._read_channel_attr("polarity")
332 def _set_polarity(self, polarity):
333 if not isinstance(polarity, str):
334 raise TypeError("Invalid polarity type, should be str.")
335 elif polarity.lower() not in ["normal", "inversed"]:
336 raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
338 self._write_channel_attr("polarity", polarity.lower())
340 polarity = property(_get_polarity, _set_polarity)
341 """Get or set the PWM's output polarity. Can be "normal" or "inversed".
343 PWMError: if an I/O or OS error occurs.
344 TypeError: if value type is not str.
345 ValueError: if value is invalid.
349 def _get_enabled(self):
350 enabled = self._read_channel_attr("enable")
357 raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
359 def _set_enabled(self, value):
360 if not isinstance(value, bool):
361 raise TypeError("Invalid enabled type, should be bool.")
363 self._write_channel_attr("enable", "1" if value else "0")
365 enabled = property(_get_enabled, _set_enabled)
366 """Get or set the PWM's output enabled state.
368 PWMError: if an I/O or OS error occurs.
369 TypeError: if value type is not bool.
373 # String representation
376 return "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%, polarity={:s}, enabled={:s})".format(
380 self.duty_cycle * 100,