This works, here, with a DC-SR04 ultra sonic transducer and a piezo speaker like yours.
EDIT: Added code to run the task every 1/2 second to slow things down and let the speaker/buzzer time out
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
More info at: http://goo.gl/kJ8Gl
*** edited by LarryD and KalELonRedKryptonite ***
*/
#define trigPin 12
#define echoPin 13
unsigned long duration, distance;
int hysteresis = 2; // 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
const unsigned long TaskAtime = 500UL; //Runs TaskA every 1/2 second
unsigned long TimeA; //Times up, Task A time
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(4,OUTPUT);
}
void loop()
{
unsigned long millisNow = millis();
if (millisNow - TimeA >= TaskAtime) //Is it time to run Task A?
{
TimeA = millis(); //Re-initialize
TaskA(); // go and execute this code
}
// Check to see if its time to turn off the buzzer, IF, it's on
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()
// FUNCTIONS
//==========================================================
void TaskA()
{
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//Don't accept too large/small of a range
if (distance >= 200 || distance <= 0)
{
Serial.println("Out of range");
return; // invalid distance, go back
}
else
{
Serial.print(distance);
Serial.println(" cm");
}
// Has the distance changed significantly?
if ((lastDistance + hysteresis) < distance || (lastDistance - hysteresis) > distance)
{
lastDistance = distance; // update to the current distance
buzzDelay = distance; // time in milliseconds the buzzer will be on
buzzMilli = millis(); // the time the buzzer was turned on
buzzState = true; // indicate the buzzer is now on
digitalWrite(4,HIGH); //turn on the buzzer
}
}