Challenge

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

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Constants
const int NUM_SAMPLES = 10;
const int TRIGGER_PIN = 2;
const int ECHO_PIN = 3;
long duration;
int distance;
int samples[NUM_SAMPLES];
int index = 0;
// LCD Display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
lcd.begin(16, 2); // Initialize the LCD display
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0);
lcd.print("Distance: ");
Serial.begin(9600);
}

void loop() {
// Generate ultrasonic pulse
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);

// Measure the pulse duration
duration = pulseIn(ECHO_PIN, HIGH);

// Calculate distance in inches
distance = duration / 74 / 2; // Speed of sound is approximately 74 inches/ms

// Update moving average samples array
samples[index] = distance;
index = (index + 1) % NUM_SAMPLES;

// Calculate moving average
int sum = 0;
for (int i = 0; i < NUM_SAMPLES; i++) {
sum += samples[i];
}
int movingAverage = sum / NUM_SAMPLES;

// Output the distance and moving average to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, cm avg: ");
Serial.println(movingAverage);

// Display distance and moving average on the LCD
lcd.setCursor(0, 1);
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" Avg: ");
lcd.print(movingAverage);

delay(500); // Wait for a moment before taking the next measurement
}

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.