pdf-icon

Arduino Quick Start

2. Devices & Examples

Air Quality Battery Level Data Retrieval

Air Quality battery-level related API and example program.

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
#include <M5Unified.h>
static constexpr int BAT_PIN = 14;
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 ratio
void setup() {
// initialize M5Unified
M5.begin();
analogSetPinAttenuation(BAT_PIN, ADC_11db);
M5.Display.clear(TFT_BLACK);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.setTextSize(3);
}
void loop() {
// read ADC once
int raw = analogRead(BAT_PIN);
// calculate voltage: raw/4095 * 3.3 * 2
float vb = (raw / float(ADC_RESOLUTION)) * VREF * DIVIDER;
// display the result on the screen
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setCursor(10, 20);
M5.Display.printf("Battery:\n%.2f V", vb);
// update every second
delay(5000);
M5.update();
}

After uploading, you will see the following effect:

On This Page