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)
35 _sysfs_path = "/sys/class/pwm/"
36 _channel_path = "pwmchip{}"
39 _export_path = "export"
40 _unexport_path = "unexport"
44 _pin_period_path = "period"
45 _pin_duty_cycle_path = "duty_cycle"
46 _pin_polarity_path = "polarity"
47 _pin_enable_path = "enable"
49 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
50 """Instantiate a PWM object and open the sysfs PWM corresponding to the
51 specified channel and pin.
54 pin (Pin): CircuitPython Pin object to output to
55 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
56 frequency (int) : target frequency in Hertz (32-bit)
57 variable_frequency (bool) : True if the frequency will change over time
60 PWMOut: PWMOut object.
63 PWMError: if an I/O or OS error occurs.
64 TypeError: if `channel` or `pin` types are invalid.
65 ValueError: if PWM channel does not exist.
72 self._open(pin, duty_cycle, frequency, variable_frequency)
80 def __exit__(self, t, value, traceback):
83 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
85 for pwmpair in pwmOuts:
87 self._channel = pwmpair[0][0]
88 self._pwmpin = pwmpair[0][1]
91 if self._channel is None:
92 raise RuntimeError("No PWM channel found for this Pin")
94 if variable_frequency:
95 print("Variable Frequency is not supported, continuing without it...")
97 channel_path = os.path.join(
98 self._sysfs_path, self._channel_path.format(self._channel)
100 if not os.path.isdir(channel_path):
102 "PWM channel does not exist, check that the required modules are loaded."
107 os.path.join(channel_path, self._unexport_path), "w"
109 f_unexport.write("%d\n" % self._pwmpin)
111 pass # not unusual, it doesnt already exist
113 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
114 f_export.write("%d\n" % self._pwmpin)
116 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
118 # Loop until 'period' is writable, because application of udev rules
119 # after the above pin export is asynchronous.
120 # Without this loop, the following properties may not be writable yet.
121 for i in range(PWMOut.PWM_STAT_RETRIES):
124 os.path.join(channel_path, self._pin_path.format(self._pwmpin), "period"), 'w'
126 print('#### okay ####')
129 if e.errno != EACCES or (e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1):
130 print('#### catch ####')
131 raise PWMError(e.errno, "Opening PWM period: " + e.strerror)
132 sleep(PWMOut.PWM_STAT_DELAY)
134 # self._set_enabled(False) # This line causes a write error when trying to enable
136 # Look up the period, for fast duty cycle updates
137 self._period = self._get_period()
139 # self.duty_cycle = 0 # This line causes a write error when trying to enable
142 self.frequency = freq
144 self.duty_cycle = duty
146 self._set_enabled(True)
149 """Deinit the sysfs PWM."""
150 if self._channel is not None:
153 channel_path = os.path.join(
154 self._sysfs_path, self._channel_path.format(self._channel)
157 os.path.join(channel_path, self._unexport_path), "w"
159 f_unexport.write("%d\n" % self._pwmpin)
162 e.errno, "Unexporting PWM pin: " + e.strerror
168 def _is_deinited(self):
169 if self._pwmpin is None:
171 "Object has been deinitialize and can no longer "
172 "be used. Create a new object."
175 def _write_pin_attr(self, attr, value):
176 # Make sure the pin is active
181 self._channel_path.format(self._channel),
182 self._pin_path.format(self._pwmpin),
186 with open(path, "w") as f_attr:
188 f_attr.write(value + "\n")
190 def _read_pin_attr(self, attr):
191 # Make sure the pin is active
196 self._channel_path.format(self._channel),
197 self._pin_path.format(self._pwmpin),
201 with open(path, "r") as f_attr:
202 return f_attr.read().strip()
206 def _get_period(self):
207 period_ns = self._read_pin_attr(self._pin_period_path)
209 period_ns = int(period_ns)
212 None, 'Unknown period value: "%s"' % period_ns
215 # Convert period from nanoseconds to seconds
216 period = period_ns / 1e9
218 # Update our cached period
219 self._period = period
223 def _set_period(self, period):
224 if not isinstance(period, (int, float)):
225 raise TypeError("Invalid period type, should be int or float.")
227 # Convert period from seconds to integer nanoseconds
228 period_ns = int(period * 1e9)
230 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
232 # Update our cached period
233 self._period = float(period)
235 period = property(_get_period, _set_period)
237 """Get or set the PWM's output period in seconds.
240 PWMError: if an I/O or OS error occurs.
241 TypeError: if value type is not int or float.
246 def _get_duty_cycle(self):
247 duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
249 duty_cycle_ns = int(duty_cycle_ns)
252 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
255 # Convert duty cycle from nanoseconds to seconds
256 duty_cycle = duty_cycle_ns / 1e9
258 # Convert duty cycle to ratio from 0.0 to 1.0
259 duty_cycle = duty_cycle / self._period
262 duty_cycle = int(duty_cycle * 65535)
265 def _set_duty_cycle(self, duty_cycle):
266 if not isinstance(duty_cycle, (int, float)):
267 raise TypeError("Invalid duty cycle type, should be int or float.")
269 # convert from 16-bit
270 duty_cycle /= 65535.0
271 if not 0.0 <= duty_cycle <= 1.0:
272 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
274 # Convert duty cycle from ratio to seconds
275 duty_cycle = duty_cycle * self._period
277 # Convert duty cycle from seconds to integer nanoseconds
278 duty_cycle_ns = int(duty_cycle * 1e9)
280 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
282 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
283 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
286 PWMError: if an I/O or OS error occurs.
287 TypeError: if value type is not int or float.
288 ValueError: if value is out of bounds of 0.0 to 1.0.
293 def _get_frequency(self):
294 return 1.0 / self._get_period()
296 def _set_frequency(self, frequency):
297 if not isinstance(frequency, (int, float)):
298 raise TypeError("Invalid frequency type, should be int or float.")
300 self._set_period(1.0 / frequency)
302 frequency = property(_get_frequency, _set_frequency)
303 """Get or set the PWM's output frequency in Hertz.
306 PWMError: if an I/O or OS error occurs.
307 TypeError: if value type is not int or float.
312 def _get_enabled(self):
313 enabled = self._read_pin_attr(self._pin_enable_path)
320 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
322 def _set_enabled(self, value):
323 """Get or set the PWM's output enabled state.
326 PWMError: if an I/O or OS error occurs.
327 TypeError: if value type is not bool.
331 if not isinstance(value, bool):
332 raise TypeError("Invalid enabled type, should be string.")
334 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
336 # String representation
339 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
343 self.duty_cycle * 100,