From 31a61b598be920abc1e35b430591e76fadededb6 Mon Sep 17 00:00:00 2001 From: Carlos Garcia Saura Date: Sun, 12 Dec 2021 21:30:47 +0100 Subject: [PATCH] Reduce timing noise in duty_cycle (#2881) --- esphome/components/duty_cycle/duty_cycle_sensor.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/esphome/components/duty_cycle/duty_cycle_sensor.cpp b/esphome/components/duty_cycle/duty_cycle_sensor.cpp index aed22312a7..9a881c81f0 100644 --- a/esphome/components/duty_cycle/duty_cycle_sensor.cpp +++ b/esphome/components/duty_cycle/duty_cycle_sensor.cpp @@ -23,22 +23,24 @@ void DutyCycleSensor::dump_config() { } void DutyCycleSensor::update() { const uint32_t now = micros(); + const uint32_t last_interrupt = this->store_.last_interrupt; // Read the measurement taken by the interrupt + uint32_t on_time = this->store_.on_time; + + this->store_.on_time = 0; // Start new measurement, exactly aligned with the micros() reading + this->store_.last_interrupt = now; + if (this->last_update_ != 0) { const bool level = this->store_.last_level; - const uint32_t last_interrupt = this->store_.last_interrupt; - uint32_t on_time = this->store_.on_time; if (level) on_time += now - last_interrupt; const float total_time = float(now - this->last_update_); - const float value = (on_time / total_time) * 100.0f; + const float value = (on_time * 100.0f) / total_time; ESP_LOGD(TAG, "'%s' Got duty cycle=%.1f%%", this->get_name().c_str(), value); this->publish_state(value); } - this->store_.on_time = 0; - this->store_.last_interrupt = now; this->last_update_ = now; }