ULTRASONIC SENSOR
An UltraSonic Sensor works by sending out a burst of ultrasound and listening for the echo when it bounces off of an object. The Arduino board sends a short pulse to trigger the detection, then listens for a pulse on the same pin using the pulseIn() function. The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.
Circuit
Code
(Reads the distance in cm and prints in it in the serial)
(Reads the distance in cm and prints in it in the serial)
const int pingPin = 7;
void setup() { Serial.begin(9600); } void loop(){ long duration, cm; pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH); cm = msecToCm(duration); Serial.print(cm); Serial.println("cm") delay(100); } long msecToCm(long microseconds){ return microseconds / 29 / 2; } |
initialize serial communication Establish variables for duration of the ping in centimeters The Sensor is triggered by a HIGH pulse of 2 or more microseconds. Give a short LOW pulse beforehand to ensure a clean HIGH pulse The same pin is used to read the signal from the Sensor: a HIGH pulse whose duration is the time (in microseconds) from the sending of the ping to the reception of its echo off of an object. Convert the time into a distance The speed of sound is 340 m/s or 29 microseconds per centimeter. The ping travels out and back, so to find the distance of the object we take half of the distance travelled. |