hc-sr04 "quick calibration"

Hi everyone!

Has anybody ever tried doing a “quick calibration” on a HC-SR04? By that I mean that I would like to find a way to place a target at a certain distance (ex: 3ft) and then tell my HC SR04 to calibrate on this item knowing the fact that it is 3ft away from the sensor.

By that I am trying to find a way to create an offset on my HC-SR04 so I could move the sensor around on my robot and recalibrate easily.


Hi !


#include <NewPing.h>

#define TRIGGER_PIN  22  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     23  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

// Motor control
#define forwardLeft 24
#define backwardLeft 25
#define pwmLeft 2
#define forwardRight 26
#define backwardRight 27
#define pwmRight 3

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

void loop() {

  if (sonar.ping_cm() < 15 && sonar.ping_cm() > 5) {
  } else {

  // delay(1000);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)

void moveMode (void) {

  // Move forward
  digitalWrite(forwardLeft, HIGH);
  digitalWrite(backwardLeft, LOW);
  analogWrite(pwmLeft, 77);
  digitalWrite(forwardRight, HIGH);
  digitalWrite(backwardRight, LOW);
  analogWrite(pwmRight, 88);

void leftMode(void) {

  // Move Left
  digitalWrite(forwardLeft, LOW);
  digitalWrite(backwardLeft, HIGH);
  analogWrite(pwmLeft, 88);
  digitalWrite(forwardRight, LOW);
  digitalWrite(backwardRight, LOW);
  analogWrite(pwmRight, 0);

This is code for my robot what I start to build. Just re-calculate cm to ft.

Add a "calibrate" button.

Place object three feet from sensor.

Push the button to enter calibrate mode, take some number of distance readings, and calculate the average distance. Disregard zero distances when calculating the average, of course.

Calculate the correction factor...equal to three feet divided by the average distance, and then multiply all subsequent readings by the correction factor.

For example, if the average distance during calibrate mode was 2.8 feet, then your sensor is reading "short," so you need to multiply subsequent readings by 3 / 2.8 = 1.071 Or, if your average was 3.1, then it is reading too long, and the correction factor is 3 / 3.1 = 0.968

Also, be sure to check out this page regarding the accuracy and precision of the sensor, and suggestions for how to use the readings. Depending on the details of your project, it could be that your proposed "calibration" is pointless.

Wow thank you all!