Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter.
Code:
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int trigPin = 7;
const int echoPin = 8;
long duration;
int distance;
void setup()
{
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.clear();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600);
}
void loop()
{
float Inches;
digitalWrite(trigPin, LOW);
delay(2000);
lcd.clear();
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delay(100);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
Inches = distance*0.39370; //cm to Inches conversion
// Prints the distance on the LCD Display.
lcd.setCursor(0,0);
lcd.print("Dist. in cm: ");
lcd.print(distance);
lcd.setCursor(0,1);
lcd.print("Inches: ");
lcd.print(Inches);
// Prints the distance on the Serial Monitor
Serial.println("Distance in cm: ");
Serial.print(distance);
Serial.println("Distance in Inches: ");
Serial.print(Inches);
}
Output:
