Challenge

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

//AJAY JOSEPH SIR

//ANSWER FOR PROJECT :

#include <LiquidCrystal.h>

const int numReadings = 10;

int readings[numReadings];

int index = 0;

int total = 0;

int inches = 0;

int cm = 0;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // LCD display object

void setup() {

lcd.begin(16, 2);

lcd.print("New String !!!"); // Display a string on the LCD

Serial.begin(9600);

pinMode(7, INPUT); // Set pin 7 as input

}

void loop() {

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

cm = 0.01723 * readUltrasonicDistance(7); // Read distance from the ultrasonic sensor in centimeters

// Update the array with the latest reading

total = total - readings[index];

readings[index] = cm;

total = total + readings[index];

index = (index + 1) % numReadings;

// Calculate the average distance

cm = total / numReadings;

inches = cm / 2.54; // Convert centimeters to inches

Serial.print("cm: ");

Serial.print(cm);

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

lcd.print("cm: "); // Display label on the LCD

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

lcd.print(cm); // Display the distance in centimeters on the LCD

Serial.print("inch: "); // Print label to the serial monitor

Serial.println(inches); // Print the distance in inches

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

lcd.print("inch: "); // Display label on the LCD

lcd.setCursor(6, 1); // Set the LCD cursor to the seventh column of the second row

lcd.print(inches); // Display the distance in inches on the LCD

delay(250); // Delay

}

long readUltrasonicDistance(int pin) {

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

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

delayMicroseconds(2); // Delay for 2 microseconds

digitalWrite(pin, HIGH); // Set the pin to high

delayMicroseconds(10); // Delay for 10 microseconds

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

pinMode(pin, INPUT); // Set the pin as input

return pulseIn(pin, HIGH);

}

//NB :CHANCE OF MISSING HEADER FILES WHILE UPLOADING

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.