1 # SPDX-FileCopyrightText: 2024 Brent Rubell for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """Mock PWMOut Wrapper for Generic Agnostic Board"""
6 class PWMError(IOError):
7 """Base class for PWM errors."""
11 """Pulse Width Modulation Output Class"""
13 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
16 self._open(pin, duty_cycle, frequency, variable_frequency)
24 def __exit__(self, t, value, traceback):
27 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
33 self.duty_cycle = duty
39 if self._pwmpin is not None:
42 def _is_deinited(self):
43 if self._pwmpin is None:
45 "Object has been deinitialize and can no longer "
46 "be used. Create a new object."
51 """Get or set the PWM's output period in seconds.
54 PWMError: if an I/O or OS error occurs.
55 TypeError: if value type is not int or float.
59 return 1.0 / self.frequency
62 def period(self, period):
63 if not isinstance(period, (int, float)):
64 raise TypeError("Invalid period type, should be int or float.")
66 self.frequency = 1.0 / period
70 """Get or set the PWM's output duty cycle which is the fraction of
71 each pulse which is high. 16-bit
74 PWMError: if an I/O or OS error occurs.
75 TypeError: if value type is not int or float.
76 ValueError: if value is out of bounds of 0.0 to 1.0.
80 return int(self._duty_cycle * 65535)
83 def duty_cycle(self, duty_cycle):
84 if not isinstance(duty_cycle, (int, float)):
85 raise TypeError("Invalid duty cycle type, should be int or float.")
87 if not 0 <= duty_cycle <= 65535:
88 raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
93 self._duty_cycle = duty_cycle
97 """Get or set the PWM's output frequency in Hertz.
100 PWMError: if an I/O or OS error occurs.
101 TypeError: if value type is not int or float.
106 return self._frequency
109 def frequency(self, frequency):
110 if not isinstance(frequency, (int, float)):
111 raise TypeError("Invalid frequency type, should be int or float.")
112 self._frequency = frequency
116 """Get or set the PWM's output enabled state.
119 PWMError: if an I/O or OS error occurs.
120 TypeError: if value type is not bool.
127 def enabled(self, value):
128 if not isinstance(value, bool):
129 raise TypeError("Invalid enabled type, should be string.")
131 self._enabled = value
133 # String representation
135 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (