# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / RELAY MOTOR
# ====================================================================
"""Experiment 3: hold a button to energize an active-low relay."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
from time import sleep

# ====================================================================
# 02 / CONFIGURE INPUT AND ACTUATOR
# ====================================================================
def main():
    from gpiozero import Button, OutputDevice
    # Pull-up: button connects GPIO25 to GND when pressed.
    # Enable the internal pull-up and debounce mechanical button transitions.
    with Button(25, pull_up=True, bounce_time=0.05) as button, \
         OutputDevice(22, active_high=False, initial_value=False) as relay:
        # Remember the previous state to avoid repeating identical commands.
        last = None
        try:
            # ====================================================================
            # 03 / MONITOR THE BUTTON AND CONTROL THE RELAY
            # ====================================================================
            while True:
                pressed = button.is_pressed  # Read state, not the GPIO number.
                # Change the relay only when the button state changes.
                if pressed != last:
                    # Logical True energizes the active-low relay (physical LOW).
                    relay.value = pressed
                    print('Motor ON' if pressed else 'Motor OFF', flush=True)
                    last = pressed
                # Poll every 20 ms without continuously consuming CPU time.
                sleep(0.02)
        # ====================================================================
        # 04 / SAFE SHUTDOWN
        # ====================================================================
        finally:
            # De-energize the motor relay before the GPIO device closes.
            relay.off()  # De-energize before releasing GPIO.

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
