Event driven loop/sleep question

Dup, the LED going on and off is a condition called hysteresis where a input will hover around a set target. The easiest way to set your LED is to “braket” the condition testing something like this:

if (magx >= 50)
  over_flag = TRUE;
else if (magx <= 20)
  over_flag = FALSE;

So the flag will come on at values over 50 but not off until the value is 20 or below (in this example). This code already exists in your program:

xx = 2000;

if (Mx > xx) {
	trigger = HIGH;
	digitalWrite(LEDpin, HIGH); //LED turns "on" when magnet is near
}
if (Mx <= xx) {
	trigger = LOW;
	digitalWrite(LEDpin, LOW); //LED turns "off" when magnet is mot near
}
// read the door input pin:
doorstate = trigger;

The only problem is you test for only one value (xx). If you change that to xU (Upper boundary) and xL (Lower boundary) then it will work as expected:

const int xU = 3000;
const int xL = 2000;

if (Mx > xU) {
	trigger = HIGH;
	digitalWrite(LEDpin, HIGH); //LED turns "on" when magnet is near
}
if (Mx <= xL) {
	trigger = LOW;
	digitalWrite(LEDpin, LOW); //LED turns "off" when magnet is mot near
}
// read the door input pin:
doorstate = trigger;

I added this to the fixed code posted here. Give that a shot and let me know how it goes. :smile:

1 Like

@peekay123
thanks! When Mx is in between both thresholds, the LED turns off and in fact, I would like it to remain on until Mx returns to a normal state. Is there a way to latch on for a certain period of time? Somethiing like when Mx>xU or Mx <= xL, then turn on LED for 10secs then re-assess ??

thanks!

Dup, the LED will be OFF if Mx bounces high then low again quickly then stays between xU and xL values. So if I understand correctly then, you want something like this:

if ( (Mx > xU) || (Mx < xL) )
  turn ON the LED for 10s

I guess the setting of trigger does not change, just the LED, correct?

@peekay123
yes, exactly :slight_smile:

Ok… I posted the updated code that should do the trick (cross your fingers). You’ll notice a new boolean variable and a new timer variable. If you look at the end of loop() you will see the new LED timer code. Hopefully, it will make sense to you. :smile:

@peekay123,
pretty slick! It seems to work fine!! I’ll mess around with the timer to see if I get different results. I may add the Magy in the mix so when Magx crosses between the thresholds, Magy won’t be at the same time.
Is there a way to make something like xU=Mx+1000. So no matter what the actual value of Mx is, the threshold is always 1000 from Mx?!

Dup, great news! You can change xU and xL by removing the “const” in front of the declaration and you can make those global (move to where the other vars are declared). Then, just set xU and xL to what you want and off it goes!

If you can express the relationship between Mx and My logically/mathematically then it can be coded. :smile: