How To Getting Values From Ultrasonic Sensor (HCSR04) With Arduino 

Required Hardware

For users who do not have Hackerspace Karachi Arduino Kit v1.0

  • Arduino Board
  • Breadboard
  • ultrasonic sensor (HCSR04)
  • Hook-up Wires

Circuit

For users who do not have Hackerspace Karachi Arduino Kit v1.0

Schematic

Code

                    

1. /*
2. Getting values from ultrasonic sensor with Arduino
3.
4. This example shows how to get values from ultrasonic sensor using Arduino.
5.
6. The circuit:
7. – Ultrasonic sensor
8. echo pin connected to digital pin 13 of Arduino
9. trig pin connected to digital pin 12 of Arduino
10. Vcc pin connected to Vcc pin of Arduino
11. Gnd pin connected to Gnd pin of Arduino
12.
13. http://hackerspacekarachi.org/
14. */
15.
16. #define echoPin 13 // define output pin
17. #define trigPin 12 //define input pin
18. long duration; //store time taken for wave to trvel
19. int distance; // store distance travel by wave
20.
21. void setup() {
22. Serial.begin(9600); //initiate program
23. pinMode(trigPin, OUTPUT); //read and store output
24. pinMode(echoPin, INPUT); //read and store input
25. }
26.
27. void loop() {
28. digitalWrite(trigPin, LOW); //trigger object with delay of 2micsec
29. delayMicroseconds(2);
30. digitalWrite(trigPin, HIGH);
31. delayMicroseconds(10);
32. digitalWrite(trigPin, LOW);
33.
34. duration = pulseIn(echoPin, HIGH); //time taken for the wave to travel
35. distance = (duration * 0.034 / 2); //distance divided by 2 for incoming
36. // outgoing waves
37.
38. Serial.print(“Distance : “); //Display results
39. Serial.print(distance);
40. Serial.println(” cm “);
41. delay(1000);
42.
43. }

1. /*