Skip to content

HC-SR04 — distance [cm] (hcsr_read_cm)

What it does: Returns the distance from HC-SR04 in centimeters as a decimal number.

hcsr_read_cm

Inputs

  • Field hc_id: selection of previously initialized sensor instance.

Output

  • Number: distance in cm (may return default value 200 cm if measurement fails).

When to use it

  • When reading in centimeters is enough and you want smoother values.
  • After initialization via hcsr_init.

Tips and pitfalls

  • The calculation in the code is (pulse_time / 2) / 29.1.
  • For borderline distances or bad reflection, validate values (e.g. minimum/maximum).

Usage example

example_hcsr

Open example in ESP IDE

Generated Python example

value = ultraSoundSensor1.distance_cm()