]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/rpi_gpio_pin.py
More changes and ran pre-commit
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / generic_linux / rpi_gpio_pin.py
1 # SPDX-FileCopyrightText: 2025 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4 """A Pin class for use with Rpi.GPIO."""
5
6 from RPi import GPIO
7
8 GPIO.setmode(GPIO.BCM)  # Use BCM pins D4 = GPIO #4
9 GPIO.setwarnings(False)  # shh!
10
11
12 class Pin:
13     """Pins dont exist in CPython so...lets make our own!"""
14
15     IN = 0
16     OUT = 1
17     LOW = 0
18     HIGH = 1
19     PULL_NONE = 0
20     PULL_UP = 1
21     PULL_DOWN = 2
22
23     id = None
24     _value = LOW
25     _mode = IN
26
27     def __init__(self, bcm_number):
28         self.id = bcm_number
29
30     def __repr__(self):
31         return str(self.id)
32
33     def __eq__(self, other):
34         return self.id == other
35
36     def init(self, mode=IN, pull=None):
37         """Initialize the Pin"""
38         if mode is not None:
39             if mode == self.IN:
40                 self._mode = self.IN
41                 GPIO.setup(self.id, GPIO.IN)
42             elif mode == self.OUT:
43                 self._mode = self.OUT
44                 GPIO.setup(self.id, GPIO.OUT)
45             else:
46                 raise RuntimeError("Invalid mode for pin: %s" % self.id)
47         if pull is not None:
48             if self._mode != self.IN:
49                 raise RuntimeError("Cannot set pull resistor on output")
50             if pull == self.PULL_UP:
51                 GPIO.setup(self.id, GPIO.IN, pull_up_down=GPIO.PUD_UP)
52             elif pull == self.PULL_DOWN:
53                 GPIO.setup(self.id, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
54             else:
55                 raise RuntimeError("Invalid pull for pin: %s" % self.id)
56
57     def value(self, val=None):
58         """Set or return the Pin Value"""
59         if val is not None:
60             if val == self.LOW:
61                 self._value = val
62                 GPIO.output(self.id, val)
63             elif val == self.HIGH:
64                 self._value = val
65                 GPIO.output(self.id, val)
66             else:
67                 raise RuntimeError("Invalid value for pin")
68             return None
69         return GPIO.input(self.id)