Introduction
Ultrasonic sensor is one of the coolest sensors out there, it is used for proximity or measuring distance. Ultrasonic sensor sends sound waves at a frequency that is too high for an human to hear, the waves are now reflected back at the sensor which helps to calculate distance of an object in front of the sensor based on the time. It has an eye-like design and of course is eye of robots as well! We can create a lot of things with Ultrasonic sensor once we learn how to program it using an Adruino board. So here we are going to create a device that measures distance between an object and the device itself.
Circuit diagram
Follow the circuit diagram given above
Code
Now comes the most important part which is to program the circuit
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor
void setup() {
Serial.begin(9600); // Serial terminal
}
void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
That is how we can program an Ultrasonic sensor with Adruino Uno.
Top comments (0)