1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-18 19:22:22 +01:00

CT Clamp ADS1115 Improvements (#647)

Fixes https://github.com/esphome/issues/issues/457
This commit is contained in:
Otto Winter
2019-07-02 13:02:46 +02:00
committed by GitHub
parent 486bafd009
commit f95d4ca106
5 changed files with 72 additions and 33 deletions

View File

@@ -8,6 +8,18 @@ namespace ct_clamp {
static const char *TAG = "ct_clamp";
void CTClampSensor::setup() {
this->is_calibrating_offset_ = true;
this->high_freq_.start();
this->set_timeout("calibrate_offset", this->sample_duration_, [this]() {
this->high_freq_.stop();
this->is_calibrating_offset_ = false;
if (this->num_samples_ != 0) {
this->offset_ = this->sample_sum_ / this->num_samples_;
}
});
}
void CTClampSensor::dump_config() {
LOG_SENSOR("", "CT Clamp Sensor", this);
ESP_LOGCONFIG(TAG, " Sample Duration: %.2fs", this->sample_duration_ / 1e3f);
@@ -15,6 +27,9 @@ void CTClampSensor::dump_config() {
}
void CTClampSensor::update() {
if (this->is_calibrating_offset_)
return;
// Update only starts the sampling phase, in loop() the actual sampling is happening.
// Request a high loop() execution interval during sampling phase.
@@ -44,12 +59,18 @@ void CTClampSensor::update() {
}
void CTClampSensor::loop() {
if (!this->is_sampling_)
if (!this->is_sampling_ || !this->is_calibrating_offset_)
return;
// Perform a single sample
float value = this->source_->sample();
if (this->is_calibrating_offset_) {
this->sample_sum_ += value;
this->num_samples_++;
return;
}
// Adjust DC offset via low pass filter (exponential moving average)
const float alpha = 0.001f;
this->offset_ = this->offset_ * (1 - alpha) + value * alpha;

View File

@@ -10,10 +10,14 @@ namespace ct_clamp {
class CTClampSensor : public sensor::Sensor, public PollingComponent {
public:
void setup() override;
void update() override;
void loop() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
float get_setup_priority() const override {
// After the base sensor has been initialized
return setup_priority::DATA - 1.0f;
}
void set_sample_duration(uint32_t sample_duration) { sample_duration_ = sample_duration; }
void set_source(voltage_sampler::VoltageSampler *source) { source_ = source; }
@@ -40,6 +44,8 @@ class CTClampSensor : public sensor::Sensor, public PollingComponent {
float sample_sum_ = 0.0f;
uint32_t num_samples_ = 0;
bool is_sampling_ = false;
/// Calibrate offset value once at boot
bool is_calibrating_offset_ = false;
};
} // namespace ct_clamp