#define trig 12 #define echo 13 #define power_pin 11 void setup() { Serial.begin(9600); pinMode(trig,OUTPUT); pinMode(echo,INPUT); pinMode(power_pin,OUTPUT); digitalWrite(power_pin,HIGH); // As because there is no external power source so we need the pin 11 as HIGH } void loop() { double distance = hc_sr04(trig, echo); // calls hc_sr04() and get the distance form it Serial.print(distance); // print the distance Serial.println("cms ahead"); } double hc_sr04(double trigPin , double echoPin) { double duration, distance; // This procedure is mentioned in the datasheet of HC-SR04 attached digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); //Check out the refernce to know about this function......select "pulseIn" then press Ctrl + Shift + F distance = ((duration/1000000)*33000)/2; // distance = speed * time/2 return constrain(distance,0,200); // dont know what constrain is just select it and Ctrl + Shift + F }