Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
const int trigPin = 9;
const int trigPin = 10;
//defines variables
long duration;
int distance;
void setup(){
pinMode(trigPin, OUTPUT);
//set the trigpin as output
pinMode(echoPin,INPUT);
//sets the echo pin as input
Serial.begin(9600);
//starts the serial communication
}
void loop(){
//clearing the trigpin
digitalWrite(trigPin, LOW);
delayMircoseconds(2);
//setting the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
//calculating the distance
distance = duration * 0.034 / 2;
//prints the distance on the serial monitor
Serial.print("Distance:");
Serial.println(distance);
}


HC-SR04 :
The HC-SR04 is an affordable and easy to use distance measuring sensor which has a range from 2cm to 400cm.The sensor is composed of two ultrasonic transducers.One is transmitter which outputs ultrasonic sound pulses and the other is reciever which listens for reflected waves.It's basically a SONAR which is used in submarines for detecting underwater objects.
It emits a ultrasound at 40000 Hz which travels through the air and if there is an object or obstacle on its path it will bounce back to the module.Considering the travel time and the speed of the sound you can calculate the distance.In order to generate the ultrasound we need to set the trig pin on a HIGH state for 10 microseconds.That will send out an 8 cycle ultrasonic brust which will travel at the speed of sound.The echo pins goes high right away after that 8 cycle ultrasonic brust is sent, and it starts listening or waiting for that wave to be reflected from an object.If there is no object or reflected pulse, the echo pin will time out after 38ms and get back to low state.
If we recieve a reflected pulse, the echo pin will go down sooner than those 38ms.According to the amount of time the echo pin was HIGH, we can determine the distance the sound wave traveled, thus the distance from the sensor to the object.For that purpose we are using the following basic formula for calculating distance = speed*time.