Intermittent Output for LEDs and Buzzer

Hi everyone,

I have a student building a "security system" where he has hooked up a tone buzzer and two LEDs to a controller. When an ultrasonic rangefinder detects something within range, the tone buzzer goes off and the LEDs turn on. For some reason, when we put something in front of the sensor, it only works intermittently. Sometimes the buzzer will turn on with no LEDs, other times LEDs will work but not the buzzer, and sometimes both, sometimes none. I've attached the code here as well as a photo of our wiring. Any help for a struggling teacher would be great! Thanks!

#define trigPin 2
#define echoPin 3
#define LED 11
#define soundbuzzer 7
int sound  = 500;


void setup() {
  Serial.begin (9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(soundbuzzer, OUTPUT);
}
void loop() {
  long durationindigit, distanceincm;
 
  digitalWrite(trigPin, LOW);
  delayMicroseconds(100);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
 
  durationindigit = pulseIn(echoPin, HIGH);

  distanceincm = (durationindigit/5) / 29.1;
 
  if (distanceincm > 50) {

      digitalWrite(LED, HIGH);
      delay(5000);

  }
 
  else {
   digitalWrite(LED, LOW);  // turn the LED on (HIGH is the voltage level)
                        // wait for a second    
  }

  if (distanceincm > 5 ||  distanceincm <= 0){
    Serial.println("Outside the permissible range of distances");

    noTone(soundbuzzer);
  }
  else {
    Serial.print(500);
    Serial.println("cm");
    tone(soundbuzzer, 1000);
  }
 
  delay(300);

}

What does the serial output tell you is happening?

The pin is (or should be) already LOW.
And a 10us HIGH is more than sufficient to trigger the sensor

This is what shows up regardless of whether I put my hand in front of the sensor. It's seemingly random.
image

Take a step back.
Strip the code down to just reading distances; forget buzzes and LEDs.
Use hard surfaces to test, like walls or physical books (PDFs don't work too well)

And think about what you think the code is doing during
delay(5000) and delay(300).
Hint. less than you think, unless your answer was...

ZERO. Deaf, blind, and dumb, might as well be dead.

This was the answer! We got this code online and tried to modify it but I am not a pro coder, I don't really remember why I put those in there.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.