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)
11 # pylint: disable=unnecessary-pass
12 class PWMError(IOError):
13 """Base class for PWM errors."""
18 # pylint: enable=unnecessary-pass
22 """Pulse Width Modulation Output Class"""
24 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
27 self._open(pin, duty_cycle, frequency, variable_frequency)
35 def __exit__(self, t, value, traceback):
38 def _open(self, pin, duty=0, freq=500, variable_frequency=True):
40 GPIO.setup(pin.id, GPIO.OUT)
41 self._pwmpin = GPIO.PWM(pin.id, freq)
43 if variable_frequency:
44 print("Variable Frequency is not supported, continuing without it...")
49 self.duty_cycle = duty
55 if self._pwmpin is not None:
57 GPIO.cleanup(self._pin.id)
60 def _is_deinited(self):
61 if self._pwmpin is None:
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.
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 100.0.
98 return int(self._duty_cycle)
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 <= 100:
107 "Invalid duty cycle value, should be between 0.0 and 100.0"
110 self._duty_cycle = duty_cycle
111 self._pwmpin.ChangeDutyCycle(round(self._duty_cycle))
115 """Get or set the PWM's output frequency in Hertz.
118 PWMError: if an I/O or OS error occurs.
119 TypeError: if value type is not int or float.
124 return self._frequency
127 def frequency(self, frequency):
128 if not isinstance(frequency, (int, float)):
129 raise TypeError("Invalid frequency type, should be int or float.")
131 self._pwmpin.ChangeFrequency(round(frequency))
132 self._frequency = frequency
136 """Get or set the PWM's output enabled state.
139 PWMError: if an I/O or OS error occurs.
140 TypeError: if value type is not bool.
147 def enabled(self, value):
148 if not isinstance(value, bool):
149 raise TypeError("Invalid enabled type, should be string.")
152 self._pwmpin.start(round(self._duty_cycle * 100))
156 self._enabled = value
158 # String representation
160 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (