Arduino - Ultrasonic Sensor
Last Updated :
26 Apr, 2024
Sensors are widely used for detecting devices by approximating their distance from the source. One such example of a sensor is the HC-SR04 ultrasonic sensor which uses the SONAR technique for the sensing purpose. The main feature of this sensor is to mimic the nature of bats and therefore predict the distance of objects without actually establishing contact with the device.
In this article, we will study how to design this ultrasonic sensor using the Arduino board and programming software. We will study the specifications needed for this sensor, and the methods and circuit diagrams used for designing this sensor. In addition to this, we will see the Arduino code written on IDE that will result in a sensor.
What is an Ultrasonic Sensor?
Similar to any other sensor, the Arduino Ultrasonic Sensor is used to sense the presence of any object and predict the distance of the object in appropriate units which is inches in this case. Therefore, we can define the Arduino Ultrasonic Sensor as a device that uses the ultrasonic sensing technique to estimate the distance of an object.
Arduino is used for creating this sensor since it needs to be programmed to detect the reflected rays from objects and display the distance in the desired format.
Technical Specifications
Before getting started with the sensor, we need to mention some specifications of the sensor that can ensure proper working conditions for the sensor.
- The Arduino board needs a minimum power supply of 5V which is required to turn the Arduino on. This must be Direct Voltage.
- The Arduino board needs a Quiescent Current which is at most 2mA and a working current of 15mA. Higher current values can burn the Arduino components.
- It is preferred that the object must be placed at the center line of the sensor but it can also be present at a certain angle from the center. This is known as effectual angle which should be less than 15°.
- The distance at which an object must be placed so that it can be detected by a sensor is around 2cm – 400 cm. The accuracy of detection decreases with an increase in distance.
Apparatus
Apparatus refers to the components that are needed for the project. The components required for designing a sensor using Arduino include.
- One Breadboard
- Arduino Uno R3 (Generally this model is only preferred_
- One Ultrasonic Sensor (HC-SR04)
- Some wires for making connections.
These devices are easily available at nearby electronics shops.
Working of the Ultrasonic Sensor
The Ultrasonic Sensor works on the principle of reflection, let us see how
- The sensor is used to emit waves known as ultrasound with a frequency of 40 KHz.
- The transmitted wave moves in a straight line path and gets obstructed by an object if present.
- After being obstructed, the wave reflects and is detected by the sensor. The time of transmission and reflection of the wave is noticed and the distance of the object is calculated using the speed-time formula.
Given Below is the Ultrasonic Sensor
Working of sensor
Principle: If you carefully look at the diagram above, you will see that there is a transmitter. This component is responsible for emitting waves of an appropriate frequency that can travel far i.e. it should be able to transmit the ultrasound. Once the ultrasound waves are emitted, they continue a straight line path until they find an object. As shown in the figure, when the ultrasound waves are blocked by any object, the waves reflect. The receiver is present to receive the incoming waves after reflection. Once the reflected wave is received, we note the time taken by the waves to detect the object and predict the distance using this formula.
s= 2d/t
where s is the speed of the wave,
d is the distance traveled until reaching the object,
and t is the total time taken
Note that the factor '2' appears because the time noted is for the period when the wave strikes the object and then comes back.
Circuit Diagram
Here is the circuit diagram for making connections.
Circuit Diagram
Given Below is the circuit diagram of
Circuit Connections
Carefully observe the diagram given above for making connections on the breadboard. Note that the ultrasonic sensor has four terminals namely +5V, Trigger, Echo, and GND, follow the steps given for making connections:
- Connect a wire to supply Vcc with 5V to the appropriate pin on Arduino.
- Make a ground-to-ground connection from GND to GND on Arduino.
- Connect the trigger i.e. Trig to any pin on Arduino like pin 8.
- Connect the Echo to any pin on Arduino like pin 9.
Arduino Code
Here is the pseudocode and code for making an ultrasonic Sensor using Arduino.
Pseudocode
Firstly, we need to initialize the constants that denote the pins to be used.
We will set PINs 8 and 9 as trigger pins and echo pins respectively.
We need to set up the Arduino in the setup() function by determining the starting terminal.
Then we set which pin will be used for output and use digitalWrite() to ensure that the pin is low first.
We will introduce a delay of 2 milliseconds using the delay() function.
We will set which pin will be used for input using the digitalWrite() function with another delay of 10 milliseconds.
We create two functions microsecondsToInches() and microsecondsToCentimeters() to give the distance at which the object is present. The parameter of this function will be the time at which the object was sensed.
Code
C
const int pingPin = 8; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 9; // Echo Pin of Ultrasonic Sensor
void setup() {
Serial.begin(9600); // Starting Serial Terminal
}
void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT); //Set which pin will be used for output
digitalWrite(pingPin, LOW); //Ensure that the pin in low first
delayMicroseconds(2); //Introducing delay of 2 milliseconds
digitalWrite(pingPin, HIGH); //Set which pin will be used for input
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH); //Function for collecting the waves
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;
}
Conclusion
Once you have uploaded this code on Arduino, the sensor will begin working. The Arduino will successfully display the distance measured by a sensor in inches and cm. It will appear on the computer screen depending on the function that you use. The sensor will work accurately in different conditions like sunlight but it might not detect certain light items. You can make further modifications to improve the project according to your needs by incorporating some advanced boards.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read