]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/sysfs_pwmout.py
add a periphery-based sysfs pwmout object - tested with LED and servo
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / generic_linux / 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     _pin_path = "pwm{}"
26
27     # Pin attribute paths
28     _pin_period_path = "period"
29     _pin_duty_cycle_path = "duty_cycle"
30     _pin_polarity_path = "polarity"
31     _pin_enable_path = "enable"
32
33     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
34         """Instantiate a PWM object and open the sysfs PWM corresponding to the
35         specified channel and pin.
36
37         Args:
38             pin (Pin): CircuitPython Pin object to output to
39             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
40             frequency (int) : target frequency in Hertz (32-bit)
41             variable_frequency (bool) : True if the frequency will change over time
42
43         Returns:
44             PWMOut: PWMOut object.
45
46         Raises:
47             PWMError: if an I/O or OS error occurs.
48             TypeError: if `channel` or `pin` types are invalid.
49             ValueError: if PWM channel does not exist.
50
51         """
52
53         self._pwmpin = None
54         self._open(pin, duty_cycle, frequency, variable_frequency)
55
56     def __del__(self):
57         self.close()
58
59     def __enter__(self):
60         return self
61
62     def __exit__(self, t, value, traceback):
63         self.close()
64
65     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
66         self._channel = None
67         for pwmpair in pwmOuts:
68             if pwmpair[1] == pin:
69                 self._channel = pwmpair[0][0]
70                 self._pwmpin = pwmpair[0][1]
71
72         self._pin = pin
73         if self._channel is None:
74             raise RuntimeError("No PWM channel found for this Pin")
75
76         channel_path = os.path.join(self._sysfs_path, self._channel_path.format(self._channel))
77         if not os.path.isdir(channel_path):
78             raise ValueError("PWM channel does not exist, check that the required modules are loaded.")
79
80         pin_path = os.path.join(channel_path, self._pin_path.format(self._pwmpin))
81         if not os.path.isdir(pin_path):
82             try:
83                 with open(os.path.join(channel_path, self._export_path), "w") as f_export:
84                     f_export.write("%d\n" % self._pwmpin)
85             except IOError as e:
86                 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror)
87
88         self._set_enabled(True)
89
90         # Look up the period, for fast duty cycle updates
91         self._period = self._get_period()
92
93         # set frequency
94         self.frequency = freq
95         # set duty
96         self.duty_cycle = duty
97
98     def close(self):
99         """Close the sysfs PWM."""
100         self._channel = None
101         self._pwmpin = None
102
103     def _write_pin_attr(self, attr, value):
104         path = os.path.join(
105             self._sysfs_path,
106             self._channel_path.format(self._channel),
107             self._pin_path.format(self._pwmpin),
108             attr)
109
110         with open(path, 'w') as f_attr:
111             #print(value, path)
112             f_attr.write(value + "\n")
113
114     def _read_pin_attr(self, attr):
115         path = os.path.join(
116             self._sysfs_path,
117             self._channel_path.format(self._channel),
118             self._pin_path.format(self._pwmpin),
119             attr)
120
121         with open(path, 'r') as f_attr:
122             return f_attr.read().strip()
123
124     # Mutable properties
125
126     def _get_period(self):
127         try:
128             period_ns = int(self._read_pin_attr(self._pin_period_path))
129         except ValueError:
130             raise PWMError(None, "Unknown period value: \"%s\"" % period_ns)
131
132         # Convert period from nanoseconds to seconds
133         period = period_ns / 1e9
134
135         # Update our cached period
136         self._period = period
137
138         return period
139
140     def _set_period(self, period):
141         if not isinstance(period, (int, float)):
142             raise TypeError("Invalid period type, should be int or float.")
143
144         # Convert period from seconds to integer nanoseconds
145         period_ns = int(period * 1e9)
146
147         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
148
149         # Update our cached period
150         self._period = float(period)
151
152     """Get or set the PWM's output period in seconds.
153
154     Raises:
155         PWMError: if an I/O or OS error occurs.
156         TypeError: if value type is not int or float.
157
158     :type: int, float
159     """
160
161     def _get_duty_cycle(self):
162         try:
163             duty_cycle_ns = int(self._read_pin_attr(self._pin_duty_cycle_path))
164         except ValueError:
165             raise PWMError(None, "Unknown duty cycle value: \"%s\"" % duty_cycle_ns)
166
167         # Convert duty cycle from nanoseconds to seconds
168         duty_cycle = duty_cycle_ns / 1e9
169
170         # Convert duty cycle to ratio from 0.0 to 1.0
171         duty_cycle = duty_cycle / self._period
172
173         # convert to 16-bit
174         duty_cycle = int(duty_cycle * 65535)
175
176         return duty_cycle
177
178     def _set_duty_cycle(self, duty_cycle):
179         # convert from 16-bit
180         duty_cycle /= 65535
181
182         if not isinstance(duty_cycle, (int, float)):
183             raise TypeError("Invalid duty cycle type, should be int or float.")
184         elif not 0.0 <= duty_cycle <= 1.0:
185             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
186
187         # Convert duty cycle from ratio to seconds
188         duty_cycle = duty_cycle * self._period
189
190         # Convert duty cycle from seconds to integer nanoseconds
191         duty_cycle_ns = int(duty_cycle * 1e9)
192
193         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
194
195     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
196     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
197
198     Raises:
199         PWMError: if an I/O or OS error occurs.
200         TypeError: if value type is not int or float.
201         ValueError: if value is out of bounds of 0.0 to 1.0.
202
203     :type: int, float
204     """
205
206     def _get_frequency(self):
207         return 1.0 / self._get_period()
208
209     def _set_frequency(self, frequency):
210         if not isinstance(frequency, (int, float)):
211             raise TypeError("Invalid frequency type, should be int or float.")
212
213         self._set_period(1.0 / frequency)
214
215     frequency = property(_get_frequency, _set_frequency)
216     """Get or set the PWM's output frequency in Hertz.
217
218     Raises:
219         PWMError: if an I/O or OS error occurs.
220         TypeError: if value type is not int or float.
221
222     :type: int, float
223     """
224
225     def _get_enabled(self):
226         enabled = self._read_pin_attr(self._pin_enable_path)
227
228         if enabled == "1":
229             return True
230         elif enabled == "0":
231             return False
232
233         raise PWMError(None, "Unknown enabled value: \"%s\"" % enabled)
234
235     def _set_enabled(self, value):
236         if not isinstance(value, bool):
237             raise TypeError("Invalid enabled type, should be string.")
238
239         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
240
241     """Get or set the PWM's output enabled state.
242
243     Raises:
244         PWMError: if an I/O or OS error occurs.
245         TypeError: if value type is not bool.
246
247     :type: bool
248     """
249
250     # String representation
251
252     def __str__(self):
253         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % \
254             (self._channel, self._pin, self.frequency, self.duty_cycle * 100,)