]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/ftdi_mpsse/mpsse/pin.py
Ran black
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / ftdi_mpsse / mpsse / pin.py
1 """MPSSE pin names"""
2
3 from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.url import (
4     get_ft232h_url,
5     get_ft2232h_url,
6 )
7
8
9 class Pin:
10     """A basic Pin class for use with FTDI MPSSEs."""
11
12     IN = 0
13     OUT = 1
14     LOW = 0
15     HIGH = 1
16     PULL_NONE = 0
17     PULL_UP = 1
18     PULL_DOWN = 2
19
20     mpsse_gpio = None
21
22     def __init__(self, pin_id=None, interface_id=None):
23         # setup GPIO controller if not done yet
24         # use one provided by I2C as default
25         if not Pin.mpsse_gpio:
26             # pylint: disable=import-outside-toplevel
27             from pyftdi.i2c import I2cController
28
29             # pylint: enable=import-outside-toplevel
30
31             i2c = I2cController()
32             if interface_id is None:
33                 i2c.configure(get_ft232h_url())
34             else:
35                 i2c.configure(get_ft2232h_url(interface_id))
36             Pin.mpsse_gpio = i2c.get_gpio()
37         # check if pin is valid
38         if pin_id:
39             if Pin.mpsse_gpio.all_pins & 1 << pin_id == 0:
40                 raise ValueError("Can not use pin {} as GPIO.".format(pin_id))
41         # ID is just bit position
42         self.id = pin_id
43
44     def init(self, mode=IN, pull=None):
45         """Initialize the Pin"""
46         if not self.id:
47             raise RuntimeError("Can not init a None type pin.")
48         # MPSSE does't have configurable internal pulls?
49         if pull:
50             raise NotImplementedError("Internal pull up/down not currently supported.")
51         pin_mask = Pin.mpsse_gpio.pins | 1 << self.id
52         current = Pin.mpsse_gpio.direction
53         if mode == self.OUT:
54             current |= 1 << self.id
55         else:
56             current &= ~(1 << self.id)
57         Pin.mpsse_gpio.set_direction(pin_mask, current)
58
59     def value(self, val=None):
60         """Set or return the Pin Value"""
61         if not self.id:
62             raise RuntimeError("Can not access a None type pin.")
63         current = Pin.mpsse_gpio.read(with_output=True)
64         # read
65         if val is None:
66             return 1 if current & 1 << self.id != 0 else 0
67         # write
68         if val in (self.LOW, self.HIGH):
69             if val == self.HIGH:
70                 current |= 1 << self.id
71             else:
72                 current &= ~(1 << self.id)
73             # must mask out any input pins
74             Pin.mpsse_gpio.write(current & Pin.mpsse_gpio.direction)
75             return None
76         # release the kraken
77         raise RuntimeError("Invalid value for pin")