1 # SPDX-FileCopyrightText: 2024 Vladimir Shtarev
3 # SPDX-License-Identifier: MIT
4 """Custom PWMOut Wrapper for VisionFive.GPIO PWM Class"""
6 import VisionFive.gpio as GPIO
8 GPIO.setmode(GPIO.Board)
9 GPIO.setwarnings(False)
12 # pylint: disable=unnecessary-pass
13 class PWMError(IOError):
14 """Base class for PWM errors."""
19 # pylint: enable=unnecessary-pass
23 """Pulse Width Modulation Output Class"""
25 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
28 self._open(pin, duty_cycle, frequency, variable_frequency)
36 def __exit__(self, t, value, traceback):
39 def _open(self, pin, duty=0, freq=500, variable_frequency=True):
41 GPIO.setup(pin.id, GPIO.OUT)
42 self._pwmpin = GPIO.PWM(pin.id, freq)
44 if variable_frequency:
45 print("Variable Frequency is not supported, continuing without it...")
50 self.duty_cycle = duty
56 if self._pwmpin is not None:
58 GPIO.cleanup(self._pin.id)
61 def _is_deinited(self):
62 if self._pwmpin is None:
64 "Object has been deinitialize and can no longer "
65 "be used. Create a new object."
70 """Get or set the PWM's output period in seconds.
73 PWMError: if an I/O or OS error occurs.
74 TypeError: if value type is not int or float.
78 return 1.0 / self.frequency
81 def period(self, period):
82 if not isinstance(period, (int, float)):
83 raise TypeError("Invalid period type, should be int or float.")
85 self.frequency = 1.0 / period
89 """Get or set the PWM's output duty cycle which is the fraction of
90 each pulse which is high.
93 PWMError: if an I/O or OS error occurs.
94 TypeError: if value type is not int or float.
95 ValueError: if value is out of bounds of 0.0 to 100.0.
99 return int(self._duty_cycle)
102 def duty_cycle(self, duty_cycle):
103 if not isinstance(duty_cycle, (int, float)):
104 raise TypeError("Invalid duty cycle type, should be int or float.")
106 if not 0 <= duty_cycle <= 100:
108 "Invalid duty cycle value, should be between 0.0 and 100.0"
111 self._duty_cycle = duty_cycle
112 self._pwmpin.ChangeDutyCycle(round(self._duty_cycle))
116 """Get or set the PWM's output frequency in Hertz.
119 PWMError: if an I/O or OS error occurs.
120 TypeError: if value type is not int or float.
125 return self._frequency
128 def frequency(self, frequency):
129 if not isinstance(frequency, (int, float)):
130 raise TypeError("Invalid frequency type, should be int or float.")
132 self._pwmpin.ChangeFrequency(round(frequency))
133 self._frequency = frequency
137 """Get or set the PWM's output enabled state.
140 PWMError: if an I/O or OS error occurs.
141 TypeError: if value type is not bool.
148 def enabled(self, value):
149 if not isinstance(value, bool):
150 raise TypeError("Invalid enabled type, should be string.")
153 self._pwmpin.start(round(self._duty_cycle * 100))
157 self._enabled = value
159 # String representation
161 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (