py32l020-adc-battery-monitor-4.ino
This example reads the battery ADC channel to estimate charge percentage and handle critical thresholds.
Uses the PY32L020 ADC module. Check the schematic to identify the exact pin connected to BAT+ (often via a voltage divider). Ensure the ADC is enabled in clock settings. Execution is periodic to avoid permanent consumption if combined with deep sleep.
py32l020-adc-battery-monitor-4.ino
/*
* M5Stamp Timer Power 2 (PY32L020) - ADC Battery Monitor
* Platform: Arduino (Core for PY32L020) or bare-metal C
* Connect: BAT+ to PY_VBAT or specific ADC pin depending on schematic revision
*/
#include <Arduino.h>
// Assuming ADC channel for Battery Voltage based on typical PY32L020 eval board
// Check specific datasheet for Pin Mapping (often PA4 or similar)
#define BATTERY_ADC_PIN A0
#define ADC_RESOLUTION_BITS 12
#define VREF_MV 3300.0
#define MAX_ADC_VALUE 4095
#define DIVIDER_RATIO 2.0 // Check schematic: is there a voltage divider? Assume 2:1 for 3.7V -> 1.85V max
void setup() {
Serial.begin(115200);
// Configure ADC pin as input
pinMode(BATTERY_ADC_PIN, INPUT);
// Optional: Set ADC resolution if supported by core
// analogReadResolution(ADC_RESOLUTION_BITS);
}
void loop() {
int rawAdc = analogRead(BATTERY_ADC_PIN);
// Convert to voltage at the ADC pin
float voltageAtPin = (rawAdc / (float)MAX_ADC_VALUE) * VREF_MV / 1000.0;
// Calculate actual battery voltage considering divider
float batteryVoltage = voltageAtPin * DIVIDER_RATIO;
// Simple percentage estimation (LiPo range approx 3.0V to 4.2V)
int batteryLevel = constrain((int)((batteryVoltage - 3.0) / (4.2 - 3.0) * 100), 0, 100);
Serial.printf("Raw ADC: %d, Batt: %.2f V, Level: %d%%\n", rawAdc, batteryVoltage, batteryLevel);
if (batteryVoltage < 3.3) {
Serial.println("WARNING: Battery Low!");
// Trigger IRQ or LED warning here
}
delay(5000);
}