Yes, you can absolutely use a Home Assistant template (specifically a template sensor) to calculate the average of two values. This is a common use case when combining data from multiple sensors.
✅ Example: Average of Two Temperature Sensors
Let's say you want to calculate the average temperature between:
sensor.living_room_temperature
sensor.bedroom_temperature
You can define a template sensor in your configuration.yaml like this:
sensor:
- platform: template
name: "Average Room Temperature"
unique_id: average_room_temperature
unit_of_measurement: "°C"
value_template: >
{% set temp1 = states('sensor.living_room_temperature') | float %}
{% set temp2 = states('sensor.bedroom_temperature') | float %}
{{ ((temp1 + temp2) / 2) | round(1) }}
This will create a new sensor called "Average Room Temperature" that shows the average of both sensors, rounded to one decimal place.
🛠️ Notes:
- Make sure both entities exist and return numeric values.
- Use
| float to safely convert the string state into a number.
- If any of the sensors are unavailable or not numeric, you may need to add fallback logic:
value_template: >
{% set temp1 = states('sensor.living_room_temperature') | float(0) if states('sensor.living_room_temperature') != 'unknown' else 0 %}
{% set temp2 = states('sensor.bedroom_temperature') | float(0) if states('sensor.bedroom_temperature') != 'unknown' else 0 %}
{% set count = [temp1, temp2] | select("!= 0") | list | length %}
{% if count > 0 %}
{{ ((temp1 + temp2) / count) | round(1) }}
{% else %}
0
{% endif %}
This version avoids errors if one or both sensors report unknown.
📐 Want More?
You can also do more advanced calculations, like:
- Weighted averages
- Time-based smoothing
- Filtering out extreme values
Let me know what kind of calculation you're aiming for — I'd be happy to help with a specific example!