Nicholas_N
Published

Distance Measurement with an Ultrasonic Sensor HY-SRF05

Measure the world around you.

BeginnerShowcase (no instructions)80,072
Distance Measurement with an Ultrasonic Sensor HY-SRF05

Things used in this project

Story

Read more

Schematics

circuit diagram

Code

Project code

Arduino
const unsigned int TRIG_PIN=13;
const unsigned int ECHO_PIN=12;
const unsigned int BAUD_RATE=9600;

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(BAUD_RATE);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  

 const unsigned long duration= pulseIn(ECHO_PIN, HIGH);
 int distance= duration/29/2;
 if(duration==0){
   Serial.println("Warning: no pulse from sensor");
   } 
  else{
      Serial.print("distance to nearest object:");
      Serial.println(distance);
      Serial.println(" cm");
  }
 delay(100);
 }

Credits

Nicholas_N

Nicholas_N

0 projects • 23 followers

Comments