2 Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
 
   3 Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
 
  10     from microcontroller.pin import pwmOuts
 
  12     raise RuntimeError("No PWM outputs defined for this board")
 
  14 # pylint: disable=unnecessary-pass
 
  15 class PWMError(IOError):
 
  16     """Base class for PWM errors."""
 
  21 # pylint: enable=unnecessary-pass
 
  25     """Pulse Width Modulation Output Class"""
 
  28     _sysfs_path = "/sys/class/pwm/"
 
  29     _channel_path = "pwmchip{}"
 
  32     _export_path = "export"
 
  33     _unexport_path = "unexport"
 
  34     _pin_path = "pwm-{}:{}"
 
  37     _pin_period_path = "period"
 
  38     _pin_duty_cycle_path = "duty_cycle"
 
  39     _pin_polarity_path = "polarity"
 
  40     _pin_enable_path = "enable"
 
  42     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
 
  43         """Instantiate a PWM object and open the sysfs PWM corresponding to the
 
  44         specified channel and pin.
 
  47             pin (Pin): CircuitPython Pin object to output to
 
  48             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
 
  49             frequency (int) : target frequency in Hertz (32-bit)
 
  50             variable_frequency (bool) : True if the frequency will change over time
 
  53             PWMOut: PWMOut object.
 
  56             PWMError: if an I/O or OS error occurs.
 
  57             TypeError: if `channel` or `pin` types are invalid.
 
  58             ValueError: if PWM channel does not exist.
 
  65         self._open(pin, duty_cycle, frequency, variable_frequency)
 
  73     def __exit__(self, t, value, traceback):
 
  76     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
 
  78         for pwmpair in pwmOuts:
 
  80                 self._channel = pwmpair[0][0]
 
  81                 self._pwmpin = pwmpair[0][1]
 
  84         if self._channel is None:
 
  85             raise RuntimeError("No PWM channel found for this Pin")
 
  87         channel_path = os.path.join(
 
  88             self._sysfs_path, self._channel_path.format(self._channel)
 
  90         if not os.path.isdir(channel_path):
 
  92                 "PWM channel does not exist, check that the required modules are loaded."
 
  95         pin_path = os.path.join(
 
  96             channel_path, self._pin_path.format(self._channel, self._pwmpin)
 
  98         if not os.path.isdir(pin_path):
 
 101                     os.path.join(channel_path, self._export_path), "w"
 
 103                     f_export.write("%d\n" % self._pwmpin)
 
 105                 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror)
 
 107         # Look up the period, for fast duty cycle updates
 
 108         self._period = self._get_period()
 
 111         self.frequency = freq
 
 113         self.duty_cycle = duty
 
 115         self._set_enabled(True)
 
 118         """Deinit the sysfs PWM."""
 
 119         # pylint: disable=broad-except
 
 121             channel_path = os.path.join(
 
 122                 self._sysfs_path, self._channel_path.format(self._channel)
 
 124             pin_path = os.path.join(
 
 125                 channel_path, self._pin_path.format(self._channel, self._pwmpin)
 
 128             if self._channel is not None:
 
 129                 # self.duty_cycle = 0
 
 130                 self._set_enabled(False)  # make to disable before unexport
 
 132                     # unexport_path = os.path.join(channel_path, self._unexport_path)
 
 134                         os.path.join(channel_path, self._unexport_path), "w"
 
 136                         f_unexport.write("%d\n" % self._pwmpin)
 
 138                     raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
 
 139         except Exception as e:
 
 140             # due to a race condition for which I have not yet been
 
 141             # able to find the root cause, deinit() often fails
 
 142             # but it does not effect future usage of the pwm pin
 
 144                 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
 
 145                     self._channel, self._pwmpin, type(e).__name__
 
 151         # pylint: enable=broad-except
 
 153     def _is_deinited(self):
 
 154         if self._pwmpin is None:
 
 156                 "Object has been deinitialize and can no longer "
 
 157                 "be used. Create a new object."
 
 160     def _write_pin_attr(self, attr, value):
 
 161         # Make sure the pin is active
 
 166             self._channel_path.format(self._channel),
 
 167             self._pin_path.format(self._channel, self._pwmpin),
 
 171         with open(path, "w") as f_attr:
 
 172             f_attr.write(value + "\n")
 
 174     def _read_pin_attr(self, attr):
 
 175         # Make sure the pin is active
 
 180             self._channel_path.format(self._channel),
 
 181             self._pin_path.format(self._channel, self._pwmpin),
 
 185         with open(path, "r") as f_attr:
 
 186             return f_attr.read().strip()
 
 190     def _get_period(self):
 
 191         period_ns = self._read_pin_attr(self._pin_period_path)
 
 193             period_ns = int(period_ns)
 
 195             raise PWMError(None, 'Unknown period value: "%s"' % period_ns)
 
 197         # Convert period from nanoseconds to seconds
 
 198         period = period_ns / 1e9
 
 200         # Update our cached period
 
 201         self._period = period
 
 205     def _set_period(self, period):
 
 206         if not isinstance(period, (int, float)):
 
 207             raise TypeError("Invalid period type, should be int or float.")
 
 209         # Convert period from seconds to integer nanoseconds
 
 210         period_ns = int(period * 1e9)
 
 212         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
 
 214         # Update our cached period
 
 215         self._period = float(period)
 
 217     period = property(_get_period, _set_period)
 
 219     """Get or set the PWM's output period in seconds.
 
 222         PWMError: if an I/O or OS error occurs.
 
 223         TypeError: if value type is not int or float.
 
 228     def _get_duty_cycle(self):
 
 229         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
 
 231             duty_cycle_ns = int(duty_cycle_ns)
 
 233             raise PWMError(None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns)
 
 235         # Convert duty cycle from nanoseconds to seconds
 
 236         duty_cycle = duty_cycle_ns / 1e9
 
 238         # Convert duty cycle to ratio from 0.0 to 1.0
 
 239         duty_cycle = duty_cycle / self._period
 
 242         duty_cycle = int(duty_cycle * 65535)
 
 245     def _set_duty_cycle(self, duty_cycle):
 
 246         if not isinstance(duty_cycle, (int, float)):
 
 247             raise TypeError("Invalid duty cycle type, should be int or float.")
 
 249         # convert from 16-bit
 
 250         duty_cycle /= 65535.0
 
 251         if not 0.0 <= duty_cycle <= 1.0:
 
 252             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
 
 254         # Convert duty cycle from ratio to seconds
 
 255         duty_cycle = duty_cycle * self._period
 
 257         # Convert duty cycle from seconds to integer nanoseconds
 
 258         duty_cycle_ns = int(duty_cycle * 1e9)
 
 260         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
 
 262     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
 
 263     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
 
 266         PWMError: if an I/O or OS error occurs.
 
 267         TypeError: if value type is not int or float.
 
 268         ValueError: if value is out of bounds of 0.0 to 1.0.
 
 273     def _get_frequency(self):
 
 274         return 1.0 / self._get_period()
 
 276     def _set_frequency(self, frequency):
 
 277         if not isinstance(frequency, (int, float)):
 
 278             raise TypeError("Invalid frequency type, should be int or float.")
 
 280         self._set_period(1.0 / frequency)
 
 282     frequency = property(_get_frequency, _set_frequency)
 
 283     """Get or set the PWM's output frequency in Hertz.
 
 286         PWMError: if an I/O or OS error occurs.
 
 287         TypeError: if value type is not int or float.
 
 292     def _get_enabled(self):
 
 293         enabled = self._read_pin_attr(self._pin_enable_path)
 
 300         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
 
 302     def _set_enabled(self, value):
 
 303         """Get or set the PWM's output enabled state.
 
 306             PWMError: if an I/O or OS error occurs.
 
 307             TypeError: if value type is not bool.
 
 311         if not isinstance(value, bool):
 
 312             raise TypeError("Invalid enabled type, should be string.")
 
 314         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
 
 316     # String representation
 
 319         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
 
 323             self.duty_cycle * 100,