1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
5 Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
6 Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
13 from microcontroller.pin import pwmOuts
15 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"""
31 _sysfs_path = "/sys/class/pwm/"
32 _channel_path = "pwmchip{}"
35 _export_path = "export"
36 _unexport_path = "unexport"
37 _pin_path = "pwm-{}:{}"
40 _pin_period_path = "period"
41 _pin_duty_cycle_path = "duty_cycle"
42 _pin_polarity_path = "polarity"
43 _pin_enable_path = "enable"
45 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
46 """Instantiate a PWM object and open the sysfs PWM corresponding to the
47 specified channel and pin.
50 pin (Pin): CircuitPython Pin object to output to
51 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
52 frequency (int) : target frequency in Hertz (32-bit)
53 variable_frequency (bool) : True if the frequency will change over time
56 PWMOut: PWMOut object.
59 PWMError: if an I/O or OS error occurs.
60 TypeError: if `channel` or `pin` types are invalid.
61 ValueError: if PWM channel does not exist.
68 self._open(pin, duty_cycle, frequency, variable_frequency)
76 def __exit__(self, t, value, traceback):
79 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
81 for pwmpair in pwmOuts:
83 self._channel = pwmpair[0][0]
84 self._pwmpin = pwmpair[0][1]
87 if self._channel is None:
88 raise RuntimeError("No PWM channel found for this Pin")
90 if variable_frequency:
91 print("Variable Frequency is not supported, continuing without it...")
93 channel_path = os.path.join(
94 self._sysfs_path, self._channel_path.format(self._channel)
96 if not os.path.isdir(channel_path):
98 "PWM channel does not exist, check that the required modules are loaded."
101 pin_path = os.path.join(
102 channel_path, self._pin_path.format(self._channel, self._pwmpin)
104 if not os.path.isdir(pin_path):
107 os.path.join(channel_path, self._export_path), "w", encoding="utf-8"
109 f_export.write("%d\n" % self._pwmpin)
111 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
113 # Look up the period, for fast duty cycle updates
114 self._period = self._get_period()
117 self.frequency = freq
119 self.duty_cycle = duty
121 self._set_enabled(True)
124 """Deinit the sysfs PWM."""
125 # pylint: disable=broad-except
127 channel_path = os.path.join(
128 self._sysfs_path, self._channel_path.format(self._channel)
131 if self._channel is not None:
132 # self.duty_cycle = 0
133 self._set_enabled(False) # make to disable before unexport
135 # unexport_path = os.path.join(channel_path, self._unexport_path)
137 os.path.join(channel_path, self._unexport_path),
141 f_unexport.write("%d\n" % self._pwmpin)
144 e.errno, "Unexporting PWM pin: " + e.strerror
146 except Exception as e:
147 # due to a race condition for which I have not yet been
148 # able to find the root cause, deinit() often fails
149 # but it does not effect future usage of the pwm pin
151 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
152 self._channel, self._pwmpin, type(e).__name__
158 # pylint: enable=broad-except
160 def _is_deinited(self):
161 if self._pwmpin is None:
163 "Object has been deinitialize and can no longer "
164 "be used. Create a new object."
167 def _write_pin_attr(self, attr, value):
168 # Make sure the pin is active
173 self._channel_path.format(self._channel),
174 self._pin_path.format(self._channel, self._pwmpin),
178 with open(path, "w", encoding="utf-8") as f_attr:
179 f_attr.write(value + "\n")
181 def _read_pin_attr(self, attr):
182 # Make sure the pin is active
187 self._channel_path.format(self._channel),
188 self._pin_path.format(self._channel, self._pwmpin),
192 with open(path, "r", encoding="utf-8") as f_attr:
193 return f_attr.read().strip()
197 def _get_period(self):
198 period_ns = self._read_pin_attr(self._pin_period_path)
200 period_ns = int(period_ns)
203 None, 'Unknown period value: "%s"' % period_ns
206 # Convert period from nanoseconds to seconds
207 period = period_ns / 1e9
209 # Update our cached period
210 self._period = period
214 def _set_period(self, period):
215 if not isinstance(period, (int, float)):
216 raise TypeError("Invalid period type, should be int or float.")
218 # Convert period from seconds to integer nanoseconds
219 period_ns = int(period * 1e9)
221 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
223 # Update our cached period
224 self._period = float(period)
226 period = property(_get_period, _set_period)
228 """Get or set the PWM's output period in seconds.
231 PWMError: if an I/O or OS error occurs.
232 TypeError: if value type is not int or float.
237 def _get_duty_cycle(self):
238 duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
240 duty_cycle_ns = int(duty_cycle_ns)
243 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
246 # Convert duty cycle from nanoseconds to seconds
247 duty_cycle = duty_cycle_ns / 1e9
249 # Convert duty cycle to ratio from 0.0 to 1.0
250 duty_cycle = duty_cycle / self._period
253 duty_cycle = int(duty_cycle * 65535)
256 def _set_duty_cycle(self, duty_cycle):
257 if not isinstance(duty_cycle, (int, float)):
258 raise TypeError("Invalid duty cycle type, should be int or float.")
260 # convert from 16-bit
261 duty_cycle /= 65535.0
262 if not 0.0 <= duty_cycle <= 1.0:
263 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
265 # Convert duty cycle from ratio to seconds
266 duty_cycle = duty_cycle * self._period
268 # Convert duty cycle from seconds to integer nanoseconds
269 duty_cycle_ns = int(duty_cycle * 1e9)
271 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
273 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
274 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
277 PWMError: if an I/O or OS error occurs.
278 TypeError: if value type is not int or float.
279 ValueError: if value is out of bounds of 0.0 to 1.0.
284 def _get_frequency(self):
285 return 1.0 / self._get_period()
287 def _set_frequency(self, frequency):
288 if not isinstance(frequency, (int, float)):
289 raise TypeError("Invalid frequency type, should be int or float.")
291 self._set_period(1.0 / frequency)
293 frequency = property(_get_frequency, _set_frequency)
294 """Get or set the PWM's output frequency in Hertz.
297 PWMError: if an I/O or OS error occurs.
298 TypeError: if value type is not int or float.
303 def _get_enabled(self):
304 enabled = self._read_pin_attr(self._pin_enable_path)
311 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
313 def _set_enabled(self, value):
314 """Get or set the PWM's output enabled state.
317 PWMError: if an I/O or OS error occurs.
318 TypeError: if value type is not bool.
322 if not isinstance(value, bool):
323 raise TypeError("Invalid enabled type, should be string.")
325 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
327 # String representation
330 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
334 self.duty_cycle * 100,