Skip to content

Commit aabbed0

Browse files
authored
analogRead() now return value according to value set in analogReadResulotion() (#5776)
Function analogReadResolution set how many bits will analogRead return. Find out that this functionality was added back 2017 by @me-no-dev in #161. Related issues: #5163
1 parent a418058 commit aabbed0

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

Diff for: cores/esp32/esp32-hal-adc.c

+19-8
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,23 @@ static uint8_t __analogVRefPin = 0;
4646
#endif
4747

4848
static uint8_t __analogAttenuation = 3;//11db
49-
#if CONFIG_IDF_TARGET_ESP32S2
50-
static uint8_t __analogWidth = 4; // 13 bits
51-
#else
52-
static uint8_t __analogWidth = 3; // 12 bits
53-
#endif
49+
static uint8_t __analogWidth = ADC_WIDTH_MAX - 1; //3 for ESP32/ESP32C3; 4 for ESP32S2
50+
static uint8_t __analogReturnedWidth = SOC_ADC_MAX_BITWIDTH; //12 for ESP32/ESP32C3; 13 for ESP32S2
5451
static uint8_t __analogClockDiv = 1;
5552
static adc_attenuation_t __pin_attenuation[SOC_GPIO_PIN_COUNT];
5653

54+
static inline uint16_t mapResolution(uint16_t value)
55+
{
56+
uint8_t from = __analogWidth + 9;
57+
if (from == __analogReturnedWidth) {
58+
return value;
59+
}
60+
if (from > __analogReturnedWidth) {
61+
return value >> (from - __analogReturnedWidth);
62+
}
63+
return value << (__analogReturnedWidth - from);
64+
}
65+
5766
void __analogSetClockDiv(uint8_t clockDiv){
5867
if(!clockDiv){
5968
clockDiv = 1;
@@ -150,6 +159,7 @@ void __analogReadResolution(uint8_t bits)
150159
if(!bits || bits > 16){
151160
return;
152161
}
162+
__analogReturnedWidth = bits;
153163
#if CONFIG_IDF_TARGET_ESP32
154164
__analogSetWidth(bits); // hadware from 9 to 12
155165
#endif
@@ -169,7 +179,7 @@ uint16_t __analogRead(uint8_t pin)
169179
channel -= 10;
170180
r = adc2_get_raw( channel, __analogWidth, &value);
171181
if ( r == ESP_OK ) {
172-
return value;
182+
return mapResolution(value);
173183
} else if ( r == ESP_ERR_INVALID_STATE ) {
174184
log_e("GPIO%u: %s: ADC2 not initialized yet.", pin, esp_err_to_name(r));
175185
} else if ( r == ESP_ERR_TIMEOUT ) {
@@ -178,9 +188,10 @@ uint16_t __analogRead(uint8_t pin)
178188
log_e("GPIO%u: %s", pin, esp_err_to_name(r));
179189
}
180190
} else {
181-
return adc1_get_raw(channel);
191+
value = adc1_get_raw(channel);
192+
return mapResolution(value);
182193
}
183-
return value;
194+
return mapResolution(value);
184195
}
185196

186197
uint32_t __analogReadMilliVolts(uint8_t pin){

0 commit comments

Comments
 (0)