Ultrasonic Sensor in Arduino Code
- Arduino Uno
- HC-SR04 Ultrasonic Sensor

2. Connecting the Components
Connect the components to the Arduino Uno.
//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);
}
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
Post a Comment