ESPHome  2024.12.2
adc_sensor_esp8266.cpp
Go to the documentation of this file.
1 #ifdef USE_ESP8266
2 
3 #include "adc_sensor.h"
4 #include "esphome/core/helpers.h"
5 #include "esphome/core/log.h"
6 
7 #ifdef USE_ADC_SENSOR_VCC
8 #include <Esp.h>
9 ADC_MODE(ADC_VCC)
10 #else
11 #include <Arduino.h>
12 #endif // USE_ADC_SENSOR_VCC
13 
14 namespace esphome {
15 namespace adc {
16 
17 static const char *const TAG = "adc.esp8266";
18 
19 void ADCSensor::setup() {
20  ESP_LOGCONFIG(TAG, "Setting up ADC '%s'...", this->get_name().c_str());
21 #ifndef USE_ADC_SENSOR_VCC
22  this->pin_->setup();
23 #endif
24 }
25 
27  LOG_SENSOR("", "ADC Sensor", this);
28 #ifdef USE_ADC_SENSOR_VCC
29  ESP_LOGCONFIG(TAG, " Pin: VCC");
30 #else
31  LOG_PIN(" Pin: ", this->pin_);
32 #endif // USE_ADC_SENSOR_VCC
33  ESP_LOGCONFIG(TAG, " Samples: %i", this->sample_count_);
34  LOG_UPDATE_INTERVAL(this);
35 }
36 
37 float ADCSensor::sample() {
38  uint32_t raw = 0;
39  for (uint8_t sample = 0; sample < this->sample_count_; sample++) {
40 #ifdef USE_ADC_SENSOR_VCC
41  raw += ESP.getVcc(); // NOLINT(readability-static-accessed-through-instance)
42 #else
43  raw += analogRead(this->pin_->get_pin()); // NOLINT
44 #endif // USE_ADC_SENSOR_VCC
45  }
46  raw = (raw + (this->sample_count_ >> 1)) / this->sample_count_; // NOLINT(clang-analyzer-core.DivideZero)
47  if (this->output_raw_) {
48  return raw;
49  }
50  return raw / 1024.0f;
51 }
52 
53 std::string ADCSensor::unique_id() { return get_mac_address() + "-adc"; }
54 
55 } // namespace adc
56 } // namespace esphome
57 
58 #endif // USE_ESP8266
uint8_t raw[35]
Definition: bl0939.h:19
virtual void setup()=0
void setup() override
Setup ADC.
virtual uint8_t get_pin() const =0
InternalGPIOPin * pin_
Definition: adc_sensor.h:68
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:723
std::string unique_id() override
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
ADC_MODE(ADC_VCC) namespace esphome
const StringRef & get_name() const
Definition: entity_base.cpp:10