Home > Back-end >  How do I get the if-statement shorter?
How do I get the if-statement shorter?

Time:04-27

I want to connect between 1 and 4 lightbarriers to my RaspberryPi, but I do not know how to do the case differentiation in shorter lines (see below). Can someone tell me how to write the following code in a shorter way? Every case written below should do the same.

LIGHT_BARRIER_PIN_1 = 24 
l2, l3, l4 = False, False, False 
if config.value("rfu630.lightbarrier") >= 2:
    l2 = True
    LIGHT_BARRIER_PIN_2 = 5
    if config.value("rfu630.lightbarrier") >= 3:
        l3 = True
        LIGHT_BARRIER_PIN_3 = 6
        if config.value("rfu630.lightbarrier") >= 4:
            l4 = True
            LIGHT_BARRIER_PIN_4 = 13

while True:
    if l4 == True:
        if GPIO.input(LIGHT_BARRIER_PIN_1) == GPIO.HIGH or GPIO.input(LIGHT_BARRIER_PIN_2) == GPIO.HIGH or GPIO.input(LIGHT_BARRIER_PIN_3) == GPIO.HIGH or GPIO.input(LIGHT_BARRIER_PIN_4) == GPIO.HIGH:
            pass
    elif l3 == True:
        if GPIO.input(LIGHT_BARRIER_PIN_1) == GPIO.HIGH or GPIO.input(LIGHT_BARRIER_PIN_2) == GPIO.HIGH or GPIO.input(LIGHT_BARRIER_PIN_3) == GPIO.HIGH:
            pass
    elif l2 == True:
        if GPIO.input(LIGHT_BARRIER_PIN_1) == GPIO.HIGH or GPIO.input(LIGHT_BARRIER_PIN_2) == GPIO.HIGH:
            pass
    else:   
        if GPIO.input(LIGHT_BARRIER_PIN_1) == GPIO.HIGH:
            pass

CodePudding user response:

For the lower part, you can precompute the statements:

while True:
    a = GPIO.input(LIGHT_BARRIER_PIN_1) == GPIO.HIGH 
    b = GPIO.input(LIGHT_BARRIER_PIN_2) == GPIO.HIGH 
    c = GPIO.input(LIGHT_BARRIER_PIN_3) == GPIO.HIGH 
    d = GPIO.input(LIGHT_BARRIER_PIN_4) == GPIO.HIGH
    
    if l4:
        if (a|b|c|d):
            pass
    elif l3:
        if (a|b|c):
            pass
    elif l2:
        if (a|b):
            pass
    else:   
        if a:
            pass

CodePudding user response:

You could work off a list of pin numbers, slice that to the list of active ones (as per your config) and then use all() and map() to check them:

# light barrier pin   #1 #2  #3 #4
LIGHT_BARRIER_PINS = [24, 5, 6, 13]

lightbarrier_max = config.value("rfu630.lightbarrier")
active_pins = LIGHT_BARRIER_PINS[:lightbarrier_max]

while True:
    if all(map(lambda p: GPIO.input(p) == GPIO.HIGH, active_pins)):
        pass

or, for readability's sake, with a helper function:

# light barrier pin   #1 #2  #3 #4
LIGHT_BARRIER_PINS = [24, 5, 6, 13]

lightbarrier_max = config.value("rfu630.lightbarrier")
active_pins = LIGHT_BARRIER_PINS[:lightbarrier_max]

def is_high(pin):
    return GPIO.input(pin) == GPIO.HIGH

while True:
    if all(map(is_high, active_pins)):
        pass
  • Related