1 # pylint: disable=invalid-name
 
   2 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
 
   4 # SPDX-License-Identifier: MIT
 
   5 # pylint: enable=invalid-name
 
   6 """ PWMOut Class for lgpio lg library tx_pwm library """
 
   9 import board    # need board to get access to the CHIP object in the pin module
 
  11 # pylint: disable=unnecessary-pass
 
  12 class PWMError(IOError):
 
  13     """Base class for PWM errors."""
 
  18 # pylint: enable=unnecessary-pass
 
  21 class PWMOut:            # pylint: disable=invalid-name
 
  22     """Pulse Width Modulation Output Class"""
 
  24     def __init__(self, pin, *, frequency=500, duty_cycle=0,
 
  25                  variable_frequency=False):
 
  26         if variable_frequency:
 
  27             print("Variable Frequency is not supported, ignoring...")
 
  29         result = lgpio.gpio_claim_output(board.pin.CHIP, self._pin.id,
 
  30                                          lFlags=lgpio.SET_PULL_NONE)
 
  32             raise RuntimeError(lgpio.error_text(result))
 
  34         self._deinited = False
 
  37         self._frequency = frequency
 
  39         self.duty_cycle = duty_cycle
 
  48     def __exit__(self, exc_type, exc_val, exc_tb):
 
  53         if not self._deinited:
 
  55                 self._enabled = False       # turn off the pwm
 
  59     def _is_deinited(self):
 
  60         """ raise Value error if the object has been de-inited """
 
  63                 "Object has been deinitialize and can no longer "
 
  64                 "be used. Create a new object."
 
  69         """Get or set the PWM's output period in seconds.
 
  72             PWMError: if an I/O or OS error occurs.
 
  73             TypeError: if value type is not int or float.
 
  77         return 1.0 / self.frequency
 
  80     def period(self, period):
 
  81         if not isinstance(period, (int, float)):
 
  82             raise TypeError("Invalid period type, should be int or float.")
 
  84         self.frequency = 1.0 / period
 
  88         """Get or set the PWM's output duty cycle which is the fraction of
 
  89         each pulse which is high. 16-bit
 
  92             PWMError: if an I/O or OS error occurs.
 
  93             TypeError: if value type is not int or float.
 
  94             ValueError: if value is out of bounds of 0.0 to 1.0.
 
  98         return int(self._duty_cycle * 65535)
 
 101     def duty_cycle(self, duty_cycle):
 
 102         if not isinstance(duty_cycle, (int, float)):
 
 103             raise TypeError("Invalid duty cycle type, should be int or float.")
 
 105         if not 0 <= duty_cycle <= 65535:
 
 107                 "Invalid duty cycle value, should be between 0 and 65535")
 
 109         # convert from 16-bit
 
 110         duty_cycle /= 65535.0
 
 112         self._duty_cycle = duty_cycle
 
 114             self.enabled = True        # turn on with new values
 
 118         """Get or set the PWM's output frequency in Hertz.
 
 121             PWMError: if an I/O or OS error occurs.
 
 122             TypeError: if value type is not int or float.
 
 127         return self._frequency
 
 130     def frequency(self, frequency):
 
 131         if not isinstance(frequency, (int, float)):
 
 132             raise TypeError("Invalid frequency type, should be int or float.")
 
 134         self._frequency = frequency
 
 136             self.enabled = True        # turn on with new values
 
 140         """Get or set the PWM's output enabled state.
 
 143             PWMError: if an I/O or OS error occurs.
 
 144             TypeError: if value type is not bool.
 
 151     def enabled(self, value):
 
 152         if not isinstance(value, bool):
 
 153             raise TypeError("Invalid enabled type, should be bool.")
 
 155         frequency = self._frequency if value else 0
 
 156         duty_cycle = round(self._duty_cycle * 100)
 
 157         self._enabled = value
 
 158         result = lgpio.tx_pwm(board.pin.CHIP, self._pin.id, frequency, duty_cycle)
 
 160             raise RuntimeError(lgpio.error_text(result))
 
 164     # String representation
 
 166         return (f"pin {self._pin} (freq={self.frequency:f} Hz, duty_cycle="
 
 167                 f"{self.duty_cycle}({round(self.duty_cycle / 655.35)}%)")