Ultrasonic Sensor Project in Arduino Code

                       Ultrasonic Sensor in Arduino Code

The purpose of this article is to demonstrate how to interface an ultrasonic sensor with Arduino using source code. Using sound waves bouncing back to itself, the ultrasonic sensor measures distances.

Steps in creating the project:

1. Gathering the Components

  • Arduino Uno
  • HC-SR04 Ultrasonic Sensor





2. Connecting the Components
Connect the components to the Arduino Uno. 






3. Coding the Arduino

In order to get started, you will need to install the library first. For this, Ultrasonic_hc_sr04 is the best library. Using the Arduino IDE library manager, download the library and install it.

//adds the library 
#include "Ultrasonic.h"

//declaration where to connect the pins
#define TRIG_PIN 5
#define ECHO_PIN 6

//declaration of baudrate in serial monitor
#define BAUDRATE 115200

//creating an instance of the ultrasonic sensor
Ultrasonic us(TRIG_PIN, ECHO_PIN);

//variable declarations
float dt;
int startTime;

void setup() {
//initialize serial communication
  Serial.begin(BAUDRATE);
  while(!Serial)
    ;

  startTime = millis();  
}

void loop() {

//the measure method tells the sensor to pulse and receive the pulses
  us.measure();

  dt = millis() - startTime;
  dt /= 1000;

//converts the values to inch and centimeters with 3 decimal places
  Serial.print(us.get_inch(), 3);
  Serial.println(" in");
  Serial.print(us.get_cm(), 3);
  Serial.println(" cm");
  
  delay(500);
}


4. Open the Serial Monitor

Once the sketch has been uploaded successfully, open the Arduino serial monitor. The sensor should be able to detect an object when an object is placed in front of it. Inches or centimeters will be displayed as the distance.






5. Things to know

The baud rate on the serial monitor is set to 9600 by default. To see expected results, change the baud rate to 115200. For further clarification, visit this project on my blog.

Video:







Photo:




By: Deenadarrshan Sathiyamoorthi

Project Inspired By: itsourcecode.com



Comments