]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/starfive/JH7110/pwmio/PWMOut.py
fixes
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / starfive / JH7110 / pwmio / PWMOut.py
1 # SPDX-FileCopyrightText: 2024 Vladimir Shtarev
2 #
3 # SPDX-License-Identifier: MIT
4 """Custom PWMOut Wrapper for VisionFive.GPIO PWM Class"""
5
6 import VisionFive.gpio as GPIO
7
8 GPIO.setmode(GPIO.BOARD)
9 GPIO.setwarnings(False)
10
11
12 # pylint: disable=unnecessary-pass
13 class PWMError(IOError):
14     """Base class for PWM errors."""
15
16     pass
17
18
19 # pylint: enable=unnecessary-pass
20
21
22 def create(pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
23     """test"""
24     return PWMOut(
25         pin,
26         frequency=frequency,
27         duty_cycle=duty_cycle,
28         variable_frequency=variable_frequency,
29     )
30
31
32 class PWMOut:
33     """Pulse Width Modulation Output Class"""
34
35     def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
36         self._pwmpin = None
37         self._period = 0
38         self._open(pin, duty_cycle, frequency, variable_frequency)
39
40     def __del__(self):
41         self.deinit()
42
43     def __enter__(self):
44         return self
45
46     def __exit__(self, t, value, traceback):
47         self.deinit()
48
49     def _open(self, pin, duty=0, freq=500, variable_frequency=True):
50         self._pin = pin
51         GPIO.setup(pin.id, GPIO.OUT)
52         self._pwmpin = GPIO.PWM(pin.id, freq)
53
54         if variable_frequency:
55             print("Variable Frequency is not supported, continuing without it...")
56
57         # set frequency
58         self.frequency = freq
59         # set duty
60         self.duty_cycle = duty
61
62         self.enabled = True
63
64     def deinit(self):
65         """Deinit the PWM."""
66         if self._pwmpin is not None:
67             self._pwmpin.stop()
68             GPIO.cleanup(self._pin.id)
69             self._pwmpin = None
70
71     def _is_deinited(self):
72         if self._pwmpin is None:
73             raise ValueError(
74                 "Object has been deinitialize and can no longer "
75                 "be used. Create a new object."
76             )
77
78     @property
79     def period(self):
80         """Get or set the PWM's output period in seconds.
81
82         Raises:
83             PWMError: if an I/O or OS error occurs.
84             TypeError: if value type is not int or float.
85
86         :type: int, float
87         """
88         return 1.0 / self.frequency
89
90     @period.setter
91     def period(self, period):
92         if not isinstance(period, (int, float)):
93             raise TypeError("Invalid period type, should be int or float.")
94
95         self.frequency = 1.0 / period
96
97     @property
98     def duty_cycle(self):
99         """Get or set the PWM's output duty cycle which is the fraction of
100         each pulse which is high. 16-bit
101
102         Raises:
103             PWMError: if an I/O or OS error occurs.
104             TypeError: if value type is not int or float.
105             ValueError: if value is out of bounds of 0.0 to 1.0.
106
107         :type: int, float
108         """
109         return int(self._duty_cycle * 65535)
110
111     @duty_cycle.setter
112     def duty_cycle(self, duty_cycle):
113         if not isinstance(duty_cycle, (int, float)):
114             raise TypeError("Invalid duty cycle type, should be int or float.")
115
116         if not 0 <= duty_cycle <= 65535:
117             raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
118
119         duty_cycle = duty_cycle / 655.35
120         self._duty_cycle = duty_cycle
121         self._pwmpin.ChangeDutyCycle(round(self._duty_cycle))
122
123     @property
124     def frequency(self):
125         """Get or set the PWM's output frequency in Hertz.
126
127         Raises:
128             PWMError: if an I/O or OS error occurs.
129             TypeError: if value type is not int or float.
130
131         :type: int, float
132         """
133
134         return self._frequency
135
136     @frequency.setter
137     def frequency(self, frequency):
138         if not isinstance(frequency, (int, float)):
139             raise TypeError("Invalid frequency type, should be int or float.")
140
141         self._pwmpin.ChangeFrequency(round(frequency))
142         self._frequency = frequency
143
144     @property
145     def enabled(self):
146         """Get or set the PWM's output enabled state.
147
148         Raises:
149             PWMError: if an I/O or OS error occurs.
150             TypeError: if value type is not bool.
151
152         :type: bool
153         """
154         return self._enabled
155
156     @enabled.setter
157     def enabled(self, value):
158         if not isinstance(value, bool):
159             raise TypeError("Invalid enabled type, should be string.")
160
161         if value:
162             self._pwmpin.start(round(self._duty_cycle * 100))
163         else:
164             self._pwmpin.stop()
165
166         self._enabled = value
167
168     # String representation
169     def __str__(self):
170         return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
171             self._pin,
172             self.frequency,
173             self.duty_cycle,
174         )