pdf-icon

Arduino Quick Start

2. Devices & Examples

DinMeter Battery Level Data Detect

DinMeter battery level related API and example.

Example

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <M5Unified.h>

static constexpr int BAT_PIN         = G10;      // DinMeter battery sensing pin
static constexpr float VREF         = 3.3f;     // ADC reference voltage
static constexpr int ADC_RESOLUTION = 4095;     // 12‑bit resolution (0–4095)
static constexpr float DIVIDER      = 2.0f;     // Voltage divider factor

void setup() {
  // Initialize M5Unified (includes Display, buttons, RTC, power management, etc.)
  auto cfg = M5.config();
  M5.begin(cfg);

  // Set ADC attenuation for battery pin to achieve full‑scale reading
  analogSetPinAttenuation(BAT_PIN, ADC_11db);

  // Initialize Display
  M5.Display.fillScreen(TFT_BLACK);
  M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
  M5.Display.setTextSize(2);
}

void loop() {
  // Read raw ADC value
  int raw = analogRead(BAT_PIN);
  // Calculate actual voltage: (raw/4095) * 3.3V * 2
  float vb = (raw / float(ADC_RESOLUTION)) * VREF * DIVIDER;

  // Display voltage
  M5.Display.fillScreen(TFT_BLACK);
  M5.Display.setCursor(10, 20);
  M5.Display.printf("Battery:\n%.2f V", vb);

  // Update every 5 seconds
  delay(5000);
  M5.update();
}

After uploading, you can see the following effect:

On This Page