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
18 # 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"""
32 _sysfs_path = "/sys/class/pwm/"
33 _channel_path = "pwmchip{}"
36 _export_path = "export"
37 _unexport_path = "unexport"
38 _pin_path = "pwm-{}:{}"
41 _pin_period_path = "period"
42 _pin_duty_cycle_path = "duty_cycle"
43 _pin_polarity_path = "polarity"
44 _pin_enable_path = "enable"
46 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
47 """Instantiate a PWM object and open the sysfs PWM corresponding to the
48 specified channel and pin.
51 pin (Pin): CircuitPython Pin object to output to
52 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
53 frequency (int) : target frequency in Hertz (32-bit)
54 variable_frequency (bool) : True if the frequency will change over time
57 PWMOut: PWMOut object.
60 PWMError: if an I/O or OS error occurs.
61 TypeError: if `channel` or `pin` types are invalid.
62 ValueError: if PWM channel does not exist.
69 self._open(pin, duty_cycle, frequency, variable_frequency)
77 def __exit__(self, t, value, traceback):
80 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
82 for pwmpair in pwmOuts:
84 self._channel = pwmpair[0][0]
85 self._pwmpin = pwmpair[0][1]
88 if self._channel is None:
89 raise RuntimeError("No PWM channel found for this Pin")
91 if variable_frequency:
92 print("Variable Frequency is not supported, continuing without it...")
94 channel_path = os.path.join(
95 self._sysfs_path, self._channel_path.format(self._channel)
97 if not os.path.isdir(channel_path):
99 "PWM channel does not exist, check that the required modules are loaded."
102 pin_path = os.path.join(
103 channel_path, self._pin_path.format(self._channel, self._pwmpin)
105 if not os.path.isdir(pin_path):
108 os.path.join(channel_path, self._export_path), "w", encoding="utf-8"
110 f_export.write("%d\n" % self._pwmpin)
112 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
114 # Look up the period, for fast duty cycle updates
115 self._period = self._get_period()
118 self.frequency = freq
120 self.duty_cycle = duty
122 self._set_enabled(True)
125 """Deinit the sysfs PWM."""
126 # pylint: disable=broad-except
128 channel_path = os.path.join(
129 self._sysfs_path, self._channel_path.format(self._channel)
132 if self._channel is not None:
133 # self.duty_cycle = 0
134 self._set_enabled(False) # make to disable before unexport
136 # unexport_path = os.path.join(channel_path, self._unexport_path)
138 os.path.join(channel_path, self._unexport_path),
142 f_unexport.write("%d\n" % self._pwmpin)
145 e.errno, "Unexporting PWM pin: " + e.strerror
147 except Exception as e:
148 # due to a race condition for which I have not yet been
149 # able to find the root cause, deinit() often fails
150 # but it does not effect future usage of the pwm pin
152 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
153 self._channel, self._pwmpin, type(e).__name__
159 # pylint: enable=broad-except
161 def _is_deinited(self):
162 if self._pwmpin is None:
164 "Object has been deinitialize and can no longer "
165 "be used. Create a new object."
168 def _write_pin_attr(self, attr, value):
169 # Make sure the pin is active
174 self._channel_path.format(self._channel),
175 self._pin_path.format(self._channel, self._pwmpin),
179 with open(path, "w", encoding="utf-8") as f_attr:
180 f_attr.write(value + "\n")
182 def _read_pin_attr(self, attr):
183 # Make sure the pin is active
188 self._channel_path.format(self._channel),
189 self._pin_path.format(self._channel, self._pwmpin),
193 with open(path, "r", encoding="utf-8") as f_attr:
194 return f_attr.read().strip()
198 def _get_period(self):
199 period_ns = self._read_pin_attr(self._pin_period_path)
201 period_ns = int(period_ns)
204 None, 'Unknown period value: "%s"' % period_ns
207 # Convert period from nanoseconds to seconds
208 period = period_ns / 1e9
210 # Update our cached period
211 self._period = period
215 def _set_period(self, period):
216 if not isinstance(period, (int, float)):
217 raise TypeError("Invalid period type, should be int or float.")
219 # Convert period from seconds to integer nanoseconds
220 period_ns = int(period * 1e9)
222 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
224 # Update our cached period
225 self._period = float(period)
227 period = property(_get_period, _set_period)
229 """Get or set the PWM's output period in seconds.
232 PWMError: if an I/O or OS error occurs.
233 TypeError: if value type is not int or float.
238 def _get_duty_cycle(self):
239 duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
241 duty_cycle_ns = int(duty_cycle_ns)
244 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
247 # Convert duty cycle from nanoseconds to seconds
248 duty_cycle = duty_cycle_ns / 1e9
250 # Convert duty cycle to ratio from 0.0 to 1.0
251 duty_cycle = duty_cycle / self._period
254 duty_cycle = int(duty_cycle * 65535)
257 def _set_duty_cycle(self, duty_cycle):
258 if not isinstance(duty_cycle, (int, float)):
259 raise TypeError("Invalid duty cycle type, should be int or float.")
261 # convert from 16-bit
262 duty_cycle /= 65535.0
263 if not 0.0 <= duty_cycle <= 1.0:
264 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
266 # Convert duty cycle from ratio to seconds
267 duty_cycle = duty_cycle * self._period
269 # Convert duty cycle from seconds to integer nanoseconds
270 duty_cycle_ns = int(duty_cycle * 1e9)
272 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
274 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
275 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
278 PWMError: if an I/O or OS error occurs.
279 TypeError: if value type is not int or float.
280 ValueError: if value is out of bounds of 0.0 to 1.0.
285 def _get_frequency(self):
286 return 1.0 / self._get_period()
288 def _set_frequency(self, frequency):
289 if not isinstance(frequency, (int, float)):
290 raise TypeError("Invalid frequency type, should be int or float.")
292 self._set_period(1.0 / frequency)
294 frequency = property(_get_frequency, _set_frequency)
295 """Get or set the PWM's output frequency in Hertz.
298 PWMError: if an I/O or OS error occurs.
299 TypeError: if value type is not int or float.
304 def _get_enabled(self):
305 enabled = self._read_pin_attr(self._pin_enable_path)
312 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
314 def _set_enabled(self, value):
315 """Get or set the PWM's output enabled state.
318 PWMError: if an I/O or OS error occurs.
319 TypeError: if value type is not bool.
323 if not isinstance(value, bool):
324 raise TypeError("Invalid enabled type, should be string.")
326 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
328 # String representation
331 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
335 self.duty_cycle * 100,