/
Ultrasonic Distance Sensor

Ultrasonic Distance Sensor

Principle

 

  • Ultrasonic sensors use the same principle bats (flying mammals) use to detect obstacles – by sending ultrasonic signals and analysing the reflection / echo

  • The time between sending a signal (a trigger pulse of width 10us) and receiving an echo is used to calculate the distance from an object

  • HC-SR04 needs +5V DC, works for obstacles at an angle <15°, for distances between 2cm – 400 cm

  • Practically, 3-300 cm is fairly accurate (up to 0.3cm). If it is too close or too far, no meaningful echo will be received, and the reading might show a high / inaccurate distance

  • Distance = (time taken from trigger to echo/2) x speed of sound

  • Speed of sound is about 345 m/s at 23oC

Connections

Assuming digital pin 9 is the triggerPin and digital pin 8 is the  echoPin.

Code

C++

Blocks

C++

Blocks

 

long readUltrasonicDistance(int triggerPin, int echoPin) { pinMode(triggerPin, OUTPUT); // Clear the trigger digitalWrite(triggerPin, LOW); delayMicroseconds(2); // Sets the trigger pin to HIGH state for 10 microseconds digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); pinMode(echoPin, INPUT); // Reads the echo pin, and returns the // sound wave travel time in microseconds return pulseIn(echoPin, HIGH); } void setup() { Serial.begin(9600); } void loop() { distanceCm = 0.01723 * readUltrasonicDistance(9, 8); // try to make sense of the above formula! Serial.println(distanceCm); delay(10); }

 

 

 

Simulation