Arduino Tutorial: How to use the HC-SR04 Distance Measuring Sensor

Schematic

VCC to Arduino 5v
GND to Arduino GND
Echo to Arduino pin 11
Trig to Arduino pin 12

Sketch:

/*
HC-SR04 
 
Circuit:
  VCC to arduino 5v 
  GND to arduino GND
  Echo to Arduino pin 11 
  Trig to Arduino pin 12
 
Based on code from http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/step3/Upload-the-sketch/
*/
const int trigPin = 12;
const int echoPin = 11;
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
void loop() {
  long duration, distance;
 
  // send the pulse
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); // low for 2 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // high for 10 microseconds
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // measure the time to the echo
  distance = (duration/2) / 29.1;  // calculate the distance in cm
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range; reading invalid");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500); 
}

A more complicated example using a servo motor to point the distance measuring sensor in different directions while taking readings, and then display the results graphically using processing. This example illustrates the problem that most sensors occasionally give erratic readings, and your program must take that into account.

Arduino code. Note that using the servo library disables analogWrite on pins 9 and 10. See the Arduino servo library reference.

 /*
Version: 0.2
This code was written by Grook.net
Please feel free to edit/add any thing to the code but email it back to us for
sharing it 
www.grook.net
http://www.youtube.com/GROOKnet
https://www.facebook.com/GROOKnet
 
Modified by Michael Shiloh 6/7/2015
 
*/
 
 
const int ECHOPIN = 7;  // Pin to receive echo pulse 
const int TRIGPIN = 8;  // Pin to trigger the beginning of a measurement
const int SERVOPIN = 9; // Servo ...
int stepSize = 10;      // The number of degrees to move in each step
int pausePerStep = 1000; // Pause this many milliseconds after each step
 
#include <Servo.h>
 
Servo myservo; // create servo object to control a servo
 
void setup() {
 Serial.begin(9600);
 
  myservo.attach(SERVOPIN); // attaches the servo on pin 9 to the servo object
 
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
}
 
void transmit (int distance , int angle)
{
   Serial.print(distance);
   Serial.print(',');
   Serial.print(angle);
   Serial.println();
   delay(100);
}
 
float measure () {
 
  // trigger the sensor to start a reading
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);
 
  // wait for the return echo
  float distance = pulseIn(ECHOPIN, HIGH);
 
  // calculate the distance 
  distance= distance/58;
  return(distance);
}
 
void loop() {
  int angle; // angle of the servo
 
  for(angle = 20; angle <= 160; angle += stepSize)
  {
    myservo.write(angle); // tell servo to go to position in variable 'pos'
    delay(pausePerStep); // waits for the servo to reach the position
    transmit( measure(), 180-angle);
  }
 
  for(angle = 160; angle>=20; angle -= stepSize)
  {
    myservo.write(angle); // tell servo to go to position in variable 'pos'
    delay(pausePerStep); // waits  for the servo to reach the position      
    transmit( measure(), 180-angle);
  }
}

Processing code:

 /*
Version: 0.2
This code was written by Grook.net
Please feel free to edit/add any thing to the code but email it back to us for sharing it 
www.grook.net
http://www.youtube.com/GROOKnet
https://www.facebook.com/GROOKnet
*/
 
import processing.serial.*;
Serial port;
String data = "";
String Radius = "";
String Theta = "";
int index = 0;
float distance = 0;
float angle = 0;
float pi = 22.0/7;
 
void setup()
{
  size(1000,1000);
  background(255,255,255);
  ellipse(500,500,1000,1000);
  line(500,0,500,1000);
  line(0,500,1000,500);
  line(500,500,1000,0);
  line(500,500,0,0);
  println(Serial.list());
  port = new Serial(this, Serial.list()[0], 9600);
  port.bufferUntil('\n');
}
 
void draw()
 
{
}
 
void serialEvent(Serial myPort) {
  // read the serial buffer:
  String myString = myPort.readStringUntil('\n');
 
  if (myString != null)
  {
  // remove linefeed etc.
    myString = trim(myString);
 
    // split the string at the commas
    // and convert the sections into integers:
    int values[] = int(split(myString, ','));
 
    if (values.length == 2) {
      print("distance " + values[0] + '\t' + "angle " + values[1] + '\n');
 
      translate(500,500);
      point (0,0);
 
      distance = float(values[0]);
      angle = float(values[1]) /180 * pi;
      fill(30,200,30);
      ellipse(distance * cos(angle) ,  -1 * distance * sin(angle) , 5, 5);
    }
  }
}
Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *