pulse_counter_ulp: Use std::chrono instead of millis()

millis() appears to jump when a time component synchronises. steady_clock() should avoid this.
This commit is contained in:
brisk 2024-07-22 22:32:28 +09:30
parent e736091950
commit b41746cc54
2 changed files with 10 additions and 8 deletions

View file

@ -135,12 +135,12 @@ void PulseCounterUlpSensor::dump_config() {
void PulseCounterUlpSensor::update() {
UlpProgram::state raw = this->storage_.pop_state();
timestamp_t now;
timestamp_t interval;
now = millis();
interval = now - this->last_time_;
if (this->last_time_ != 0) {
float value = (60000.0f * raw.edge_count) / float(interval); // per minute
clock::time_point now;
std::chrono::duration<float, std::ratio<60>> minutes;
now = clock::now();
minutes = now - this->last_time_;
if (this->last_time_ != clock::time_point{}) {
float value = raw.edge_count / minutes.count(); // pulses per minute
ESP_LOGD(TAG, "'%s': Retrieved counter: %0.2f pulses/min", this->get_name().c_str(), value);
this->publish_state(value);
}

View file

@ -5,13 +5,15 @@
#include "esphome/components/sensor/sensor.h"
#include <cinttypes>
#include <chrono>
namespace esphome {
namespace pulse_counter_ulp {
enum class CountMode { disable = 0, increment = 1, decrement = -1 };
using timestamp_t = int64_t;
// millis() jumps when a time component synchronises, so we use steady_clock instead
using clock = std::chrono::steady_clock;
struct UlpProgram {
struct state {
@ -47,7 +49,7 @@ class PulseCounterUlpSensor : public sensor::Sensor, public PollingComponent {
protected:
InternalGPIOPin *pin_;
UlpProgram storage_;
timestamp_t last_time_{0};
clock::time_point last_time_{};
uint32_t current_total_{0};
sensor::Sensor *total_sensor_{nullptr};
};