//Define pins for ultrasonic sensor
#define trig 7
#define echo 6
void setup() {
Serial.begin(9600); //set the baud rate of serial communication to 9600
pinMode(trig, OUTPUT); //trig will have output pulses
pinMode(echo, INPUT); //echo will be input pulses
}
void loop() {
// Duration will be the input pulse and distance will be the distance to the obstacle in centimetres
int duration, distance;
digitalWrite(trig, HIGH);
delay(1); //output pulse with 1ms width on trig
digitalWrite(trig, LOW);
//Measure the pulse input in echo pin
duration=pulseIn(echo, HIGH);//blocks the program to wait for echo to go HIGH
//Distance is half the duration multipied by 0.342 cm/μs (microsecond)
distance = (duration*0.0343/2);
//waiting 60ms
delay(60);
Serial.print("Distance :");
Serial.print(distance);
Serial.println(" cm ");
}