Tuesday, June 7, 2016

Playing With HC-SR04 Ultrasonic Ranging Module

 Introduction

 HC-SR04 is a ultrasonic  ranging module which is working like bats.ie it uses sonar technique for ranging.This module is widely used in between arduino hackers and diy enthusiast.The main attraction of this module is it is one of the simplest module and can be recommend to any newbie
 

 

 Applications

HC-SR04 is a module which can be used in various applications in our DIY projects.
  • As obstacle detector in obstacle avoiding robot.
  • In walking assistant system for visually impaired people.
  • As parking sensor in vehicles. 
  • As sensor in bugler alarm type projects.

 

 

Example project

Arduino based ultrasonic obstacle detector 

components needed

  1.  Arduino ProMini x 1
  2. HC-SR04 x1
  3. Buzzer x 1
  4. LED x 1
  5. 220 ohm resistor x1

 Connections 

Arduino                                                 HC-SR04

pin 9                                                         trig
  pin8                                                          echo
  vcc                                                           vcc
  gnd                                                           gnd 



arduino pin 6 is connected to LED.
arduino pin A3 is connected to a buzzer.
arduino can be power via usb/ftdi or a 5v battery

working 

 In this demo project HC-SR04 is used as simple obstacle detector.it detects objects in front and will reply how far the obstacle is from the sensor.If an obstacle is detected it will alarm with a buzzer.If the obstacle is very close the led will ON.

Arduino code

//http://anasdalintakam.blogspot.com/2016/06/playing-with-hc-sr04-ultrasonic-ranging.html
//this is a simple project to demo working of HC-SR04
//connctions
//pin9-hcsr04 trig
//pin8-hcsr04 echo
//vcc-hcsr04 vcc
//gnd-hcsr04 gnd
//pin6-led
//pin A3-buzzer



int trig=9;
int echo=8;
int duration;       
float distance;
int val; 
float meter;      
void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);//trigger to hcsr04
  pinMode(echo, INPUT);//echo from hcsr04
  pinMode(6,OUTPUT);// led pin
  pinMode(A3,OUTPUT);// buzzer pin
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
 
  delay(6000);
  Serial.println("Distance:");
}
void loop()

  digitalWrite(trig, HIGH);   
  delayMicroseconds(10);              
  digitalWrite(trig, LOW);   

  duration = pulseIn(echo, HIGH);

  if(duration>=38000){
      Serial.print("Out range"); 
      }    

  else{
      distance = duration/58;
      val=200-distance;  
      Serial.print("value:");
      Serial.print(val);
      Serial.print("\n");
      Serial.print(distance);   
      Serial.print("cm");
      meter=distance/100;
      Serial.print("\t");
      Serial.print(meter);
      Serial.println("m");
   if (distance >10){
   digitalWrite(6,LOW);
    }
    else {
   digitalWrite(6,HIGH);
      }
analogWrite(A3,val);
     
      }
  //   delay(1000);  
}