Obtaining the median value for a sensor

I have a sensor created using an ESP8266 module running ESPEasy that relays information via MQTT to Home Assistant. However the data is not stable from the sensor, and I would like to take the median of the previous 20 readings to obtain a more accurate result. The majority of the readings are accurate, but occasionally an outlier is sent from the sensor. I have been trying the Statistics Sensor, but I can’t work out how to directly obtain the median and display it in the web interface. I can create a sensor to detect the mean, but this is affected significantly by outliers. I can see the median value when I click on the statistics sensor, but can’t work out how to create a specific median sensor from it so I can use it for automation etc. I’m not concerned about the update speed of the variable because it will only be changing very slowly. Any tips for a newbie?

1 Like

how about doing the median calculation in the ESP8266 and sending that to HA?

Use a template sensor to get the mean which is an attribute of the statistics sensor:

Or skip the statistics sensor and to everything with the template sensor.

Try something like

value_template: >-
  {{ state_attr('sensor.mysensor', 'mean') }}
1 Like

You could also use the filter sensor to get rid of any outliers

Thank you all for your help. I ended up using a template sensor to solve the issue. The configuration.yaml entry I ended up using is

`value_template: '{{ states.sensor.statistics_sensor_name.attributes.median }}'`
3 Likes

See this is what I love about hass. All the naysayers who want GUI configuration, how you gonna do that?

1 Like