Using this code to get a buzzer to go off when an ultrasonic sensor reads under a certain distance. It was working for a while but then it just started reading zeros, tried switching out the sensor with a couple different ones and the issue persisted. Is there something wrong with the code?
int trigPin = 9;
int echoPin = 10;
int buzzer = 7;
void setup() {
Serial.begin(9600);
pinMode(buzzer, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
Serial.print(distance);
Serial.println(" CM");
if (distance <= 10) {
digitalWrite(buzzer, HIGH);
} else {
digitalWrite(buzzer, LOW);
}
delay(10);
}