Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
#include <LiquidCrystal.h>
#define trigger 18
#define echo 19
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
float time = 0, distance = 0;
void setup()
{
lcd.begin(16, 2);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
lcd.print("Ultra Sonic");
lcd.setCursor(0, 1);
lcd.print("Distance Meter");
delay(2000);
lcd.clear();
lcd.print("Circuit Digest");
delay(2000);
}
void loop()
{
lcd.clear();
// Trigger the ultrasonic sensor by sending a 10-microsecond pulse
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
// Measure the duration of the pulse from the echo pin
time = pulseIn(echo, HIGH);
// Calculate the distance based on the speed of sound
distance = (time / 2) / 29.1; // Divide by 2 because the sound travels back and forth
// Print the distance on the LCD screen
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
delay(1000); // Wait for a second before taking the next measurement
}