Challenge

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

Answer:

Components Needed:

Arduino Uno (2 units)

Ultrasonic Distance Sensor (HC-SR04)

Wire jumpers

PCB Breadboard

Connections:

Connect the VCC pin of the ultrasonic sensor to the 5V output on the Arduino.

Connect the GND pin of the ultrasonic sensor to the GND on the Arduino.

Connect the Trig pin of the ultrasonic sensor to a digital pin (e.g., Pin 9) on the Arduino.

Connect the Echo pin of the ultrasonic sensor to a digital pin (e.g., Pin 10) on the Arduino.

Connect the components as per the connections mentioned above.

Code for master node to measure the distance:

#define TRIG_PIN 9

#define ECHO_PIN 10

void setup() {

Serial.begin(9600);

pinMode(TRIG_PIN, OUTPUT);

pinMode(ECHO_PIN, INPUT);

}

void loop() {

long duration, distance;

digitalWrite(TRIG_PIN, LOW);

delayMicroseconds(2);

digitalWrite(TRIG_PIN, HIGH);

delayMicroseconds(10);

digitalWrite(TRIG_PIN, LOW);

duration = pulseIn(ECHO_PIN, HIGH);

distance = (duration / 2) / 29.1; // Divide by 29.1 to get distance in inches

Serial.println(distance);

delay(500); // Adjust delay based on your preference

}

Slave code smoothening with moving average filer:

#define WINDOW_SIZE 5 // Adjust the window size based on your preference

int sensorData[WINDOW_SIZE]; // Array to store sensor data for moving average

int dataIndex = 0; // Index to update sensorData array

void setup() {

Serial.begin(9600);

}

void loop() {

int distance = readDistance();

int smoothDistance = movingAverageFilter(distance);

Serial.print("Raw Distance: ");

Serial.print(distance);

Serial.print(" inches, Smoothed Distance: ");

Serial.println(smoothDistance);

delay(500); // Adjust delay based on your preference

}

int readDistance() {

// Read distance from master node (replace with actual communication)

while (!Serial.available()); // Wait for data

return Serial.parseInt();

}

int movingAverageFilter(int newData) {

sensorData[dataIndex] = newData;

dataIndex = (dataIndex + 1) % WINDOW_SIZE;

// Calculate average

int sum = 0;

for (int i = 0; i < WINDOW_SIZE; i++) {

sum += sensorData[i];

}

return sum / WINDOW_SIZE;

}

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.