1
0
mirror of https://github.com/esphome/esphome.git synced 2024-10-06 02:40:56 +01:00

Reduce timing noise in duty_cycle (#2881)

This commit is contained in:
Carlos Garcia Saura 2021-12-12 21:30:47 +01:00 committed by GitHub
parent 9c0506592b
commit 31a61b598b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

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