This is what I came up with. According to the serial monitor the sensor is working just fine, but the buzzer is not buzzing, ever. Where did I go wrong editing the code? Thank you, I do appreciate your time.
/*
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
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(4,OUTPUT);
}
void loop() {
int duration, 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
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
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()