esphome / issues

Issue Tracker for ESPHome
https://esphome.io/
291 stars 36 forks source link

pulse_counter incorrect with higher frequencies (kHz) #6416

Open gmanic opened 4 days ago

gmanic commented 4 days ago

The problem

I use higher frequencies (10-200 kHz) to implement a capacitive tank monitor via an ESP32 (-> hardware pulse counter).

These higher frequencies are not counted correctly, I even get negative values from the pulse_counter (while only incrementing) - this should be impossible. I would tend to think that the counter overflow is not properly setup to count such high pulse counts correctly. This is possible, as a ESP32 frequency monitor up to / above 1 MHz has been successfully implemented (https://esp32.com/viewtopic.php?t=17018)

Correct values read with a scope on that GPIO are between like 60kHz and 150kHz, while the sensor yaml below shows like -130kHz and 45kHz.

Which version of ESPHome has the issue?

2024.10.3

What type of installation are you using?

Home Assistant Add-on

Which version of Home Assistant has the issue?

2024.11.0

What platform are you using?

ESP32

Board

esp32 D1 mini

Component causing the issue

pulse_counter

Example YAML snippet

sensor:
  - platform: pulse_counter
    pin: 
      number: GPIO15
      mode:
        input: true
        pulldown: true
    internal_filter: 2us
    update_interval: 1s
    id: grau_tanklevel
    device_class: frequency
    state_class: measurement
    unit_of_measurement: "kHz"
    filters:
      - multiply: 0.001
      - multiply: 60

Anything in the logs that might be useful for us?

No response

Additional information

My understanding of the src is, that in case the hw-pcnt (esp32) is used, the variable counter (via pulse_counter_t) is defined as int16_t, while the software pcnt uses int32_t. The +/- problem seems to be directly related to overflows.

gmanic commented 4 days ago

Additional information: The hardware connected to the GPIO is a square signal generation as of this template (scope shows clean signal and frequency): https://www.ramser-elektro.at/der-gies-o-shield-fuer-den-arduino/#Sensoren (-> article in German; very rough translation: it's a R-C oscillator with a back fed inverted schmitt-trigger; I'm running this on 3.3V).

gmanic commented 3 days ago

On further investigation (using a scope and an adjusted circuit and interval_filter set to 2us), I found out that pulse_counter works just fine up to ca. 64kHz (or approx. 3.8m pulses/minute). Above that number: negative value, seemingly an integer overflow.

pulse_meter in comparison counts up to ca. 256kHz without a glitch (which is approx. the limit for the 2us interval_filter).

prchal commented 1 day ago

Same here. Max is 32kHz, probably 32767 (int16), then -32kHz, with higher freq going down to 0.