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
53 GPIO.cleanup(self._pin.id)
56 def _is_deinited(self):
57 if self._pwmpin is None:
59 "Object has been deinitialize and can no longer "
60 "be used. Create a new object."
65 """Get or set the PWM's output period in seconds.
68 PWMError: if an I/O or OS error occurs.
69 TypeError: if value type is not int or float.
73 return 1.0 / self.frequency
76 def period(self, period):
77 if not isinstance(period, (int, float)):
78 raise TypeError("Invalid period type, should be int or float.")
80 self.frequency = 1.0 / period
84 """Get or set the PWM's output duty cycle which is the fraction of
85 each pulse which is high. 16-bit
88 PWMError: if an I/O or OS error occurs.
89 TypeError: if value type is not int or float.
90 ValueError: if value is out of bounds of 0.0 to 1.0.
94 return int(self._duty_cycle * 65535)
97 def duty_cycle(self, duty_cycle):
98 if not isinstance(duty_cycle, (int, float)):
99 raise TypeError("Invalid duty cycle type, should be int or float.")
101 if not 0 <= duty_cycle <= 65535:
102 raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
104 # convert from 16-bit
105 duty_cycle /= 65535.0
107 self._duty_cycle = duty_cycle
108 self._pwmpin.ChangeDutyCycle(round(self._duty_cycle * 100))
112 """Get or set the PWM's output frequency in Hertz.
115 PWMError: if an I/O or OS error occurs.
116 TypeError: if value type is not int or float.
121 return self._frequency
124 def frequency(self, frequency):
125 if not isinstance(frequency, (int, float)):
126 raise TypeError("Invalid frequency type, should be int or float.")
128 self._pwmpin.ChangeFrequency(round(frequency))
129 self._frequency = frequency
133 """Get or set the PWM's output enabled state.
136 PWMError: if an I/O or OS error occurs.
137 TypeError: if value type is not bool.
144 def enabled(self, value):
145 if not isinstance(value, bool):
146 raise TypeError("Invalid enabled type, should be string.")
149 self._pwmpin.start(round(self._duty_cycle * 100))
153 self._enabled = value
155 # String representation
157 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (