Temperature-compensated ultrasonic distance meter with Arduino: design worksheet and code

A ₹895 design worksheet that corrects an HC-SR04 reading for air temperature using a DS18B20, with the speed-of-sound maths, a table of how much error to expect, a median-filtered sketch and a test plan.

About the author · Sources, testing and AI policy

  • Parts₹895
  • Bench time2–3 h
  • LevelIntermediate
  • ReviewedNov 2026

A ₹895 distance meter that corrects for the weather. An HC-SR04 measures how long a sound pulse takes to bounce back, and the speed of sound changes with air temperature. A DS18B20 probe supplies the temperature, and the sketch uses it to scale every reading. The page shows how big the error is without the fix, how the correction works, and how to test it with a ruler.

Scope: intermediate. This is a design worksheet with illustrative costs. It has not been bench-tested by this site. The error figures below were computed from the speed-of-sound formula. The sketch uses the OneWire and DallasTemperature libraries, installed from the Library Manager; check the calls against the installed versions. The correction is small, so it matters most when a robot must stop a set distance from a wall across a warm workshop or a cold morning.

How it works

The sensor sends a burst of ultrasound and times the echo. Distance is the speed of sound times half the round-trip time. Most sketches assume the speed is fixed, often 343 m/s, which is right at about 20 °C. In air, the speed rises with temperature, and a common approximation is v = 331.3 + 0.606 × T metres per second, with T in degrees Celsius. At 0 °C that is 331.3 m/s, at 20 °C 343.4 m/s and at 35 °C 352.5 m/s.

If the sketch assumes 343 m/s but the air is warmer, sound arrives sooner than expected and the reading comes out short. If the air is colder, it comes out long. The sketch measures the temperature, computes the real speed, and uses that instead.

Bill of materials

PartQtyUnitTotal
Arduino Uno clone1₹550₹550
HC-SR04 ultrasonic sensor1₹110₹110
DS18B20 waterproof probe1₹120₹120
4.7 kΩ resistor1₹5₹5
Small breadboard1₹60₹60
Jumper wire set1₹50₹50
Parts total₹895

Scroll the table sideways to see every column.

Prices checked Nov 2026. Shipping and tools are not included.

Prices are illustrative figures for Indian sellers in November 2026, before shipping, and have not been checked against current listings. The 4.7 kΩ resistor is the pull-up the DS18B20 data line needs.

How big is the error?

Air temperatureSpeed of soundReading for a true 100 cm, if 343 m/s is assumedError
10 °C337.4 m/s101.7 cm+1.7 cm (+1.7 %)
20 °C343.4 m/s99.9 cm−0.1 cm (−0.1 %)
35 °C352.5 m/s97.3 cm−2.7 cm (−2.7 %)
40 °C355.5 m/s96.5 cm−3.5 cm (−3.5 %)
Computed from v = 331.3 + 0.606 × T. The formula is an approximation for dry air near normal pressure.

At 35 °C an uncorrected sensor reads about 2.7 cm short at one metre. For a toy that stops roughly near a wall that is nothing. For a robot that must stop 10 cm from a target all year, a couple of percent of the distance is worth fixing, and it costs one cheap sensor. The correction cannot remove noise or the beam’s sideways spread; it only removes the temperature effect.

Power and wiring

PartArduino UnoNote
HC-SR04 VCC / GND5V / GND
HC-SR04 TRIGD7Needs a 10 µs high pulse
HC-SR04 ECHOD6Echo is a pulse whose width is the round-trip time
DS18B20 VCC / GND5V / GNDMost probes accept 3–5.5 V
DS18B20 dataD4With 4.7 kΩ between data and VCC
Probe positionIn the air path, shadedAway from the board, motors and your hand

Keep the probe in the air the sound actually crosses, not touching the Uno or a motor. A probe warmed by the electronics reports the warmth of the electronics, and the correction becomes wrong in a new way. If the probe reads −127 °C, the wiring or pull-up is faulty; see DS18B20 reads −127 or 85.

The sketch

// Temperature-compensated ultrasonic distance: Uno + HC-SR04 + DS18B20
// Libraries: OneWire and DallasTemperature (Library Manager).
// Design worksheet: check the library calls against the installed versions.

#include <OneWire.h>
#include <DallasTemperature.h>

const int TRIG_PIN = 7;
const int ECHO_PIN = 6;
const int ONEWIRE_PIN = 4;

OneWire oneWire(ONEWIRE_PIN);
DallasTemperature sensors(&oneWire);

float tempC = 20.0;                 // used until the first good reading
unsigned long lastTemp = 0;

float speedOfSound(float t) {       // metres per second
  return 331.3 + 0.606 * t;
}

long pingMicros() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  return pulseIn(ECHO_PIN, HIGH, 30000UL);   // 0 means no echo
}

float medianDistanceCm() {
  long v[5];
  for (int i = 0; i < 5; i++) {
    v[i] = pingMicros();
    delay(30);                      // let echoes die away between pings
  }
  for (int i = 0; i < 4; i++)       // small sort
    for (int j = i + 1; j < 5; j++)
      if (v[j] < v[i]) { long t = v[i]; v[i] = v[j]; v[j] = t; }
  long us = v[2];
  if (us == 0) return -1;           // no echo
  // distance in cm = (speed m/s * time s / 2) * 100
  return speedOfSound(tempC) * (us / 1000000.0) / 2.0 * 100.0;
}

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

void loop() {
  if (millis() - lastTemp > 2000) {
    lastTemp = millis();
    sensors.requestTemperatures();
    float t = sensors.getTempCByIndex(0);
    if (t > -50 && t < 100) tempC = t;       // ignore -127 and bad reads
  }
  float cm = medianDistanceCm();
  Serial.print("temp="); Serial.print(tempC, 1);
  Serial.print(" C  distance=");
  if (cm < 0) Serial.println("no echo");
  else { Serial.print(cm, 1); Serial.println(" cm"); }
}

The sketch keeps the last good temperature if a read fails, takes the middle of five pings to throw away stray echoes, and gives up after 30 ms, which is roughly 5 m at room temperature. The temperature call blocks while the probe converts, so the sketch asks only every two seconds; the temperature of a room does not change faster than that.

Test plan

  1. Temperature sanity: compare the probe with another thermometer in the same room. The two should agree to about a degree or two. If not, check the wiring and the probe’s position.
  2. Fixed targets: fix the sensor to a table and place a flat board at 50 cm and 100 cm, measured with a steel rule from the sensor face. Record 20 readings at each.
  3. Compare: edit the sketch to print the uncorrected reading too, using 343 m/s, and compare the two against the rule.
  4. Temperature change: repeat in a cool room and a warm one, or near a gentle heat source with the probe in the air path. The corrected value should stay closer to the rule than the uncorrected one.
  5. Angle: tilt the board and note when the echo is lost. Flat targets facing the sensor work best.
  6. Soft targets: try cloth or foam. Soft and angled surfaces return weak echoes and may read too far or not at all.

What other builders report

This section summarises public material in our own words. None of it is our measurement, and where we could not open a source to confirm a detail, we say so.

  • The speed-of-sound formula used here, 331.3 + 0.606 × T, is the standard approximation in tutorials on temperature-compensated ultrasonic sensors. Our own arithmetic gives about 0.18 percent per degree (0.606 / 343).
  • Tutorials such as DroneBot Workshop’s HC-SR04 guide describe adding a temperature (and humidity) sensor to improve accuracy by compensating for how air conditions change the speed of sound. That page gives no measured figure.
  • We did not find a controlled test of an HC-SR04 corrected with a DS18B20 that reports measured error. One vendor guide claims a 2 to 4 percent reduction but gives no source, so we have not repeated it. Your own ruler test in the plan below is the real evidence.
  • The sensor’s own noise may be comparable to the temperature error near room temperature, which is why the median filter and the ruler test both matter.

What this means for the build: expect the correction to remove a steady bias when the air is far from 20 °C, and measure it yourself before claiming a gain.

What usually goes wrong

SymptomLikely causeFix
Distance always reads 0 or no echoWiring wrong or target too closeCheck TRIG and ECHO, stay beyond a few centimetres
Reading jumps by a lotStray echoesUse the median, add a delay between pings
Temperature stuck at the start valueProbe not read or failingCheck the pull-up and wiring
Correction makes it worseProbe warmed by the electronicsMove the probe out into the air path
Wrong at long rangeBeam spreads and finds a side objectAim carefully, use a flat target
Soft target not seenWeak echoUse a hard surface for measurements

Upgrades

  • Display: show the distance on a small OLED.
  • Sweep: mount the sensor on a servo as in the ultrasonic radar scanner.
  • Alarm: add a buzzer that sounds below a set distance.
  • Humidity: add a humidity sensor if you need to push the correction further; the effect of humidity on sound speed is smaller than the effect of temperature.

Cost and parts notes

The ₹895 total is an illustration and does not include shipping. A waterproof DS18B20 probe is convenient because the wire lets you place it away from the board. Use the cost calculator to compare sellers.

Common questions

Does the HC-SR04 need temperature correction?

Not for rough work. The error is about 1 to 4 percent across 10 to 40 °C, which matters only when you need distance to a centimetre or so at a metre or more.

Why not just use a laser sensor?

Laser time-of-flight sensors are less affected by air temperature and have a narrower beam, and cost more. The ultrasonic sensor is cheap and teaches the physics.

Why take the median of five pings?

A single ping can pick up a stray echo or miss. The middle value discards the odd ones.

Is the formula exact?

No. It is a standard approximation for dry air. Humidity and pressure shift the speed slightly.

Last reviewed: November 2026. This is a design worksheet with illustrative costs. It has not been bench-tested by this site; library names, pins and limits must be checked against your board and the current library versions, and measurements from your build are welcome.

More builds

Next builds to try

Free: the final-year project pack

A shortlist with BOMs, a report outline that matches the usual chapter scheme, a costing sheet and 40 viva questions. Built for the February–April submission season.

The Build Note

One short email when something is worth your bench time.

A new build sheet, a part price that moved, or a mistake worth avoiding. No daily drip, no recycled news.

One short email when a build or a price is worth your time. Unsubscribe in one click.