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
12 # pylint: disable=unnecessary-pass
13 class PWMError(IOError):
14 """Base class for PWM errors."""
19 # pylint: enable=unnecessary-pass
22 class PWMOut: # pylint: disable=invalid-name
23 """Pulse Width Modulation Output Class"""
25 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
26 if variable_frequency:
27 print("Variable Frequency is not supported, ignoring...")
29 result = lgpio.gpio_claim_output(
30 board.pin.CHIP, self._pin.id, lFlags=lgpio.SET_PULL_NONE
33 raise RuntimeError(lgpio.error_text(result))
35 self._deinited = False
38 self._frequency = frequency
40 self.duty_cycle = duty_cycle
49 def __exit__(self, exc_type, exc_val, exc_tb):
54 if not self._deinited:
56 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:
106 raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
108 # convert from 16-bit
109 duty_cycle /= 65535.0
111 self._duty_cycle = duty_cycle
113 self.enabled = True # turn on with new values
117 """Get or set the PWM's output frequency in Hertz.
120 PWMError: if an I/O or OS error occurs.
121 TypeError: if value type is not int or float.
126 return self._frequency
129 def frequency(self, frequency):
130 if not isinstance(frequency, (int, float)):
131 raise TypeError("Invalid frequency type, should be int or float.")
133 self._frequency = frequency
135 self.enabled = True # turn on with new values
139 """Get or set the PWM's output enabled state.
142 PWMError: if an I/O or OS error occurs.
143 TypeError: if value type is not bool.
150 def enabled(self, value):
151 if not isinstance(value, bool):
152 raise TypeError("Invalid enabled type, should be bool.")
154 frequency = self._frequency if value else 0
155 duty_cycle = round(self._duty_cycle * 100)
156 self._enabled = value
157 result = lgpio.tx_pwm(board.pin.CHIP, self._pin.id, frequency, duty_cycle)
159 raise RuntimeError(lgpio.error_text(result))
162 # String representation
165 f"pin {self._pin} (freq={self.frequency:f} Hz, duty_cycle="
166 f"{self.duty_cycle}({round(self.duty_cycle / 655.35)}%)"