1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
 
   3 # SPDX-License-Identifier: MIT
 
   4 """PWMOut Class for Binho Nova"""
 
   7     from microcontroller.pin import pwmOuts
 
   9     raise RuntimeError("No PWM outputs defined for this board") from ImportError
 
  11 from microcontroller.pin import Pin
 
  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"""
 
  29     MAX_CYCLE_LEVEL = 1024
 
  31     def __init__(self, pin, *, frequency=750, duty_cycle=0, variable_frequency=False):
 
  32         """Instantiate a PWM object and open the sysfs PWM corresponding to the
 
  33         specified channel and pin.
 
  36             pin (Pin): CircuitPython Pin object to output to
 
  37             duty_cycle (int) : The fraction of each pulse which is high. 16-bit
 
  38             frequency (int) : target frequency in Hertz (32-bit)
 
  39             variable_frequency (bool) : True if the frequency will change over time
 
  42             PWMOut: PWMOut object.
 
  45             PWMError: if an I/O or OS error occurs.
 
  46             TypeError: if `channel` or `pin` types are invalid.
 
  47             ValueError: if PWM channel does not exist.
 
  50         if PWMOut._nova is None:
 
  51             # pylint: disable=import-outside-toplevel
 
  52             from adafruit_blinka.microcontroller.nova import Connection
 
  54             # pylint: enable=import-outside-toplevel
 
  56             PWMOut._nova = Connection.getInstance()
 
  58         PWMOut._nova.setOperationMode(0, "IO")
 
  62         self._open(pin, duty_cycle, frequency, variable_frequency)
 
  71     def __exit__(self, t, value, traceback):
 
  74     def _open(self, pin, duty=0, freq=750, variable_frequency=False):
 
  76         for pwmpair in pwmOuts:
 
  78                 self._channel = pwmpair[0][0]
 
  79                 self._pwmpin = pwmpair[0][1]
 
  82         if self._channel is None:
 
  83             raise RuntimeError("No PWM channel found for this Pin")
 
  85         if variable_frequency:
 
  86             print("Variable Frequency is not supported, continuing without it...")
 
  88         PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
 
  93         self._period = self._get_period()
 
  96         self.duty_cycle = duty
 
  98         self._set_enabled(True)
 
 101         """Deinit the Nova PWM."""
 
 102         # pylint: disable=broad-except
 
 104             if self._channel is not None:
 
 105                 # self.duty_cycle = 0
 
 106                 self._set_enabled(False)  # make to disable before unexport
 
 108         except Exception as e:
 
 109             # due to a race condition for which I have not yet been
 
 110             # able to find the root cause, deinit() often fails
 
 111             # but it does not effect future usage of the pwm pin
 
 113                 "warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
 
 114                     self._channel, self._pwmpin, type(e).__name__
 
 120         # pylint: enable=broad-except
 
 122     def _is_deinited(self):
 
 123         if self._pwmpin is None:
 
 125                 "Object has been deinitialize and can no longer "
 
 126                 "be used. Create a new object."
 
 131     def _get_period(self):
 
 132         return 1.0 / self._get_frequency()
 
 134     def _set_period(self, period):
 
 135         if not isinstance(period, (int, float)):
 
 136             raise TypeError("Invalid period type, should be int or float.")
 
 138         self._set_frequency(1.0 / period)
 
 140     period = property(_get_period, _set_period)
 
 142     """Get or set the PWM's output period in seconds.
 
 145         PWMError: if an I/O or OS error occurs.
 
 146         TypeError: if value type is not int or float.
 
 151     def _get_duty_cycle(self):
 
 152         duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
 
 154         # Convert duty cycle to ratio from 0.0 to 1.0
 
 155         duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
 
 158         duty_cycle = int(duty_cycle * 65535)
 
 161     def _set_duty_cycle(self, duty_cycle):
 
 162         if not isinstance(duty_cycle, (int, float)):
 
 163             raise TypeError("Invalid duty cycle type, should be int or float.")
 
 165         # convert from 16-bit
 
 166         duty_cycle /= 65535.0
 
 167         if not 0.0 <= duty_cycle <= 1.0:
 
 168             raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
 
 170         # Convert duty cycle from ratio to 1024 levels
 
 171         duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
 
 174         # pylint: disable=protected-access
 
 175         Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
 
 176         # pylint: enable=protected-access
 
 178     duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
 
 179     """Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
 
 182         PWMError: if an I/O or OS error occurs.
 
 183         TypeError: if value type is not int or float.
 
 184         ValueError: if value is out of bounds of 0.0 to 1.0.
 
 189     def _get_frequency(self):
 
 190         return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split("PWMFREQ ")[1])
 
 192     def _set_frequency(self, frequency):
 
 193         if not isinstance(frequency, (int, float)):
 
 194             raise TypeError("Invalid frequency type, should be int or float.")
 
 196         PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
 
 198     frequency = property(_get_frequency, _set_frequency)
 
 199     """Get or set the PWM's output frequency in Hertz.
 
 202         PWMError: if an I/O or OS error occurs.
 
 203         TypeError: if value type is not int or float.
 
 208     def _get_enabled(self):
 
 209         enabled = self._enable
 
 216         raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
 
 218     def _set_enabled(self, value):
 
 219         """Get or set the PWM's output enabled state.
 
 222             PWMError: if an I/O or OS error occurs.
 
 223             TypeError: if value type is not bool.
 
 227         if not isinstance(value, bool):
 
 228             raise TypeError("Invalid enabled type, should be string.")
 
 231             self._set_duty_cycle(0.0)
 
 233     # String representation
 
 236         return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
 
 240             self.duty_cycle * 100,