I did not have a sensor so I used a POT.
Add/delete/change lines as needed.
You should be able to modify the code to your ultrasonic application.
Change hysteresis as needed.
int duration;
int distance;
int hysteresis = 5; // minimum acceptable change
boolean buzzState = false; // false = buzzer is off
unsigned long buzzDelay; //Time the buzzer will be On
unsigned long buzzMilli; //Time the buzzer went On
int lastDistance; // = the last read distance value
void setup()
{
Serial.begin (9600);
buzzState = false;
pinMode(4,OUTPUT);
}
void loop()
{
duration = analogRead(A0);
distance = (duration);
if (distance >= 200 || distance <= 0)
{
Serial.println("Out of range");
}
else
{
Serial.print(distance);
Serial.println(" cm");
}
// Has the distance changed significantly?
if ((lastDistance + hysteresis) < distance || (lastDistance - hysteresis) > distance)
{
lastDistance = distance;
buzzDelay = distance;
buzzMilli = millis();
buzzState = true; // indicate the buzzer is now on
digitalWrite(4,HIGH); //turn on the buzzer
}
if (buzzState == true && (millis() - buzzMilli >= buzzDelay)) //is time left and is the buzzer ON?
{
digitalWrite(4,LOW); //turn off the buzzer
buzzState = false; //indicate the buzzer is now off
}
}
// END of loop()