How To Ultrasonics Sensor With Push Button

Required Hardware

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

  • Arduino Board
  • Breadboard
  • Ultrasonic Sensor (HC-SR04)
  • PUSH button
  • Hook-up Wires

Circuit

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

Schematic

Code

                    

1. /*
2. Ultrasonic Sensor with Push Button
3. This example shows how to use Ultrasonic Sensor with Push Button
4. The circuit:
5. – Ultrasonic sensor
6. echo pin connected to digital pin 13 of Arduino
7. trig pin connected to digital pin 12 of Arduino
8. Vcc pin connected to Vcc pin of Arduino
9. Gnd pin connected to Gnd pin of Arduino
10. – Push Button
11. Anode connected to VCC.
12. Cathode connected to digital pin 2.
13. Cathode connected to GND through 220 resistor.
14.
15. http://hackerspacekarachi.org/
16. */
17.
18. #define echoPin 13 // define output pin
19. #define trigPin 12 //define input pin
20. long duration; //store time taken for wave to trvel
21. int distance; // store distance travel by wave
22.
23. void setup() {
24. Serial.begin(9600); //initiate program
25. pinMode(trigPin, OUTPUT); //read and store output
26. pinMode(echoPin, INPUT); //read and store input
27. pinMode(2, INPUT); // declaration of input
28. }
29.
30. void loop() {
31.
32. digitalWrite(trigPin, LOW); //trigger object with delay of 2micsec
33. delayMicroseconds(2);
34. digitalWrite(trigPin, HIGH);
35. delayMicroseconds(10);
36. digitalWrite(trigPin, LOW);
37.
38. duration = pulseIn(echoPin, HIGH); //time taken for the wave to travel
39. distance = (duration * 0.034 / 2); //distance divided by 2 for incoming
40. // outgoing waves
41. int d = digitalRead(2); // read and store input
42. if (d == 1)
43. {
44. Serial.print(“Distance : “); //Display results
45. Serial.print(distance);
46. Serial.println(” cm “);
47. delay(1000);
48. }
49. else
50. {
51. Serial.print(“Press Button”);
52. }
53. }
54.

1. /*