Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

code :

#include <Adafruit_LiquidCrystal.h> // Header file for I2C liquid crystal display

// Global variable to store the sensor value

float sensorvalue = 0;

// Initialize the LCD object with the I2C address (0 for autodetect)

Adafruit_LiquidCrystal lcd(0);

// Function to read the distance from the ultrasonic sensor

// Note: In the 28015 PING sensor, there is no separate trigger and echo pin,

// only a single SIG (signal) pin, so connect it to any digital pin (e.g., Digital PWM pin 13 on Arduino)

float Distance(int pin) {

pinMode(pin, OUTPUT); // Set the pin as an output pin for triggering

digitalWrite(pin, LOW); // Set the pin to LOW to start

delayMicroseconds(5); // Small delay

// Send a 10 microsecond HIGH pulse to trigger the sensor

digitalWrite(pin, HIGH);

delayMicroseconds(10);

digitalWrite(pin, LOW); // Set the pin to LOW after triggering

pinMode(pin, INPUT); // Set the pin as an input pin to read the echo

long duration = pulseIn(pin, HIGH); // Measure the time for the echo to return

// Calculate the distance in cm based on the duration

return duration * 0.01723;

}

void setup() {

lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows

lcd.clear(); // Clear the LCD screen

}

void loop() {

// Call the Distance function with pin 13 for both trigger and echo

sensorvalue = Distance(13);

// Display the distance on the LCD

lcd.setCursor(0, 0); // Set the cursor to the first row, first column

lcd.print("Distance:"); // Print the label "Distance:"

lcd.print(sensorvalue); // Print the measured distance

lcd.print("cm"); // Print the unit "cm"

delay(1000); // Wait for 1 second before taking the next measurement

lcd.clear(); // Clear the LCD screen for the next value

}

output :

its in attachments

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.