Ultrasonic Sensor

Ultrasonic sensor test. It works. Nice.

Ultrasonic sensor module is HC-SR04. I purchased this from virtuabotix.com. The company provides a Ultrasonic library.

  • Go to https://www.virtuabotix.com/feed/?page_id=1587 and find the Ultrasonic section.
  • Download the library.
  • Unzip it and copy the unzipped folder to your Arduino libraries folder.
  • You may restart Arduino to let it recognize the new library.
  • Use an example code for your starting step.

Here is the example.

#include <Ultrasonic.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 13
Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  float cmMsec, inMsec;
  long microsec = ultrasonic.timing();
  cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
  inMsec = ultrasonic.convert(microsec, Ultrasonic::IN);
  //Serial.print("MS: ");
  Serial.print(microsec);
  Serial.print(", ");
  //Serial.print(", CM: ");
  Serial.print(cmMsec);
  Serial.print(", ");
  //Serial.print(", IN: ");
  Serial.println(inMsec);
  delay(1000);
}

Just wire pins as the source code says. Then open the Serial Monitor from Arduino. You will see he raw milliseconds and distance in centimeter and inch.

That’s it.