Recently, I bought a HC-SR04 ultrasonic sensor nad plug it into an Arduino UNO board.
#define trigPin 9
#define echoPin 8
#define ledPin 13
long duration;
int distanceThreshold = 20; // Adjust this threshold according to your requirements
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
int distance = duration * 0.034 / 2;
// Print distance to Serial Monitor (optional)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the object is within the specified range
if (distance < distanceThreshold) {
// Light up the LED (representing the bulb)
digitalWrite(ledPin, HIGH);
} else {
// Turn off the LED if no object is detected or it's outside the range
digitalWrite(ledPin, LOW);
}
// Delay before the next reading
delay(500);
}
Here are the code I upload, but it it keep outputting 0 and 12 and 11.
13:46:55.487 -> Distance: 0 cm
13:46:55.990 -> Distance: 0 cm
13:46:56.474 -> Distance: 0 cm
13:46:56.978 -> Distance: 12 cm
13:46:57.486 -> Distance: 12 cm
13:46:57.954 -> Distance: 11 cm
13:46:58.501 -> Distance: 0 cm
13:46:59.005 -> Distance: 0 cm
13:46:59.501 -> Distance: 11 cm
13:46:59.978 -> Distance: 0 cm
Eventough it is facing the celling still it give output of 12 n 11 n 0.
anyone could help me Thanks very much.