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