Improves ct_clamp component accuracy (#2283)

Co-authored-by: Rafa Treviño <rafael.trevino@bbva.com>
This commit is contained in:
Rafael Treviño 2021-10-12 21:42:51 +02:00 committed by GitHub
parent 34db9d9ef2
commit c33077bc61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 8 deletions

View File

@ -31,19 +31,20 @@ void CTClampSensor::update() {
return; return;
} }
float dc = this->sample_sum_ / this->num_samples_; const float rms_ac_dc_squared = this->sample_squared_sum_ / this->num_samples_;
float var = (this->sample_squared_sum_ / this->num_samples_) - dc * dc; const float rms_dc = this->sample_sum_ / this->num_samples_;
float ac = std::sqrt(var); const float rms_ac = std::sqrt(rms_ac_dc_squared - rms_dc * rms_dc);
ESP_LOGD(TAG, "'%s' - Got %d samples", this->name_.c_str(), this->num_samples_); ESP_LOGD(TAG, "'%s' - Raw AC Value: %.3fA after %d different samples (%d SPS)", this->name_.c_str(), rms_ac,
ESP_LOGD(TAG, "'%s' - Raw AC Value: %.3fA", this->name_.c_str(), ac); this->num_samples_, 1000 * this->num_samples_ / this->sample_duration_);
this->publish_state(ac); this->publish_state(rms_ac);
}); });
// Set sampling values // Set sampling values
this->is_sampling_ = true; this->last_value_ = 0.0;
this->num_samples_ = 0; this->num_samples_ = 0;
this->sample_sum_ = 0.0f; this->sample_sum_ = 0.0f;
this->sample_squared_sum_ = 0.0f; this->sample_squared_sum_ = 0.0f;
this->is_sampling_ = true;
} }
void CTClampSensor::loop() { void CTClampSensor::loop() {
@ -55,9 +56,14 @@ void CTClampSensor::loop() {
if (std::isnan(value)) if (std::isnan(value))
return; 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_sum_ += value;
this->sample_squared_sum_ += value * value; this->sample_squared_sum_ += value * value;
this->num_samples_++;
} }
} // namespace ct_clamp } // namespace ct_clamp

View File

@ -43,6 +43,7 @@ class CTClampSensor : public sensor::Sensor, public PollingComponent {
* https://en.wikipedia.org/wiki/Root_mean_square * https://en.wikipedia.org/wiki/Root_mean_square
*/ */
float last_value_ = 0.0f;
float sample_sum_ = 0.0f; float sample_sum_ = 0.0f;
float sample_squared_sum_ = 0.0f; float sample_squared_sum_ = 0.0f;
uint32_t num_samples_ = 0; uint32_t num_samples_ = 0;