Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Arduino ultrasonic sensor


May 15, 2021 Arduino


Table of contents


The HC-SR04 ultrasonic sensor uses sonar to determine the distance of an object, just like a bat. It offers excellent non-contact range detection, high accuracy, stable readings and ease of use, ranging in size from 2 cm to 400 cm or 1 inch to 13 feet.

Its operation is not affected by sunlight or black materials, although acoustically soft materials such as cloth may be difficult to detect. It is equipped with an ultrasonic transmitter and receiver module.

Arduino ultrasonic sensor

Arduino ultrasonic sensor

Technical specifications

Power supply - 5V DC
Static current - slt;2mA
Current - 15mA
Effective angle - slt;15 degrees
Range - 2 cm-400 cm/1 in-13 ft
Resolution - 0.3 cm
Measurement angle - 30 degrees

The required component

You will need the following components:

  • 1 × breadboard breadboard
  • 1 × Arduino Uno R3
  • 1 × ultrasonic sensor (HC-SR04)

Program

Connect according to the circuit diagram, as shown in the following image.

Arduino ultrasonic sensor

Sketch

Turn on the Arduino IDE software on your computer. U se arduino to encode and control your circuitry. Open a new sketch file by clicking New.

Arduino ultrasonic sensor

Arduino code

const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor

void setup() {
   Serial.begin(9600); // Starting 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;
}

Code description

The ultrasonic sensor has four terminals: : 5V, Trigger, Echo and GGND, connected as follows:

  • Connect the .5V pin to the .5v on the Arduino board.
  • Connect Trigger to the digital pin 7 on the Arduino board.
  • Connect the Echo to the digital pin 6 on the Arduino board.
  • Connect the GD to the GD on Arduino.

In our program, we show the distance measured by the sensor in inches and centimeters through the serial port.

Results

You will see the distance measured by the sensor in inches and centimeters on the Arduino serial monitor.