Base on your limited code fragment, I’m assuming that you basically want to toggle the state variable “currentState” only when distance is less than 50.
Assuming your currentState is defined as a boolean you could do the following:
int distance;
bool currentState = 0; // Assuming this is your initial state
// Test for distance less than 50 and toggle state
if(distance < 50)
{
currentState = !currentState; // Toggle state
}
These are of course also code fragments, not complete code, so you would need to incorporate them (the initialization and test) in the appropriate sections of your complete code.
I want to toggle “currentState” between 0 and 1 for every 1 time distance becomes less than 50.
Do you mean if it’s less than 50 on any read, then toggle currentState. Or to you mean toggle currentState when less than 50 if and only if the prior read was not less than 50?
OK, so what may be happening is that once you enter the <50 state you are toggling your state variable at a rate roughly equivalent to 500ms delay and driving your on/off LED accordingly. If you want to slow down the toggle than yes, adjust the delay. But to me that may not be the behavior you really want.
How is your LED supposed to behave when your hand is in front of the sensor and distance < 50? I’m guessing here, but you either want it be on (solid) when <50 or you want it to blink when <50, then be off when >=50. Bare with me, I’m just still confused about what you want to happen. The code should not be difficult once we figure that out.
The Light will turn on through pin 13 and stay on when I pass my hand through the ultrasound at less than 50cm.
I did set the relay to 1500ms so that I can remove my hand by then so that it will not flash on and off.
But ideally, I wanted to have the light turn on and stay on until I REMOVE MY HAND PAST 50CM AND PUT IT BACK AGAIN in which case it would turn off.
Described in another way: currentState toggles between 0 and 1 using the if (distance < 50) { currentState = 1 - currentState; line but only toggles once for every time the distance is less than 50cm
when my hand goes in front of the ultrasound, the light should turn on if it was off and off if it was on and stay that way no matter how long I leave my hand in front of it. It should only toggle back after I remove my hand and then put it back.
Well damn you paulvha (just kidding) you beat me to it. Must be a time zone time. Yes that will work.
I had just this morning (PST) finished my version (very similar) and was about to post when I saw this. The difficult part was trying to understand what Ardalan wanted. Once he described it in full it made sense that he wanted to created a proximity sensor that toggled a switch.