I just received my XIAO BLE Sense board and was disappointed to see this thread indicating problems reading the battery voltage.
I note that the return value trying analogRead from P0_31 is 0xFFFFFFFF, which is the traditional return value when trying to do an analogRead from a pin not connected to an ADC input.
So, poking around in the pins_arduino.h file in the variants directory for this board, I found the following:
#define PIN_VBAT (32u)
I decided to try PIN_VBAT in my analogRead, and, guess what?
Taa-daa!
Here’s my test sketch:
/*
* Test to read a LiPo battery connected to VBAT on the
* underside of XIAO BLE boards.
*
* Note that the ADC input from the VBAT voltage divider is
* NOT pin P0_31 as shown on the schematic!
*
* March, 2022
* davekw7x
*/
// For mbed compilers, the following allows us to use the
// standard printf() function.
REDIRECT_STDOUT_TO(Serial)
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
while (!Serial)
;
printf("\nBattery Test compiled by davekw7x on %s at %s\n", __DATE__, __TIME__);
printf("Note: PIN_VBAT = %u\n\n", PIN_VBAT);
pinMode(P0_14, OUTPUT);
digitalWrite(P0_14, LOW);
} // End of setup()
const double vRef = 3.3; // Assumes 3.3V regulator output is ADC reference voltage
const unsigned int numReadings = 1024; // 10-bit ADC readings 0-1023, so the factor is 1024
void loop()
{
unsigned int adcCount = analogRead(PIN_VBAT);
double adcVoltage = (adcCount * vRef) / numReadings;
double vBat = adcVoltage*1510.0/510.0; // Voltage divider from Vbat to ADC
printf("adcCount = %3u = 0x%03X, adcVoltage = %.3fV, vBat = %.3f\n",
adcCount, adcCount, adcVoltage, vBat);
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
delay(1000);
} // End of loop()
And here’s the output, consistent with my very freshly charged LiPo battery:
Regards,
Dave