Getting a sensor to report a number is easy in ESPHome. Getting it to report a number you can trust, at a sensible rate, and act on it reliably even when Home Assistant is offline takes a little more thought. This guide covers the patterns that separate a quick experiment from a device you can leave running for years: choosing pins and buses, filtering and calibrating readings, and writing automations that run on the microcontroller itself.
How sensors are structured in YAML
Every sensor in ESPHome lives under one of a few top-level keys, depending on the kind of value it produces:
sensor:for numbers, such as temperature, humidity, voltage, power or distance.binary_sensor:for on/off states, such as a door contact, a motion detector or a button.text_sensor:for strings, such as a firmware version, an IP address or a decoded RFID tag.
Each entry is a list item with a platform: that selects the driver, plus options for that driver and generic options shared by all sensors: name, id, unit_of_measurement, accuracy_decimals, device_class, state_class, filters and automation triggers.
Some platforms produce several values at once. A BME280 delivers temperature, humidity and pressure, so its entry contains nested blocks for each value, and you only include the ones you need.
Choosing pins without surprises
Before writing YAML, check which pins are safe on your board.
On the classic ESP32:
- GPIO34 to GPIO39 are input-only and have no internal pull-up resistors. They suit analog sensors and buttons with external resistors.
- GPIO0, GPIO2, GPIO5, GPIO12 and GPIO15 are strapping pins that influence boot mode. Avoid connecting hardware to them that pulls them high or low at power-up.
- GPIO6 to GPIO11 connect to the module's flash memory and must not be used.
- ADC2 pins (GPIO0, 2, 4, 12–15, 25–27) cannot read analog values while Wi-Fi is active. Use ADC1 pins (GPIO32–39) for analog sensors.
On the ESP8266, there is only one analog input, A0, with a range of roughly 0–1 V on bare chips (many boards add a divider to accept up to 3.3 V). GPIO0, GPIO2 and GPIO15 are strapping pins, and GPIO16 cannot use interrupts.
Newer chips such as the ESP32-C3 and ESP32-S3 have their own pin maps and strapping pins. ESPHome's validation warns you when a configuration uses a risky pin, so read those warnings rather than dismissing them.
Using shared buses
Many digital sensors share a bus rather than using one pin each.
I²C
i2c:
sda: GPIO21
scl: GPIO22
frequency: 100kHz
scan: true
With scan: true, the device logs every address it finds at boot. If your sensor does not appear, check wiring, power and pull-up resistors before suspecting the YAML. Two sensors with the same fixed address cannot share a bus; use a second i2c bus with its own id or a multiplexer.
One-Wire
DS18B20 temperature probes use a single data pin with a 4.7 kΩ pull-up resistor to 3.3 V, and several probes can share it:
one_wire:
- platform: gpio
pin: GPIO4
sensor:
- platform: dallas_temp
address: 0x1c0000031edd2a28
name: "Tank Top"
- platform: dallas_temp
address: 0x5e0000031f0b4128
name: "Tank Bottom"
The logs list each probe's address at boot, so you can label them correctly.
UART
Sensors such as particulate monitors, CO₂ sensors and mmWave radars often use a serial UART. Define the UART with its pins and baud rate, give it an id, and reference that id from the sensor platform.
Cleaning up readings with filters
Raw readings are often noisy, too frequent or in the wrong units. Filters run on the device, in order, before a value is published.
sensor:
- platform: adc
pin: GPIO34
name: "Soil Moisture"
update_interval: 10s
attenuation: 12db
unit_of_measurement: "%"
accuracy_decimals: 0
filters:
- median:
window_size: 7
send_every: 6
- calibrate_linear:
- 2.85 -> 0.0
- 1.32 -> 100.0
- clamp:
min_value: 0
max_value: 100
Reading this from top to bottom:
- The sensor samples every 10 seconds.
- The median filter takes the middle value of the last seven samples, which removes spikes, and publishes only every sixth result, so Home Assistant receives a value once a minute.
- calibrate_linear maps the measured voltage to a percentage. Here, 2.85 V (dry air) becomes 0 % and 1.32 V (in water) becomes 100 %.
- clamp keeps the result between 0 and 100, even if the probe reads slightly beyond the calibration points.
Other filters worth knowing:
sliding_window_moving_averageandexponential_moving_averagesmooth gradual noise.throttlelimits how often a value is sent, whileheartbeatforces a resend at a fixed interval.deltaonly publishes when the value changes by more than a threshold, which keeps the Home Assistant database small.offsetandmultiplyapply simple corrections, such as compensating a temperature sensor warmed by the board.filter_outdiscards a specific bad value that a sensor reports on error.timeoutpublishes a fallback value, or marks the sensor unavailable, when no reading arrives within a set time.
Calibrating properly
Calibration turns a sensor that is roughly right into one that is reliably right. The method is simple: record the raw reading at known reference points, then map them.
For a temperature sensor inside an enclosure, place a trusted thermometer next to it, let both settle for an hour, and note the difference. An offset filter corrects a constant error. If the error grows with temperature, take readings at two or three temperatures and use calibrate_linear with those pairs.
For analog sensors, always calibrate on the actual board and wiring you will deploy. ADC readings vary between chips, and the reference points measured on a breadboard rarely match a finished device.
Binary sensors and debouncing
Buttons and contacts bounce: one press produces several rapid transitions. Filters clean this up:
binary_sensor:
- platform: gpio
pin:
number: GPIO14
mode: INPUT_PULLUP
inverted: true
name: "Workshop Door"
device_class: door
filters:
- delayed_on: 50ms
- delayed_off: 50ms
INPUT_PULLUP enables the internal resistor, and inverted: true makes a closed contact to ground read as "on". The delays ignore transitions shorter than 50 ms.
Automations: triggers, conditions and actions
ESPHome automations follow a consistent pattern. A trigger starts the automation, optional conditions decide whether it continues, and actions do the work.
binary_sensor:
- platform: gpio
pin: GPIO27
name: "Stair Motion"
device_class: motion
on_press:
- if:
condition:
sensor.in_range:
id: hall_lux
below: 40
then:
- light.turn_on:
id: stair_light
brightness: 60%
- delay: 2min
- light.turn_off: stair_light
Here, motion turns on the stair light at 60 % brightness only if the ambient light sensor reads below 40 lux, then turns it off after two minutes.
Common triggers include on_press, on_release, on_click, on_multi_click (for double and long presses), on_value, on_value_range, on_boot, on_time with the time component, and interval for periodic work.
Scripts for reusable and restartable logic
The example above has a weakness: if motion is detected again during the two-minute delay, a second copy of the automation starts. Scripts solve this:
script:
- id: stair_timer
mode: restart
then:
- light.turn_on:
id: stair_light
brightness: 60%
- delay: 2min
- light.turn_off: stair_light
binary_sensor:
- platform: gpio
pin: GPIO27
name: "Stair Motion"
on_press:
- script.execute: stair_timer
With mode: restart, each new trigger restarts the timer, so the light stays on while someone keeps moving. Other modes are single (ignore new triggers while running), queued and parallel.
Periodic tasks with interval and time
interval runs actions at a fixed period from boot:
interval:
- interval: 30min
then:
- switch.turn_on: pump
- delay: 20s
- switch.turn_off: pump
For actions at specific times of day, add a time source and use on_time:
time:
- platform: homeassistant
id: ha_time
on_time:
- seconds: 0
minutes: 30
hours: 6
days_of_week: MON-FRI
then:
- switch.turn_on: coffee_machine
Use platform: sntp instead of homeassistant if the device should keep time without Home Assistant.
Global variables and lambdas
For state that must survive between automation runs, use globals:
globals:
- id: pump_runs_today
type: int
restore_value: true
initial_value: "0"
When YAML actions are not expressive enough, a lambda inserts a short piece of C++:
sensor:
- platform: template
name: "Dew Point"
unit_of_measurement: "°C"
update_interval: 60s
lambda: |-
float t = id(room_temp).state;
float h = id(room_hum).state;
float a = 17.27, b = 237.7;
float g = (a * t) / (b + t) + log(h / 100.0);
return (b * g) / (a - g);
Keep lambdas short. If one grows beyond a dozen lines, consider whether a component, a script or an external component would be clearer.
Making automations resilient
Automations on the device should behave sensibly when things go wrong:
- Sensor unavailable. Check
isnan(id(sensor).state)in lambdas, or use thetimeoutfilter, before acting on a value. - Reboot mid-action. Choose
restore_modefor switches and lights carefully. A pump or heater should usually startALWAYS_OFF. - Network loss. Logic that only depends on local sensors keeps working. Anything that relies on
homeassistantsensors should have a sensible default. - Blocking code. Never use long loops or
delay()inside lambdas; they freeze the device. Use YAMLdelayactions, which yield to the main loop.
Three sensor recipes worth knowing
The same principles apply across hundreds of components. These three examples cover patterns that appear again and again.
Room presence with an mmWave radar
Passive infrared detectors only see movement, so a person sitting still at a desk eventually "disappears". Millimetre-wave radar modules such as the HLK-LD2410 detect the tiny movements of breathing and report stationary presence as well. They connect over UART and expose several entities at once: overall presence, moving and still targets, and detection distance. Tune their sensitivity per distance gate from Home Assistant, and combine presence with a delayed_off filter of a minute or two so lights do not switch off between movements.
Energy monitoring in a reflashed smart plug
Many plugs contain a metering chip such as the HLW8012, BL0937 or CSE7766. ESPHome has a platform for each, reporting voltage, current and power. Because plug manufacturers use different resistor values, the readings need calibration: connect a known load such as a kettle or an incandescent lamp, compare with a reference meter, and apply calibrate_linear or the platform's own calibration options. Add a total_daily_energy sensor, with state_class: total_increasing, and Home Assistant's energy dashboard can use it directly.
Tank or bin level with an ultrasonic sensor
Ultrasonic modules such as the JSN-SR04T measure the distance to a surface. Converting distance to a fill level is a filter job: subtract the reading from the empty-tank distance, divide by the full range, and clamp the result. Ultrasonic readings in enclosed tanks are noisy because of echoes, so a median filter over several samples is essential, and a filter_out for the sensor's out-of-range value prevents false "empty" readings.
Naming and organising sensors
Clear names save time when a device has a dozen entities. Name each sensor for what it measures, not for the hardware: "Supply Air Temperature" rather than "DS18B20 2". Use id values in snake_case that match the name, such as supply_air_temp, so lambdas and automations read naturally. Move technical values, raw voltages, signal strengths and debug counters into entity_category: diagnostic, or mark them internal: true if Home Assistant never needs them. A tidy device page makes it obvious which values matter at a glance.
Choosing update intervals sensibly
How often a sensor reads and how often it reports are separate decisions, and getting them right keeps both the device and Home Assistant healthy.
Sample at the rate the physical quantity changes and the sensor allows. Room temperature changes slowly, so sampling every 30 to 60 seconds is plenty. Power consumption changes quickly, so energy meters often sample every second. Soil moisture changes over hours.
Report at the rate the data is useful. Home Assistant records every published value in its database. A temperature sensor that publishes every two seconds generates more than forty thousand rows a day, almost all of them redundant. Combine a fast update_interval with a median, throttle or delta filter, so the device samples often for accuracy but publishes only when something meaningful changes.
Battery-powered devices change the picture entirely. With deep_sleep, the device wakes, takes a reading, publishes and sleeps again. Here, every wake costs energy, so fewer readings and a fast Wi-Fi connection, often with a static IP address, matter more than smoothing.
Template sensors and switches
Template platforms create entities whose value comes from logic rather than hardware. They are the glue between components.
switch:
- platform: template
name: "Away Mode"
id: away_mode
optimistic: true
restore_mode: RESTORE_DEFAULT_OFF
binary_sensor:
- platform: template
name: "Window Open Too Long"
lambda: |-
return id(window_contact).state && id(outside_temp).state < 10;
filters:
- delayed_on: 10min
The first creates a virtual switch you can flip from Home Assistant and read in automations. The second becomes true only when a window has been open for ten minutes while it is cold outside. Both work without extra hardware and both appear in Home Assistant like any other entity.
Testing changes without risk
When building automations that drive real equipment, such as pumps, heaters or garage doors, test the logic before connecting the load.
- Point the automation at an LED or an unused GPIO first and watch the logs.
- Use a template switch in place of the real relay while tuning thresholds.
- Lower long delays to seconds during testing, then restore them before the final install.
- Add
logger.logactions at key points so the log shows exactly which branch an automation took.
Frequently asked questions
Should automations live on the device or in Home Assistant?
Put anything safety-related or time-critical on the device: a pump that must stop when a tank is full, a fan tied to humidity, a light that follows a button. Keep automations that combine many devices, depend on presence or schedules across the house, or change often in Home Assistant, where they are easier to edit.
Why does my analog sensor read differently on another board?
ADC characteristics vary between chips and even between pins on the same chip. Calibrate each device individually with calibrate_linear using readings taken on that specific board.
Key takeaways
- Check pin restrictions before wiring, especially strapping pins and ADC2 on the ESP32.
- Use filters to sample often but publish rarely, and to remove noise and spikes.
- Calibrate on the final hardware with known reference points.
- Wrap timed behaviour in scripts with the right mode to avoid overlapping runs.
- Keep critical automations on the device so they work without the network.


