3 from microcontroller.pin import pwmOuts
5 raise RuntimeError("No PWM outputs defined for this board")
7 from microcontroller.pin import Pin
9 class PWMError(IOError):
10 """Base class for PWM errors."""
17 MAX_CYCLE_LEVEL = 1024
19 def __init__(self, pin, *, frequency=750, duty_cycle=0, variable_frequency=False):
20 """Instantiate a PWM object and open the sysfs PWM corresponding to the
21 specified channel and pin.
24 pin (Pin): CircuitPython Pin object to output to
25 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
26 frequency (int) : target frequency in Hertz (32-bit)
27 variable_frequency (bool) : True if the frequency will change over time
30 PWMOut: PWMOut object.
33 PWMError: if an I/O or OS error occurs.
34 TypeError: if `channel` or `pin` types are invalid.
35 ValueError: if PWM channel does not exist.
38 if PWMOut._nova is None:
39 from adafruit_blinka.microcontroller.nova import Connection
40 PWMOut._nova = Connection.getInstance()
42 PWMOut._nova.setOperationMode(0, 'IO')
44 self._open(pin, duty_cycle, frequency, variable_frequency)
52 def __exit__(self, t, value, traceback):
55 def _open(self, pin, duty=0, freq=750, variable_frequency=False):
57 for pwmpair in pwmOuts:
59 self._channel = pwmpair[0][0]
60 self._pwmpin = pwmpair[0][1]
63 if self._channel is None:
64 raise RuntimeError("No PWM channel found for this Pin")
66 PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
71 self._period = self._get_period()
74 self.duty_cycle = duty
76 self._set_enabled(True)
80 """Deinit the Nova PWM."""
81 if self._channel is not None:
83 self._set_enabled(False) # make to disable before unexport
85 except Exception as e:
86 # due to a race condition for which I have not yet been
87 # able to find the root cause, deinit() often fails
88 # but it does not effect future usage of the pwm pin
89 print("warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(self._channel, self._pwmpin, type(e).__name__))
94 def _is_deinited(self):
95 if self._pwmpin is None:
96 raise ValueError("Object has been deinitialize and can no longer "
97 "be used. Create a new object.")
101 def _get_period(self):
102 return 1.0 / self._get_frequency()
104 def _set_period(self, period):
105 if not isinstance(period, (int, float)):
106 raise TypeError("Invalid period type, should be int or float.")
108 self._set_frequency(1.0 / period)
110 period = property(_get_period, _set_period)
112 """Get or set the PWM's output period in seconds.
115 PWMError: if an I/O or OS error occurs.
116 TypeError: if value type is not int or float.
121 def _get_duty_cycle(self):
122 duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
124 # Convert duty cycle to ratio from 0.0 to 1.0
125 duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
128 duty_cycle = int(duty_cycle * 65535)
131 def _set_duty_cycle(self, duty_cycle):
132 if not isinstance(duty_cycle, (int, float)):
133 raise TypeError("Invalid duty cycle type, should be int or float.")
135 # convert from 16-bit
136 duty_cycle /= 65535.0
137 if not 0.0 <= duty_cycle <= 1.0:
138 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
140 # Convert duty cycle from ratio to 1024 levels
141 duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
144 Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
146 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
147 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
150 PWMError: if an I/O or OS error occurs.
151 TypeError: if value type is not int or float.
152 ValueError: if value is out of bounds of 0.0 to 1.0.
157 def _get_frequency(self):
158 return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split('PWMFREQ ')[1])
160 def _set_frequency(self, frequency):
161 if not isinstance(frequency, (int, float)):
162 raise TypeError("Invalid frequency type, should be int or float.")
164 PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
166 frequency = property(_get_frequency, _set_frequency)
167 """Get or set the PWM's output frequency in Hertz.
170 PWMError: if an I/O or OS error occurs.
171 TypeError: if value type is not int or float.
176 def _get_enabled(self):
177 enabled = self._enable
184 raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
186 def _set_enabled(self, value):
187 if not isinstance(value, bool):
188 raise TypeError("Invalid enabled type, should be string.")
191 self._set_duty_cycle(0.0)
192 """Get or set the PWM's output enabled state.
195 PWMError: if an I/O or OS error occurs.
196 TypeError: if value type is not bool.
201 # String representation
204 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
205 (self._pin, self._pin, self.frequency, self.duty_cycle * 100,)