Skip to content

Instantly share code, notes, and snippets.

@sixtyfive
Created August 26, 2019 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sixtyfive/0dbf08822b3bacb0adde37572f25f3af to your computer and use it in GitHub Desktop.
Save sixtyfive/0dbf08822b3bacb0adde37572f25f3af to your computer and use it in GitHub Desktop.
Some experiments on how to deal with the ESP32's ADC in Arduino IDE code
float v_supply = 3.29; // measured: 3.29
int adc_pin = 4;
int adc_bits = 12;
/* effective range of measurement:
* ADC_0db: 100-950mV (+-23mV)
* ADC_2_5db: 100-1250mV (+-30mV)
* ADC_6db: 150-1750mV (+-40mV)
* ADC_11db: 150-2450mV (+-60mV) - default value
*/
adc_attenuation_t adc_attn = ADC_0db;
/* taken from
* https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf
* page 23
*/
float adc_max = pow(2, adc_bits);
float v_ref_internal = 1.1; // should reroute to GPIO and also measure!
float v_adc_max() {
float val;
switch (adc_attn) {
case ADC_0db:
val = 0.95;
break;
case ADC_2_5db:
val = 1.25;
break;
case ADC_6db:
val = 1.75;
break;
default:
val = 2.45;
break;
}
return val;
}
float v_adc_min() {
float val;
switch (adc_attn) {
case ADC_0db:
case ADC_2_5db:
val = 0.1;
break;
default:
val = 0.15;
break;
}
return val;
}
void setup() {
Serial.begin(115200);
analogReadResolution(adc_bits);
analogSetAttenuation(adc_attn); // or analogSetPinAttenuation(pin, atten)
}
float adc_val = 0;
float V = 0;
void loop() {
adc_val = analogRead(adc_pin);
// also check sources for https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/adc.html#_CPPv426esp_adc_cal_raw_to_voltage8uint32_tPK29esp_adc_cal_characteristics_t
V = (adc_val / adc_max * v_adc_max()) * v_ref_internal;
delay(100);
Serial.print("Own code:\t\t\t");
Serial.print(V); Serial.println("V");
Serial.print("Radio amateur guy's code:\t");
Serial.print(ReadVoltage(adc_pin)); Serial.println("V\n");
}
// from https://github.com/G6EJD/ESP32-ADC-Accuracy-Improvement-function/blob/master/ESP32_ADC_Read_Voltage_Accurate.ino
// doesn't handle ADC attenuation settings other than ADC_11db yet...
double ReadVoltage(byte pin){
double reading = analogRead(pin);
if(reading < 1 || reading > adc_max) return 0;
// use either
// return -0.000000000009824 * pow(reading, 3) + 0.000000016557283 * pow(reading, 2) + 0.000854596860691 * reading + 0.065440348345433;
return -0.000000000000016 * pow(reading, 4) + 0.000000000118171 * pow(reading, 3)- 0.000000301211691 * pow(reading, 2)+ 0.001109019271794 * reading + 0.034143524634089;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment