Ultrasonic sensor 

The HC-SR04 is a cheap ultrasonic sensor. It is used to measure the range between itself and an object. Each HC-SR04 module includes an ultrasonic transmitter, a receiver, and a control circuit. You can see that the HC-SR04 has four pins: GND, VCC, Trigger, and Echo. You can buy HC-SR04 from SparkFun, at https://www.sparkfun.com/products/13959, as shown in the next image. You can also find this sensor on Seeed Studio at https://www.seeedstudio.com/Ultra-Sonic-range- measurement-module-p-626.html:

To work with the HC-SR04 module, we can use the NewPing library on our Sketch program. You can download it from http://playground.arduino.cc/Code/NewPing and then deploy it into the Arduino libraries folder. After it is deployed, you can start writing your Sketch program.

Now open a Sketch and write the following code:

    #include <NewPing.h>

#define TRIGGER_PIN 2
#define ECHO_PIN 4
#define MAX_DISTANCE 600

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

long duration, distance;

void setup() {
pinMode(13, OUTPUT);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
}

void loop() {
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);

digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);

digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);

//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;

Serial.print("Distance=");
Serial.println(distance);
delay(200);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.78.106