ESPHome  2024.10.2
duty_cycle_sensor.cpp
Go to the documentation of this file.
1 #include "duty_cycle_sensor.h"
2 #include "esphome/core/log.h"
3 #include "esphome/core/helpers.h"
4 
5 namespace esphome {
6 namespace duty_cycle {
7 
8 static const char *const TAG = "duty_cycle";
9 
11  ESP_LOGCONFIG(TAG, "Setting up Duty Cycle Sensor '%s'...", this->get_name().c_str());
12  this->pin_->setup();
13  this->store_.pin = this->pin_->to_isr();
14  this->store_.last_level = this->pin_->digital_read();
15  this->store_.last_interrupt = micros();
16 
18 }
20  LOG_SENSOR("", "Duty Cycle Sensor", this);
21  LOG_PIN(" Pin: ", this->pin_);
22  LOG_UPDATE_INTERVAL(this);
23 }
25  const uint32_t now = micros();
26  const uint32_t last_interrupt = this->store_.last_interrupt; // Read the measurement taken by the interrupt
27  uint32_t on_time = this->store_.on_time;
28 
29  this->store_.on_time = 0; // Start new measurement, exactly aligned with the micros() reading
30  this->store_.last_interrupt = now;
31 
32  if (this->last_update_ != 0) {
33  const bool level = this->store_.last_level;
34 
35  if (level)
36  on_time += now - last_interrupt;
37 
38  const float total_time = float(now - this->last_update_);
39 
40  const float value = (on_time * 100.0f) / total_time;
41  ESP_LOGD(TAG, "'%s' Got duty cycle=%.1f%%", this->get_name().c_str(), value);
42  this->publish_state(value);
43  }
44  this->last_update_ = now;
45 }
46 
48 
50  const bool new_level = arg->pin.digital_read();
51  if (new_level == arg->last_level)
52  return;
53  arg->last_level = new_level;
54  const uint32_t now = micros();
55 
56  if (!new_level)
57  arg->on_time += now - arg->last_interrupt;
58 
59  arg->last_interrupt = now;
60 }
61 
62 } // namespace duty_cycle
63 } // namespace esphome
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:19
Store data in a class that doesn't use multiple-inheritance (vtables in flash)
virtual void setup()=0
uint32_t IRAM_ATTR HOT micros()
Definition: core.cpp:27
static void gpio_intr(DutyCycleSensorStore *arg)
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
virtual bool digital_read()=0
virtual ISRInternalGPIOPin to_isr() const =0
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition: gpio.h:81
const StringRef & get_name() const
Definition: entity_base.cpp:10