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
10 from microcontroller.pin import pwmOuts
12 raise RuntimeError("No PWM outputs defined for this board") from ImportError
15 # pylint: disable=unnecessary-pass
16 class PWMError(IOError):
17 """Base class for PWM errors."""
22 # pylint: enable=unnecessary-pass
26 """Pulse Width Modulation Output Class"""
29 _sysfs_path = "/sys/class/pwm/"
30 _channel_path = "pwmchip{}"
33 _export_path = "export"
34 _unexport_path = "unexport"
38 _pin_period_path = "period"
39 _pin_duty_cycle_path = "duty_cycle"
40 _pin_polarity_path = "polarity"
41 _pin_enable_path = "enable"
43 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
44 """Instantiate a PWM object and open the sysfs PWM corresponding to the
45 specified channel and pin.
48 pin (Pin): CircuitPython Pin object to output to
49 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
50 frequency (int) : target frequency in Hertz (32-bit)
51 variable_frequency (bool) : True if the frequency will change over time
54 PWMOut: PWMOut object.
57 PWMError: if an I/O or OS error occurs.
58 TypeError: if `channel` or `pin` types are invalid.
59 ValueError: if PWM channel does not exist.
66 self._open(pin, duty_cycle, frequency, variable_frequency)
74 def __exit__(self, t, value, traceback):
77 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
79 for pwmpair in pwmOuts:
81 self._channel = pwmpair[0][0]
82 self._pwmpin = pwmpair[0][1]
85 if self._channel is None:
86 raise RuntimeError("No PWM channel found for this Pin")
88 if variable_frequency:
89 print("Variable Frequency is not supported, continuing without it...")
91 channel_path = os.path.join(
92 self._sysfs_path, self._channel_path.format(self._channel)
94 if not os.path.isdir(channel_path):
96 "PWM channel does not exist, check that the required modules are loaded."
101 os.path.join(channel_path, self._unexport_path), "w"
103 f_unexport.write("%d\n" % self._pwmpin)
105 pass # not unusual, it doesnt already exist
107 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
108 f_export.write("%d\n" % self._pwmpin)
110 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
112 # self._set_enabled(False) # This line causes a write error when trying to enable
114 # Look up the period, for fast duty cycle updates
115 self._period = self._get_period()
117 # self.duty_cycle = 0 # This line causes a write error when trying to enable
120 self.frequency = freq
122 self.duty_cycle = duty
124 self._set_enabled(True)
127 """Deinit the sysfs PWM."""
128 if self._channel is not None:
131 channel_path = os.path.join(
132 self._sysfs_path, self._channel_path.format(self._channel)
135 os.path.join(channel_path, self._unexport_path), "w"
137 f_unexport.write("%d\n" % self._pwmpin)
140 e.errno, "Unexporting PWM pin: " + e.strerror
146 def _is_deinited(self):
147 if self._pwmpin is None:
149 "Object has been deinitialize and can no longer "
150 "be used. Create a new object."
153 def _write_pin_attr(self, attr, value):
154 # Make sure the pin is active
159 self._channel_path.format(self._channel),
160 self._pin_path.format(self._pwmpin),
164 with open(path, "w") as f_attr:
166 f_attr.write(value + "\n")
168 def _read_pin_attr(self, attr):
169 # Make sure the pin is active
174 self._channel_path.format(self._channel),
175 self._pin_path.format(self._pwmpin),
179 with open(path, "r") as f_attr:
180 return f_attr.read().strip()
184 def _get_period(self):
185 period_ns = self._read_pin_attr(self._pin_period_path)
187 period_ns = int(period_ns)
190 None, 'Unknown period value: "%s"' % period_ns
193 # Convert period from nanoseconds to seconds
194 period = period_ns / 1e9
196 # Update our cached period
197 self._period = period
201 def _set_period(self, period):
202 if not isinstance(period, (int, float)):
203 raise TypeError("Invalid period type, should be int or float.")
205 # Convert period from seconds to integer nanoseconds
206 period_ns = int(period * 1e9)
208 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
210 # Update our cached period
211 self._period = float(period)
213 period = property(_get_period, _set_period)
215 """Get or set the PWM's output period in seconds.
218 PWMError: if an I/O or OS error occurs.
219 TypeError: if value type is not int or float.
224 def _get_duty_cycle(self):
225 duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
227 duty_cycle_ns = int(duty_cycle_ns)
230 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
233 # Convert duty cycle from nanoseconds to seconds
234 duty_cycle = duty_cycle_ns / 1e9
236 # Convert duty cycle to ratio from 0.0 to 1.0
237 duty_cycle = duty_cycle / self._period
240 duty_cycle = int(duty_cycle * 65535)
243 def _set_duty_cycle(self, duty_cycle):
244 if not isinstance(duty_cycle, (int, float)):
245 raise TypeError("Invalid duty cycle type, should be int or float.")
247 # convert from 16-bit
248 duty_cycle /= 65535.0
249 if not 0.0 <= duty_cycle <= 1.0:
250 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
252 # Convert duty cycle from ratio to seconds
253 duty_cycle = duty_cycle * self._period
255 # Convert duty cycle from seconds to integer nanoseconds
256 duty_cycle_ns = int(duty_cycle * 1e9)
258 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
260 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
261 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
264 PWMError: if an I/O or OS error occurs.
265 TypeError: if value type is not int or float.
266 ValueError: if value is out of bounds of 0.0 to 1.0.
271 def _get_frequency(self):
272 return 1.0 / self._get_period()
274 def _set_frequency(self, frequency):
275 if not isinstance(frequency, (int, float)):
276 raise TypeError("Invalid frequency type, should be int or float.")
278 self._set_period(1.0 / frequency)
280 frequency = property(_get_frequency, _set_frequency)
281 """Get or set the PWM's output frequency in Hertz.
284 PWMError: if an I/O or OS error occurs.
285 TypeError: if value type is not int or float.
290 def _get_enabled(self):
291 enabled = self._read_pin_attr(self._pin_enable_path)
298 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
300 def _set_enabled(self, value):
301 """Get or set the PWM's output enabled state.
304 PWMError: if an I/O or OS error occurs.
305 TypeError: if value type is not bool.
309 if not isinstance(value, bool):
310 raise TypeError("Invalid enabled type, should be string.")
312 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
314 # String representation
317 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
321 self.duty_cycle * 100,