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"""
29 # Number of retries to check for successful PWM export on open
31 # Delay between check for scucessful PWM export on open (100ms)
34 # Number of retries to check for successful PWM export on open
36 # Delay between check for scucessful PWM export on open (100ms)
40 _sysfs_path = "/sys/class/pwm/"
41 _channel_path = "pwmchip{}"
44 _export_path = "export"
45 _unexport_path = "unexport"
49 _pin_period_path = "period"
50 _pin_duty_cycle_path = "duty_cycle"
51 _pin_polarity_path = "polarity"
52 _pin_enable_path = "enable"
54 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
55 """Instantiate a PWM object and open the sysfs PWM corresponding to the
56 specified channel and pin.
59 pin (Pin): CircuitPython Pin object to output to
60 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
61 frequency (int) : target frequency in Hertz (32-bit)
62 variable_frequency (bool) : True if the frequency will change over time
65 PWMOut: PWMOut object.
68 PWMError: if an I/O or OS error occurs.
69 TypeError: if `channel` or `pin` types are invalid.
70 ValueError: if PWM channel does not exist.
77 self._open(pin, duty_cycle, frequency, variable_frequency)
85 def __exit__(self, t, value, traceback):
88 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
90 for pwmpair in pwmOuts:
92 self._channel = pwmpair[0][0]
93 self._pwmpin = pwmpair[0][1]
96 if self._channel is None:
97 raise RuntimeError("No PWM channel found for this Pin")
99 if variable_frequency:
100 print("Variable Frequency is not supported, continuing without it...")
102 channel_path = os.path.join(
103 self._sysfs_path, self._channel_path.format(self._channel)
105 if not os.path.isdir(channel_path):
107 "PWM channel does not exist, check that the required modules are loaded."
112 os.path.join(channel_path, self._unexport_path), "w"
114 f_unexport.write("%d\n" % self._pwmpin)
116 pass # not unusual, it doesnt already exist
118 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
119 f_export.write("%d\n" % self._pwmpin)
121 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
123 # Loop until 'period' is writable, because application of udev rules
124 # after the above pin export is asynchronous.
125 # Without this loop, the following properties may not be writable yet.
126 for i in range(PWMOut.PWM_STAT_RETRIES):
130 channel_path, self._pin_path.format(self._pwmpin), "period"
136 if e.errno != EACCES or (
137 e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
139 raise PWMError(e.errno, "Opening PWM period: " + e.strerror)
140 sleep(PWMOut.PWM_STAT_DELAY)
142 # self._set_enabled(False) # This line causes a write error when trying to enable
144 # Look up the period, for fast duty cycle updates
145 self._period = self._get_period()
147 # self.duty_cycle = 0 # This line causes a write error when trying to enable
150 self.frequency = freq
152 self.duty_cycle = duty
154 self._set_enabled(True)
157 """Deinit the sysfs PWM."""
158 if self._channel is not None:
161 channel_path = os.path.join(
162 self._sysfs_path, self._channel_path.format(self._channel)
165 os.path.join(channel_path, self._unexport_path), "w"
167 f_unexport.write("%d\n" % self._pwmpin)
170 e.errno, "Unexporting PWM pin: " + e.strerror
176 def _is_deinited(self):
177 if self._pwmpin is None:
179 "Object has been deinitialize and can no longer "
180 "be used. Create a new object."
183 def _write_pin_attr(self, attr, value):
184 # Make sure the pin is active
189 self._channel_path.format(self._channel),
190 self._pin_path.format(self._pwmpin),
194 with open(path, "w") as f_attr:
196 f_attr.write(value + "\n")
198 def _read_pin_attr(self, attr):
199 # Make sure the pin is active
204 self._channel_path.format(self._channel),
205 self._pin_path.format(self._pwmpin),
209 with open(path, "r") as f_attr:
210 return f_attr.read().strip()
214 def _get_period(self):
215 period_ns = self._read_pin_attr(self._pin_period_path)
217 period_ns = int(period_ns)
220 None, 'Unknown period value: "%s"' % period_ns
223 # Convert period from nanoseconds to seconds
224 period = period_ns / 1e9
226 # Update our cached period
227 self._period = period
231 def _set_period(self, period):
232 if not isinstance(period, (int, float)):
233 raise TypeError("Invalid period type, should be int or float.")
235 # Convert period from seconds to integer nanoseconds
236 period_ns = int(period * 1e9)
238 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
240 # Update our cached period
241 self._period = float(period)
243 period = property(_get_period, _set_period)
245 """Get or set the PWM's output period in seconds.
248 PWMError: if an I/O or OS error occurs.
249 TypeError: if value type is not int or float.
254 def _get_duty_cycle(self):
255 duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
257 duty_cycle_ns = int(duty_cycle_ns)
260 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
263 # Convert duty cycle from nanoseconds to seconds
264 duty_cycle = duty_cycle_ns / 1e9
266 # Convert duty cycle to ratio from 0.0 to 1.0
267 duty_cycle = duty_cycle / self._period
270 duty_cycle = int(duty_cycle * 65535)
273 def _set_duty_cycle(self, duty_cycle):
274 if not isinstance(duty_cycle, (int, float)):
275 raise TypeError("Invalid duty cycle type, should be int or float.")
277 # convert from 16-bit
278 duty_cycle /= 65535.0
279 if not 0.0 <= duty_cycle <= 1.0:
280 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
282 # Convert duty cycle from ratio to seconds
283 duty_cycle = duty_cycle * self._period
285 # Convert duty cycle from seconds to integer nanoseconds
286 duty_cycle_ns = int(duty_cycle * 1e9)
288 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
290 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
291 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
294 PWMError: if an I/O or OS error occurs.
295 TypeError: if value type is not int or float.
296 ValueError: if value is out of bounds of 0.0 to 1.0.
301 def _get_frequency(self):
302 return 1.0 / self._get_period()
304 def _set_frequency(self, frequency):
305 if not isinstance(frequency, (int, float)):
306 raise TypeError("Invalid frequency type, should be int or float.")
308 self._set_period(1.0 / frequency)
310 frequency = property(_get_frequency, _set_frequency)
311 """Get or set the PWM's output frequency in Hertz.
314 PWMError: if an I/O or OS error occurs.
315 TypeError: if value type is not int or float.
320 def _get_enabled(self):
321 enabled = self._read_pin_attr(self._pin_enable_path)
328 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
330 def _set_enabled(self, value):
331 """Get or set the PWM's output enabled state.
334 PWMError: if an I/O or OS error occurs.
335 TypeError: if value type is not bool.
339 if not isinstance(value, bool):
340 raise TypeError("Invalid enabled type, should be string.")
342 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
344 # String representation
347 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
351 self.duty_cycle * 100,