Arduino Interfacing With Ultrasonic Sensor (HC-SR04)
Circuit Diagram :- Code:- const int trigPin = 4; const int echoPin = 5; long duration; int distance; void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); } void loop() { digitalWrite(trigPin,LOW); delayMicroseconds(1); digitalWrite(trigPin,HIGH); delayMicroseconds(20); digitalWrite(trigPin,LOW); // Reads the echopin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin,HIGH); // Calculation of distance distance = duration*0.034/2; //prints the distance on serial Monitor Serial.print("Distance:"); Serial.println(distance); delay(500); }