Ultrasonic sensor (HCSR04)

The main purpose of using this sensor is for the measurement of distances. In our case it may not be needed, but it is very useful in beginner robotics:

Ultrasonic sensor HCSR04

It emits ultrasonic sound waves, which, if anything is present, then gets back a reflected and picked up by the receiver. Based on the duration of pulse output and the pulse received, we calculate the distance.

The sensor can provide readings ranging from 2 cm to 400 cm. It contains the emitter and the receiver, and thus we can just plug and play with our Intel Edison. The operating voltage is +5V DC. The operation isn't affected by sunlight or dark materials, and is thus efficient for finding distances. Another thing to be noted is that the beam angle is 15 degrees:

Beam angle

Let's have a look at some sample code for using the preceding module.

There is no direct method of calculating the distance directly from the sensors. We need to use two GPIO pins. The first will be the trigger pin, which will be configured as the output, while the second will be the echo pin, which will be in input mode. The moment we send a pulse through the trigger pin, we wait for an incoming pulse in the echo pin. The timing difference and a little bit of mathematics gives us the distance:

inttrigPin=2; 
intechoPin=3;
void setup()
{
pinMode(trigPin,OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop()
{
long duration, distance;
//Send pulses
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

//Receive pulses
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

//Calculation
distance = microsecondsToCentimeters(duration);
Serial.println(distance);
delay(200);
}

longmicrosecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}

In the preceding code, concentrate on the loop method. Initially, we send a low pulse to get a clean high pulse. Next, we send a high pulse for 10 seconds. Finally, we get the high pulse in the echo pin and use the pulseIn() method to calculate the duration. The duration is sent to another method, where we use the known parameter of the speed of sound to calculate the distance. To use this code on the Edison, connect the HCSR04 sensor to the Edison by following this circuit diagram:

Circuit diagram

Use the preceding circuitry to connect your HCSR04 to your Edison. Next, upload the code and open the serial monitor:

Serial monitor reading for HCSR04

The preceding screenshot shows us the serial monitor where we get the readings of the distance measured.

..................Content has been hidden....................

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