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 from adafruit_blinka.microcontroller.nova import Connection
42 PWMOut._nova = Connection.getInstance()
45 self._open(pin, duty_cycle, frequency, variable_frequency)
53 def __exit__(self, t, value, traceback):
56 def _open(self, pin, duty=0, freq=750, variable_frequency=False):
58 for pwmpair in pwmOuts:
60 self._channel = pwmpair[0][0]
61 self._pwmpin = pwmpair[0][1]
64 if self._channel is None:
65 raise RuntimeError("No PWM channel found for this Pin")
67 PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
72 self._period = self._get_period()
75 self.duty_cycle = duty
77 self._set_enabled(True)
81 """Deinit the Nova PWM."""
82 if self._channel is not None:
84 self._set_enabled(False) # make to disable before unexport
86 except Exception as e:
87 # due to a race condition for which I have not yet been
88 # able to find the root cause, deinit() often fails
89 # but it does not effect future usage of the pwm pin
90 print("warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(self._channel, self._pwmpin, type(e).__name__))
95 def _is_deinited(self):
96 if self._pwmpin is None:
97 raise ValueError("Object has been deinitialize and can no longer "
98 "be used. Create a new object.")
102 def _get_period(self):
103 return 1.0 / self._get_frequency()
105 def _set_period(self, period):
106 if not isinstance(period, (int, float)):
107 raise TypeError("Invalid period type, should be int or float.")
109 self._set_frequency(1.0 / period)
111 period = property(_get_period, _set_period)
113 """Get or set the PWM's output period in seconds.
116 PWMError: if an I/O or OS error occurs.
117 TypeError: if value type is not int or float.
122 def _get_duty_cycle(self):
123 duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
125 # Convert duty cycle to ratio from 0.0 to 1.0
126 duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
129 duty_cycle = int(duty_cycle * 65535)
132 def _set_duty_cycle(self, duty_cycle):
133 if not isinstance(duty_cycle, (int, float)):
134 raise TypeError("Invalid duty cycle type, should be int or float.")
136 # convert from 16-bit
137 duty_cycle /= 65535.0
138 if not 0.0 <= duty_cycle <= 1.0:
139 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
141 # Convert duty cycle from ratio to 1024 levels
142 duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
145 Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
147 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
148 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
151 PWMError: if an I/O or OS error occurs.
152 TypeError: if value type is not int or float.
153 ValueError: if value is out of bounds of 0.0 to 1.0.
158 def _get_frequency(self):
159 return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split('PWMFREQ ')[1])
161 def _set_frequency(self, frequency):
162 if not isinstance(frequency, (int, float)):
163 raise TypeError("Invalid frequency type, should be int or float.")
165 PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
167 frequency = property(_get_frequency, _set_frequency)
168 """Get or set the PWM's output frequency in Hertz.
171 PWMError: if an I/O or OS error occurs.
172 TypeError: if value type is not int or float.
177 def _get_enabled(self):
178 enabled = self._enable
185 raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
187 def _set_enabled(self, value):
188 if not isinstance(value, bool):
189 raise TypeError("Invalid enabled type, should be string.")
192 self._set_duty_cycle(0.0)
193 """Get or set the PWM's output enabled state.
196 PWMError: if an I/O or OS error occurs.
197 TypeError: if value type is not bool.
202 # String representation
205 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
206 (self._pin, self._pin, self.frequency, self.duty_cycle * 100,)