I found a solution that I believe works great.
Although the ADC_MODE macro cannot be modified after the board is started, we can actually set its integer input as the output of a function and then use RTC memory to trigger different modes, depending for example on how many times the board has been started.
#include "ESP8266WiFi.h"
#define QUERY_VCC_INTERVAL 10
int adc_selection;
ADC_MODE(get_adc());
int get_adc(){
typedef struct {
uint32_t adc_mode;
uint32_t count;
} rtcStore;
rtcStore rtcMem;
system_rtc_mem_read(100, &rtcMem, sizeof(rtcMem));
if ((rtcMem.adc_mode != ADC_VCC) && (rtcMem.adc_mode != ADC_TOUT)) return ADC_TOUT;
return rtcMem.adc_mode;
}
int get_adc_and_write_change(){
typedef struct {
uint32_t adc_mode;
uint32_t count;
} rtcStore;
int a;
rtcStore rtcMem;
system_rtc_mem_read(100, &rtcMem, sizeof(rtcMem));
a = rtcMem.adc_mode;
Serial.print("CYCLE NUMBER: ");
Serial.println(rtcMem.count);
if (rtcMem.count > QUERY_VCC_INTERVAL){
rtcMem.adc_mode = ADC_VCC;
rtcMem.count = 0;
} else {
rtcMem.adc_mode = ADC_TOUT;
rtcMem.count++;
}
system_rtc_mem_write(100, &rtcMem, sizeof(rtcMem));
return a;
}
void setup() {
int vcc;
Serial.begin(9600);
Serial.println(" ---------- ");
delay(1000);
adc_selection = get_adc_and_write_change();
Serial.print("VALUE FOR ADC MODE WAS: ");
Serial.println(adc_selection);
vcc = ESP.getVcc();
Serial.print("VALUE WHEN READING VCC: ");
Serial.println(vcc);
if (adc_selection == ADC_TOUT){
Serial.println("VCC SHOULD BE 65535");
} else {
Serial.println("VCC SHOULD NOT BE 65535");
}
Serial.println("RESET BOARD TO CONTINUE");
delay(1000);
}
void loop() {
}
Note that the function gets executed very early on the board startup, so we cannot even count on using or writing to global variable definitions of the script's code. This is why all structures are defined within the get_adc function.
The above code triggers ADC_MODE(ADC_VCC) for every 10 times that ADC_MODE(ADC_TOUT) is triggered. This allows me to read analogue sensors for 10 times after the board is woken up from deep sleep and then read the VCC level to gauge the battery voltage once every 10 times.
Note also that to have VCC readings work correctly I need to connect analogue sensor power to a digital pin and use that to power the sensors ON/OFF as needed.
I have tested the above code with a NodeMCU v3, on the Arduino IDE.
that disables the reading of the sensor
... so enable it after you read the voltage ... what is the problem?