pdf-icon

Arduino入門

2. デバイス&サンプル

Air Quality バッテリーレベルデータの取得

Air Quality のバッテリー残量に関する API とサンプルプログラム。

サンプルプログラム

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 参照電圧
static constexpr int ADC_RESOLUTION = 4095;   // 12ビット分解能 (0~4095)
static constexpr float DIVIDER      = 2.0f;   // 分圧比

void setup() {
  // 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() {
  // ADC を一度読み取る
  int raw = analogRead(BAT_PIN);
  // 電圧を計算: raw/4095 * 3.3 * 2
  float vb = (raw / float(ADC_RESOLUTION)) * VREF * DIVIDER;

  // 結果を画面に表示
  M5.Display.fillScreen(TFT_BLACK);
  M5.Display.setCursor(10, 20);
  M5.Display.printf("Battery:\n%.2f V", vb);

  // 毎秒更新
  delay(5000);
  M5.update();
}

アップロード後、以下のように表示されます:

On This Page