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);
}