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
16 # pylint: disable=unnecessary-pass
19 class PWMError(IOError):
20 """Base class for PWM errors."""
24 # pylint: enable=unnecessary-pass
28 """Pulse Width Modulation Output Class"""
30 # Number of retries to check for successful PWM export on open
32 # Delay between check for successful PWM export on open (100ms)
36 _sysfs_path = "/sys/class/pwm"
37 _chip_path = "pwmchip{}"
38 _channel_path = "pwm{}"
42 _unexport = "unexport"
45 _pin_period = "period"
46 _pin_duty_cycle = "duty_cycle"
47 _pin_polarity = "polarity"
48 _pin_enable = "enable"
50 def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
51 """Instantiate a PWM object and open the sysfs PWM corresponding to the
52 specified chip and channel.
55 frequency (int, float): target frequency in Hertz (32-bit).
56 duty_cycle (int, float): The fraction of each pulse which is high (16-bit).
57 variable_frequency (bool): True if the frequency will change over time.
61 PWMError: if an I/O or OS error occurs.
62 TypeError: if `chip` or `channel` types are invalid.
63 LookupError: if PWM chip does not exist.
64 TimeoutError: if waiting for PWM export times out.
70 self._open(pwm, frequency, duty_cycle, variable_frequency)
78 def __exit__(self, exc_type, exc_val, exc_tb):
81 def _open(self, pwm, frequency, duty_cycle, variable_frequency):
82 for pwmout in pwmOuts:
84 self._chip = pwmout[0][0]
85 self._channel = pwmout[0][1]
89 self._chip_path = os.path.join(
90 self._sysfs_path, self._chip_path.format(self._chip)
92 self._channel_path = os.path.join(
93 self._chip_path, self._channel_path.format(self._channel)
96 if variable_frequency:
97 print("Variable Frequency is not supported, continuing without it...")
99 if not os.path.isdir(self._chip_path):
100 raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
102 if not os.path.isdir(self._channel_path):
105 with open(os.path.join(self._chip_path, self._export), "w") as f_export:
106 f_export.write("{:d}\n".format(self._channel))
108 raise PWMError(e.errno, "Exporting PWM channel: " + e.strerror)
110 # Loop until PWM is exported
112 for i in range(PWMOut.PWM_STAT_RETRIES):
113 if os.path.isdir(self._channel_path):
117 sleep(PWMOut.PWM_STAT_DELAY)
121 'Exporting PWM: waiting for "{:s}" timed out.'.format(
126 # Loop until 'period' is writable, This could take some time after
127 # export as application of the udev rules after export is asynchronous.
128 # Without this loop, the following properties may not be writable yet.
129 for i in range(PWMOut.PWM_STAT_RETRIES):
132 os.path.join(self._channel_path, "period"),
137 if e.errno != EACCES or (
138 e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
141 e.errno, "Opening PWM period: " + e.strerror
144 sleep(PWMOut.PWM_STAT_DELAY)
146 self.frequency = frequency
147 self.duty_cycle = duty_cycle
149 # Cache the period for fast duty cycle updates
150 self._period_ns = self._get_period_ns()
154 if self._channel is not None:
155 # Unexporting the PWM channel
157 unexport_fd = os.open(
158 os.path.join(self._chip_path, self._unexport), os.O_WRONLY
160 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
161 os.close(unexport_fd)
163 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror)
168 def _write_channel_attr(self, attr, value):
169 with open(os.path.join(self._channel_path, attr), "w") as f_attr:
170 f_attr.write(value + "\n")
172 def _read_channel_attr(self, attr):
173 with open(os.path.join(self._channel_path, attr), "r") as f_attr:
174 return f_attr.read().strip()
179 """Enable the PWM output."""
183 """Disable the PWM output."""
188 def _get_period(self):
189 return float(self.period_ms) / 1000
191 def _set_period(self, period):
192 if not isinstance(period, (int, float)):
193 raise TypeError("Invalid period type, should be int.")
195 self.period_ms = int(period * 1000)
197 period = property(_get_period, _set_period)
198 """Get or set the PWM's output period in seconds.
201 PWMError: if an I/O or OS error occurs.
202 TypeError: if value type is not int.
207 def _get_period_ms(self):
208 return self.period_us / 1000
210 def _set_period_ms(self, period_ms):
211 if not isinstance(period_ms, (int, float)):
212 raise TypeError("Invalid period type, should be int or float.")
213 self.period_us = int(period_ms * 1000)
215 period_ms = property(_get_period_ms, _set_period_ms)
216 """Get or set the PWM's output period in milliseconds.
219 PWMError: if an I/O or OS error occurs.
220 TypeError: if value type is not int.
225 def _get_period_us(self):
226 return self.period_ns / 1000
228 def _set_period_us(self, period_us):
229 if not isinstance(period_us, int):
230 raise TypeError("Invalid period type, should be int.")
232 self.period_ns = int(period_us * 1000)
234 period_us = property(_get_period_us, _set_period_us)
235 """Get or set the PWM's output period in microseconds.
238 PWMError: if an I/O or OS error occurs.
239 TypeError: if value type is not int.
244 def _get_period_ns(self):
245 period_ns = self._read_channel_attr(self._pin_period)
247 period_ns = int(period_ns)
250 None, 'Unknown period value: "%s".' % period_ns
253 self._period_ns = period_ns
257 def _set_period_ns(self, period_ns):
258 if not isinstance(period_ns, int):
259 raise TypeError("Invalid period type, should be int.")
261 self._write_channel_attr("period", str(period_ns))
263 # Update our cached period
264 self._period_ns = period_ns
266 period_ns = property(_get_period_ns, _set_period_ns)
267 """Get or set the PWM's output period in nanoseconds.
270 PWMError: if an I/O or OS error occurs.
271 TypeError: if value type is not int.
276 def _get_duty_cycle_ns(self):
277 duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
280 duty_cycle_ns = int(duty_cycle_ns_str)
283 None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
288 def _set_duty_cycle_ns(self, duty_cycle_ns):
289 if not isinstance(duty_cycle_ns, int):
290 raise TypeError("Invalid duty cycle type, should be int.")
292 self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
294 duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
295 """Get or set the PWM's output duty cycle in nanoseconds.
298 PWMError: if an I/O or OS error occurs.
299 TypeError: if value type is not int.
304 def _get_duty_cycle(self):
305 return float(self.duty_cycle_ns) / self._period_ns
307 def _set_duty_cycle(self, duty_cycle):
308 if not isinstance(duty_cycle, (int, float)):
309 raise TypeError("Invalid duty cycle type, should be int or float.")
310 elif not 0.0 <= duty_cycle <= 1.0:
311 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
313 # Convert duty cycle from ratio to nanoseconds
314 self.duty_cycle_ns = int(duty_cycle * self._period_ns)
316 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
317 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
319 PWMError: if an I/O or OS error occurs.
320 TypeError: if value type is not int or float.
321 ValueError: if value is out of bounds of 0.0 to 1.0.
325 def _get_frequency(self):
326 return 1.0 / self.period
328 def _set_frequency(self, frequency):
329 if not isinstance(frequency, (int, float)):
330 raise TypeError("Invalid frequency type, should be int or float.")
332 self.period = 1.0 / frequency
334 frequency = property(_get_frequency, _set_frequency)
335 """Get or set the PWM's output frequency in Hertz.
337 PWMError: if an I/O or OS error occurs.
338 TypeError: if value type is not int or float.
342 def _get_polarity(self):
343 return self._read_channel_attr("polarity")
345 def _set_polarity(self, polarity):
346 if not isinstance(polarity, str):
347 raise TypeError("Invalid polarity type, should be str.")
348 elif polarity.lower() not in ["normal", "inversed"]:
349 raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
351 self._write_channel_attr("polarity", polarity.lower())
353 polarity = property(_get_polarity, _set_polarity)
354 """Get or set the PWM's output polarity. Can be "normal" or "inversed".
356 PWMError: if an I/O or OS error occurs.
357 TypeError: if value type is not str.
358 ValueError: if value is invalid.
362 def _get_enabled(self):
363 enabled = self._read_channel_attr("enable")
370 raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
372 def _set_enabled(self, value):
373 if not isinstance(value, bool):
374 raise TypeError("Invalid enabled type, should be bool.")
376 self._write_channel_attr("enable", "1" if value else "0")
378 enabled = property(_get_enabled, _set_enabled)
379 """Get or set the PWM's output enabled state.
381 PWMError: if an I/O or OS error occurs.
382 TypeError: if value type is not bool.
386 # String representation
389 return "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%, polarity={:s}, enabled={:s})".format(
393 self.duty_cycle * 100,