Ultrasonic guidance needed!

Hi all!

I just bought a couple of SR04 ultrasonic sensors, and they work just fine with the new ping library.

It was a while since i was coding and I want my code to behave lika a On/Off switch. For example if the distance is more then 250 centimeters, I want it to turn on the led. If less I want it to turn of the led. Sounds simple but I want some logic to this. I dont want the leds to flicker around and I want it to be a steady operation. Maybe add a timer to avoid missreading, or a boolean?

Does anyone have any examples or any ideas on how this could be solved?

Best regards, Joakim

You get a number from the reading, so you use an IF statement to tell if that number is above or below a threshold.

However if this number is noisy then the way to stop it bouncing around is to have some hysteresis. That is simple to implement with two thresholds, one for switching an LED on and the other for switching the LED off.
So your code knows the current state of the LED, then take a reading and if the LED is on see if it is below the off threshold or if it is off see if it above the on threshold. Make a note in a variable of the state of the LED and update the value each time you turn the LED on or off.