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."""
25 # pylint: enable=unnecessary-pass
29 """Pulse Width Modulation Output Class"""
31 # Number of retries to check for successful PWM export on open
33 # Delay between check for successful PWM export on open (100ms)
37 _sysfs_path = "/sys/class/pwm"
38 _chip_path = "pwmchip{}"
39 _channel_path = "pwm{}"
43 _unexport = "unexport"
46 _pin_period = "period"
47 _pin_duty_cycle = "duty_cycle"
48 _pin_polarity = "polarity"
49 _pin_enable = "enable"
51 def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
52 """Instantiate a PWM object and open the sysfs PWM corresponding to the
53 specified chip and channel.
56 frequency (int, float): target frequency in Hertz (32-bit).
57 duty_cycle (int, float): The fraction of each pulse which is high (16-bit).
58 variable_frequency (bool): True if the frequency will change over time.
62 PWMError: if an I/O or OS error occurs.
63 TypeError: if `chip` or `channel` types are invalid.
64 LookupError: if PWM chip does not exist.
65 TimeoutError: if waiting for PWM export times out.
71 self._open(pwm, frequency, duty_cycle, variable_frequency)
79 def __exit__(self, exc_type, exc_val, exc_tb):
82 def _open(self, pwm, frequency, duty_cycle, variable_frequency):
83 for pwmout in pwmOuts:
85 self._chip = pwmout[0][0]
86 self._channel = pwmout[0][1]
90 self._chip_path = os.path.join(
91 self._sysfs_path, self._chip_path.format(self._chip)
93 self._channel_path = os.path.join(
94 self._chip_path, self._channel_path.format(self._channel)
97 if variable_frequency:
98 print("Variable Frequency is not supported, continuing without it...")
100 if not os.path.isdir(self._chip_path):
101 raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
103 if not os.path.isdir(self._channel_path):
106 with open(os.path.join(self._chip_path, self._export), "w") as f_export:
107 f_export.write("{:d}\n".format(self._channel))
109 raise PWMError(e.errno, "Exporting PWM channel: " + e.strerror)
111 # Loop until PWM is exported
113 for i in range(PWMOut.PWM_STAT_RETRIES):
114 if os.path.isdir(self._channel_path):
118 sleep(PWMOut.PWM_STAT_DELAY)
122 'Exporting PWM: waiting for "{:s}" timed out.'.format(
127 # Loop until 'period' is writable, This could take some time after
128 # export as application of the udev rules after export is asynchronous.
129 # Without this loop, the following properties may not be writable yet.
130 for i in range(PWMOut.PWM_STAT_RETRIES):
133 os.path.join(self._channel_path, "period"),
138 if e.errno != EACCES or (
139 e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
142 e.errno, "Opening PWM period: " + e.strerror
145 sleep(PWMOut.PWM_STAT_DELAY)
147 self.frequency = frequency
148 self.duty_cycle = duty_cycle
150 # Cache the period for fast duty cycle updates
151 self._period_ns = self._get_period_ns()
155 if self._channel is not None:
156 # Unexporting the PWM channel
158 unexport_fd = os.open(
159 os.path.join(self._chip_path, self._unexport), os.O_WRONLY
161 os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
162 os.close(unexport_fd)
164 raise PWMError(e.errno, "Unexporting PWM: " + e.strerror)
169 def _write_channel_attr(self, attr, value):
170 with open(os.path.join(self._channel_path, attr), "w") as f_attr:
171 f_attr.write(value + "\n")
173 def _read_channel_attr(self, attr):
174 with open(os.path.join(self._channel_path, attr), "r") as f_attr:
175 return f_attr.read().strip()
180 """Enable the PWM output."""
184 """Disable the PWM output."""
189 def _get_period(self):
190 return float(self.period_ms) / 1000
192 def _set_period(self, period):
193 if not isinstance(period, (int, float)):
194 raise TypeError("Invalid period type, should be int.")
196 self.period_ms = int(period * 1000)
198 period = property(_get_period, _set_period)
199 """Get or set the PWM's output period in seconds.
202 PWMError: if an I/O or OS error occurs.
203 TypeError: if value type is not int.
208 def _get_period_ms(self):
209 return self.period_us / 1000
211 def _set_period_ms(self, period_ms):
212 if not isinstance(period_ms, (int, float)):
213 raise TypeError("Invalid period type, should be int or float.")
214 self.period_us = int(period_ms * 1000)
216 period_ms = property(_get_period_ms, _set_period_ms)
217 """Get or set the PWM's output period in milliseconds.
220 PWMError: if an I/O or OS error occurs.
221 TypeError: if value type is not int.
226 def _get_period_us(self):
227 return self.period_ns / 1000
229 def _set_period_us(self, period_us):
230 if not isinstance(period_us, int):
231 raise TypeError("Invalid period type, should be int.")
233 self.period_ns = int(period_us * 1000)
235 period_us = property(_get_period_us, _set_period_us)
236 """Get or set the PWM's output period in microseconds.
239 PWMError: if an I/O or OS error occurs.
240 TypeError: if value type is not int.
245 def _get_period_ns(self):
246 period_ns = self._read_channel_attr(self._pin_period)
248 period_ns = int(period_ns)
251 None, 'Unknown period value: "%s".' % period_ns
254 self._period_ns = period_ns
258 def _set_period_ns(self, period_ns):
259 if not isinstance(period_ns, int):
260 raise TypeError("Invalid period type, should be int.")
262 self._write_channel_attr("period", str(period_ns))
264 # Update our cached period
265 self._period_ns = period_ns
267 period_ns = property(_get_period_ns, _set_period_ns)
268 """Get or set the PWM's output period in nanoseconds.
271 PWMError: if an I/O or OS error occurs.
272 TypeError: if value type is not int.
277 def _get_duty_cycle_ns(self):
278 duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
281 duty_cycle_ns = int(duty_cycle_ns_str)
284 None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
289 def _set_duty_cycle_ns(self, duty_cycle_ns):
290 if not isinstance(duty_cycle_ns, int):
291 raise TypeError("Invalid duty cycle type, should be int.")
293 self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
295 duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
296 """Get or set the PWM's output duty cycle in nanoseconds.
299 PWMError: if an I/O or OS error occurs.
300 TypeError: if value type is not int.
305 def _get_duty_cycle(self):
306 return float(self.duty_cycle_ns) / self._period_ns
308 def _set_duty_cycle(self, duty_cycle):
309 if not isinstance(duty_cycle, (int, float)):
310 raise TypeError("Invalid duty cycle type, should be int or float.")
311 elif not 0.0 <= duty_cycle <= 1.0:
312 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
314 # Convert duty cycle from ratio to nanoseconds
315 self.duty_cycle_ns = int(duty_cycle * self._period_ns)
317 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
318 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
320 PWMError: if an I/O or OS error occurs.
321 TypeError: if value type is not int or float.
322 ValueError: if value is out of bounds of 0.0 to 1.0.
326 def _get_frequency(self):
327 return 1.0 / self.period
329 def _set_frequency(self, frequency):
330 if not isinstance(frequency, (int, float)):
331 raise TypeError("Invalid frequency type, should be int or float.")
333 self.period = 1.0 / frequency
335 frequency = property(_get_frequency, _set_frequency)
336 """Get or set the PWM's output frequency in Hertz.
338 PWMError: if an I/O or OS error occurs.
339 TypeError: if value type is not int or float.
343 def _get_polarity(self):
344 return self._read_channel_attr("polarity")
346 def _set_polarity(self, polarity):
347 if not isinstance(polarity, str):
348 raise TypeError("Invalid polarity type, should be str.")
349 elif polarity.lower() not in ["normal", "inversed"]:
350 raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
352 self._write_channel_attr("polarity", polarity.lower())
354 polarity = property(_get_polarity, _set_polarity)
355 """Get or set the PWM's output polarity. Can be "normal" or "inversed".
357 PWMError: if an I/O or OS error occurs.
358 TypeError: if value type is not str.
359 ValueError: if value is invalid.
363 def _get_enabled(self):
364 enabled = self._read_channel_attr("enable")
371 raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
373 def _set_enabled(self, value):
374 if not isinstance(value, bool):
375 raise TypeError("Invalid enabled type, should be bool.")
377 self._write_channel_attr("enable", "1" if value else "0")
379 enabled = property(_get_enabled, _set_enabled)
380 """Get or set the PWM's output enabled state.
382 PWMError: if an I/O or OS error occurs.
383 TypeError: if value type is not bool.
387 # String representation
390 return "PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%, polarity={:s}, enabled={:s})".format(
394 self.duty_cycle * 100,