Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Measuring distance of an object using ultrasonic distance sensor (28015 Ping) and also smoothen the sensor data using moving average filter.
Answer:
code:
#include
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);
void setup() {
lcd.begin(16, 2);
lcd.print("New String !!!");
Serial.begin(9600);
pinMode(7, INPUT);
}
void loop() {
lcd.clear();
cm = 0.01723 * readUltrasonicDistance(7);
total = total - readings[index];
readings[index] = cm;
total = total + readings[index];
index = (index + 1) % numReadings;
cm = total / numReadings;
inches = cm / 2.54;
Serial.print("cm: ");
Serial.print(cm);
lcd.setCursor(0, 0);
lcd.print("cm: ");
lcd.setCursor(4, 0);
lcd.print(cm);
Serial.print("inch: ");
Serial.println(inches);
lcd.setCursor(0, 1);
lcd.print("inch: ");
lcd.setCursor(6, 1);
lcd.print(inches);
delay(250);
}
long readUltrasonicDistance(int pin) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(2);
digitalWrite(pin, HIGH);
delayMicroseconds(10);
digitalWrite(pin, LOW);
pinMode(pin, INPUT);
return pulseIn(pin, HIGH);
}
List of components:
| Name | Quantity | Component |
|---|---|---|
| U1 | 1 | Arduino Uno R3 |
| PING1 | 1 | Ultrasonic Distance Sensor |
| U2 | 1 | LCD 16 x 2 |
| Rpot2 | 1 | 250 kΩ Potentiometer |
| R2 | 1 | 220 Ω Resistor |