]> Repositories - Adafruit_Blinka-hackapet.git/commitdiff
Added PWMOut functionality for the Raspberry Pi
authorMelissa LeBlanc-Williams <melissa@adafruit.com>
Wed, 1 Jul 2020 20:10:07 +0000 (13:10 -0700)
committerMelissa LeBlanc-Williams <melissa@adafruit.com>
Wed, 1 Jul 2020 20:10:07 +0000 (13:10 -0700)
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PWMOut.py [new file with mode: 0644]
src/pulseio.py

diff --git a/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PWMOut.py b/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PWMOut.py
new file mode 100644 (file)
index 0000000..77824b0
--- /dev/null
@@ -0,0 +1,160 @@
+"""Custom PWMOut Wrapper for Rpi.GPIO PWM Class"""
+import RPi.GPIO as GPIO
+
+GPIO.setmode(GPIO.BCM)  # Use BCM pins D4 = GPIO #4
+GPIO.setwarnings(False)  # shh!
+
+
+# pylint: disable=unnecessary-pass
+class PWMError(IOError):
+    """Base class for PWM errors."""
+
+    pass
+
+
+# pylint: enable=unnecessary-pass
+
+
+class PWMOut:
+    """Pulse Width Modulation Output Class"""
+
+    def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
+        self._pwmpin = None
+        self._period = 0
+        self._open(pin, duty_cycle, frequency, variable_frequency)
+
+    def __del__(self):
+        self.deinit()
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, t, value, traceback):
+        self.deinit()
+
+    def _open(self, pin, duty=0, freq=500, variable_frequency=False):
+        self._pin = pin
+        GPIO.setup(pin.id, GPIO.OUT)
+        self._pwmpin = GPIO.PWM(pin.id, freq)
+
+        if variable_frequency:
+            print("Variable Frequency is not supported, continuing without it...")
+
+        # set frequency
+        self.frequency = freq
+        # set duty
+        self.duty_cycle = duty
+
+        self.enabled = True
+
+    def deinit(self):
+        """Deinit the PWM."""
+        self._pwmpin.stop()
+        GPIO.cleanup(self._pin.id)
+        self._pwmpin = None
+
+    def _is_deinited(self):
+        if self._pwmpin is None:
+            raise ValueError(
+                "Object has been deinitialize and can no longer "
+                "be used. Create a new object."
+            )
+
+    @property
+    def period(self):
+        """Get or set the PWM's output period in seconds.
+
+        Raises:
+            PWMError: if an I/O or OS error occurs.
+            TypeError: if value type is not int or float.
+
+        :type: int, float
+        """
+        return 1.0 / self.frequency
+
+    @period.setter
+    def period(self, period):
+        if not isinstance(period, (int, float)):
+            raise TypeError("Invalid period type, should be int or float.")
+
+        self.frequency = 1.0 / period
+
+    @property
+    def duty_cycle(self):
+        """Get or set the PWM's output duty cycle which is the fraction of
+        each pulse which is high. 16-bit
+
+        Raises:
+            PWMError: if an I/O or OS error occurs.
+            TypeError: if value type is not int or float.
+            ValueError: if value is out of bounds of 0.0 to 1.0.
+
+        :type: int, float
+        """
+        return int(self._duty_cycle * 65535)
+
+    @duty_cycle.setter
+    def duty_cycle(self, duty_cycle):
+        if not isinstance(duty_cycle, (int, float)):
+            raise TypeError("Invalid duty cycle type, should be int or float.")
+
+        # convert from 16-bit
+        duty_cycle /= 65535.0
+        if not 0.0 <= duty_cycle <= 1.0:
+            raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
+
+        self._pwmpin.ChangeDutyCycle(round(duty_cycle * 100))
+        self._duty_cycle = duty_cycle
+
+    @property
+    def frequency(self):
+        """Get or set the PWM's output frequency in Hertz.
+
+        Raises:
+            PWMError: if an I/O or OS error occurs.
+            TypeError: if value type is not int or float.
+
+        :type: int, float
+        """
+
+        return self._frequency
+
+    @frequency.setter
+    def frequency(self, frequency):
+        if not isinstance(frequency, (int, float)):
+            raise TypeError("Invalid frequency type, should be int or float.")
+
+        self._pwmpin.ChangeFrequency(round(frequency))
+        self._frequency = frequency
+
+    @property
+    def enabled(self):
+        """Get or set the PWM's output enabled state.
+
+        Raises:
+            PWMError: if an I/O or OS error occurs.
+            TypeError: if value type is not bool.
+
+        :type: bool
+        """
+        return self._enabled
+
+    @enabled.setter
+    def enabled(self, value):
+        if not isinstance(value, bool):
+            raise TypeError("Invalid enabled type, should be string.")
+
+        if value:
+            self._pwmpin.start(self.duty_cycle)
+        else:
+            self._pwmpin.stop()
+
+        self._enabled = value
+
+    # String representation
+    def __str__(self):
+        return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
+            self._pin,
+            self.frequency,
+            self.duty_cycle * 100,
+        )
index ab44c69e360723817cf761a94e52f7a6f83f6b4b..7c53457a9c223bd7b6f4a24fb25ccaebd3ff3f3c 100644 (file)
@@ -11,6 +11,7 @@ from adafruit_blinka.agnostic import detector
 
 if detector.board.any_raspberry_pi:
     from adafruit_blinka.microcontroller.bcm283x.pulseio.PulseIn import PulseIn
 
 if detector.board.any_raspberry_pi:
     from adafruit_blinka.microcontroller.bcm283x.pulseio.PulseIn import PulseIn
+    from adafruit_blinka.microcontroller.bcm283x.pulseio.PWMOut import PWMOut
 if detector.board.any_coral_board:
     from adafruit_blinka.microcontroller.generic_linux.sysfs_pwmout import PWMOut
 if detector.board.any_giant_board:
 if detector.board.any_coral_board:
     from adafruit_blinka.microcontroller.generic_linux.sysfs_pwmout import PWMOut
 if detector.board.any_giant_board: