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
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;
}
Arduino – Ultrasonic Sensor
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.
Table of Content
- Ultrasonic Sensor
- Technical Specifications
- Apparatus
- Working
- Circuit Diagram
- Arduino Code