mirror of
https://github.com/esphome/esphome.git
synced 2024-12-22 21:44:55 +01:00
Reduce timing noise in duty_cycle (#2881)
This commit is contained in:
parent
9c0506592b
commit
31a61b598b
1 changed files with 7 additions and 5 deletions
|
@ -23,22 +23,24 @@ void DutyCycleSensor::dump_config() {
|
||||||
}
|
}
|
||||||
void DutyCycleSensor::update() {
|
void DutyCycleSensor::update() {
|
||||||
const uint32_t now = micros();
|
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) {
|
if (this->last_update_ != 0) {
|
||||||
const bool level = this->store_.last_level;
|
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)
|
if (level)
|
||||||
on_time += now - last_interrupt;
|
on_time += now - last_interrupt;
|
||||||
|
|
||||||
const float total_time = float(now - this->last_update_);
|
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);
|
ESP_LOGD(TAG, "'%s' Got duty cycle=%.1f%%", this->get_name().c_str(), value);
|
||||||
this->publish_state(value);
|
this->publish_state(value);
|
||||||
}
|
}
|
||||||
this->store_.on_time = 0;
|
|
||||||
this->store_.last_interrupt = now;
|
|
||||||
this->last_update_ = now;
|
this->last_update_ = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue