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
9 from errno import EACCES
12 from microcontroller.pin import pwmOuts
14 raise RuntimeError("No PWM outputs defined for this board.") from ImportError
17 # pylint: disable=unnecessary-pass, too-many-instance-attributes
20 class PWMError(IOError):
21 """Base class for PWM errors."""
26 # pylint: enable=unnecessary-pass
30 """Pulse Width Modulation Output Class"""
32 # Number of retries to check for successful PWM export on open
34 # Delay between check for successful PWM export on open (100ms)
38 _chip_path = "pwmchip{}"
39 _channel_path = "pwm{}"
41 def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
42 """Instantiate a PWM object and open the sysfs PWM corresponding to the
43 specified chip and channel.
46 frequency (int, float): target frequency in Hertz (32-bit).
47 duty_cycle (int, float): The fraction of each pulse which is high (16-bit).
48 variable_frequency (bool): True if the frequency will change over time.
52 PWMError: if an I/O or OS error occurs.
53 TypeError: if `chip` or `channel` types are invalid.
54 LookupError: if PWM chip does not exist.
55 TimeoutError: if waiting for PWM export times out.
61 self._open(pwm, frequency, duty_cycle, variable_frequency)
69 def __exit__(self, exc_type, exc_val, exc_tb):
72 def _open(self, pwm, frequency, duty_cycle, variable_frequency):
73 for pwmout in pwmOuts:
75 self._chip = pwmout[0][0]
76 self._channel = pwmout[0][1]
78 self._chip_path = os.path.join(
79 "/sys/class/pwm", self._chip_path.format(self._chip)
81 self._channel_path = os.path.join(
82 self._chip_path, self._channel_path.format(self._channel)
85 if variable_frequency:
86 print("Variable Frequency is not supported, continuing without it...")
88 if not os.path.isdir(self._chip_path):
89 raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
91 if not os.path.isdir(self._channel_path):
94 with open(os.path.join(self._chip_path, "export"), "w") as f_export:
95 f_export.write("{:d}\n".format(self._channel))
98 e.errno, "Exporting PWM channel: " + e.strerror
101 # Loop until PWM is exported
103 for i in range(PWMOut.PWM_STAT_RETRIES):
104 if os.path.isdir(self._channel_path):
108 sleep(PWMOut.PWM_STAT_DELAY)
112 'Exporting PWM: waiting for "{:s}" timed out.'.format(
117 # Loop until 'period' is writable, This could take some time after
118 # export as application of the udev rules after export is asynchronous.
119 # Without this loop, the following properties may not be writable yet.
120 for i in range(PWMOut.PWM_STAT_RETRIES):
123 os.path.join(self._channel_path, "period"),
128 if e.errno != EACCES or (
129 e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
132 e.errno, "Opening PWM period: " + e.strerror
135 sleep(PWMOut.PWM_STAT_DELAY)
137 self.frequency = frequency
138 self.duty_cycle = duty_cycle
140 # Cache the period for fast duty cycle updates
141 self._period_ns = self._get_period_ns()
145 if self._channel is not None:
146 # Unexporting the PWM channel
148 unexport_fd = os.open(
149 os.path.join(self._chip_path, "unexport"), os.O_WRONLY
151 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
152 os.close(unexport_fd)
154 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror) from OSError
159 def _write_channel_attr(self, attr, value):
160 with open(os.path.join(self._channel_path, attr), "w") as f_attr:
161 f_attr.write(value + "\n")
163 def _read_channel_attr(self, attr):
164 with open(os.path.join(self._channel_path, attr), "r") as f_attr:
165 return f_attr.read().strip()
170 """Enable the PWM output."""
174 """Disable the PWM output."""
179 def _get_period(self):
180 return float(self.period_ms) / 1000
182 def _set_period(self, period):
183 if not isinstance(period, (int, float)):
184 raise TypeError("Invalid period type, should be int.")
186 self.period_ms = int(period * 1000)
188 period = property(_get_period, _set_period)
189 """Get or set the PWM's output period in seconds.
192 PWMError: if an I/O or OS error occurs.
193 TypeError: if value type is not int.
198 def _get_period_ms(self):
199 return self.period_us / 1000
201 def _set_period_ms(self, period_ms):
202 if not isinstance(period_ms, (int, float)):
203 raise TypeError("Invalid period type, should be int or float.")
204 self.period_us = int(period_ms * 1000)
206 period_ms = property(_get_period_ms, _set_period_ms)
207 """Get or set the PWM's output period in milliseconds.
210 PWMError: if an I/O or OS error occurs.
211 TypeError: if value type is not int.
216 def _get_period_us(self):
217 return self.period_ns / 1000
219 def _set_period_us(self, period_us):
220 if not isinstance(period_us, int):
221 raise TypeError("Invalid period type, should be int.")
223 self.period_ns = int(period_us * 1000)
225 period_us = property(_get_period_us, _set_period_us)
226 """Get or set the PWM's output period in microseconds.
229 PWMError: if an I/O or OS error occurs.
230 TypeError: if value type is not int.
235 def _get_period_ns(self):
236 period_ns = self._read_channel_attr("period")
238 period_ns = int(period_ns)
241 None, 'Unknown period value: "%s".' % period_ns
244 self._period_ns = period_ns
248 def _set_period_ns(self, period_ns):
249 if not isinstance(period_ns, int):
250 raise TypeError("Invalid period type, should be int.")
252 self._write_channel_attr("period", str(period_ns))
254 # Update our cached period
255 self._period_ns = period_ns
257 period_ns = property(_get_period_ns, _set_period_ns)
258 """Get or set the PWM's output period in nanoseconds.
261 PWMError: if an I/O or OS error occurs.
262 TypeError: if value type is not int.
267 def _get_duty_cycle_ns(self):
268 duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
271 duty_cycle_ns = int(duty_cycle_ns_str)
274 None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
279 def _set_duty_cycle_ns(self, duty_cycle_ns):
280 if not isinstance(duty_cycle_ns, int):
281 raise TypeError("Invalid duty cycle type, should be int.")
283 self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
285 duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
286 """Get or set the PWM's output duty cycle in nanoseconds.
289 PWMError: if an I/O or OS error occurs.
290 TypeError: if value type is not int.
295 def _get_duty_cycle(self):
296 return float(self.duty_cycle_ns) / self._period_ns
298 def _set_duty_cycle(self, duty_cycle):
299 if not isinstance(duty_cycle, (int, float)):
300 raise TypeError("Invalid duty cycle type, should be int or float.")
302 if not 0.0 <= duty_cycle <= 1.0:
303 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
305 # Convert duty cycle from ratio to nanoseconds
306 self.duty_cycle_ns = int(duty_cycle * self._period_ns)
308 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
309 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
311 PWMError: if an I/O or OS error occurs.
312 TypeError: if value type is not int or float.
313 ValueError: if value is out of bounds of 0.0 to 1.0.
317 def _get_frequency(self):
318 return 1.0 / self.period
320 def _set_frequency(self, frequency):
321 if not isinstance(frequency, (int, float)):
322 raise TypeError("Invalid frequency type, should be int or float.")
324 self.period = 1.0 / frequency
326 frequency = property(_get_frequency, _set_frequency)
327 """Get or set the PWM's output frequency in Hertz.
329 PWMError: if an I/O or OS error occurs.
330 TypeError: if value type is not int or float.
334 def _get_polarity(self):
335 return self._read_channel_attr("polarity")
337 def _set_polarity(self, polarity):
338 if not isinstance(polarity, str):
339 raise TypeError("Invalid polarity type, should be str.")
341 if polarity.lower() not in ["normal", "inversed"]:
342 raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
344 self._write_channel_attr("polarity", polarity.lower())
346 polarity = property(_get_polarity, _set_polarity)
347 """Get or set the PWM's output polarity. Can be "normal" or "inversed".
349 PWMError: if an I/O or OS error occurs.
350 TypeError: if value type is not str.
351 ValueError: if value is invalid.
355 def _get_enabled(self):
356 enabled = self._read_channel_attr("enable")
363 raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
365 def _set_enabled(self, value):
366 if not isinstance(value, bool):
367 raise TypeError("Invalid enabled type, should be bool.")
369 self._write_channel_attr("enable", "1" if value else "0")
371 enabled = property(_get_enabled, _set_enabled)
372 """Get or set the PWM's output enabled state.
374 PWMError: if an I/O or OS error occurs.
375 TypeError: if value type is not bool.
379 # String representation
383 "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%,"
384 " polarity={:s}, enabled={:s})".format(
388 self.duty_cycle * 100,