Well that figures, the old code works now too, even better than the new code haha ![]()
Clearly I had something wrong yesterday and repeatedly missed it.
EDIT:
This code works, mostly, and buzzes AND flashes an LED though it could be tweaked to be more accurate I think.
/*
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
 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
void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(4,OUTPUT);
 pinMode(6,OUTPUT);
Â
}
void loop() {
Â
Â
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
  digitalWrite(6,HIGH); //turn on the LED
 }
 if (buzzState == true && (millis() - buzzMilli >= buzzDelay))  //is time left and is the buzzer ON?
 {
  digitalWrite(4,LOW); //turn off the buzzer
  digitalWrite(6,LOW); //turn off the LED
  buzzState = false; //indicate the buzzer is now off
 }
Â
}Â
 // END of loop()
I haven't done functions yet, so I'm going to read up on them first before I attempt to do the same with the newer code.