ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
adc_sensor_common.cpp
Go to the documentation of this file.
1#include "adc_sensor.h"
2#include "esphome/core/log.h"
3
4namespace esphome::adc {
5
6static const char *const TAG = "adc.common";
7
9 switch (mode) {
11 return LOG_STR("average");
13 return LOG_STR("minimum");
15 return LOG_STR("maximum");
16 }
17 return LOG_STR("unknown");
18}
19
21 this->mode_ = mode;
22 // set to max uint if mode is "min"
23 if (mode == SamplingMode::MIN) {
24 this->aggr_ = std::numeric_limits<T>::max();
25 }
26}
27
28template<typename T> void Aggregator<T>::add_sample(T value) {
29 this->samples_ += 1;
30
31 switch (this->mode_) {
33 this->aggr_ += value;
34 break;
35
37 if (value < this->aggr_) {
38 this->aggr_ = value;
39 }
40 break;
41
43 if (value > this->aggr_) {
44 this->aggr_ = value;
45 }
46 }
47}
48
49template<typename T> T Aggregator<T>::aggregate() {
50 if (this->mode_ == SamplingMode::AVG) {
51 if (this->samples_ == 0) {
52 return this->aggr_;
53 }
54
55 return (this->aggr_ + (this->samples_ >> 1)) / this->samples_; // NOLINT(clang-analyzer-core.DivideZero)
56 }
57
58 return this->aggr_;
59}
60
61#ifdef USE_ZEPHYR
62template class Aggregator<int32_t>;
63#else
64template class Aggregator<uint32_t>;
65#endif
66
68 float value_v = this->sample();
69 ESP_LOGV(TAG, "'%s': Voltage=%.4fV", this->get_name().c_str(), value_v);
70 this->publish_state(value_v);
71}
72
73void ADCSensor::set_sample_count(uint8_t sample_count) {
74 if (sample_count != 0) {
75 this->sample_count_ = sample_count;
76 }
77}
78
79void ADCSensor::set_sampling_mode(SamplingMode sampling_mode) { this->sampling_mode_ = sampling_mode; }
80
81} // namespace esphome::adc
BedjetMode mode
BedJet operating mode.
const StringRef & get_name() const
Definition entity_base.h:71
void set_sampling_mode(SamplingMode sampling_mode)
Set the sampling mode for how multiple ADC samples are combined into a single measurement.
void set_sample_count(uint8_t sample_count)
Set the number of samples to be taken for ADC readings to improve accuracy.
float sample() override
Perform a single ADC sampling operation and return the measured value.
void update() override
Update the sensor's state by reading the current ADC value.
SamplingMode sampling_mode_
Definition adc_sensor.h:134
Aggregator(SamplingMode mode)
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
const LogString * sampling_mode_to_str(SamplingMode mode)