Lecture 13
Lecture 13
Ultrasonic Sensor
• Ultrasonic Sensor HC-SR04 is a sensor that can measure distance. It emits
an ultrasound at 40000 Hz (40kHz) which travels through the air and if there is an object or
obstacle on its path It will bounce back to the module. Considering the travel time and the
speed of the sound you can calculate the distance.
• The configuration pin of HC-SR04 is VCC (1), TRIG (2), ECHO (3), and GND (4). The supply
voltage of VCC is +5V and you can attach TRIG and ECHO pin to any Digital I/O in your
Arduino Board.
OUTP
UT
input
2
Working of Sensor
3
Pulse working of Sensor
4
Calculating Distance through Sensors
If the object is 20 cm away from the sensor, and the speed of the sound is 340 m/s or 0.034 cm/µs
the sound wave will need to travel about 588 microseconds. But what you will get from the Echo pin
will be double that number because the sound wave needs to travel forward and bounce backward.
So in order to get the distance in cm we need to multiply the received travel time value from the echo
pin by 0.034 and divide it by 2.
Arduino Sentax
distance = (duration / 2) * 0.0343;
5
pulseIn()
6
Code
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Serial.print("Distance: ");
Serial.println(distance);
}
7
Question
8
4