]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/mcp2221/pin.py
initial working MCP2221
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / mcp2221 / pin.py
1 from .mcp2221 import mcp2221
2
3 class Pin:
4     """A basic Pin class for use with MCP2221."""
5
6     # pin modes
7     OUT     = 0
8     IN      = 1
9     ADC     = 2
10     DAC     = 3
11     # pin values
12     LOW     = 0
13     HIGH    = 1
14
15     def __init__(self, pin_id=None):
16         self.id = pin_id
17         self._mode = None
18
19     def init(self, mode=IN, pull=None):
20         if self.id is None:
21             raise RuntimeError("Can not init a None type pin.")
22         if mode in (Pin.IN, Pin.OUT):
23             mcp2221.gp_set_mode(self.id, mcp2221.GP_GPIO)
24             mcp2221.gpio_set_direction(self.id, mode)
25         elif mode == Pin.ADC:
26             mcp2221.gp_set_mode(self.id, mcp2221.GP_ALT0)
27             mcp2221.adc_configure()
28         elif mode == Pin.DAC:
29             mcp2221.gp_set_mode(self.id, mcp2221.GP_ALT1)
30             mcp2221.dac_configure()
31         else:
32             raise ValueError("Incorrect pin mode: {}".format(mode))
33         self._mode = mode
34
35     def value(self, val=None):
36         # Digital In / Out
37         if self._mode in (Pin.IN, Pin.OUT):
38             # digital read
39             if val is None:
40                 return mcp2221.gpio_get_pin(self.id)
41             # digital write
42             elif val in (Pin.LOW, Pin.HIGH):
43                 mcp2221.gpio_set_pin(self.id, val)
44             # nope
45             else:
46                 raise ValueError("Invalid value for pin.")
47         # Analog In
48         elif self._mode == Pin.ADC:
49             if val is None:
50                 # MCP2221 ADC is 10 bit, scale to 16 bit per CP API
51                 return mcp2221.adc_read(self.id) * 64
52             else:
53                 # read only
54                 raise AttributeError("'AnalogIn' object has no attribute 'value'")
55         # Analog Out
56         elif self._mode == Pin.DAC:
57             if val is None:
58                 # write only
59                 raise AttributeError("unreadable attribute")
60             else:
61                 # scale 16 bit value to MCP2221 5 bit DAC (yes 5 bit)
62                 mcp2221.dac_write(self.id, val // 2048)
63         else:
64             raise RuntimeError("No action for mode {} with value {}".format(self._mode, val))
65
66
67 # create pin instances for each pin
68 G0 = Pin(0)
69 G1 = Pin(1)
70 G2 = Pin(2)
71 G3 = Pin(3)
72
73 SCL = Pin()
74 SDA = Pin()