1 # SPDX-FileCopyrightText: 2024 Brent Rubell for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """Mock PWMOut Wrapper for Generic Agnostic Board"""
7 class PWMError(IOError):
8 """Base class for PWM errors."""
12 """Pulse Width Modulation Output Class"""
14 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
17 self._open(pin, duty_cycle, frequency, variable_frequency)
25 def __exit__(self, t, value, traceback):
28 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
33 self._variable_frequency = variable_frequency
35 self.duty_cycle = duty
41 if self._pwmpin is not None:
44 def _is_deinited(self):
45 if self._pwmpin is None:
47 "Object has been deinitialize and can no longer "
48 "be used. Create a new object."
53 """Get or set the PWM's output period in seconds.
56 PWMError: if an I/O or OS error occurs.
57 TypeError: if value type is not int or float.
61 return 1.0 / self.frequency
64 def period(self, period):
65 if not isinstance(period, (int, float)):
66 raise TypeError("Invalid period type, should be int or float.")
68 self.frequency = 1.0 / period
72 """Get or set the PWM's output duty cycle which is the fraction of
73 each pulse which is high. 16-bit
76 PWMError: if an I/O or OS error occurs.
77 TypeError: if value type is not int or float.
78 ValueError: if value is out of bounds of 0.0 to 1.0.
82 return int(self._duty_cycle * 65535)
85 def duty_cycle(self, duty_cycle):
86 if not isinstance(duty_cycle, (int, float)):
87 raise TypeError("Invalid duty cycle type, should be int or float.")
89 if not 0 <= duty_cycle <= 65535:
90 raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
95 self._duty_cycle = duty_cycle
99 """Get or set the PWM's output frequency in Hertz.
102 PWMError: if an I/O or OS error occurs.
103 TypeError: if value type is not int or float.
108 return self._frequency
111 def frequency(self, frequency):
112 if not isinstance(frequency, (int, float)):
113 raise TypeError("Invalid frequency type, should be int or float.")
114 self._frequency = frequency
118 """Get or set the PWM's output enabled state.
121 PWMError: if an I/O or OS error occurs.
122 TypeError: if value type is not bool.
129 def enabled(self, value):
130 if not isinstance(value, bool):
131 raise TypeError("Invalid enabled type, should be string.")
133 self._enabled = value
135 # String representation
137 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (