Q:

How to switch LED ON / OFF based upon Temperature readings?

I have the following mockup DS18B20 connected to an Arduino that is slave for Raspberrypi.
I'm trying to turn led 13 on Arduino when temperature is over 29 degrees.
The only way that I've manage to do it is inside a while loop.
Is there any way to do it outside a while loop but to keep the readings running?
My code looks like this:
def led on()
def led off()
def function():
   while True:
       "Get Temp readings from arduino and display them"
       If Temp > 29:
           "Led on"
function()

Because is inside the while loop is not helping me. I would like something like when LED is on the function to be executed once and then the while loop to continue ignoring the LED on and just looking for temp readings.
Maybe is doesn't make sense but let say instead of one LED I have a function that will run a multitude of LEDs in order.

A:

Have you tried using finite state machines?. It's really easy and efficient, using python. Just create a global state variable, and define states like "READING_TEMP", "CHECKING_LED_STATES", etc. Inside your infinite while, you could include several if-then to check states.
And if you want to ignore led on, you could create another function like current_led_sate(), or is_led_on(). If you have multiple LEDS, may be use bit masking. I love bit masking because LED state(s) can be represented by only using 1 bit.
Or maybe using threads will be easier for you. Check this:
    import time
    import threading
def get_temp():
    #return temperature

def is_led_on():
    #return led state, true or false

#Temperature threshold in celsius degrees
TEMP_THD = 29

def temp_thread():
    while(True):
        Temp = get_temp()
        if( Temp>TEMP_THD):
            if(is_led_on()==False):
                led_on()
        time.sleep(2)

t = threading.Thread(target=temp_thread)
t.start()

while (True):
    time.sleep(0.1)

