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
 
   9 from errno import EACCES
 
  12     from microcontroller.pin import pwmOuts
 
  14     raise RuntimeError("No PWM outputs defined for this board") from ImportError
 
  17 # pylint: disable=unnecessary-pass
 
  18 class PWMError(IOError):
 
  19     """Base class for PWM errors."""
 
  24 # pylint: enable=unnecessary-pass
 
  28     """Pulse Width Modulation Output Class"""
 
  30     # Number of retries to check for successful PWM export on open
 
  32     # Delay between check for scucessful PWM export on open (100ms)
 
  36     _sysfs_path = "/sys/class/pwm/"
 
  37     _channel_path = "pwmchip{}"
 
  40     _export_path = "export"
 
  41     _unexport_path = "unexport"
 
  45     _pin_period_path = "period"
 
  46     _pin_duty_cycle_path = "duty_cycle"
 
  47     _pin_polarity_path = "polarity"
 
  48     _pin_enable_path = "enable"
 
  50     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
 
  51         """Instantiate a PWM object and open the sysfs PWM corresponding to the
 
  52         specified channel and pin.
 
  55             pin (Pin): CircuitPython Pin object to output to
 
  56             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
 
  57             frequency (int) : target frequency in Hertz (32-bit)
 
  58             variable_frequency (bool) : True if the frequency will change over time
 
  61             PWMOut: PWMOut object.
 
  64             PWMError: if an I/O or OS error occurs.
 
  65             TypeError: if `channel` or `pin` types are invalid.
 
  66             ValueError: if PWM channel does not exist.
 
  73         self._open(pin, duty_cycle, frequency, variable_frequency)
 
  81     def __exit__(self, t, value, traceback):
 
  84     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
 
  86         for pwmpair in pwmOuts:
 
  88                 self._channel = pwmpair[0][0]
 
  89                 self._pwmpin = pwmpair[0][1]
 
  92         if self._channel is None:
 
  93             raise RuntimeError("No PWM channel found for this Pin")
 
  95         if variable_frequency:
 
  96             print("Variable Frequency is not supported, continuing without it...")
 
  98         channel_path = os.path.join(
 
  99             self._sysfs_path, self._channel_path.format(self._channel)
 
 101         if not os.path.isdir(channel_path):
 
 103                 "PWM channel does not exist, check that the required modules are loaded."
 
 108                 os.path.join(channel_path, self._unexport_path), "w"
 
 110                 f_unexport.write("%d\n" % self._pwmpin)
 
 112             pass  # not unusual, it doesnt already exist
 
 114             with open(os.path.join(channel_path, self._export_path), "w") as f_export:
 
 115                 f_export.write("%d\n" % self._pwmpin)
 
 117             raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
 
 119         # Loop until 'period' is writable, because application of udev rules
 
 120         # after the above pin export is asynchronous.
 
 121         # Without this loop, the following properties may not be writable yet.
 
 122         for i in range(PWMOut.PWM_STAT_RETRIES):
 
 126                         channel_path, self._pin_path.format(self._pwmpin), "period"
 
 132                 if e.errno != EACCES or (
 
 133                     e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
 
 135                     raise PWMError(e.errno, "Opening PWM period: " + e.strerror) from e
 
 136             sleep(PWMOut.PWM_STAT_DELAY)
 
 138         # self._set_enabled(False) # This line causes a write error when trying to enable
 
 140         # Look up the period, for fast duty cycle updates
 
 141         self._period = self._get_period()
 
 143         # self.duty_cycle = 0  # This line causes a write error when trying to enable
 
 146         self.frequency = freq
 
 148         self.duty_cycle = duty
 
 150         self._set_enabled(True)
 
 153         """Deinit the sysfs PWM."""
 
 154         if self._channel is not None:
 
 157                 channel_path = os.path.join(
 
 158                     self._sysfs_path, self._channel_path.format(self._channel)
 
 161                     os.path.join(channel_path, self._unexport_path), "w"
 
 163                     f_unexport.write("%d\n" % self._pwmpin)
 
 166                     e.errno, "Unexporting PWM pin: " + e.strerror
 
 172     def _is_deinited(self):
 
 173         if self._pwmpin is None:
 
 175                 "Object has been deinitialize and can no longer "
 
 176                 "be used. Create a new object."
 
 179     def _write_pin_attr(self, attr, value):
 
 180         # Make sure the pin is active
 
 185             self._channel_path.format(self._channel),
 
 186             self._pin_path.format(self._pwmpin),
 
 190         with open(path, "w") as f_attr:
 
 192             f_attr.write(value + "\n")
 
 194     def _read_pin_attr(self, attr):
 
 195         # Make sure the pin is active
 
 200             self._channel_path.format(self._channel),
 
 201             self._pin_path.format(self._pwmpin),
 
 205         with open(path, "r") as f_attr:
 
 206             return f_attr.read().strip()
 
 210     def _get_period(self):
 
 211         period_ns = self._read_pin_attr(self._pin_period_path)
 
 213             period_ns = int(period_ns)
 
 216                 None, 'Unknown period value: "%s"' % period_ns
 
 219         # Convert period from nanoseconds to seconds
 
 220         period = period_ns / 1e9
 
 222         # Update our cached period
 
 223         self._period = period
 
 227     def _set_period(self, period):
 
 228         if not isinstance(period, (int, float)):
 
 229             raise TypeError("Invalid period type, should be int or float.")
 
 231         # Convert period from seconds to integer nanoseconds
 
 232         period_ns = int(period * 1e9)
 
 234         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
 
 236         # Update our cached period
 
 237         self._period = float(period)
 
 239     period = property(_get_period, _set_period)
 
 241     """Get or set the PWM's output period in seconds.
 
 244         PWMError: if an I/O or OS error occurs.
 
 245         TypeError: if value type is not int or float.
 
 250     def _get_duty_cycle(self):
 
 251         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
 
 253             duty_cycle_ns = int(duty_cycle_ns)
 
 256                 None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
 
 259         # Convert duty cycle from nanoseconds to seconds
 
 260         duty_cycle = duty_cycle_ns / 1e9
 
 262         # Convert duty cycle to ratio from 0.0 to 1.0
 
 263         duty_cycle = duty_cycle / self._period
 
 266         duty_cycle = int(duty_cycle * 65535)
 
 269     def _set_duty_cycle(self, duty_cycle):
 
 270         if not isinstance(duty_cycle, (int, float)):
 
 271             raise TypeError("Invalid duty cycle type, should be int or float.")
 
 273         # convert from 16-bit
 
 274         duty_cycle /= 65535.0
 
 275         if not 0.0 <= duty_cycle <= 1.0:
 
 276             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
 
 278         # Convert duty cycle from ratio to seconds
 
 279         duty_cycle = duty_cycle * self._period
 
 281         # Convert duty cycle from seconds to integer nanoseconds
 
 282         duty_cycle_ns = int(duty_cycle * 1e9)
 
 284         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
 
 286     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
 
 287     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
 
 290         PWMError: if an I/O or OS error occurs.
 
 291         TypeError: if value type is not int or float.
 
 292         ValueError: if value is out of bounds of 0.0 to 1.0.
 
 297     def _get_frequency(self):
 
 298         return 1.0 / self._get_period()
 
 300     def _set_frequency(self, frequency):
 
 301         if not isinstance(frequency, (int, float)):
 
 302             raise TypeError("Invalid frequency type, should be int or float.")
 
 304         self._set_period(1.0 / frequency)
 
 306     frequency = property(_get_frequency, _set_frequency)
 
 307     """Get or set the PWM's output frequency in Hertz.
 
 310         PWMError: if an I/O or OS error occurs.
 
 311         TypeError: if value type is not int or float.
 
 316     def _get_enabled(self):
 
 317         enabled = self._read_pin_attr(self._pin_enable_path)
 
 324         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
 
 326     def _set_enabled(self, value):
 
 327         """Get or set the PWM's output enabled state.
 
 330             PWMError: if an I/O or OS error occurs.
 
 331             TypeError: if value type is not bool.
 
 335         if not isinstance(value, bool):
 
 336             raise TypeError("Invalid enabled type, should be string.")
 
 338         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
 
 340     # String representation
 
 343         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
 
 347             self.duty_cycle * 100,