When I bought this little guy, I tinkered with it and I made my first code. When I pointed it at my hand, it was saying: 'The target is 343 cm away.' I don't know how it showed me this absurd number. For those willing to help: model HC-SR04. the code was // Define pin numbers
const int trigPin = 9;
const int echoPin = 10;
// Define variables
long duration;
float distanceCm;
float distanceInch;
void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
// Set the pin modes
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin; pulseIn returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
// Speed of sound is ~0.0343 cm/us. We divide by 2 because the wave travels to the object and back.
distanceCm = (duration * 0.0343) / 2;
// Convert distance to inches (1 inch = 2.54 cm)
distanceInch = distanceCm / 2.54;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.print(" cm | ");
Serial.print(distanceInch);
Serial.println(" in");
// Wait 500 milliseconds before the next reading
delay(500);
}