rpi-interface-board/rpi-scripts/examples/pass_through_inputs_to_outputs.py

58 lines
2.0 KiB
Python

import os
import sys
import time
import RPi.GPIO as GPIO
# Add the parent directory to the module search path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Import pin assignments and custom libraries
from interface_board_pins import GPIO_DIGITAL_INPUTS # Input GPIO mapping
from interface_board_pins import ( # Shift register pin assignment
GPIO_SHIFT_REG_DATA,
GPIO_SHIFT_REG_LATCH,
GPIO_SHIFT_REG_CLOCK,
)
from interface_board_libs.shift_register import ShiftRegister # Custom shift register class
# Initialize GPIO for digital inputs
GPIO.setmode(GPIO.BCM)
for pin in GPIO_DIGITAL_INPUTS.values():
print(f"Configuring GPIO pin {pin} as input")
GPIO.setup(pin, GPIO.IN)
# Initialize shift register
sr = ShiftRegister(GPIO_SHIFT_REG_DATA, GPIO_SHIFT_REG_LATCH, GPIO_SHIFT_REG_CLOCK)
# Main loop: Read inputs and write to shift register
print("\nStarting passthrough mode: Digital inputs → Shift register outputs")
try:
while True:
shift_register_value = 0 # Byte to be written to the shift register
print("\nReading inputs and updating shift register...")
for i, (label, pin) in enumerate(GPIO_DIGITAL_INPUTS.items()):
state = GPIO.input(pin) # Read GPIO state
print(f"Input {label} (GPIO {pin}): {'HIGH' if state else 'LOW'}")
# Set corresponding bit in shift register byte
if state:
shift_register_value |= (1 << i) # Set bit at position `i`
else:
shift_register_value &= ~(1 << i) # Clear bit at position `i`
# Write the final byte to the shift register
sr.write_byte(shift_register_value)
print(f"Shift Register Output: {bin(shift_register_value)}")
time.sleep(0.5) # Small delay to prevent excessive polling
except KeyboardInterrupt:
print("\nExiting...")
finally:
sr.clear() # Clear shift register before exiting
print("Shift register cleared.")
GPIO.cleanup() # Cleanup GPIO settings