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