Getting Started with Ultrasonic Sensor HC-SR04 (Arduino IDE)

Ultrasonic Sensor HC-SR04 Pins:

VCC : +5VDC
Trig : Trigger (INPUT) – Pin 7
Echo : Echo (OUTPUT) – Pin 8
GND : GND

Upload the code using Arduino IDE.

int trigPin = 7;    // Trigger
int echoPin = 8;    // Echo
long duration, cm, inches;

void setup() {

  Serial.begin (9600);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
 
void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  cm = (duration/2) / 29.1;
  inches = (duration/2) / 74;
  
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  delay(1000);
}