I'm totally stuck with this rather trivial (?) problem, i've got this pseudo code that i will convert to C (i'm programming a ATmega8 MCU):
Include libraries
Threshold = 40 //Celsius
While true
Temp = Read_temp_from_sensor()
If Temp > Threshold
Turn on LED
Else
Turn off LED
Is there a way to make the LED stay on for the duration of the While-loop but only as long as the temperature read from the sensor is higher than the threshold value?
I'm guessing that i don't want to evaluate the values in the If/Else block at every cycle, am i on the right track here?
Best Answer
This is exactly what you do - you evaluate if/else at every cycle. Your code is basically ok, it just has one flaw - if the temperature is near the threshold your LED will blink rapidly as temperature readings will be above 40 and below 40 a little bit. You might not want that. To avoid this you have to implement hysteresis - have some margin temperature has to overcome to either turn LED on or off. Something like this:
You might want to consider sleeping the microcontroller in between loop cycles, using interrupts form the watchdog to wake it up in equal time intervals.