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