How to run only part of my code in a loop?

Viewed 72

I'm trying to find a way to optimize my code. For the moment I have a while loop in which several sensors are read out. But in the beginning of my code I first check what sensors that needs to be read out and I simply add an if function before every part of code. Is there a better way of doing this?

sensor1_actif=1
sensor2_actif=0

while True:
    if(sensor1_actif==1):
        x=sensor1read()
    
    if(sensor2_actif==1):
        y=sensor2read()

    ...
2 Answers

You can use a for loop:

funcs = [sensor1read, sensor2read, ...] # Store the functions in order
while True:
    actifs = [sensor1_actif, sensor2_actif, ...] # Store the variables in order
    sensor_readings = [None for _ in range(len(funcs))]
    for i, (func, actif) in enumerate(zip(funcs, actifs)): # Iterate through
        if actif: # Equivalent to if actif != 0
            sensor_readings[i] = func()

This stores the outputs in a list. sensor_readings[0] will be the output of the first function, sensor_readings[1] the output of the second function, etc. If the function did not get called it defaults to None.

Perhaps best to do this is with a control dictionary. Something like this:

def sensor1read():
    pass

def sensor2read():
    pass

CONTROL = {'sensor_1': {'active': True, 'func': sensor1read, 'val': None}, 'sensor_2': {'active': True, 'func': sensor2read, 'val': None}}

def read_sensors():
    for v in CONTROL.values():
        if v['active']:
            v['val'] = v['func']()

In this way you just set the 'active' value accordingly then this single function will update all values for all active sensors

Related