5 from microcontroller.pin import pwmOuts
7 raise RuntimeError("No PWM outputs defined for this board")
9 from microcontroller.pin import Pin
11 class PWMError(IOError):
12 """Base class for PWM errors."""
19 MAX_CYCLE_LEVEL = 1024
21 def __init__(self, pin, *, frequency=750, duty_cycle=0, variable_frequency=False):
22 """Instantiate a PWM object and open the sysfs PWM corresponding to the
23 specified channel and pin.
26 pin (Pin): CircuitPython Pin object to output to
27 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
28 frequency (int) : target frequency in Hertz (32-bit)
29 variable_frequency (bool) : True if the frequency will change over time
32 PWMOut: PWMOut object.
35 PWMError: if an I/O or OS error occurs.
36 TypeError: if `channel` or `pin` types are invalid.
37 ValueError: if PWM channel does not exist.
40 if PWMOut._nova is None:
41 if Pin._nova is not None:
42 # check if Pin already connected to Binho Nova
43 PWMOut._nova = Pin._nova
45 from binhoHostAdapter import binhoHostAdapter
46 from binhoHostAdapter import binhoUtilities
48 utilities = binhoUtilities.binhoUtilities()
49 devices = utilities.listAvailableDevices()
52 PWMOut._nova = binhoHostAdapter.binhoHostAdapter(devices[0])
54 raise RuntimeError('No Binho Host Adapter found!')
57 self._open(pin, duty_cycle, frequency, variable_frequency)
65 def __exit__(self, t, value, traceback):
68 def _open(self, pin, duty=0, freq=750, variable_frequency=False):
70 for pwmpair in pwmOuts:
72 self._channel = pwmpair[0][0]
73 self._pwmpin = pwmpair[0][1]
76 if self._channel is None:
77 raise RuntimeError("No PWM channel found for this Pin")
79 PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
83 PWMOut._nova.setIOpinPWMFreq(self._pwmpin, self.frequency)
85 self._period = self._get_period()
88 self.duty_cycle = duty
90 self._set_enabled(True)
94 """Deinit the Nova PWM."""
95 if self._channel is not None:
97 self._set_enabled(False) # make to disable before unexport
100 #unexport_path = os.path.join(channel_path, self._unexport_path)
101 with open(os.path.join(channel_path, self._unexport_path), "w") as f_unexport:
102 f_unexport.write("%d\n" % self._pwmpin)
104 raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
106 except Exception as e:
107 # due to a race condition for which I have not yet been
108 # able to find the root cause, deinit() often fails
109 # but it does not effect future usage of the pwm pin
110 print("warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(self._channel, self._pwmpin, type(e).__name__))
115 def _is_deinited(self):
116 if self._pwmpin is None:
117 raise ValueError("Object has been deinitialize and can no longer "
118 "be used. Create a new object.")
122 def _get_period(self):
123 return 1.0 / self._get_frequency()
125 def _set_period(self, period):
126 if not isinstance(period, (int, float)):
127 raise TypeError("Invalid period type, should be int or float.")
129 self._set_frequency(1.0 / period)
131 period = property(_get_period, _set_period)
133 """Get or set the PWM's output period in seconds.
136 PWMError: if an I/O or OS error occurs.
137 TypeError: if value type is not int or float.
142 def _get_duty_cycle(self):
143 duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
145 # Convert duty cycle to ratio from 0.0 to 1.0
146 duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
149 duty_cycle = int(duty_cycle * 65535)
152 def _set_duty_cycle(self, duty_cycle):
153 if not isinstance(duty_cycle, (int, float)):
154 raise TypeError("Invalid duty cycle type, should be int or float.")
156 # convert from 16-bit
157 duty_cycle /= 65535.0
158 if not 0.0 <= duty_cycle <= 1.0:
159 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
161 # Convert duty cycle from ratio to 1024 levels
162 duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
165 Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
167 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
168 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
171 PWMError: if an I/O or OS error occurs.
172 TypeError: if value type is not int or float.
173 ValueError: if value is out of bounds of 0.0 to 1.0.
178 def _get_frequency(self):
179 return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split('PWMFREQ ')[1])
181 def _set_frequency(self, frequency):
182 if not isinstance(frequency, (int, float)):
183 raise TypeError("Invalid frequency type, should be int or float.")
185 PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
187 frequency = property(_get_frequency, _set_frequency)
188 """Get or set the PWM's output frequency in Hertz.
191 PWMError: if an I/O or OS error occurs.
192 TypeError: if value type is not int or float.
197 def _get_enabled(self):
198 enabled = self._enable
205 raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
207 def _set_enabled(self, value):
208 if not isinstance(value, bool):
209 raise TypeError("Invalid enabled type, should be string.")
212 self._set_duty_cycle(0.0)
213 """Get or set the PWM's output enabled state.
216 PWMError: if an I/O or OS error occurs.
217 TypeError: if value type is not bool.
222 # String representation
225 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
226 (self._pin, self._pin, self.frequency, self.duty_cycle * 100,)