1 # SPDX-FileCopyrightText: 2024 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """generic_agnostic_board pin interface"""
9 """A basic Pin class for use with generic_agnostic_board"""
20 def return_toggle(self):
21 """Returns the pin's expected value, toggling between True and False"""
22 toggle_state = not self.previous_value
25 def return_false(self):
26 """Returns the pin's expected value, False"""
29 def return_true(self):
30 """Returns the pin's expected value, True"""
33 def return_random_int(self):
34 """Returns a random integer"""
35 return random.randint(0, 65535)
37 def return_fixed_int_pi(self):
38 """Returns the first five digits of Pi, 31415"""
41 def __init__(self, pin_id=None):
44 self.previous_value = None
45 self.current_value = None
46 # TODO: Can we simplify the pin behavior dict and the pin map dict?
47 # mapping of pin definition names to expected behavior
48 self.expected_pin_behavior = {
49 "Dx_INPUT_TRUE": self.return_true,
50 "Dx_INPUT_FALSE": self.return_false,
51 "Dx_INPUT_TRUE_THEN_FALSE": self.return_toggle,
52 "Dx_INPUT_TRUE_PULL_UP": self.return_true,
53 "Dx_INPUT_TRUE_PULL_DOWN": self.return_true,
54 "Dx_OUTPUT_TRUE": self.return_true,
55 "Dx_OUTPUT_FALSE": self.return_false,
56 "Ax_INPUT_RAND_INT": self.return_random_int,
58 # mapping of pin numbers to pin definition names
59 self.pin_number_to_pin_definition_name = {
62 2: "Dx_INPUT_TRUE_PULL_UP",
63 3: "Dx_INPUT_TRUE_PULL_DOWN",
67 7: "Ax_INPUT_RAND_INT",
68 8: "Ax_INPUT_FIXED_INT_PI",
69 9: "Ax_OUTPUT_WAVE_SINE",
70 10: "Ax_OUTPUT_WAVE_SAWTOOTH",
73 def init(self, mode=IN, pull=None):
74 """Initialize the Pin"""
76 raise RuntimeError("Can not init a None type pin.")
78 raise NotImplementedError("Internal pullups and pulldowns not supported")
81 def write(self, new_value):
82 """Saves the new_value to the pin for subsequent calls to .value"""
83 self.previous_value = self.current_value
84 self.current_value = new_value
87 """Returns the pin's expected value."""
88 self.previous_value = self.current_value
89 # lookup the pin id's name from the mapping
90 pin_name = self.pin_number_to_pin_definition_name.get(self.id)
92 self.current_value = self.expected_pin_behavior[pin_name]()
93 else: # default to False if the pin is not in the mapping
94 self.current_value = False
95 return self.current_value
97 def value(self, val=None):
98 """Set or return the Pin Value"""
100 if self._mode in (Pin.IN, Pin.OUT):
105 if val in (Pin.LOW, Pin.HIGH):
106 return self.write(val)
108 raise ValueError("Invalid value for pin.")
110 if self._mode == Pin.ADC:
114 raise AttributeError("'AnalogIn' object has no attribute 'value'")
116 if self._mode == Pin.DAC:
119 raise AttributeError("unreadable attribute")
123 "No action for mode {} with value {}".format(self._mode, val)
127 # create pin instances for each pin
134 # Special "digital" pins