How to increase sensitivity of ultrasonic sensor hc-sr04

I am using hc-sr04 sensor for measuring height of liquid level continuously, but i find the sensitivity of sensor very bad. for example if i place object at 10cm the values it gives wud be around 9.4cm (which is kinda ok) but if i move object to 10.3 cm it gives around 12.1cm. Now how do i tackle this issue.

#include <WiFi.h>
#include <ESPAsyncWebServer.h>

#define TRIG_PIN 0  // G0
#define ECHO_PIN 1  // G1

const char* ssid = "TP-Link_2750";
const char* password = "84066107";

AsyncWebServer server(80);
bool recording = false;
String data = "";

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("Connected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", R"rawliteral(
      <!DOCTYPE HTML>
      <html>
      <head>
        <title>ESP32 Distance Readings</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script>
          let recording = false;
          let data = [];

          function fetchReadings() {
            fetch('/readings')
              .then(response => response.text())
              .then(readings => {
                document.getElementById('readings').innerText = readings;
                if (recording) {
                  let timestamp = new Date().toLocaleString();
                  data.push(`${timestamp},${readings}`);
                }
              });
          }

          function startRecording() {
            recording = true;
            data = [];
            document.getElementById('status').innerText = "Recording...";
          }

          function stopRecording() {
            recording = false;
            document.getElementById('status').innerText = "Recording stopped";
          }

          function downloadData() {
            let csvContent = "data:text/csv;charset=utf-8,Time,Distance (mm)\n" + data.join("\n");
            let encodedUri = encodeURI(csvContent);
            let link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "distance_readings.csv");
            document.body.appendChild(link);
            link.click();
          }

          setInterval(fetchReadings, 1000); // Fetch readings every second
        </script>
      </head>
      <body>
        <h1>ESP32 Distance Readings</h1>
        <p id="readings">Loading...</p>
        <p id="status">Not recording</p>
        <button onclick="startRecording()">Start Recording</button>
        <button onclick="stopRecording()">Stop Recording</button>
        <button onclick="downloadData()">Download Data</button>
      </body>
      </html>
    )rawliteral");
  });

  server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){
    long duration;
    float distance;

    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(2);

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

    duration = pulseIn(ECHO_PIN, HIGH);
    distance = (duration / 2.0) * 0.343; // Convert to millimeters

    String readings = String(distance) + " mm";
    request->send(200, "text/plain", readings);

    if (recording) {
      String timestamp = String(millis() / 1000.0);
      data += timestamp + "," + readings + "\n";
    }
  });

  server.on("/start", HTTP_GET, [](AsyncWebServerRequest *request){
    recording = true;
    data = "";
    request->send(200, "text/plain", "Recording started.");
  });

  server.on("/stop", HTTP_GET, [](AsyncWebServerRequest *request){
    recording = false;
    request->send(200, "text/plain", "Recording stopped.");
  });

  server.on("/download", HTTP_GET, [](AsyncWebServerRequest *request){
    String csvContent = "data:text/csv;charset=utf-8,Time,Distance (mm)\n" + data;
    request->send(200, "text/csv", csvContent);
  });

  server.begin();
  Serial.println("Server started");
}

void loop() {
  // No need to handle anything in the loop
}

This code saves and records the data thru wifi.

I don't know much about increasing sensitivity .I usually adjusts the delay .Try increasing them /even putting same value.
If you want to update the data in the webpage faster try websocket .it is good for applications like this

I agree, adjust delays in transmitting. I would guess the 12cm/bad reading is due to constructive interference of late-arriving echos being stronger than primary echo, but arriving in the "valid echo" time.

You can modify the circuit if you like increasing the gain of the receiver and increasing the output power to the transmitter. The schematic is available on line.

Are you certain the problem is sensitivity. Please study the documentation on the device. Do you see there are a series of several pulses of sound that are emitted. You do not know which one produced the echo that was returned.
In addition, the only fair test is to have a flat, hard, smooth surface at 90 degrees to the sound emitter/receiver.

Try putting the ultrasonic sensor through a hole in the end of a plastic coffee cup.

This will concentrate the beam and shield the sensor from reflections that come off at wide reflections.

Is this on the bench with a object.
OR
Using the liquid container you are making the project for?

What is the container?
What range of distance are you looking for?

Did you write this code in stages?

If so, have you got code JUST for the sr04, to test your project?
Forget all the other stuff for a while.

If not, then write some simple code and test the perfromance of the sr04 ON ITS OWN.

Tom... :smiley: :+1: :coffee: :australia:

Wrote a library a while ago - GitHub - RobTillaart/SRF05: Arduino library for SRF05 distance sensor
It supports averaging or taking the median and has some correction for the speed of sound which is affected by both temperature and humidity.
So quite some knobs to turn to improve measurements.

Give it a try