]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/am335x/sysfs_pwmout.py
Merge branch 'master' of https://github.com/binhollc/Adafruit_Blinka
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / am335x / sysfs_pwmout.py
1 # Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
2 # Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
3 # License: MIT
4
5 import os
6 import digitalio
7
8 try:
9     from microcontroller.pin import pwmOuts
10 except ImportError:
11     raise RuntimeError("No PWM outputs defined for this board")
12
13 class PWMError(IOError):
14     """Base class for PWM errors."""
15     pass
16
17
18 class PWMOut(object):
19     # Sysfs paths
20     _sysfs_path = "/sys/class/pwm/"
21     _channel_path = "pwmchip{}"
22
23     # Channel paths
24     _export_path = "export"
25     _unexport_path = "unexport"
26     _pin_path = "pwm-{}:{}"
27
28     # Pin attribute paths
29     _pin_period_path = "period"
30     _pin_duty_cycle_path = "duty_cycle"
31     _pin_polarity_path = "polarity"
32     _pin_enable_path = "enable"
33
34     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
35         """Instantiate a PWM object and open the sysfs PWM corresponding to the
36         specified channel and pin.
37
38         Args:
39             pin (Pin): CircuitPython Pin object to output to
40             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
41             frequency (int) : target frequency in Hertz (32-bit)
42             variable_frequency (bool) : True if the frequency will change over time
43
44         Returns:
45             PWMOut: PWMOut object.
46
47         Raises:
48             PWMError: if an I/O or OS error occurs.
49             TypeError: if `channel` or `pin` types are invalid.
50             ValueError: if PWM channel does not exist.
51
52         """
53
54         self._pwmpin = None
55         self._open(pin, duty_cycle, frequency, variable_frequency)
56
57     def __del__(self):
58         self.deinit()
59
60     def __enter__(self):
61         return self
62
63     def __exit__(self, t, value, traceback):
64         self.deinit()
65
66     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
67         self._channel = None
68         for pwmpair in pwmOuts:
69             if pwmpair[1] == pin:
70                 self._channel = pwmpair[0][0]
71                 self._pwmpin = pwmpair[0][1]
72
73         self._pin = pin
74         if self._channel is None:
75             raise RuntimeError("No PWM channel found for this Pin")
76
77         channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
78         if not os.path.isdir(channel_path):
79             raise ValueError("PWM channel does not exist, check that the required modules are loaded.")
80
81         pin_path = os.path.join(channel_path, self._pin_path.format(self._channel,self._pwmpin))
82         if not os.path.isdir(pin_path):
83             try:
84                 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
85                     f_export.write("%d\n" % self._pwmpin)
86             except IOError as e:
87                 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror)
88
89         # Look up the period, for fast duty cycle updates
90         self._period = self._get_period()
91
92         # set frequency
93         self.frequency = freq
94         # set duty
95         self.duty_cycle = duty
96
97         self._set_enabled(True)
98
99     def deinit(self):
100       try:
101         """Deinit the sysfs PWM."""
102         channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
103         pin_path = os.path.join(channel_path, self._pin_path.format(self._channel,self._pwmpin))
104  
105         if self._channel is not None:
106             #self.duty_cycle = 0
107             self._set_enabled(False) # make to disable before unexport
108             try:
109                 #unexport_path = os.path.join(channel_path, self._unexport_path)
110                 with open(os.path.join(channel_path, self._unexport_path), "w") as f_unexport:
111                     f_unexport.write("%d\n" % self._pwmpin)
112             except IOError as e:
113                 raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
114       except Exception as e:
115           # due to a race condition for which I have not yet been
116           # able to find the root cause, deinit() often fails
117           # but it does not effect future usage of the pwm pin
118           print("warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(self._channel, self._pwmpin, type(e).__name__))
119       finally:
120           self._channel = None
121           self._pwmpin = None
122
123     def _is_deinited(self):
124         if self._pwmpin is None:
125             raise ValueError("Object has been deinitialize and can no longer "
126                              "be used. Create a new object.")
127
128     def _write_pin_attr(self, attr, value):
129         # Make sure the pin is active
130         self._is_deinited()
131
132         path = os.path.join(
133             self._sysfs_path,
134             self._channel_path.format(self._channel),
135             self._pin_path.format(self._channel,self._pwmpin),
136             attr)
137
138         with open(path, 'w') as f_attr:
139             f_attr.write(value + "\n")
140
141     def _read_pin_attr(self, attr):
142         # Make sure the pin is active
143         self._is_deinited()
144
145         path = os.path.join(
146             self._sysfs_path,
147             self._channel_path.format(self._channel),
148             self._pin_path.format(self._channel,self._pwmpin),
149             attr)
150
151         with open(path, 'r') as f_attr:
152             return f_attr.read().strip()
153
154     # Mutable properties
155
156     def _get_period(self):
157         period_ns = self._read_pin_attr(self._pin_period_path)
158         try:
159             period_ns = int(period_ns)
160         except ValueError:
161             raise PWMError(None, "Unknown period value: \"%s\"" % period_ns)
162
163         # Convert period from nanoseconds to seconds
164         period = period_ns / 1e9
165
166         # Update our cached period
167         self._period = period
168
169         return period
170
171     def _set_period(self, period):
172         if not isinstance(period, (int, float)):
173             raise TypeError("Invalid period type, should be int or float.")
174
175         # Convert period from seconds to integer nanoseconds
176         period_ns = int(period * 1e9)
177
178         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
179
180         # Update our cached period
181         self._period = float(period)
182
183     period = property(_get_period, _set_period)
184
185     """Get or set the PWM's output period in seconds.
186
187     Raises:
188         PWMError: if an I/O or OS error occurs.
189         TypeError: if value type is not int or float.
190
191     :type: int, float
192     """
193
194     def _get_duty_cycle(self):
195         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
196         try:
197             duty_cycle_ns = int(duty_cycle_ns)
198         except ValueError:
199             raise PWMError(None, "Unknown duty cycle value: \"%s\"" % duty_cycle_ns)
200
201         # Convert duty cycle from nanoseconds to seconds
202         duty_cycle = duty_cycle_ns / 1e9
203
204         # Convert duty cycle to ratio from 0.0 to 1.0
205         duty_cycle = duty_cycle / self._period
206
207         # convert to 16-bit
208         duty_cycle = int(duty_cycle * 65535)
209         return duty_cycle
210
211     def _set_duty_cycle(self, duty_cycle):
212         if not isinstance(duty_cycle, (int, float)):
213             raise TypeError("Invalid duty cycle type, should be int or float.")
214
215         # convert from 16-bit
216         duty_cycle /= 65535.0
217         if not 0.0 <= duty_cycle <= 1.0:
218             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
219
220         # Convert duty cycle from ratio to seconds
221         duty_cycle = duty_cycle * self._period
222
223         # Convert duty cycle from seconds to integer nanoseconds
224         duty_cycle_ns = int(duty_cycle * 1e9)
225
226         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
227
228     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
229     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
230
231     Raises:
232         PWMError: if an I/O or OS error occurs.
233         TypeError: if value type is not int or float.
234         ValueError: if value is out of bounds of 0.0 to 1.0.
235
236     :type: int, float
237     """
238
239     def _get_frequency(self):
240         return 1.0 / self._get_period()
241
242     def _set_frequency(self, frequency):
243         if not isinstance(frequency, (int, float)):
244             raise TypeError("Invalid frequency type, should be int or float.")
245
246         self._set_period(1.0 / frequency)
247
248     frequency = property(_get_frequency, _set_frequency)
249     """Get or set the PWM's output frequency in Hertz.
250
251     Raises:
252         PWMError: if an I/O or OS error occurs.
253         TypeError: if value type is not int or float.
254
255     :type: int, float
256     """
257
258     def _get_enabled(self):
259         enabled = self._read_pin_attr(self._pin_enable_path)
260
261         if enabled == "1":
262             return True
263         elif enabled == "0":
264             return False
265
266         raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
267
268     def _set_enabled(self, value):
269         if not isinstance(value, bool):
270             raise TypeError("Invalid enabled type, should be string.")
271
272         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
273
274     """Get or set the PWM's output enabled state.
275
276     Raises:
277         PWMError: if an I/O or OS error occurs.
278         TypeError: if value type is not bool.
279
280     :type: bool
281     """
282
283     # String representation
284
285     def __str__(self):
286         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
287             (self._channel, self._pin, self.frequency, self.duty_cycle * 100,)