Skip to content

File gpio.py#

File List > build > lib.linux-armv7l-cpython-311 > pypisoundmicro > gpio.py

Go to the documentation of this file

from ._utils import copy_doc
from . import Element, ElementName
from .swig import pypisoundmicro as psm
from typing import Self, Type, Union
from .types import PinDirection, PinPull

@copy_doc(psm.Gpio)
class Gpio(Element):

    @classmethod
    def setup_input(cls: Type[Self], name: Union[str, ElementName, psm.ElementName], pin: int, pull: PinPull) -> Self:
        """
        Set up a GPIO element as input.
        See also: upisnd_setup_gpio_input
        """
        if isinstance(name, str):
            name = psm.ElementName.regular(name)
        elif isinstance(name, ElementName):
            name = name._name
        native_obj = psm.Gpio.setupInput(name, pin, pull)
        return cls(native_obj)

    @classmethod
    def setup_output(cls: Type[Self], name: Union[str, ElementName, psm.ElementName], pin: int, high: int) -> Self:
        """
        Set up a GPIO element as output.
        See also: upisnd_setup_gpio_output
        """
        if isinstance(name, str):
            name = psm.ElementName.regular(name)
        elif isinstance(name, ElementName):
            name = name._name
        native_obj = psm.Gpio.setupOutput(name, pin, high)
        return cls(native_obj)

    @property
    def direction(self) -> PinDirection:
        """ Get the direction of the GPIO element."""
        return self._native_obj.getDirection()

    @property
    def pull(self) -> PinPull:
        """
        Get the pull of the GPIO Input element.
        :rtype: int
        :return: Returns #UPISND_PIN_PULL_INVALID if the element is not an input.
        """
        return self._native_obj.getPull()

    def get_value(self) -> int:
        """
        This is for quick access to the value, otherwise, it's recommended to keep the
        ValueFd returned by Element::openValueFd, to avoid file open and close overhead.
        :rtype: int
        :return: Negative return value indicates an error.
        """
        return self._native_obj.get()

    def set_value(self, high: int) -> int:
        """
        Set the output value of the GPIO output element.
        :rtype: int
        :return: Negative return value indicates an error.
        """
        return self._native_obj.set(high)