1 # Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
2 # Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
9 from microcontroller.pin import pwmOuts
11 raise RuntimeError("No PWM outputs defined for this board")
13 class PWMError(IOError):
14 """Base class for PWM errors."""
20 _sysfs_path = "/sys/class/pwm/"
21 _channel_path = "pwmchip{}"
24 _export_path = "export"
25 _unexport_path = "unexport"
29 _pin_period_path = "period"
30 _pin_duty_cycle_path = "duty_cycle"
31 _pin_polarity_path = "polarity"
32 _pin_enable_path = "enable"
34 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
35 """Instantiate a PWM object and open the sysfs PWM corresponding to the
36 specified channel and pin.
39 pin (Pin): CircuitPython Pin object to output to
40 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
41 frequency (int) : target frequency in Hertz (32-bit)
42 variable_frequency (bool) : True if the frequency will change over time
45 PWMOut: PWMOut object.
48 PWMError: if an I/O or OS error occurs.
49 TypeError: if `channel` or `pin` types are invalid.
50 ValueError: if PWM channel does not exist.
55 self._open(pin, duty_cycle, frequency, variable_frequency)
63 def __exit__(self, t, value, traceback):
69 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
71 for pwmpair in pwmOuts:
73 self._channel = pwmpair[0][0]
74 self._pwmpin = pwmpair[0][1]
77 if self._channel is None:
78 raise RuntimeError("No PWM channel found for this Pin")
80 channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
81 if not os.path.isdir(channel_path):
82 raise ValueError("PWM channel does not exist, check that the required modules are loaded.")
84 pin_path = os.path.join(channel_path, self._pin_path.format(self._pwmpin))
86 with open(os.path.join(channel_path, self._unexport_path), "w") as f_unexport:
87 f_unexport.write("%d\n" % self._pwmpin)
89 pass # not unusual, it doesnt already exist
91 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
92 f_export.write("%d\n" % self._pwmpin)
94 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror)
96 self._set_enabled(False)
98 # Look up the period, for fast duty cycle updates
99 self._period = self._get_period()
104 self.frequency = freq
106 self.duty_cycle = duty
108 self._set_enabled(True)
111 """Close the sysfs PWM."""
112 if self._channel is not None:
115 channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
116 with open(os.path.join(channel_path, self._unexport_path), "w") as f_unexport:
117 f_unexport.write("%d\n" % self._pwmpin)
119 raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
124 def _write_pin_attr(self, attr, value):
127 self._channel_path.format(self._channel),
128 self._pin_path.format(self._pwmpin),
131 with open(path, 'w') as f_attr:
133 f_attr.write(value + "\n")
135 def _read_pin_attr(self, attr):
138 self._channel_path.format(self._channel),
139 self._pin_path.format(self._pwmpin),
142 with open(path, 'r') as f_attr:
143 return f_attr.read().strip()
147 def _get_period(self):
149 period_ns = int(self._read_pin_attr(self._pin_period_path))
151 raise PWMError(None, "Unknown period value: \"%s\"" % period_ns)
153 # Convert period from nanoseconds to seconds
154 period = period_ns / 1e9
156 # Update our cached period
157 self._period = period
161 def _set_period(self, period):
162 if not isinstance(period, (int, float)):
163 raise TypeError("Invalid period type, should be int or float.")
165 # Convert period from seconds to integer nanoseconds
166 period_ns = int(period * 1e9)
168 self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
170 # Update our cached period
171 self._period = float(period)
173 """Get or set the PWM's output period in seconds.
176 PWMError: if an I/O or OS error occurs.
177 TypeError: if value type is not int or float.
182 def _get_duty_cycle(self):
184 duty_cycle_ns = int(self._read_pin_attr(self._pin_duty_cycle_path))
186 raise PWMError(None, "Unknown duty cycle value: \"%s\"" % duty_cycle_ns)
188 # Convert duty cycle from nanoseconds to seconds
189 duty_cycle = duty_cycle_ns / 1e9
191 # Convert duty cycle to ratio from 0.0 to 1.0
192 duty_cycle = duty_cycle / self._period
195 duty_cycle = int(duty_cycle * 65535)
198 def _set_duty_cycle(self, duty_cycle):
199 if not isinstance(duty_cycle, (int, float)):
200 raise TypeError("Invalid duty cycle type, should be int or float.")
202 # convert from 16-bit
203 duty_cycle /= 65535.0
204 if not 0.0 <= duty_cycle <= 1.0:
205 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
207 # Convert duty cycle from ratio to seconds
208 duty_cycle = duty_cycle * self._period
210 # Convert duty cycle from seconds to integer nanoseconds
211 duty_cycle_ns = int(duty_cycle * 1e9)
213 self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
215 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
216 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
219 PWMError: if an I/O or OS error occurs.
220 TypeError: if value type is not int or float.
221 ValueError: if value is out of bounds of 0.0 to 1.0.
226 def _get_frequency(self):
227 return 1.0 / self._get_period()
229 def _set_frequency(self, frequency):
230 if not isinstance(frequency, (int, float)):
231 raise TypeError("Invalid frequency type, should be int or float.")
233 self._set_period(1.0 / frequency)
235 frequency = property(_get_frequency, _set_frequency)
236 """Get or set the PWM's output frequency in Hertz.
239 PWMError: if an I/O or OS error occurs.
240 TypeError: if value type is not int or float.
245 def _get_enabled(self):
246 enabled = self._read_pin_attr(self._pin_enable_path)
253 raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
255 def _set_enabled(self, value):
256 if not isinstance(value, bool):
257 raise TypeError("Invalid enabled type, should be string.")
259 self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
261 """Get or set the PWM's output enabled state.
264 PWMError: if an I/O or OS error occurs.
265 TypeError: if value type is not bool.
270 # String representation
273 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
274 (self._channel, self._pin, self.frequency, self.duty_cycle * 100,)