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") from ImportError
 
  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         if variable_frequency:
 
  88             print("Variable Frequency is not supported, continuing without it...")
 
  90         channel_path = os.path.join(
 
  91             self._sysfs_path, self._channel_path.format(self._channel)
 
  93         if not os.path.isdir(channel_path):
 
  95                 "PWM channel does not exist, check that the required modules are loaded."
 
  98         pin_path = os.path.join(
 
  99             channel_path, self._pin_path.format(self._channel, self._pwmpin)
 
 101         if not os.path.isdir(pin_path):
 
 104                     os.path.join(channel_path, self._export_path), "w"
 
 106                     f_export.write("%d\n" % self._pwmpin)
 
 108                 raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
 
 110         # Look up the period, for fast duty cycle updates
 
 111         self._period = self._get_period()
 
 114         self.frequency = freq
 
 116         self.duty_cycle = duty
 
 118         self._set_enabled(True)
 
 121         """Deinit the sysfs PWM."""
 
 122         # pylint: disable=broad-except
 
 124             channel_path = os.path.join(
 
 125                 self._sysfs_path, self._channel_path.format(self._channel)
 
 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)
 
 139                         e.errno, "Unexporting PWM pin: " + e.strerror
 
 141         except Exception as e:
 
 142             # due to a race condition for which I have not yet been
 
 143             # able to find the root cause, deinit() often fails
 
 144             # but it does not effect future usage of the pwm pin
 
 146                 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
 
 147                     self._channel, self._pwmpin, type(e).__name__
 
 153         # pylint: enable=broad-except
 
 155     def _is_deinited(self):
 
 156         if self._pwmpin is None:
 
 158                 "Object has been deinitialize and can no longer "
 
 159                 "be used. Create a new object."
 
 162     def _write_pin_attr(self, attr, value):
 
 163         # Make sure the pin is active
 
 168             self._channel_path.format(self._channel),
 
 169             self._pin_path.format(self._channel, self._pwmpin),
 
 173         with open(path, "w") as f_attr:
 
 174             f_attr.write(value + "\n")
 
 176     def _read_pin_attr(self, attr):
 
 177         # Make sure the pin is active
 
 182             self._channel_path.format(self._channel),
 
 183             self._pin_path.format(self._channel, self._pwmpin),
 
 187         with open(path, "r") as f_attr:
 
 188             return f_attr.read().strip()
 
 192     def _get_period(self):
 
 193         period_ns = self._read_pin_attr(self._pin_period_path)
 
 195             period_ns = int(period_ns)
 
 198                 None, 'Unknown period value: "%s"' % period_ns
 
 201         # Convert period from nanoseconds to seconds
 
 202         period = period_ns / 1e9
 
 204         # Update our cached period
 
 205         self._period = period
 
 209     def _set_period(self, period):
 
 210         if not isinstance(period, (int, float)):
 
 211             raise TypeError("Invalid period type, should be int or float.")
 
 213         # Convert period from seconds to integer nanoseconds
 
 214         period_ns = int(period * 1e9)
 
 216         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
 
 218         # Update our cached period
 
 219         self._period = float(period)
 
 221     period = property(_get_period, _set_period)
 
 223     """Get or set the PWM's output period in seconds.
 
 226         PWMError: if an I/O or OS error occurs.
 
 227         TypeError: if value type is not int or float.
 
 232     def _get_duty_cycle(self):
 
 233         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
 
 235             duty_cycle_ns = int(duty_cycle_ns)
 
 238                 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
 
 241         # Convert duty cycle from nanoseconds to seconds
 
 242         duty_cycle = duty_cycle_ns / 1e9
 
 244         # Convert duty cycle to ratio from 0.0 to 1.0
 
 245         duty_cycle = duty_cycle / self._period
 
 248         duty_cycle = int(duty_cycle * 65535)
 
 251     def _set_duty_cycle(self, duty_cycle):
 
 252         if not isinstance(duty_cycle, (int, float)):
 
 253             raise TypeError("Invalid duty cycle type, should be int or float.")
 
 255         # convert from 16-bit
 
 256         duty_cycle /= 65535.0
 
 257         if not 0.0 <= duty_cycle <= 1.0:
 
 258             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
 
 260         # Convert duty cycle from ratio to seconds
 
 261         duty_cycle = duty_cycle * self._period
 
 263         # Convert duty cycle from seconds to integer nanoseconds
 
 264         duty_cycle_ns = int(duty_cycle * 1e9)
 
 266         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
 
 268     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
 
 269     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
 
 272         PWMError: if an I/O or OS error occurs.
 
 273         TypeError: if value type is not int or float.
 
 274         ValueError: if value is out of bounds of 0.0 to 1.0.
 
 279     def _get_frequency(self):
 
 280         return 1.0 / self._get_period()
 
 282     def _set_frequency(self, frequency):
 
 283         if not isinstance(frequency, (int, float)):
 
 284             raise TypeError("Invalid frequency type, should be int or float.")
 
 286         self._set_period(1.0 / frequency)
 
 288     frequency = property(_get_frequency, _set_frequency)
 
 289     """Get or set the PWM's output frequency in Hertz.
 
 292         PWMError: if an I/O or OS error occurs.
 
 293         TypeError: if value type is not int or float.
 
 298     def _get_enabled(self):
 
 299         enabled = self._read_pin_attr(self._pin_enable_path)
 
 306         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
 
 308     def _set_enabled(self, value):
 
 309         """Get or set the PWM's output enabled state.
 
 312             PWMError: if an I/O or OS error occurs.
 
 313             TypeError: if value type is not bool.
 
 317         if not isinstance(value, bool):
 
 318             raise TypeError("Invalid enabled type, should be string.")
 
 320         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
 
 322     # String representation
 
 325         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
 
 329             self.duty_cycle * 100,