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
18 class PWMError(IOError):
19 """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 scucessful PWM export on open (100ms)
35 # Number of retries to check for successful PWM export on open
37 # Delay between check for scucessful PWM export on open (100ms)
40 # Number of retries to check for successful PWM export on open
42 # Delay between check for scucessful PWM export on open (100ms)
46 _sysfs_path = "/sys/class/pwm/"
47 _channel_path = "pwmchip{}"
50 _export_path = "export"
51 _unexport_path = "unexport"
55 _pin_period_path = "period"
56 _pin_duty_cycle_path = "duty_cycle"
57 _pin_polarity_path = "polarity"
58 _pin_enable_path = "enable"
60 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
61 """Instantiate a PWM object and open the sysfs PWM corresponding to the
62 specified channel and pin.
65 pin (Pin): CircuitPython Pin object to output to
66 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
67 frequency (int) : target frequency in Hertz (32-bit)
68 variable_frequency (bool) : True if the frequency will change over time
71 PWMOut: PWMOut object.
74 PWMError: if an I/O or OS error occurs.
75 TypeError: if `channel` or `pin` types are invalid.
76 ValueError: if PWM channel does not exist.
83 self._open(pin, duty_cycle, frequency, variable_frequency)
91 def __exit__(self, t, value, traceback):
94 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
96 for pwmpair in pwmOuts:
98 self._channel = pwmpair[0][0]
99 self._pwmpin = pwmpair[0][1]
102 if self._channel is None:
103 raise RuntimeError("No PWM channel found for this Pin")
105 if variable_frequency:
106 print("Variable Frequency is not supported, continuing without it...")
108 channel_path = os.path.join(
109 self._sysfs_path, self._channel_path.format(self._channel)
111 if not os.path.isdir(channel_path):
113 "PWM channel does not exist, check that the required modules are loaded."
118 os.path.join(channel_path, self._unexport_path), "w"
120 f_unexport.write("%d\n" % self._pwmpin)
122 pass # not unusual, it doesnt already exist
124 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
125 f_export.write("%d\n" % self._pwmpin)
127 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
129 # Loop until 'period' is writable, because application of udev rules
130 # after the above pin export is asynchronous.
131 # Without this loop, the following properties may not be writable yet.
132 for i in range(PWMOut.PWM_STAT_RETRIES):
136 channel_path, self._pin_path.format(self._pwmpin), "period"
142 if e.errno != EACCES or (
143 e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
145 raise PWMError(e.errno, "Opening PWM period: " + e.strerror)
146 sleep(PWMOut.PWM_STAT_DELAY)
148 # self._set_enabled(False) # This line causes a write error when trying to enable
150 # Look up the period, for fast duty cycle updates
151 self._period = self._get_period()
153 # self.duty_cycle = 0 # This line causes a write error when trying to enable
156 self.frequency = freq
158 self.duty_cycle = duty
160 self._set_enabled(True)
163 """Deinit the sysfs PWM."""
164 if self._channel is not None:
167 channel_path = os.path.join(
168 self._sysfs_path, self._channel_path.format(self._channel)
171 os.path.join(channel_path, self._unexport_path), "w"
173 f_unexport.write("%d\n" % self._pwmpin)
176 e.errno, "Unexporting PWM pin: " + e.strerror
182 def _is_deinited(self):
183 if self._pwmpin is None:
185 "Object has been deinitialize and can no longer "
186 "be used. Create a new object."
189 def _write_pin_attr(self, attr, value):
190 # Make sure the pin is active
195 self._channel_path.format(self._channel),
196 self._pin_path.format(self._pwmpin),
200 with open(path, "w") as f_attr:
202 f_attr.write(value + "\n")
204 def _read_pin_attr(self, attr):
205 # Make sure the pin is active
210 self._channel_path.format(self._channel),
211 self._pin_path.format(self._pwmpin),
215 with open(path, "r") as f_attr:
216 return f_attr.read().strip()
220 def _get_period(self):
221 period_ns = self._read_pin_attr(self._pin_period_path)
223 period_ns = int(period_ns)
226 None, 'Unknown period value: "%s"' % period_ns
229 # Convert period from nanoseconds to seconds
230 period = period_ns / 1e9
232 # Update our cached period
233 self._period = period
237 def _set_period(self, period):
238 if not isinstance(period, (int, float)):
239 raise TypeError("Invalid period type, should be int or float.")
241 # Convert period from seconds to integer nanoseconds
242 period_ns = int(period * 1e9)
244 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
246 # Update our cached period
247 self._period = float(period)
249 period = property(_get_period, _set_period)
251 """Get or set the PWM's output period in seconds.
254 PWMError: if an I/O or OS error occurs.
255 TypeError: if value type is not int or float.
260 def _get_duty_cycle(self):
261 duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
263 duty_cycle_ns = int(duty_cycle_ns)
266 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
269 # Convert duty cycle from nanoseconds to seconds
270 duty_cycle = duty_cycle_ns / 1e9
272 # Convert duty cycle to ratio from 0.0 to 1.0
273 duty_cycle = duty_cycle / self._period
276 duty_cycle = int(duty_cycle * 65535)
279 def _set_duty_cycle(self, duty_cycle):
280 if not isinstance(duty_cycle, (int, float)):
281 raise TypeError("Invalid duty cycle type, should be int or float.")
283 # convert from 16-bit
284 duty_cycle /= 65535.0
285 if not 0.0 <= duty_cycle <= 1.0:
286 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
288 # Convert duty cycle from ratio to seconds
289 duty_cycle = duty_cycle * self._period
291 # Convert duty cycle from seconds to integer nanoseconds
292 duty_cycle_ns = int(duty_cycle * 1e9)
294 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
296 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
297 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
300 PWMError: if an I/O or OS error occurs.
301 TypeError: if value type is not int or float.
302 ValueError: if value is out of bounds of 0.0 to 1.0.
307 def _get_frequency(self):
308 return 1.0 / self._get_period()
310 def _set_frequency(self, frequency):
311 if not isinstance(frequency, (int, float)):
312 raise TypeError("Invalid frequency type, should be int or float.")
314 self._set_period(1.0 / frequency)
316 frequency = property(_get_frequency, _set_frequency)
317 """Get or set the PWM's output frequency in Hertz.
320 PWMError: if an I/O or OS error occurs.
321 TypeError: if value type is not int or float.
326 def _get_enabled(self):
327 enabled = self._read_pin_attr(self._pin_enable_path)
334 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
336 def _set_enabled(self, value):
337 """Get or set the PWM's output enabled state.
340 PWMError: if an I/O or OS error occurs.
341 TypeError: if value type is not bool.
345 if not isinstance(value, bool):
346 raise TypeError("Invalid enabled type, should be string.")
348 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
350 # String representation
353 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
357 self.duty_cycle * 100,