/*
* Arduino Distance Measurement using Ultrasonic Sensor
* Crated by Kishor Mahata
* www.circuitgeeks.com
*
* Pin config
* echo pin >> arduino pin 8
* trigger pin >> arduino pin 9
* ground pin >> arduino ground pin
* vcc pin >> arduino vcc pin
* lcd SCL pin >> arduino SCL pin, in case of arduino uno this is pin A5
* lcd SDA pin >> arduino SDA pin, in case of arduino uno this is pin A4
* lcd ground >> arduino ground
* lcd vcc >> arduino 5v pin
*/
#include <Wire.h>
#include
#define trig 9 //define trigger pin at arduino pin 9.
#define echo 8 //define echo pin at arduino pin 8.
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
// defines variables
float duration,dist_inch;
int dist_cm;
void setup() {
Serial.begin(9600); // initialize serial communications at 9600 bps.
lcd.clear();
lcd.backlight(); // Turn on the blacklight and print a message.
lcd.begin(); // initialize the LCD
lcd.setCursor(0, 0); // Set the cursor to column 0,row 0.
lcd.print("dist. cm :"); // Print the massage
lcd.setCursor(0, 1); // Set the cursor to column 0,row 1.
lcd.print("dist. inch:"); // Print the massage
}
void loop() {
// Clears the trigPin
digitalWrite(trig, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Reads the echoPin
duration = pulseIn(echo, HIGH);
// Calculating the distance
dist_cm = duration/58;
dist_inch = dist_cm/2.54;
// Prints the distance on the LCD Display
lcd.setCursor(11, 0);
lcd.print(dist_cm); // Prints the distance in cm
lcd.setCursor(11, 1);
lcd.print(dist_inch); // Prints the distance in meter
delay(500);
// Clear the LCD
lcd.setCursor(11, 0);
lcd.print(" ");
lcd.setCursor(11, 1);
lcd.print(" ");
delay(10); // wait 10 milliseconds before the next loop
}