1 """Custom PWMOut Wrapper for Rpi.GPIO PWM Class"""
2 import RPi.GPIO as GPIO
4 GPIO.setmode(GPIO.BCM) # Use BCM pins D4 = GPIO #4
5 GPIO.setwarnings(False) # shh!
8 # pylint: disable=unnecessary-pass
9 class PWMError(IOError):
10 """Base class for PWM errors."""
15 # pylint: enable=unnecessary-pass
19 """Pulse Width Modulation Output Class"""
21 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
24 self._open(pin, duty_cycle, frequency, variable_frequency)
32 def __exit__(self, t, value, traceback):
35 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
37 GPIO.setup(pin.id, GPIO.OUT)
38 self._pwmpin = GPIO.PWM(pin.id, freq)
40 if variable_frequency:
41 print("Variable Frequency is not supported, continuing without it...")
46 self.duty_cycle = duty
52 if self._pwmpin is not None:
54 GPIO.cleanup(self._pin.id)
57 def _is_deinited(self):
58 if self._pwmpin is None:
60 "Object has been deinitialize and can no longer "
61 "be used. Create a new object."
66 """Get or set the PWM's output period in seconds.
69 PWMError: if an I/O or OS error occurs.
70 TypeError: if value type is not int or float.
74 return 1.0 / self.frequency
77 def period(self, period):
78 if not isinstance(period, (int, float)):
79 raise TypeError("Invalid period type, should be int or float.")
81 self.frequency = 1.0 / period
85 """Get or set the PWM's output duty cycle which is the fraction of
86 each pulse which is high. 16-bit
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.
95 return int(self._duty_cycle * 65535)
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.")
102 if not 0 <= duty_cycle <= 65535:
103 raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
105 # convert from 16-bit
106 duty_cycle /= 65535.0
108 self._duty_cycle = duty_cycle
109 self._pwmpin.ChangeDutyCycle(round(self._duty_cycle * 100))
113 """Get or set the PWM's output frequency in Hertz.
116 PWMError: if an I/O or OS error occurs.
117 TypeError: if value type is not int or float.
122 return self._frequency
125 def frequency(self, frequency):
126 if not isinstance(frequency, (int, float)):
127 raise TypeError("Invalid frequency type, should be int or float.")
129 self._pwmpin.ChangeFrequency(round(frequency))
130 self._frequency = frequency
134 """Get or set the PWM's output enabled state.
137 PWMError: if an I/O or OS error occurs.
138 TypeError: if value type is not bool.
145 def enabled(self, value):
146 if not isinstance(value, bool):
147 raise TypeError("Invalid enabled type, should be string.")
150 self._pwmpin.start(round(self._duty_cycle * 100))
154 self._enabled = value
156 # String representation
158 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (