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

View file

@ -5,13 +5,15 @@
#include "esphome/components/sensor/sensor.h" #include "esphome/components/sensor/sensor.h"
#include <cinttypes> #include <cinttypes>
#include <chrono>
namespace esphome { namespace esphome {
namespace pulse_counter_ulp { namespace pulse_counter_ulp {
enum class CountMode { disable = 0, increment = 1, decrement = -1 }; 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 UlpProgram {
struct state { struct state {
@ -47,7 +49,7 @@ class PulseCounterUlpSensor : public sensor::Sensor, public PollingComponent {
protected: protected:
InternalGPIOPin *pin_; InternalGPIOPin *pin_;
UlpProgram storage_; UlpProgram storage_;
timestamp_t last_time_{0}; clock::time_point last_time_{};
uint32_t current_total_{0}; uint32_t current_total_{0};
sensor::Sensor *total_sensor_{nullptr}; sensor::Sensor *total_sensor_{nullptr};
}; };