Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
Measuring the distance of an object using an ultrasonic sensor (HC-SR04)
Goals:
- Measuring the distance of an object using Ultrasonic Distance Sensor (HC-SR04)
- Usage of Input Capture Mode
Key Highlights of the Project:
- Measuring the distance traveled by the wave to the object and getting bounced back from the object to the sensor.
- Measuring Pulse width using Input Capture Mode
Deliverables of this project:
- The distance traveled by a wave to the object for which we want to measure the distance using Ultrasonic Distance Sensor (HC-SR04).
- Measuring Pulse width using Input Capture Mode of Timer 1
Code :
const int trigPin = 9;
const int echoPin = 8;
long duration;
int distance;
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
// Sets the trigPin on HIGH state for 1
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
duration= pulseIn(echoPin, HIGH);
distance= duration* 0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
delay(100);
}
Connection:
