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

67 lines
2.3 KiB
Python

# Include external libraries
import os
import sys
from time import sleep
# Add the parent directory to the module search path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Include custom files
from interface_board_libs.shift_register import ShiftRegister # custom shift register class
from interface_board_pins import ( # pin / channel assignment
GPIO_SHIFT_REG_DATA,
GPIO_SHIFT_REG_LATCH,
GPIO_SHIFT_REG_CLOCK,
SHIFT_REG_CHANNEL_BUZZER,
SHIFT_REG_CHANNEL_RELAY1,
SHIFT_REG_CHANNEL_RELAY2,
)
# Initialize the shift register
sr = ShiftRegister(GPIO_SHIFT_REG_DATA, GPIO_SHIFT_REG_LATCH, GPIO_SHIFT_REG_CLOCK)
try:
print("Writing to shift register...")
# repeatedly write to shift register
while True:
# # Cycle through all combinations of pin states (write entire byte)
# print("Writing all byte values (0-255)...")
# for value in range(256):
# sr.write_byte(value) # Write the current value
# print(f"Output: {bin(value)}") # Print binary representation
# sleep(0.05) # Delay between each byte
# Turn each pin on and off one by one
print("\nToggling each pin one by one...")
# channels 0-4 are connected to terminal only
for pin in range(4): # 0-4 are connected to terminal only
print(f"Setting pin {pin} HIGH.")
sr.set_pin(pin, True) # Set the pin HIGH
sleep(0.5)
print(f"Setting pin {pin} LOW.")
sr.set_pin(pin, False) # Set the pin LOW
sleep(0.5)
# channels 5-7 are connected to terminal AND buzzer/relays
print("Activating buzzer...")
sr.set_pin(SHIFT_REG_CHANNEL_BUZZER, True) # Turn buzzer ON
sleep(0.5)
sr.set_pin(SHIFT_REG_CHANNEL_BUZZER, False) # Turn buzzer OFF
print("Toggling Relay 1...")
sr.toggle_pin(SHIFT_REG_CHANNEL_RELAY1)
sleep(0.5)
sr.toggle_pin(SHIFT_REG_CHANNEL_RELAY1)
print("Activating Relay 2...")
sr.set_pin(SHIFT_REG_CHANNEL_RELAY2, True) # Turn relay ON
sleep(0.5)
sr.set_pin(SHIFT_REG_CHANNEL_RELAY2, False) # Turn relay OFF
finally:
sr.clear() # Clear the shift register
print("Shift register cleared.")
GPIO.cleanup() # Clean up GPIO settings