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