]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/nova/pwmout.py
Merge pull request #338 from makermelissa/master
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / nova / pwmout.py
1 """PWMOut Class for Binho Nova"""
2
3 try:
4     from microcontroller.pin import pwmOuts
5 except ImportError:
6     raise RuntimeError("No PWM outputs defined for this board") from ImportError
7
8 from microcontroller.pin import Pin
9
10
11 # pylint: disable=unnecessary-pass
12 class PWMError(IOError):
13     """Base class for PWM errors."""
14
15     pass
16
17
18 # pylint: enable=unnecessary-pass
19
20
21 class PWMOut:
22     """Pulse Width Modulation Output Class"""
23
24     # Nova instance
25     _nova = None
26     MAX_CYCLE_LEVEL = 1024
27
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.
31
32         Args:
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
37
38         Returns:
39             PWMOut: PWMOut object.
40
41         Raises:
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.
45
46         """
47         if PWMOut._nova is None:
48             # pylint: disable=import-outside-toplevel
49             from adafruit_blinka.microcontroller.nova import Connection
50
51             # pylint: enable=import-outside-toplevel
52
53             PWMOut._nova = Connection.getInstance()
54
55         PWMOut._nova.setOperationMode(0, "IO")
56         self._pwmpin = None
57         self._channel = None
58         self._enable = False
59         self._open(pin, duty_cycle, frequency, variable_frequency)
60
61     def __del__(self):
62         self.deinit()
63         PWMOut._nova.close()
64
65     def __enter__(self):
66         return self
67
68     def __exit__(self, t, value, traceback):
69         self.deinit()
70
71     def _open(self, pin, duty=0, freq=750, variable_frequency=False):
72         self._channel = None
73         for pwmpair in pwmOuts:
74             if pwmpair[1] == pin:
75                 self._channel = pwmpair[0][0]
76                 self._pwmpin = pwmpair[0][1]
77
78         self._pin = pin
79         if self._channel is None:
80             raise RuntimeError("No PWM channel found for this Pin")
81
82         if variable_frequency:
83             print("Variable Frequency is not supported, continuing without it...")
84
85         PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
86
87         # set frequency
88         self.frequency = freq
89         # set period
90         self._period = self._get_period()
91
92         # set duty
93         self.duty_cycle = duty
94
95         self._set_enabled(True)
96
97     def deinit(self):
98         """Deinit the Nova PWM."""
99         # pylint: disable=broad-except
100         try:
101             if self._channel is not None:
102                 # self.duty_cycle = 0
103                 self._set_enabled(False)  # make to disable before unexport
104
105         except Exception as e:
106             # due to a race condition for which I have not yet been
107             # able to find the root cause, deinit() often fails
108             # but it does not effect future usage of the pwm pin
109             print(
110                 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
111                     self._channel, self._pwmpin, type(e).__name__
112                 )
113             )
114         finally:
115             self._channel = None
116             self._pwmpin = None
117         # pylint: enable=broad-except
118
119     def _is_deinited(self):
120         if self._pwmpin is None:
121             raise ValueError(
122                 "Object has been deinitialize and can no longer "
123                 "be used. Create a new object."
124             )
125
126     # Mutable properties
127
128     def _get_period(self):
129         return 1.0 / self._get_frequency()
130
131     def _set_period(self, period):
132         if not isinstance(period, (int, float)):
133             raise TypeError("Invalid period type, should be int or float.")
134
135         self._set_frequency(1.0 / period)
136
137     period = property(_get_period, _set_period)
138
139     """Get or set the PWM's output period in seconds.
140
141     Raises:
142         PWMError: if an I/O or OS error occurs.
143         TypeError: if value type is not int or float.
144
145     :type: int, float
146     """
147
148     def _get_duty_cycle(self):
149         duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
150
151         # Convert duty cycle to ratio from 0.0 to 1.0
152         duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
153
154         # convert to 16-bit
155         duty_cycle = int(duty_cycle * 65535)
156         return duty_cycle
157
158     def _set_duty_cycle(self, duty_cycle):
159         if not isinstance(duty_cycle, (int, float)):
160             raise TypeError("Invalid duty cycle type, should be int or float.")
161
162         # convert from 16-bit
163         duty_cycle /= 65535.0
164         if not 0.0 <= duty_cycle <= 1.0:
165             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
166
167         # Convert duty cycle from ratio to 1024 levels
168         duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
169
170         # Set duty cycle
171         # pylint: disable=protected-access
172         Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
173         # pylint: enable=protected-access
174
175     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
176     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
177
178     Raises:
179         PWMError: if an I/O or OS error occurs.
180         TypeError: if value type is not int or float.
181         ValueError: if value is out of bounds of 0.0 to 1.0.
182
183     :type: int, float
184     """
185
186     def _get_frequency(self):
187         return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split("PWMFREQ ")[1])
188
189     def _set_frequency(self, frequency):
190         if not isinstance(frequency, (int, float)):
191             raise TypeError("Invalid frequency type, should be int or float.")
192
193         PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
194
195     frequency = property(_get_frequency, _set_frequency)
196     """Get or set the PWM's output frequency in Hertz.
197
198     Raises:
199         PWMError: if an I/O or OS error occurs.
200         TypeError: if value type is not int or float.
201
202     :type: int, float
203     """
204
205     def _get_enabled(self):
206         enabled = self._enable
207
208         if enabled == "1":
209             return True
210         if enabled == "0":
211             return False
212
213         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
214
215     def _set_enabled(self, value):
216         """Get or set the PWM's output enabled state.
217
218         Raises:
219             PWMError: if an I/O or OS error occurs.
220             TypeError: if value type is not bool.
221
222         :type: bool
223         """
224         if not isinstance(value, bool):
225             raise TypeError("Invalid enabled type, should be string.")
226         self._enable = value
227         if not self._enable:
228             self._set_duty_cycle(0.0)
229
230     # String representation
231
232     def __str__(self):
233         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
234             self._pin,
235             self._pin,
236             self.frequency,
237             self.duty_cycle * 100,
238         )