ESPHome  2025.2.0
adc_sensor_common.cpp
Go to the documentation of this file.
1 #include "adc_sensor.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace adc {
6 
7 static const char *const TAG = "adc.common";
8 
10  switch (mode) {
11  case SamplingMode::AVG:
12  return LOG_STR("average");
13  case SamplingMode::MIN:
14  return LOG_STR("minimum");
15  case SamplingMode::MAX:
16  return LOG_STR("maximum");
17  }
18  return LOG_STR("unknown");
19 }
20 
22  this->mode_ = mode;
23  // set to max uint if mode is "min"
24  if (mode == SamplingMode::MIN) {
25  this->aggr_ = UINT32_MAX;
26  }
27 }
28 
29 void Aggregator::add_sample(uint32_t value) {
30  this->samples_ += 1;
31 
32  switch (this->mode_) {
33  case SamplingMode::AVG:
34  this->aggr_ += value;
35  break;
36 
37  case SamplingMode::MIN:
38  if (value < this->aggr_) {
39  this->aggr_ = value;
40  }
41  break;
42 
43  case SamplingMode::MAX:
44  if (value > this->aggr_) {
45  this->aggr_ = value;
46  }
47  }
48 }
49 
51  if (this->mode_ == SamplingMode::AVG) {
52  if (this->samples_ == 0) {
53  return this->aggr_;
54  }
55 
56  return (this->aggr_ + (this->samples_ >> 1)) / this->samples_; // NOLINT(clang-analyzer-core.DivideZero)
57  }
58 
59  return this->aggr_;
60 }
61 
63  float value_v = this->sample();
64  ESP_LOGV(TAG, "'%s': Got voltage=%.4fV", this->get_name().c_str(), value_v);
65  this->publish_state(value_v);
66 }
67 
68 void ADCSensor::set_sample_count(uint8_t sample_count) {
69  if (sample_count != 0) {
70  this->sample_count_ = sample_count;
71  }
72 }
73 
74 void ADCSensor::set_sampling_mode(SamplingMode sampling_mode) { this->sampling_mode_ = sampling_mode; }
75 
77 
78 } // namespace adc
79 } // namespace esphome
const LogString * sampling_mode_to_str(SamplingMode mode)
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:19
Aggregator(SamplingMode mode)
void set_sampling_mode(SamplingMode sampling_mode)
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:183
void set_sample_count(uint8_t sample_count)
void update() override
Update ADC values.
void add_sample(uint32_t value)
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
float get_setup_priority() const override
HARDWARE_LATE setup priority