manodeep
Published © CC BY

Distance measurement using HCSR04

DIY distance measuring device using HCSR04 ultrasonic sensor.

BeginnerFull instructions provided292
Distance measurement using HCSR04

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Distance Measurement using HCSR04

Code

Distance Measurement using HCSR04

Arduino
#define trigPin 10
#define echoPin 11

void setup() 
{
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() 
{
  long duration, distance;
  digitalWrite(trigPin, LOW);        
  delayMicroseconds(2);              
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);           
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0)
  {
    Serial.println("Out of range");
  }
  else 
  {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

Credits

manodeep
0 projects • 4 followers

Comments