ESPHome 2025.9.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
5namespace esphome {
6namespace duty_cycle {
7
8static const char *const TAG = "duty_cycle";
9
19 LOG_SENSOR("", "Duty Cycle Sensor", this);
20 LOG_PIN(" Pin: ", this->pin_);
21 LOG_UPDATE_INTERVAL(this);
22}
24 const uint32_t now = micros();
25 const uint32_t last_interrupt = this->store_.last_interrupt; // Read the measurement taken by the interrupt
26 uint32_t on_time = this->store_.on_time;
27
28 this->store_.on_time = 0; // Start new measurement, exactly aligned with the micros() reading
29 this->store_.last_interrupt = now;
30
31 if (this->last_update_ != 0) {
32 const bool level = this->store_.last_level;
33
34 if (level)
35 on_time += now - last_interrupt;
36
37 const float total_time = float(now - this->last_update_);
38
39 const float value = (on_time * 100.0f) / total_time;
40 ESP_LOGD(TAG, "'%s' Got duty cycle=%.1f%%", this->get_name().c_str(), value);
41 this->publish_state(value);
42 }
43 this->last_update_ = now;
44}
45
47
49 const bool new_level = arg->pin.digital_read();
50 if (new_level == arg->last_level)
51 return;
52 arg->last_level = new_level;
53 const uint32_t now = micros();
54
55 if (!new_level)
56 arg->on_time += now - arg->last_interrupt;
57
58 arg->last_interrupt = now;
59}
60
61} // namespace duty_cycle
62} // namespace esphome
const StringRef & get_name() const
virtual void setup()=0
virtual bool digital_read()=0
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:88
virtual ISRInternalGPIOPin to_isr() const =0
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
@ INTERRUPT_ANY_EDGE
Definition gpio.h:43
const float DATA
For components that import data from directly connected sensors like DHT.
Definition component.cpp:50
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:30
Store data in a class that doesn't use multiple-inheritance (vtables in flash)
static void gpio_intr(DutyCycleSensorStore *arg)