From c33077bc61a214df23d82753ae9077898c280786 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Trevi=C3=B1o?= Date: Tue, 12 Oct 2021 21:42:51 +0200 Subject: [PATCH] Improves ct_clamp component accuracy (#2283) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Rafa TreviƱo --- .../components/ct_clamp/ct_clamp_sensor.cpp | 22 ++++++++++++------- esphome/components/ct_clamp/ct_clamp_sensor.h | 1 + 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/esphome/components/ct_clamp/ct_clamp_sensor.cpp b/esphome/components/ct_clamp/ct_clamp_sensor.cpp index 0052b1426d..51b0f1318c 100644 --- a/esphome/components/ct_clamp/ct_clamp_sensor.cpp +++ b/esphome/components/ct_clamp/ct_clamp_sensor.cpp @@ -31,19 +31,20 @@ void CTClampSensor::update() { return; } - float dc = this->sample_sum_ / this->num_samples_; - float var = (this->sample_squared_sum_ / this->num_samples_) - dc * dc; - float ac = std::sqrt(var); - ESP_LOGD(TAG, "'%s' - Got %d samples", this->name_.c_str(), this->num_samples_); - ESP_LOGD(TAG, "'%s' - Raw AC Value: %.3fA", this->name_.c_str(), ac); - this->publish_state(ac); + const float rms_ac_dc_squared = this->sample_squared_sum_ / this->num_samples_; + const float rms_dc = this->sample_sum_ / this->num_samples_; + const float rms_ac = std::sqrt(rms_ac_dc_squared - rms_dc * rms_dc); + ESP_LOGD(TAG, "'%s' - Raw AC Value: %.3fA after %d different samples (%d SPS)", this->name_.c_str(), rms_ac, + this->num_samples_, 1000 * this->num_samples_ / this->sample_duration_); + this->publish_state(rms_ac); }); // Set sampling values - this->is_sampling_ = true; + this->last_value_ = 0.0; this->num_samples_ = 0; this->sample_sum_ = 0.0f; this->sample_squared_sum_ = 0.0f; + this->is_sampling_ = true; } void CTClampSensor::loop() { @@ -55,9 +56,14 @@ void CTClampSensor::loop() { if (std::isnan(value)) return; + // Assuming a sine wave, avoid requesting values faster than the ADC can provide them + if (this->last_value_ == value) + return; + this->last_value_ = value; + + this->num_samples_++; this->sample_sum_ += value; this->sample_squared_sum_ += value * value; - this->num_samples_++; } } // namespace ct_clamp diff --git a/esphome/components/ct_clamp/ct_clamp_sensor.h b/esphome/components/ct_clamp/ct_clamp_sensor.h index 10601ab852..db4dc1ea57 100644 --- a/esphome/components/ct_clamp/ct_clamp_sensor.h +++ b/esphome/components/ct_clamp/ct_clamp_sensor.h @@ -43,6 +43,7 @@ class CTClampSensor : public sensor::Sensor, public PollingComponent { * https://en.wikipedia.org/wiki/Root_mean_square */ + float last_value_ = 0.0f; float sample_sum_ = 0.0f; float sample_squared_sum_ = 0.0f; uint32_t num_samples_ = 0;