Challenge

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

Arduino Code

// C++ code
//
#include


float inches = 0;

float cm = 0;

Adafruit_LiquidCrystal lcd_1(0);

void setup()
{
lcd_1.begin(16, 2);
lcd_1.setBacklight(1);

//lcd_1.print("hello world");
}

long readUltrasonicDistance(int signalPin)
{
pinMode(signalPin, OUTPUT); // Clear the trigger
digitalWrite(signalPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(signalPin, HIGH);
delayMicroseconds(10);
digitalWrite(signalPin, LOW);
pinMode(signalPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(signalPin, HIGH);
}


void loop()
{
lcd_1.clear();
lcd_1.setCursor(0, 0);

// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(7);

// convert to inches by dividing by 2.54
inches = (cm / 2.54);

// displaying the distance on lcd
lcd_1.print(inches);
lcd_1.print(" in");
lcd_1.setCursor(0, 1);
lcd_1.print(cm);
lcd_1.println(" cm");
delay(100); // Wait for 100 millisecond(s)
}

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.