py32l020-adc-battery-monitor-4.ino

M5Stamp Timer Power 2 (PY32L020) · Fichier : py32l020-adc-battery-monitor-4.ino · Langage : C · Usage : Surveiller la tension de la batterie LiPo en temps réel via l'ADC interne pour déclencher une alerte de batterie faible.

Cet exemple lit le canal ADC lié à la batterie pour estimer le pourcentage de charge et gérer les seuils critiques.

Utilise le module ADC du PY32L020. Vérifiez le schéma pour identifier la broche exacte reliée au BAT+ (souvent divisée par un pont diviseur). Assurez-vous que l'ADC est activé dans le reglage clock. L'exécution est périodique pour éviter une consommation permanente si combiné avec un 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);
}

← Retour à la fiche