@@ -46,14 +46,23 @@ static uint8_t __analogVRefPin = 0;
46
46
#endif
47
47
48
48
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
54
51
static uint8_t __analogClockDiv = 1 ;
55
52
static adc_attenuation_t __pin_attenuation [SOC_GPIO_PIN_COUNT ];
56
53
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
+
57
66
void __analogSetClockDiv (uint8_t clockDiv ){
58
67
if (!clockDiv ){
59
68
clockDiv = 1 ;
@@ -150,6 +159,7 @@ void __analogReadResolution(uint8_t bits)
150
159
if (!bits || bits > 16 ){
151
160
return ;
152
161
}
162
+ __analogReturnedWidth = bits ;
153
163
#if CONFIG_IDF_TARGET_ESP32
154
164
__analogSetWidth (bits ); // hadware from 9 to 12
155
165
#endif
@@ -169,7 +179,7 @@ uint16_t __analogRead(uint8_t pin)
169
179
channel -= 10 ;
170
180
r = adc2_get_raw ( channel , __analogWidth , & value );
171
181
if ( r == ESP_OK ) {
172
- return value ;
182
+ return mapResolution ( value ) ;
173
183
} else if ( r == ESP_ERR_INVALID_STATE ) {
174
184
log_e ("GPIO%u: %s: ADC2 not initialized yet." , pin , esp_err_to_name (r ));
175
185
} else if ( r == ESP_ERR_TIMEOUT ) {
@@ -178,9 +188,10 @@ uint16_t __analogRead(uint8_t pin)
178
188
log_e ("GPIO%u: %s" , pin , esp_err_to_name (r ));
179
189
}
180
190
} else {
181
- return adc1_get_raw (channel );
191
+ value = adc1_get_raw (channel );
192
+ return mapResolution (value );
182
193
}
183
- return value ;
194
+ return mapResolution ( value ) ;
184
195
}
185
196
186
197
uint32_t __analogReadMilliVolts (uint8_t pin ){
0 commit comments