problems with timing

My program is supposed to make my buzzer sound a tone whenever my ultrasonic sensor detects an object less than 5 cm away for more than 5 seconds. However, i’m having difficulties getting the program to run consistently. After fulfilling my requirement the first time, the timing of it all gets messed up. I’m new to programming so any help would be much appreciated.

this is my program:

unsigned long delaystart = 0;
unsigned long delaytime = 5000;

int trigPin = 22 ; // Trigger
int echoPin = 23; // Echo
float duration, cm; // Ultrasonic sensor measurements
int buzzer = 12 ; //buzzer to arduino pin 12

void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT); //ultrasonic sensor
pinMode(echoPin, INPUT); //ultrasonic sensor
pinMode(buzzer, OUTPUT);

delaystart = millis();

}

void loop(){

digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
cm = ((duration/2) / 29.1);

if(cm>=5)
{
noTone(buzzer);
}

if(cm<5)
{
if((millis() - delaystart) >= delaytime)
{
delaystart += (delaytime);
tone(buzzer, 500);
}
}

}

You’re pinging far too frequently.
You should limit the ping rate to around 20 - 30 Hz.

Please remember to use code tags when posting code

I don't think the ultrasonic sensor can work with distances less than 5cm. The spec says 2cm but that is cutting it close.

…And don’t cross-post.
It’s a fast-track to the sin bin

Your duplicate topic in another forum section has been deleted

Cross-posting is against the rules of the forum. The reason is that duplicate posts can waste the time of the people trying to help. Someone might spend 15 minutes (or more) writing a detailed answer on this topic, without knowing that someone else already did the same in the other topic.

Repeated cross-posting will result in a timeout from the forum.

In the future, please take some time to pick the forum board that best suits the topic of your question and then only post once to that forum board. This is basic forum etiquette, as explained in the sticky "How to use this forum - please read." post you will find at the top of every forum board. It contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.