Search code examples
pythongpio

GPIO Python Checking to see if an input state has changed


Good evening all,

Please see code below. Is there anyway once inputs 23 & 24 and output 4 have been activated I can continuously check to see if any of the inputs have become false and if so send output 4 high?

Any help would be highly appreciated.

B.

import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.setup(18,GPIO.OUT)
GPIO.output(18,0)
GPIO.setup(4,GPIO.OUT)
GPIO.output(4,1)


while True:
    if(GPIO.input(23) ==1):
        print("UP")
        GPIO.output(18, GPIO.LOW)
        time.sleep(2)

    if(GPIO.input(23) ==0):
        print("DOWN")
        GPIO.output(18, GPIO.HIGH)
        time.sleep(2)

    input_state = GPIO.input(24) and GPIO.input(23)
    if input_state == True:
        GPIO.output(4, GPIO.LOW)

Solution

  • Without knowing the schematic and/or what you're trying to do with the circuit, i won't really be able to improve the code. but this should work:

    import pigpio, time
    
    Debounce = 0.02
    
    Input23 = 23
    Input24 = 24
    
    Output18 = 18
    Output4 = 4
    
    pi_GPIO = pigpio.pi()
    
    pi_GPIO.set_mode(Input23, pigpio.INPUT)
    pi_GPIO.set_pull_up_down(Input23 , pigpio.PUD_UP)
    
    pi_GPIO.set_mode(Input24, pigpio.INPUT)
    pi_GPIO.set_pull_up_down(Input24 , pigpio.PUD_UP)
    
    pi_GPIO.set_mode(Output18, pigpio.OUTPUT)
    pi_GPIO.set_pull_up_down(Output18, pigpio.PUD_UP)
    
    pi_GPIO.set_mode(Output4, pigpio.OUTPUT)
    
    
    def cbf(gpio, level, tick):
        time.sleep(Debounce) # only used if using a button or any mechanical switch. Change value according to the type of switch, see datasheet and/or experimentation
        if pi_GPIO.read(Input23):
            print("Input23 UP")
            pi_GPIO.write(Output18, 0)
    
        else:
            print("Input23 DOWN")
            pi_GPIO.write(Output18, 0)
    
    
    cb = pi_GPIO.callback(Input23, pigpio.FALLING_EDGE, cbf)
    
    
    while True:
        if pi_GPIO.read(Input24) and pi_GPIO.read(Input23):
            time.sleep(Debounce) # only used if using a button or any mechanical switch. Change value according to the type of switch, see datasheet and/or experimentation
            if pi_GPIO.read(Input24) and pi_GPIO.read(Input23):  # only used if using a button or any mechanical switch. Change value according to the type of switch, see datasheet and/or experimentation
                pi_GPIO.write(Output4, 0)
    

    The function CBF will be called whenever there's a change in the value, independent of the while loop.

    You will need to install pigpio if you don't have it already. a more full-featured RPi.GPIO library that also supports remote access if enabled on the pi device.

    pip install pigpio
    

    Let me know if there are any more details you can provide.