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

79 lines
2.6 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,
)
# Config
COUNT_UP_TEST_ENABLED = True
# 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)
if COUNT_UP_TEST_ENABLED:
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.01) # Delay between each byte
sleep(1)
sr.clear() # Clear the shift register
# Turn each pin on and off one by one
print("\nToggling each pin one by one...")
# channels 0-2 are connected to buzzer and relays:
print(f"Num {SHIFT_REG_CHANNEL_BUZZER}: Toggling buzzer...") # channel 0
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(f"Num {SHIFT_REG_CHANNEL_RELAY1}: Toggling Relay 1...") # channel 1
sr.toggle_pin(SHIFT_REG_CHANNEL_RELAY1)
sleep(0.5)
sr.toggle_pin(SHIFT_REG_CHANNEL_RELAY1)
print(f"Num {SHIFT_REG_CHANNEL_RELAY2}: Toggling Relay 2...") # channel 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
# channels 3-7 are connected to terminals only (no dedicated device on pcb):
for pin in range(3,8): # 3-7 are connected to terminal only
print(f"Num: {pin}: Toggling Terminal")
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)
finally:
sr.clear() # Clear the shift register
print("Shift register cleared.")
GPIO.cleanup() # Clean up GPIO settings