ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
duty_cycle_sensor.cpp
Go to the documentation of this file.
1#include "duty_cycle_sensor.h"
3#include "esphome/core/log.h"
4
6
7static const char *const TAG = "duty_cycle";
8
18 LOG_SENSOR("", "Duty Cycle Sensor", this);
19 LOG_PIN(" Pin: ", this->pin_);
20 LOG_UPDATE_INTERVAL(this);
21}
23 const uint32_t now = micros();
24 const uint32_t last_interrupt = this->store_.last_interrupt; // Read the measurement taken by the interrupt
25 uint32_t on_time = this->store_.on_time;
26
27 this->store_.on_time = 0; // Start new measurement, exactly aligned with the micros() reading
28 this->store_.last_interrupt = now;
29
30 if (this->last_update_ != 0) {
31 const bool level = this->store_.last_level;
32
33 if (level)
34 on_time += now - last_interrupt;
35
36 const float total_time = float(now - this->last_update_);
37
38 const float value = (on_time * 100.0f) / total_time;
39 ESP_LOGD(TAG, "'%s' Got duty cycle=%.1f%%", this->get_name().c_str(), value);
40 this->publish_state(value);
41 }
42 this->last_update_ = now;
43}
44
46 const bool new_level = arg->pin.digital_read();
47 if (new_level == arg->last_level)
48 return;
49 arg->last_level = new_level;
50 const uint32_t now = micros();
51
52 if (!new_level)
53 arg->on_time += now - arg->last_interrupt;
54
55 arg->last_interrupt = now;
56}
57
58} // namespace esphome::duty_cycle
const StringRef & get_name() const
Definition entity_base.h:71
virtual void setup()=0
virtual bool digital_read()=0
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:107
virtual ISRInternalGPIOPin to_isr() const =0
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
@ INTERRUPT_ANY_EDGE
Definition gpio.h:52
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
static void uint32_t
Store data in a class that doesn't use multiple-inheritance (vtables in flash)
static void gpio_intr(DutyCycleSensorStore *arg)