Using Exponents in a Lambda Filter

The standard calibrate_polynomial filter was not working for calibrating the temperature on a DHT22. I plugged my datapoints into Wolfram Alpha and got a cubic polynomial (0.0166222 x^3 - 4.19248 x^2 + 352.991 x - 9846.87) that perfectly matches my points, so I want to use that. When plugging it into a lambda filter, I get a few errors.

Config:

sensor:  
  - platform: dht
    model: AM2302
    pin: D6
    temperature:
      name: "Office Temperature"
      filters:
        lambda: return ((x ** 3) * 0.0166222) - ((x ** 2) * 4.19248) + (352.991 - x) - 9846.87;

Error:

/config/esphome/ofc-dht22-01.yaml: In lambda function:
/config/esphome/ofc-dht22-01.yaml:39:19: error: invalid type argument of unary '*' (have 'int')
   39 |         lambda: return ((x ** 3) * 0.0166222) - ((x ** 2) * 4.19248) + (352.991 - x) - 9846.87;
      |                   ^~~
/config/esphome/ofc-dht22-01.yaml:39:44: error: invalid type argument of unary '*' (have 'int')
   39 |         lambda: return ((x ** 3) * 0.0166222) - ((x ** 2) * 4.19248) + (352.991 - x) - 9846.87;
      |                                            ^~~
*** [/data/ofc-dht22-01/.pioenvs/ofc-dht22-01/src/main.cpp.o] Error 1

** is the exponent operator in Python. Lambdas use the C language. So you need to use the pow() function. See https://linuxhint.com/write-exponent-c-language/

It works for me.

  - platform: template
    name: "Lawn Moisture"
    unit_of_measurement: "%"
    device_class: humidity
    state_class: measurement
    lambda: |-
      return (id(raw_v).state);
    filters:
      - calibrate_polynomial:
         degree: 5
         datapoints:
          # Map from sensor -> true value
          - 0.1 -> 0
          - 0.2 -> 1
          - 0.3 -> 2
          - 0.4 -> 3
          - 0.5 -> 4
          - 0.6 -> 5
          - 0.7 -> 6
          - 0.8 -> 7
          - 0.9 -> 8
          - 1 -> 9
          - 1.1 -> 10
          - 1.2 -> 12.5
          - 1.3 -> 15.004
          - 1.4 -> 19.812
          - 1.5 -> 24.62
          - 1.6 -> 29.428
          - 1.7 -> 34.236
          - 1.8 -> 39.044
          - 1.9 -> 42.118
          - 2 -> 44.75
          - 2.1 -> 47.382
          - 2.2 -> 50.014
          - 2.3 -> 52.646
          - 2.4 -> 55.278
          - 2.5 -> 57.91
          - 2.6 -> 60.542
          - 2.7 -> 63.174
          - 2.8 -> 65.806
          - 2.9 -> 68.438
          - 3 -> 71.07
      - sliding_window_moving_average:
          window_size: 12
          send_every: 12
          send_first_at: 12

I figured out why it wasn’t working. My DHT-22 is sending the temperature in C, and HA is converting it to F. All of my calibration readings were in F, so ESPHome was applying F calibration to C readings.

My formulas were working perfectly, it was the data used to generate them that was the issue.

That may be the case but you also have a lambda error, as shown in your log above.