I am trying to test the ultrasonic sensor (HC-SR04) using a ESP32 development board. The code I used is this:
#define TRIG_PIN 34 // Arduino pin connected to TRIG pin of HC-SR04
#define ECHO_PIN 35 // Arduino pin connected to ECHO pin of HC-SR04
void setup() {
Serial.begin(9600); // Start the Serial communication
pinMode(TRIG_PIN, OUTPUT); // Set TRIG_PIN as output
pinMode(ECHO_PIN, INPUT); // Set ECHO_PIN as input
}
void loop() {
// Clear the TRIG_PIN
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting TRIG_PIN high for 10 microseconds
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echo pin, and calculate the distance
// long duration = pulseIn(ECHO_PIN, HIGH);
// Read the echo pin with a timeout of 25,000 microseconds (25 milliseconds)
long duration = pulseIn(ECHO_PIN, HIGH, 25000);
Serial.print("Dur = ");
Serial.println(duration);
// Calculate the distance in centimeters
float distanceCm = (duration / 2.0) * 0.0343;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
delay(1000); // Wait for a second before the next measurement
}
I have connected the Trig pin of sensor to D5 (34) pin in board. And the Echo pin of sensor to the D18 (35).
And the VCC of sensor to the Vin of ESP32 board. Right now, there is no external power source. The board is connected via USB.
The problem is, I am receiving values in the serial monitor like this:
Distance: 164.88 cm
Dur = 1
Distance: 0.02 cm
Dur = 9613
Distance: 164.86 cm
Dur = 1
Distance: 0.02 cm
Dur = 9605
Distance: 164.73 cm
Dur = 9579
Distance: 164.28 cm
Dur = 1
Distance: 0.02 cm
Dur = 9603
Distance: 164.69 cm
Dur = 9610
Distance: 164.81 cm
Dur = 9579
Distance: 164.28 cm
Dur = 2
Distance: 0.03 cm
Dur = 2
Distance: 0.03 cm
Dur = 1
Distance: 0.02 cm
Dur = 9599
Distance: 164.62 cm
Dur = 9579
Distance: 164.28 cm
These values are received when I keep my hand very close to the sensor. And even when I remove my hand, similar values are shown. It looks like the distance calculation is wrong. So I tried testing the value returned by the echo. That's what the "Dur = " values are.
What could be the reason? I tried testing with other sensors (I had 4 of them). All are working like this.
Btw, am a newbie. Is there something I missed?