[Arduino] Ultrasonic Sensor (HC-SR04)

HC-SR04 is a cheap and easy to use Ultrasonic Sensor, it is especially useful for robotics.  The sensor pretty much contain 4 pins: VCC (5 V), Trig, Echo, GND.

For wiring, pretty much wire VCC to your micro-controller’s 5V power supply pin and GND to ground. For Trig and Echo, just wire them to a free Digital Pin.

Here’s the code for using it with an Arduino:

//Ultrasound Sensor Script for HC-SR04
#define trig_pin 13
#define echo_pin 12

void setup()
{
  pinMode(trig_pin, OUTPUT);
  pinMode(echo_pin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  double dt = activate_ultrasound();
  double distance = calculate_distance(dt);

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(100);
}

double activate_ultrasound()
{
  //Creating a 10 Microseconds pulse to activate sensor

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

  //Return time before Recieving Echo Signal in Microseconds
  //Divide by 2 to get time of signal traveling one way
  return pulseIn(echo_pin, HIGH)/2;
}

double calculate_distance(double time)
{
  //Speed of Sound = 340.29 m/s
  double speedSound = 340.29 * pow(10,-6);
  double distance = time * speedSound;

  //Convert meters to centimeters
  distance = distance * 100;

  return distance;
}

4 thoughts on “[Arduino] Ultrasonic Sensor (HC-SR04)

  1. Something of the sort
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package sonar;

    import jssc.SerialPort;
    import jssc.SerialPortException;

    /**
    *
    * @author Z
    */
    public class Sonar {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) throws InterruptedException {
    // TODO code application logic here
    SerialPort serialPort = new SerialPort(“COM5”);
    try {
    serialPort.openPort();//Open serial port
    serialPort.setParams(SerialPort.BAUDRATE_9600,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
    for (int i = 0; i < args.length; i++) {

    serialPort.writeBytes("This is a test string".getBytes());//Write data to port
    // serialPort.closePort();//Close serial port

    double dt = activate_ultrasound();
    double distance = calculate_distance(dt);

    System.out.println("Distance: ");
    System.out.println(distance);

    System.out.println(" cm");

    byte[] buffer = serialPort.readBytes(10);//Read 10 bytes from serial port
    System.out.println(buffer);
    }
    serialPort.closePort();//Close serial port
    } catch (SerialPortException ex) {
    System.out.println(ex);
    }

    }

    double activate_ultrasound() {
    //Creating a 10 Microseconds pulse to activate sensor

    digitalWrite(trig_pin, LOW);
    digitalWrite(trig_pin, HIGH);
    Thread.sleep(10);
    digitalWrite(trig_pin, LOW);

    //Return time before Recieving Echo Signal in Microseconds
    //Divide by 2 to get time of signal traveling one way
    return pulseIn(echo_pin, HIGH) / 2;
    }

    double calculate_distance(double time) {
    //Speed of Sound = 340.29 m/s
    double speedSound = 340.29 * Math.pow(10, -6);
    double distance = time * speedSound;

    //Convert meters to centimeters
    distance = distance * 100;

    return distance;
    }
    }

    • hmm… this look like you merged the Arduino code with the Java code, idk if this is the best idea. For me, I would merge the ultrasonic detection code with the Arduino jSSC code. Basically use the Arduino as a data acquisition device and then send the data back to PC through Serial. I would then write a program in java on the PC side to read the info. Much like this:

      [Engineering] Arduino to Java Serial Communication

      But again, I am not that advance in computer science. You could be totally correct and that I just don’t know what I am talking about =D

  2. Pingback: [Arduino] Ultrasonic Range Finder (XL-MaxSonar) | Billwaa's Blog

Leave a reply to nihunter Cancel reply