Saturday, February 27, 2016

Measure Distance using Ultrasonic Sensor (HC-SR04) for Robots using Arduino



                 This is simple example to use HC-SR04 ultrasonic transceiver to calculate the distance of a object.  This is simply done by sending a pulse from the module and receiving the echo by it. Then the distance is calculated by considering the time elapsed to receive the echo.



                  I have tested it with Arduino and checked with scale and result is pretty awesome. Simply connect the sensor to Arduino by connecting Vcc and Gnd and connect the Echo and Trig pins to any digital pin of Arduino but remember to change so in the Sketch..

Sketch:

#define TRIGGER_PIN 11
#define ECHO_PIN 12

long duration, cm;
 
void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}
 
void loop()
{
 
 
  // Provide a high pulse to the GPIO trigger and wait until echo is received
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(5);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);
 
  pinMode(ECHO_PIN, INPUT);
  duration = pulseIn(ECHO_PIN, HIGH);// Gets back the time pulse Recived
 
  // convert the time into a distance
  cm = (duration/2) / 29.1;
  
  Serial.print("cm");
  Serial.println();
  
  delay(250);
}

No comments:

Post a Comment