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; }