The most reliable general-purpose setup is an ultrasonic sensor connected to an ESP32 or ESP8266 running ESPHome, with Home Assistant receiving the readings through its native ESPHome integration. An HC-SR04 is suitable for a dry indoor prototype. For tanks, condensation, splashing, or outdoor construction-related monitoring, start with a waterproof JSN-SR04T or DFRobot A02YYUW instead.
Home Assistant receives a distance measurement—not a ready-made “percentage full” or presence result. Level, volume, parking position, and object detection must be calculated from that distance and validated against the installation.
As an Amazon Associate I earn from qualifying purchases.
What an ultrasonic sensor can do in Home Assistant
Ultrasonic sensors measure the time taken for a sound pulse to reflect from a surface. In a Home Assistant project, that can provide:
- Water, rainwater, cistern, heating-oil, or fuel-tank level
- Water-softener salt, pellet, grain, recycling-bin, or waste-bin fill level
- Distance to a vehicle in a garage or fixed parking bay
- Object presence at a known location
- Liquid-surface height or the height of material in a container
- Experimental door, drawer, cabinet, or equipment-position monitoring
It is not automatically a room-occupancy sensor. An ultrasonic module might report that an object is 0.42 m away, but it is generally not the right technology for reliably detecting human presence or a stationary person.
#1 Best Overall
- HC-SR04 Ultrasonic Sensor:This is a device that can use sound waves to measure the distance of an object. It measures distance by emitting a sound wave of a specific frequency and listening to the bounce of that sound wave. The distance between the sonar sensor and the object can be calculated by recording the time elapsed between the generation of the sound wave and the bounce of the sound wave
- Working Voltage: 5V DC;Quiescent current: less than 2mA
- Ranging Distance:2cm - 450 cm;High precision: 0.3 cm
- Effectual Angle: <15°
- Test mode :Test distance = ((Duration of high level)*(Sonic :340m/s))/2
The software path is straightforward: sensor → ESP32/ESP8266 → ESPHome → Home Assistant. Home Assistant’s ESPHome integration uses the device’s native API and a persistent local connection that pushes state changes. See the Home Assistant ESPHome integration documentation.
Choose the sensor before you wire it
| Sensor | Best use | Interface | Important limitation | ESPHome path |
|---|---|---|---|---|
| HC-SR04 | Dry indoor prototypes, bins, shelves, and short-range experiments | Trigger and echo GPIO | Exposed electronics; unsuitable for wet or condensing locations | Ultrasonic sensor |
| JSN-SR04T / AJ-SR04M | Tanks and damp installations | Typically UART or module-specific trigger/echo modes | Board revisions, clones, pinouts, and mode selection vary | JSN-SR04T component |
| DFRobot A02YYUW | A more integrated waterproof module | UART | ESPHome’s component does not support the PWM and RS485 versions | A02YYUW component |
| Zio Ultrasonic | Projects already using I²C | I²C | Less universally available than HC-SR04-style modules | Zio Ultrasonic component |
Published range and resolution figures are module specifications, not guarantees of field accuracy. Alignment, surface texture, temperature, humidity, turbulence, container geometry, and sensor quality all affect the result. ESPHome notes that many common ultrasonic sensors are not reliable beyond approximately 2 m; its standard component uses a 2 m default timeout. Check the exact sensor documentation before designing an installation.
When each option makes sense
- Choose HC-SR04 for a cheap, dry, low-risk proof of concept.
- Choose JSN-SR04T when the transducer needs better protection from water, but verify the exact board revision and operating mode.
- Choose A02YYUW when you prefer a sealed integrated sensor and UART wiring. DFRobot describes it as IP67 waterproof; that does not make the controller enclosure or cable installation waterproof.
- Choose an industrial 4–20 mA or RS-485 sensor when a bad measurement could cause flooding, equipment damage, unsafe operation, or a costly service failure.
What you need for an HC-SR04 build
- Home Assistant
- The ESPHome add-on or ESPHome dashboard
- An ESP32 or ESP8266 development board with USB programming
- An HC-SR04 module
- USB cable and suitable power supply
- Jumper wires, breadboard, or permanent wiring hardware
- A suitable logic-level shifter or voltage divider if the sensor’s echo output is not safe for the controller input
Do not assume that every HC-SR04 board has identical electrical behavior. Many inexpensive modules use 5 V electronics, while common ESP GPIO inputs are 3.3 V. Check the exact sensor and development-board documentation. Never connect a potentially 5 V echo signal directly to a 3.3 V input without confirming compatibility or adding appropriate level protection.
Free tools Windows power users keep installed
One-click scans. No signup required.
Wire the HC-SR04 to the ESP board
The sensor has four functional connections:
| HC-SR04 connection | ESP connection |
|---|---|
| VCC | Suitable sensor power |
| GND | ESP ground; both devices must share a common ground |
| TRIG | One output-capable ESP GPIO |
| ECHO | One input-capable ESP GPIO, with verified voltage-level protection where required |
The GPIOs below are examples only. Pin names and safe boot pins differ by board, so match the wiring to your actual ESP32 or ESP8266 model.
Configure ESPHome
Create a device in ESPHome, enter your Wi-Fi credentials, and use a configuration like this. Replace the board definition and GPIOs with values appropriate for your hardware.
Rank #2
- NON-CONTACT DISTANCE SENSING: Add object detection to robot navigation, parking-distance prototypes, automatic lids, counters and interactive projects; each HC-SR04 uses a 40 kHz ultrasonic burst and echo timing to estimate distance
- 5-PACK FOR REPEATABLE PROTOTYPING: Use multiple HC-SR04 modules across builds, compare sensor positions or keep spares for testing and replacement; each module integrates an ultrasonic transmitter, receiver and control circuit
- 5 V MODULE WITH 3-450 CM RANGE: Connect VCC, Trig, Echo and GND, use a 10 µs trigger pulse and measure Echo duration; resolution is 0.3 cm with an effective angle under 15°, while the controller board and external power source are not included
- PROTECT 3.3 V GPIO: The HC-SR04 operates from 5 V and its Echo output is 5 V, so use a voltage divider or suitable level shifting with 3.3 V inputs; keep the module dry and use it for prototyping rather than calibrated measurement
- FOR ROBOTICS & STEM PROJECTS: Suitable for distance measurement, object detection, automatic lids, parking alerts, robot navigation and other hands-on electronics builds
esphome:
name: ultrasonic-distance
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
api:
ota:
- platform: esphome
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
sensor:
- platform: ultrasonic
trigger_pin: GPIO5
echo_pin: GPIO18
name: "Ultrasonic Distance"
id: ultrasonic_distance
unit_of_measurement: "m"
device_class: distance
state_class: measurement
accuracy_decimals: 2
update_interval: 10s
timeout: 2m
The essential ESPHome configuration is the ultrasonic sensor platform with trigger_pin and echo_pin. ESPHome documents default values of a 60-second update interval, a 2 m timeout, and a 10-microsecond trigger pulse; the example deliberately uses a 10-second interval for a more responsive demonstration. See the ESPHome ultrasonic sensor documentation.
Install the first firmware over USB. Once the device is online and its API is configured, later firmware updates can normally be made wirelessly through ESPHome. Use a sensible device name and keep the YAML backed up.
Recommended Free Tools
Add the ESPHome device to Home Assistant
- Wait for the ESPHome node to join Wi-Fi.
- Open Settings → Devices & services.
- Accept the discovered ESPHome device, or choose to add the ESPHome integration manually and enter the node’s network details.
- Open the device and confirm that Ultrasonic Distance reports a measurement.
- Add the entity to a dashboard or use it in an automation.
Menu wording can change between Home Assistant releases. If the device is not discovered, check its Wi-Fi connection, ESPHome logs, API configuration, and network isolation settings. Home Assistant currently notes that new ESPHome devices require ESPHome 2025.4.0 or later; verify the current compatibility requirement in the integration documentation.
Use a waterproof sensor without mixing interfaces
JSN-SR04T in UART mode
Many JSN-SR04T, JSN-SR04M, AJ-SR04M, and “V3” listings combine different revisions. Their wiring, firmware behavior, and mode-selection hardware may differ. Inspect the board, identify its actual pinout, and verify whether it is configured for UART or trigger/echo operation before choosing an ESPHome component.
For a JSN-SR04T configured for the UART path, the ESPHome structure is:
Rank #3
- HC-SR04 Ultrasonic Sensor:Compatible with for Arduino R3 UNO MEGA Mega2560 Duemilanove XBee Nano Robot With 5Pcs mounting bracket
- Working Voltage: 5V DC; Quiescent current: Less than 2mA
- Ranging Distance:2 - 450 cm;High precision:0.3 cm;Effectual Angle: < 15°
- Test distance=((high level duration)*(sound wave: 340m/s))/2
- Merchandise included:5Pcs HC-SR04 Ultrasonic Sensor;5Pcs Mounting bracket;20Pcs Mounting screw;10Pcs Female to Female Wire; 10Pcs Male to Female Wire
uart:
tx_pin: GPIO17
rx_pin: GPIO16
baud_rate: 9600
sensor:
- platform: jsn_sr04t
name: "Tank Distance"
update_interval: 10s
ESPHome documents this as a 9600-baud UART sensor. Some modes continuously output measurements at roughly 100 ms intervals, while others respond to requests. Continuous-output installations particularly benefit from filtering. Do not use the HC-SR04 trigger/echo YAML unchanged for a UART module.
DFRobot A02YYUW
The A02YYUW ESPHome component is for the UART version. ESPHome documents a nominal 3–450 cm range and 1 mm resolution; treat those as specifications rather than guaranteed accuracy. Its PWM and RS485 variants are not supported by that component. Follow the ESPHome A02YYUW documentation and the sensor’s own wiring instructions.
Convert distance into a tank or bin level
The sensor measures the gap from the transducer to the material surface. First record two calibrated distances:
empty_distance: distance when the container is emptyfull_distance: distance when the container is full
For a simple container where height and volume are approximately proportional:
percentage_full =
(empty_distance - current_distance)
/
(empty_distance - full_distance)
× 100
Clamp the result to 0–100 and treat an unavailable or timed-out reading as invalid, not as an empty or full container. A rectangular tank may be close to linear. A horizontal cylindrical tank or irregular hopper is not: use a volume formula or calibrated lookup table if actual volume matters.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallRank #4
- HC-SR04 Ultrasonic Distance Sensor: Power Supply: 5V DC; Quiescent Current : <2mA; Effectual Angle: <15°; Detection Distance: 2 - 500cm; Resolution: 0.3cm
- All in One Designed: HC-SR04 Consists of Ultrasonic Transmitter, Receiver, and Control Circuit;When Trigged it Sends Out a Series of 40KHz Ultrasonic Pulses and Receives Echo from an Object.
- Easy to Install: HC-SR04 Ultrasonic Distance Sensor with 4 Pins: VCC; Trig(Control Side); Echo (Receiver); Out (Empty); GND; Small Size Designed,Easy for Embedded Installation.
- Applications: HC-SR04 Ultrasonic Distance Sensor Widely used for Robot Obstacle Avoidance, Object Distance Measuring, Liquid Level Detection, Public Security, Parking Lot Detection etc.
- Package Contents: You will Get 10pcs HC-SR04 Ultrasonic Distance Sensor,1pc 10pin Cable 20cm(M-F) and 1pc 10pin Cable 20cm(F-F)
You can calculate the percentage in ESPHome after the raw distance sensor is working:
sensor:
- platform: template
name: "Tank Level"
unit_of_measurement: "%"
state_class: measurement
update_interval: 10s
lambda: |-
const float empty_distance = 1.80;
const float full_distance = 0.25;
const float distance = id(ultrasonic_distance).state;
if (isnan(distance) || distance < full_distance || distance > empty_distance) {
return NAN;
}
float percentage =
(empty_distance - distance) /
(empty_distance - full_distance) * 100.0;
return clamp(percentage, 0.0f, 100.0f);
filters:
- median:
window_size: 5
send_every: 1
send_first_at: 1
The exact entity metadata should match the meaning of the value. A container percentage is not a battery, so do not label it with device_class: battery. Omit the device class if no supported class accurately describes the measurement.
Improve measurement reliability
Filtering cannot fix poor geometry, incorrect wiring, a wrong sensor mode, or a surface that reflects ultrasound badly. Improve the installation first:
- Mount the transducer perpendicular to a hard, clearly defined target.
- Keep the target within the sensor’s practical range and outside its minimum or “dead” zone.
- Allow clearance from side walls, braces, pipes, ladders, and other obstructions.
- For liquid levels, measure during calm conditions; a stilling tube or calm section can reduce waves and turbulence where the installation permits it.
- Use a slower update interval for slowly changing tanks or bins.
- Stagger readings from multiple ultrasonic sensors so they do not transmit simultaneously.
- Protect outdoor electronics with a sealed enclosure, cable glands, drainage, and suitable UV-resistant cable. Consider surge and lightning protection on long outdoor runs.
A practical ESPHome filter for a 0.02–2.00 m installation is:
filters:
- median:
window_size: 7
send_every: 1
send_first_at: 1
- clamp:
min_value: 0.02
max_value: 2.00
A median filter rejects isolated spikes. An average or sliding filter produces smoother gradual changes but adds lag. The ESPHome sensor documentation covers filter behavior. Always inspect raw readings before deciding that a filter has solved the problem.
Best Value
- Measures distances from 2cm to 450cm with ±3mm accuracy using high-frequency ultrasonic pulses and optimized echo detection circuitry
- Wide voltage support (3V–5.5V) enables seamless integration with 3.3V microcontrollers like Raspberry Pi and ESP32, eliminating the need for voltage level conversion
- 4-pin digital interface (VCC, GND, TRIG, ECHO) allows direct connection to Arduino-compatible boards, STM32, and other MCUs with no additional components required
- High refresh rate up to 50Hz ensures real-time feedback for dynamic applications such as robotic navigation and automated door systems
- Low-power design draws under 15mA during active measurement
Use safe automations
Do not operate a pump, heater, gate, or other consequential equipment from one raw ultrasonic reading. Require a valid state, persistence, and hysteresis. For example, a low-level notification can require the percentage to remain below a threshold:
alias: Notify when tank is low
trigger:
- platform: numeric_state
entity_id: sensor.tank_level
below: 20
for: "00:10:00"
condition:
- condition: template
value_template: "{{ states('sensor.tank_level') not in ['unknown', 'unavailable'] }}"
action:
- service: notify.notify
data:
message: "Tank level has remained below 20% for 10 minutes."
For equipment control, add a separate high-level cutoff, a minimum run time, manual override, and an independent safety device where failure has serious consequences.
Troubleshooting
| Symptom | Likely causes | What to check |
|---|---|---|
| No entity appears | Device offline, Wi-Fi/API problem, firmware failure | ESPHome logs, Wi-Fi credentials, API configuration, network isolation, and Home Assistant integration discovery |
| “Distance measurement timed out” | No target, incorrect pins, missing ground, wrong sensor mode, incompatible echo voltage, poor target reflection | Test against a flat hard target at a known distance; verify power, ground, GPIOs, voltage protection, mode, and UART wiring |
| Constant zero or invalid values | Echo wiring or signal-level problem, wrong component, sensor not powered | Confirm the interface type and inspect logs before adding filters |
| Values jump or spike | Turbulence, angled/irregular surface, side-wall reflections, interference, electrical noise | Improve alignment, slow the update rate, stagger sensors, and apply a median filter |
| Stable but wrong value | Obstruction, dead-zone violation, clone behavior, incorrect calibration, non-linear tank geometry | Measure empty/full reference points and test the sensor’s actual field of view |
| Works on the bench but not installed | Long cable voltage drop, inadequate power, condensation, poor Wi-Fi, changed target geometry | Test power at the sensor, reseal the enclosure, improve network coverage, and compare readings against a known distance |
For a timeout, increase the timeout only within the sensor’s realistic range and reduce the measurement frequency if necessary. A very long timeout can make a missing echo look like a plausible measurement. Obtain valid raw readings first; filtering is a later step.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
“Waterproof sensor” also does not mean “weatherproof system.” Protect the controller, connectors, cable entry points, and power supply, and account for condensation, freezing, and ice on the measured surface.
When ultrasonic is the wrong choice
| Requirement | Consider instead | Trade-off |
|---|---|---|
| Room occupancy or stationary human presence | mmWave presence sensor | More configuration-sensitive and often more expensive, but designed for presence |
| Simple one-level alarm | Float switch | Very simple and often robust, but no continuous level |
| Short-range compact measurement | Time-of-flight or optical sensor | Can be affected by surface color, reflectivity, transparency, or sunlight |
| Motion detection | PIR sensor | Good for movement, but poor for detecting a stationary person |
| Enclosed-tank measurement | Pressure-based level sensor | Requires suitable installation and calibration |
| Long cables, harsh conditions, or high consequence of failure | Industrial 4–20 mA or RS-485 instrument | Higher cost and additional interface hardware |
ESPHome’s component index lists a broader selection of ultrasonic, optical, and time-of-flight distance devices.
Bottom line
Use an HC-SR04 with an ESP32 and ESPHome for a dry indoor prototype. Use a JSN-SR04T or A02YYUW when water or condensation is part of the environment, but verify the exact module interface and board revision. Calibrate empty and full distances, account for container geometry, filter noisy measurements, and make automations tolerate invalid readings. If the project involves human presence or safety-critical level control, choose a technology and hardware platform designed specifically for that job.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →

