// LCD 20 x 4
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
const int trigPin = 18;
const int echoPin = 5;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
/*For reference, under standard conditions at room temperature,
The speed of sound in dry air is about 343 meters per second or
about 0.343 meters per millisecond (343 m/s or 0.343 mm/ms).
The given calibration reference is (0.393701) conversion from
centimeters (cm) to inches (inches). It is used in calculations
conversion between two different measurement systems.
Example:
To convert 10 centimeters to inches: 10 cm * 0.393701 = 3.93701 inches.
To convert 5 inches to centimeters: 5 inches / 0.393701 = 12.7 centimeters.
*/
long duration;
float distanceCm;
float distanceInch;
//
void setup() {
Serial.begin(115200); // Starts the serial communication
lcd.init();
lcd.clear();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Distance Sensor : ");
lcd.setCursor(0,1);
lcd.print("HC-SR04");
delay(5000);
lcd.clear();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
lcd.setCursor(0,0);
lcd.print("Distance : ");
lcd.setCursor(0,1);
lcd.print(distanceCm);
lcd.print(" ");
lcd.print("Cm");
delay(1000);
}