SUPPLIES AND COMPONENTS
Connecting an Arduino to an HC-SR04 sensor
Connecting an Ultrasonic Sensor to an Arduino UNO in Normal Mode |
Installing a library
Example Code for an Ultrasonic Sensor
// Include NewPing Library
#include "NewPing.h"
// Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
#define TRIGGER_PIN 9
#define ECHO_PIN 10
// Maximum distance we want to ping for (in centimeters).
#define MAX_DISTANCE 400
// NewPing setup of pins and maximum distance.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Distance = ");
Serial.print(sonar.ping_cm());
Serial.println(" cm");
delay(500);
}
Open your serial monitor and adjust the baud rate to 9600 bps after the sketch has been uploaded. Try aiming the sensor at nearby things that are laying about. The calculated distance should start to stream soon.
Code Explanation:
The recently installed NewPing library is first incorporated into the drawing.
// Include NewPing Library
#include "NewPing.h"
The Trig and Echo pins of the HC-SR04 are connected to the designated Arduino pins first. A second constant, MAX DISTANCE
, has also been defined. Pings sent beyond the specified maximum distance will be interpreted as "no ping clear." Currently, MAX DISTANCE
is set at 400 [default = 500cm].
After that, a sonar-named instance of the NewPing library is built.
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400
After that, a sonar-named instance of the NewPing library is built.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
Following that, the first instance of the NewPing library is generated.
void setup() {
Serial.begin(9600);
}
We only use the ping cm()
method in the loop and output the outcome on the serial monitor. The distance in centimetres is returned once a ping is sent using this method.
void loop() {
Serial.print("Distance = ");
Serial.print(sonar.ping_cm());
Serial.println(" cm");
delay(500);
}
Additional features of the NewPing Library
You may utilise a few helpful functions with the NewPing object.
The distance is displayed in millimetres in the above drawing. Use the sonar.ping in()
method if you want the result to be in inches.
Serial.print(sonar.ping_in());
The resolution of the aforementioned drawing is just one centimetre. Use NewPing in duration mode as opposed to distance mode to receive the result in decimal form. This line needs to be changed:
Serial.print(sonar.ping_cm());
along with line
Serial.print((sonar.ping() / 2) * 0.0343);
To increase the accuracy of your HC-SR04, use the function ping median(iterations) in the NewPing library. This approach averages the remaining values after discarding out-of-range readings and taking many measurements as opposed to just one. It only takes five readings by default, but you may set any number.
int iterations = 5;
Serial.print((sonar.ping_median(iterations) / 2) * 0.0343);