Arduino codes for ultrasonic sensor HC-SR04



Ultrasonic sensor comes very handy for small projects. It can be used for making radar, measuring distance, different types of  alarm system. You can download ultrasonic sensor HC-SR04 datasheet. Arduino connection with ultrasonic sensor is shown in picture.




Image result for ultrasonic sensor connections

Arduino code is given below:

void setup()
{
  pinMode(11,OUTPUT);
  pinMode(12,INPUT);
  Serial.begin(9600);
}
void loop()
{
  digitalWrite(11,HIGH);
  delayMicroseconds(30);
  digitalWrite(11,LOW);
  delayMicroseconds(2);
  int a=pulseIn(12,HIGH);//gives time after which high pulse is coming
  int d=(a*0.034)/2;
  Serial.print(d);//show value in serial monitor
  Serial.println(" cm");
  delay(50);
  }

For any querry ask in comment.

Comments