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")
 
  15 # pylint: disable=unnecessary-pass
 
  16 class PWMError(IOError):
 
  17     """Base class for PWM errors."""
 
  22 # pylint: enable=unnecessary-pass
 
  26     """Pulse Width Modulation Output Class"""
 
  29     _sysfs_path = "/sys/class/pwm/"
 
  30     _channel_path = "pwmchip{}"
 
  33     _export_path = "export"
 
  34     _unexport_path = "unexport"
 
  38     _pin_period_path = "period"
 
  39     _pin_duty_cycle_path = "duty_cycle"
 
  40     _pin_polarity_path = "polarity"
 
  41     _pin_enable_path = "enable"
 
  43     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
 
  44         """Instantiate a PWM object and open the sysfs PWM corresponding to the
 
  45         specified channel and pin.
 
  48             pin (Pin): CircuitPython Pin object to output to
 
  49             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
 
  50             frequency (int) : target frequency in Hertz (32-bit)
 
  51             variable_frequency (bool) : True if the frequency will change over time
 
  54             PWMOut: PWMOut object.
 
  57             PWMError: if an I/O or OS error occurs.
 
  58             TypeError: if `channel` or `pin` types are invalid.
 
  59             ValueError: if PWM channel does not exist.
 
  66         self._open(pin, duty_cycle, frequency, variable_frequency)
 
  74     def __exit__(self, t, value, traceback):
 
  77     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
 
  79         for pwmpair in pwmOuts:
 
  81                 self._channel = pwmpair[0][0]
 
  82                 self._pwmpin = pwmpair[0][1]
 
  85         if self._channel is None:
 
  86             raise RuntimeError("No PWM channel found for this Pin")
 
  88         if variable_frequency:
 
  89             print("Variable Frequency is not supported, continuing without it...")
 
  91         channel_path = os.path.join(
 
  92             self._sysfs_path, self._channel_path.format(self._channel)
 
  94         if not os.path.isdir(channel_path):
 
  96                 "PWM channel does not exist, check that the required modules are loaded."
 
 101                 os.path.join(channel_path, self._unexport_path), "w"
 
 103                 f_unexport.write("%d\n" % self._pwmpin)
 
 105             pass  # not unusual, it doesnt already exist
 
 107             with open(os.path.join(channel_path, self._export_path), "w") as f_export:
 
 108                 f_export.write("%d\n" % self._pwmpin)
 
 110             raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror)
 
 112         # self._set_enabled(False) # This line causes a write error when trying to enable
 
 114         # Look up the period, for fast duty cycle updates
 
 115         self._period = self._get_period()
 
 117         # self.duty_cycle = 0  # This line causes a write error when trying to enable
 
 120         self.frequency = freq
 
 122         self.duty_cycle = duty
 
 124         self._set_enabled(True)
 
 127         """Deinit the sysfs PWM."""
 
 128         if self._channel is not None:
 
 131                 channel_path = os.path.join(
 
 132                     self._sysfs_path, self._channel_path.format(self._channel)
 
 135                     os.path.join(channel_path, self._unexport_path), "w"
 
 137                     f_unexport.write("%d\n" % self._pwmpin)
 
 139                 raise PWMError(e.errno, "Unexporting PWM pin: " + e.strerror)
 
 144     def _is_deinited(self):
 
 145         if self._pwmpin is None:
 
 147                 "Object has been deinitialize and can no longer "
 
 148                 "be used. Create a new object."
 
 151     def _write_pin_attr(self, attr, value):
 
 152         # Make sure the pin is active
 
 157             self._channel_path.format(self._channel),
 
 158             self._pin_path.format(self._pwmpin),
 
 162         with open(path, "w") as f_attr:
 
 164             f_attr.write(value + "\n")
 
 166     def _read_pin_attr(self, attr):
 
 167         # Make sure the pin is active
 
 172             self._channel_path.format(self._channel),
 
 173             self._pin_path.format(self._pwmpin),
 
 177         with open(path, "r") as f_attr:
 
 178             return f_attr.read().strip()
 
 182     def _get_period(self):
 
 183         period_ns = self._read_pin_attr(self._pin_period_path)
 
 185             period_ns = int(period_ns)
 
 187             raise PWMError(None, 'Unknown period value: "%s"' % period_ns)
 
 189         # Convert period from nanoseconds to seconds
 
 190         period = period_ns / 1e9
 
 192         # Update our cached period
 
 193         self._period = period
 
 197     def _set_period(self, period):
 
 198         if not isinstance(period, (int, float)):
 
 199             raise TypeError("Invalid period type, should be int or float.")
 
 201         # Convert period from seconds to integer nanoseconds
 
 202         period_ns = int(period * 1e9)
 
 204         self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
 
 206         # Update our cached period
 
 207         self._period = float(period)
 
 209     period = property(_get_period, _set_period)
 
 211     """Get or set the PWM's output period in seconds.
 
 214         PWMError: if an I/O or OS error occurs.
 
 215         TypeError: if value type is not int or float.
 
 220     def _get_duty_cycle(self):
 
 221         duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
 
 223             duty_cycle_ns = int(duty_cycle_ns)
 
 225             raise PWMError(None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns)
 
 227         # Convert duty cycle from nanoseconds to seconds
 
 228         duty_cycle = duty_cycle_ns / 1e9
 
 230         # Convert duty cycle to ratio from 0.0 to 1.0
 
 231         duty_cycle = duty_cycle / self._period
 
 234         duty_cycle = int(duty_cycle * 65535)
 
 237     def _set_duty_cycle(self, duty_cycle):
 
 238         if not isinstance(duty_cycle, (int, float)):
 
 239             raise TypeError("Invalid duty cycle type, should be int or float.")
 
 241         # convert from 16-bit
 
 242         duty_cycle /= 65535.0
 
 243         if not 0.0 <= duty_cycle <= 1.0:
 
 244             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
 
 246         # Convert duty cycle from ratio to seconds
 
 247         duty_cycle = duty_cycle * self._period
 
 249         # Convert duty cycle from seconds to integer nanoseconds
 
 250         duty_cycle_ns = int(duty_cycle * 1e9)
 
 252         self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
 
 254     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
 
 255     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
 
 258         PWMError: if an I/O or OS error occurs.
 
 259         TypeError: if value type is not int or float.
 
 260         ValueError: if value is out of bounds of 0.0 to 1.0.
 
 265     def _get_frequency(self):
 
 266         return 1.0 / self._get_period()
 
 268     def _set_frequency(self, frequency):
 
 269         if not isinstance(frequency, (int, float)):
 
 270             raise TypeError("Invalid frequency type, should be int or float.")
 
 272         self._set_period(1.0 / frequency)
 
 274     frequency = property(_get_frequency, _set_frequency)
 
 275     """Get or set the PWM's output frequency in Hertz.
 
 278         PWMError: if an I/O or OS error occurs.
 
 279         TypeError: if value type is not int or float.
 
 284     def _get_enabled(self):
 
 285         enabled = self._read_pin_attr(self._pin_enable_path)
 
 292         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
 
 294     def _set_enabled(self, value):
 
 295         """Get or set the PWM's output enabled state.
 
 298             PWMError: if an I/O or OS error occurs.
 
 299             TypeError: if value type is not bool.
 
 303         if not isinstance(value, bool):
 
 304             raise TypeError("Invalid enabled type, should be string.")
 
 306         self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
 
 308     # String representation
 
 311         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
 
 315             self.duty_cycle * 100,