How to Program an Ultrasonic Sensor

An Ultrasonic Sensor uses sonar to detect the distance of an object. In this tutorial, we’re going to learn how to program an ultrasonic sensor to receive distance values of objects. For this tutorial, we’re going to be using an HC-SRO4 ultrasonic sensor to get the distance value in inches of any object that is in front of the sensor.

How it works

It works by sending ultrasonic waves at a frequency of 40,0000 Hz to an object which are bounced back to the sensor. It works at a minimum range of 2 centimeters and a max of 4 meters The Trigger pin is responsible for sending the waves while the Echo is responsible for receiving the values.

Schematic

Code

#define Trig 7
#define Echo 5

We’re going to begin by defining our Echo and Trigger pins here.

void setup() {
   Serial.begin(9600);
   pinMode(Trig, OUTPUT);
   pinMode(Echo, INPUT);
}

Set “Trigger” as OUTPUT and Echo as INPUT. Make sure that the serial monitor is instantiated here

void loop() {
long duration, inches;

digitalWrite(Trig, LOW); //Makes sure that the Trigger pin is clear
delayMicroseconds(2);

digitalWrite(Trig, HIGH);
delayMicroseconds(2);
digitalWrite(Trig, LOW);

duration = pulseIn(Echo, HIGH); //Counts in microseconds the distance while Trigger is HIGH
...

Now what we have here is how our signals are going to work. We make sure that the Trigger pin is clear by setting it to LOW first. After that, we start sending ultrasonic waves by setting the Trigger pin to HIGH. This is when the Echo pin in “pulseIn(Echo, HIGH)” starts counting in microseconds how long it takes the waves to go to the object and bounce back to the sensor. We stop the counting by setting it to LOW.

inches = microsecondstoInches(duration);
Serial.println(inches);
delay(1);
}

long microsecondstoInches(long microseconds)
{
  return microseconds / 74 / 2;
  
}

The “microsecondstoInches” method simply does as the name suggests. We use this formula to convert our values. Since we got the entire distance of the object and back, we have to divide it by two to only get the distance to the object . Then, we make the “inches” variable equal to the return value of the method and we print it to the serial monitor.

Final Code

#define Trigger 7
#define Echo 5
void setup() {
  // put your setup code here, to run once:
   Serial.begin(9600);
   pinMode(Trigger, OUTPUT);
   pinMode(Echo, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
long duration, inches;

digitalWrite(Trigger, LOW);
delayMicroseconds(2);

digitalWrite(Trigger, HIGH);
delayMicroseconds(2);
digitalWrite(Trigger, LOW);


duration = pulseIn(Echo, HIGH);
inches = microsecondstoInches(duration);
Serial.println(inches);
delay(1);
}
long microsecondstoInches(long microseconds)
{
  return microseconds / 74 / 2;
  
}

Leave a comment

Your email address will not be published. Required fields are marked *