1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """Custom PWMOut Wrapper for Jetson GPIO PWM Class"""
7 GPIO.setmode(GPIO.TEGRA_SOC) # Use BCM pins D4 = GPIO #4
8 GPIO.setwarnings(True) # shh!
11 class PWMError(IOError):
12 """Base class for PWM errors."""
16 """Pulse Width Modulation Output Class"""
18 def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
21 self._open(pin, duty_cycle, frequency, variable_frequency)
29 def __exit__(self, t, value, traceback):
32 def _open(self, pin, duty=0, freq=500, variable_frequency=False):
34 GPIO.setup(pin.id, GPIO.OUT, initial=GPIO.HIGH)
35 self._pwmpin = GPIO.PWM(pin.id, freq)
37 if variable_frequency:
38 print("Variable Frequency is not supported, continuing without it...")
43 self.duty_cycle = duty
49 if self._pwmpin is not None:
51 GPIO.cleanup(self._pin.id)
54 def _is_deinited(self):
55 if self._pwmpin is None:
57 "Object has been deinitialize and can no longer "
58 "be used. Create a new object."
63 """Get or set the PWM's output period in seconds.
66 PWMError: if an I/O or OS error occurs.
67 TypeError: if value type is not int or float.
71 return 1.0 / self.frequency
74 def period(self, period):
75 if not isinstance(period, (int, float)):
76 raise TypeError("Invalid period type, should be int or float.")
78 self.frequency = 1.0 / period
82 """Get or set the PWM's output duty cycle which is the fraction of
83 each pulse which is high. 16-bit
86 PWMError: if an I/O or OS error occurs.
87 TypeError: if value type is not int or float.
88 ValueError: if value is out of bounds of 0.0 to 1.0.
92 return int(self._duty_cycle * 65535)
95 def duty_cycle(self, duty_cycle):
96 if not isinstance(duty_cycle, (int, float)):
97 raise TypeError("Invalid duty cycle type, should be int or float.")
99 if not 0 <= duty_cycle <= 65535:
100 raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
102 # convert from 16-bit
103 duty_cycle /= 65535.0
105 self._duty_cycle = duty_cycle
106 self._pwmpin.ChangeDutyCycle(round(self._duty_cycle * 100))
110 """Get or set the PWM's output frequency in Hertz.
113 PWMError: if an I/O or OS error occurs.
114 TypeError: if value type is not int or float.
119 return self._frequency
122 def frequency(self, frequency):
123 if not isinstance(frequency, (int, float)):
124 raise TypeError("Invalid frequency type, should be int or float.")
126 self._pwmpin.ChangeFrequency(round(frequency))
127 self._frequency = frequency
131 """Get or set the PWM's output enabled state.
134 PWMError: if an I/O or OS error occurs.
135 TypeError: if value type is not bool.
142 def enabled(self, value):
143 if not isinstance(value, bool):
144 raise TypeError("Invalid enabled type, should be string.")
147 self._pwmpin.start(round(self._duty_cycle * 100))
151 self._enabled = value
153 # String representation
155 return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (