ESPHome 2025.6.3
Loading...
Searching...
No Matches
adc_sensor_rp2040.cpp
Go to the documentation of this file.
1#ifdef USE_RP2040
2
3#include "adc_sensor.h"
4#include "esphome/core/log.h"
5
6#ifdef CYW43_USES_VSYS_PIN
7#include "pico/cyw43_arch.h"
8#endif // CYW43_USES_VSYS_PIN
9#include <hardware/adc.h>
10
11namespace esphome {
12namespace adc {
13
14static const char *const TAG = "adc.rp2040";
15
16void ADCSensor::setup() {
17 ESP_LOGCONFIG(TAG, "Running setup for '%s'", this->get_name().c_str());
18 static bool initialized = false;
19 if (!initialized) {
20 adc_init();
21 initialized = true;
22 }
23}
24
26 LOG_SENSOR("", "ADC Sensor", this);
27 if (this->is_temperature_) {
28 ESP_LOGCONFIG(TAG, " Pin: Temperature");
29 } else {
30#ifdef USE_ADC_SENSOR_VCC
31 ESP_LOGCONFIG(TAG, " Pin: VCC");
32#else
33 LOG_PIN(" Pin: ", this->pin_);
34#endif // USE_ADC_SENSOR_VCC
35 }
36 ESP_LOGCONFIG(TAG,
37 " Samples: %i\n"
38 " Sampling mode: %s",
39 this->sample_count_, LOG_STR_ARG(sampling_mode_to_str(this->sampling_mode_)));
40 LOG_UPDATE_INTERVAL(this);
41}
42
43float ADCSensor::sample() {
44 uint32_t raw = 0;
45 auto aggr = Aggregator(this->sampling_mode_);
46
47 if (this->is_temperature_) {
48 adc_set_temp_sensor_enabled(true);
49 delay(1);
50 adc_select_input(4);
51
52 for (uint8_t sample = 0; sample < this->sample_count_; sample++) {
53 raw = adc_read();
54 aggr.add_sample(raw);
55 }
56 adc_set_temp_sensor_enabled(false);
57 if (this->output_raw_) {
58 return aggr.aggregate();
59 }
60 return aggr.aggregate() * 3.3f / 4096.0f;
61 }
62
63 uint8_t pin = this->pin_->get_pin();
64#ifdef CYW43_USES_VSYS_PIN
65 if (pin == PICO_VSYS_PIN) {
66 // Measuring VSYS on Raspberry Pico W needs to be wrapped with
67 // `cyw43_thread_enter()`/`cyw43_thread_exit()` as discussed in
68 // https://github.com/raspberrypi/pico-sdk/issues/1222, since Wifi chip and
69 // VSYS ADC both share GPIO29
70 cyw43_thread_enter();
71 }
72#endif // CYW43_USES_VSYS_PIN
73
74 adc_gpio_init(pin);
75 adc_select_input(pin - 26);
76
77 for (uint8_t sample = 0; sample < this->sample_count_; sample++) {
78 raw = adc_read();
79 aggr.add_sample(raw);
80 }
81
82#ifdef CYW43_USES_VSYS_PIN
83 if (pin == PICO_VSYS_PIN) {
84 cyw43_thread_exit();
85 }
86#endif // CYW43_USES_VSYS_PIN
87
88 if (this->output_raw_) {
89 return aggr.aggregate();
90 }
91 float coeff = pin == PICO_VSYS_PIN ? 3.0f : 1.0f;
92 return aggr.aggregate() * 3.3f / 4096.0f * coeff;
93}
94
95} // namespace adc
96} // namespace esphome
97
98#endif // USE_RP2040
uint8_t raw[35]
Definition bl0939.h:0
const StringRef & get_name() const
virtual uint8_t get_pin() const =0
void setup() override
Setup ADC.
InternalGPIOPin * pin_
Definition adc_sensor.h:84
SamplingMode sampling_mode_
Definition adc_sensor.h:87
const LogString * sampling_mode_to_str(SamplingMode mode)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29