1 """PWMOut Class for Binho Nova"""
4 from microcontroller.pin import pwmOuts
6 raise RuntimeError("No PWM outputs defined for this board")
8 from microcontroller.pin import Pin
11 # pylint: disable=unnecessary-pass
12 class PWMError(IOError):
13 """Base class for PWM errors."""
18 # pylint: enable=unnecessary-pass
22 """Pulse Width Modulation Output Class"""
26 MAX_CYCLE_LEVEL = 1024
28 def __init__(self, pin, *, frequency=750, duty_cycle=0, variable_frequency=False):
29 """Instantiate a PWM object and open the sysfs PWM corresponding to the
30 specified channel and pin.
33 pin (Pin): CircuitPython Pin object to output to
34 duty_cycle (int) : The fraction of each pulse which is high. 16-bit
35 frequency (int) : target frequency in Hertz (32-bit)
36 variable_frequency (bool) : True if the frequency will change over time
39 PWMOut: PWMOut object.
42 PWMError: if an I/O or OS error occurs.
43 TypeError: if `channel` or `pin` types are invalid.
44 ValueError: if PWM channel does not exist.
47 if PWMOut._nova is None:
48 # pylint: disable=import-outside-toplevel
49 from adafruit_blinka.microcontroller.nova import Connection
51 # pylint: enable=import-outside-toplevel
53 PWMOut._nova = Connection.getInstance()
55 PWMOut._nova.setOperationMode(0, "IO")
59 self._open(pin, duty_cycle, frequency, variable_frequency)
67 def __exit__(self, t, value, traceback):
70 def _open(self, pin, duty=0, freq=750, variable_frequency=False):
72 for pwmpair in pwmOuts:
74 self._channel = pwmpair[0][0]
75 self._pwmpin = pwmpair[0][1]
78 if self._channel is None:
79 raise RuntimeError("No PWM channel found for this Pin")
81 PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
86 self._period = self._get_period()
89 self.duty_cycle = duty
91 self._set_enabled(True)
94 """Deinit the Nova PWM."""
95 # pylint: disable=broad-except
97 if self._channel is not None:
99 self._set_enabled(False) # make to disable before unexport
101 except Exception as e:
102 # due to a race condition for which I have not yet been
103 # able to find the root cause, deinit() often fails
104 # but it does not effect future usage of the pwm pin
106 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
107 self._channel, self._pwmpin, type(e).__name__
113 # pylint: enable=broad-except
115 def _is_deinited(self):
116 if self._pwmpin is None:
118 "Object has been deinitialize and can no longer "
119 "be used. Create a new object."
124 def _get_period(self):
125 return 1.0 / self._get_frequency()
127 def _set_period(self, period):
128 if not isinstance(period, (int, float)):
129 raise TypeError("Invalid period type, should be int or float.")
131 self._set_frequency(1.0 / period)
133 period = property(_get_period, _set_period)
135 """Get or set the PWM's output period in seconds.
138 PWMError: if an I/O or OS error occurs.
139 TypeError: if value type is not int or float.
144 def _get_duty_cycle(self):
145 duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
147 # Convert duty cycle to ratio from 0.0 to 1.0
148 duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
151 duty_cycle = int(duty_cycle * 65535)
154 def _set_duty_cycle(self, duty_cycle):
155 if not isinstance(duty_cycle, (int, float)):
156 raise TypeError("Invalid duty cycle type, should be int or float.")
158 # convert from 16-bit
159 duty_cycle /= 65535.0
160 if not 0.0 <= duty_cycle <= 1.0:
161 raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
163 # Convert duty cycle from ratio to 1024 levels
164 duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
167 # pylint: disable=protected-access
168 Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
169 # pylint: enable=protected-access
171 duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
172 """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
175 PWMError: if an I/O or OS error occurs.
176 TypeError: if value type is not int or float.
177 ValueError: if value is out of bounds of 0.0 to 1.0.
182 def _get_frequency(self):
183 return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split("PWMFREQ ")[1])
185 def _set_frequency(self, frequency):
186 if not isinstance(frequency, (int, float)):
187 raise TypeError("Invalid frequency type, should be int or float.")
189 PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
191 frequency = property(_get_frequency, _set_frequency)
192 """Get or set the PWM's output frequency in Hertz.
195 PWMError: if an I/O or OS error occurs.
196 TypeError: if value type is not int or float.
201 def _get_enabled(self):
202 enabled = self._enable
209 raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
211 def _set_enabled(self, value):
212 """Get or set the PWM's output enabled state.
215 PWMError: if an I/O or OS error occurs.
216 TypeError: if value type is not bool.
220 if not isinstance(value, bool):
221 raise TypeError("Invalid enabled type, should be string.")
224 self._set_duty_cycle(0.0)
226 # String representation
229 return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
233 self.duty_cycle * 100,