]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/horizon/pwmio/PWMOut.py
Merge pull request #931 from Roman3349/feature/neopixel_rpi_pwm1
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / horizon / pwmio / PWMOut.py
1 # SPDX-FileCopyrightText: 2024 Hajime Fujimoto
2 #
3 # SPDX-License-Identifier: MIT
4 """Custom PWMOut Wrapper for Hobot.GPIO PWM Class"""
5 from Hobot import GPIO
6
7 GPIO.setmode(GPIO.BCM)  # Use BCM pins D4 = GPIO #4
8 GPIO.setwarnings(False)  # shh!
9 GPIO.cleanup()
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 class PWMOut:
23     """Pulse Width Modulation Output Class"""
24
25     def __init__(self, pin, *, frequency=48000, duty_cycle=0, variable_frequency=False):
26         self._pwmpin = None
27         self._period = 0
28         self._open(pin, duty_cycle, frequency, variable_frequency)
29
30     def __del__(self):
31         self.deinit()
32
33     def __enter__(self):
34         return self
35
36     def __exit__(self, t, value, traceback):
37         self.deinit()
38
39     def _open(self, pin, duty=0, freq=500, variable_frequency=False):
40         if pin == (0, 25):
41             gpio_pin = 12
42         elif pin == (0, 4):
43             gpio_pin = 13
44         else:
45             raise ValueError("PWM is only available on D12 or D13.")
46         self._pin = gpio_pin
47         GPIO.setmode(GPIO.BCM)
48         #        GPIO.setup(self._pin, GPIO.OUT)
49         self._pwmpin = GPIO.PWM(self._pin, freq)
50
51         if variable_frequency:
52             print("Variable Frequency is not supported, continuing without it...")
53
54         # set frequency
55         self.frequency = freq
56         # set duty
57         duty = 656 if duty <= 656 else duty
58         self.duty_cycle = duty
59
60         self.enabled = True
61
62     def deinit(self):
63         """Deinit the PWM."""
64         if self._pwmpin is not None:
65             self._pwmpin.stop()
66             GPIO.cleanup(self._pin)
67             self._pwmpin = None
68
69     def _is_deinited(self):
70         if self._pwmpin is None:
71             raise ValueError(
72                 "Object has been deinitialize and can no longer "
73                 "be used. Create a new object."
74             )
75
76     @property
77     def period(self):
78         """Get or set the PWM's output period in seconds.
79
80         Raises:
81             PWMError: if an I/O or OS error occurs.
82             TypeError: if value type is not int or float.
83
84         :type: int, float
85         """
86         return 1.0 / self.frequency
87
88     @period.setter
89     def period(self, period):
90         if not isinstance(period, (int, float)):
91             raise TypeError("Invalid period type, should be int or float.")
92
93         self.frequency = 1.0 / period
94
95     @property
96     def duty_cycle(self):
97         """Get or set the PWM's output duty cycle which is the fraction of
98         each pulse which is high. 16-bit
99
100         Raises:
101             PWMError: if an I/O or OS error occurs.
102             TypeError: if value type is not int or float.
103             ValueError: if value is out of bounds of 0.0 to 1.0.
104
105         :type: int, float
106         """
107         return int(self._duty_cycle * 65535)
108
109     @duty_cycle.setter
110     def duty_cycle(self, duty_cycle):
111         if not isinstance(duty_cycle, (int, float)):
112             raise TypeError("Invalid duty cycle type, should be int or float.")
113
114         if not 0 <= duty_cycle <= 65535:
115             raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
116
117         # convert from 16-bit
118         duty_cycle /= 65535.0
119
120         self._duty_cycle = duty_cycle
121         self._pwmpin.ChangeDutyCycle(round(self._duty_cycle * 100))
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         )