SensESP 3.0.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
analog_reader.h
Go to the documentation of this file.
1#ifndef SENSESP_SENSORS_ANALOG_READER_H_
2#define SENSESP_SENSORS_ANALOG_READER_H_
3
4#include "sensesp.h"
5
6#include "Arduino.h"
7#if defined(ESP32)
8#include "esp_adc_cal.h"
9#endif
10
11namespace sensesp {
12
17 private:
18 int output_scale_;
19
20 public:
21 virtual bool configure() = 0;
22 virtual float read() = 0;
23};
24
26 protected:
27 int pin_;
28 adc_atten_t attenuation_ = ADC_ATTEN_DB_12;
29 // This should work with ESP32 and newer variants, ADCs are different
30 adc_bits_width_t bit_width_ = (adc_bits_width_t)ADC_WIDTH_BIT_DEFAULT;
31 // maximum voltage readout for 3.3V VDDA when attenuation_ is set to 11 dB
32 const float kVmax_ = 3300;
34 esp_adc_cal_characteristics_t adc_characteristics_;
35 const int kVref_ = 1100; // voltage reference, in mV
36
37 public:
38 ESP32AnalogReader(int pin) : pin_{pin} {
39 if (!(32 <= pin && pin <= 39)) {
40 ESP_LOGE(__FILENAME__, "Only ADC1 is supported at the moment");
41 adc_channel_ = -1;
42 return;
43 }
44 adc_channel_ = digitalPinToAnalogChannel(pin);
45 }
46
47 bool configure() {
48 if (adc_channel_ == -1) {
49 return false;
50 }
51 adc1_config_width(bit_width_);
52 adc1_config_channel_atten((adc1_channel_t)adc_channel_, attenuation_);
53 esp_adc_cal_characterize(ADC_UNIT_1, attenuation_, bit_width_, kVref_,
55 return true;
56 }
57
58 float read() {
59 uint32_t voltage;
60 esp_adc_cal_get_voltage((adc_channel_t)adc_channel_, &adc_characteristics_,
61 &voltage);
62 return voltage / kVmax_;
63 }
64};
66
67} // namespace sensesp
68
69#endif
Used by AnalogInput as a hardware abstraction layer.
virtual float read()=0
virtual bool configure()=0
adc_bits_width_t bit_width_
esp_adc_cal_characteristics_t adc_characteristics_
ESP32AnalogReader AnalogReader