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