m5stackで組込み!!

Arduinoによるm5stack開発のいろいろと...

電池の残量を表示

今回は電池の残量を表示をしてみましょう。

初期化

電源関係の初期化はM5.begin()では行っていないのでこちらの関数で初期化しましょう。
私は初期化を忘れてかなりの時間、正しい電池残量を取得出来てませんでした。。。

  M5.Power.begin();


さらに自身のM5stackが電源関係の制御できるかこちらの関数で確認できます。
trueが戻り値で返ってきたら制御できます。

  M5.Power.canControl();


電池残量を取得する関数はこちらです。戻り値に残量のパーセンテージが返ってきます。

  M5.Power.getBatteryLevel();

サンプルコード

#include <M5Stack.h>

static int giBattery = 0;
static int giBatteryOld = 0xFF;

void setup() {
  M5.begin();
  M5.Power.begin();
  if(!M5.Power.canControl()) {
    //can't control.
    M5.Lcd.print("NG");
    return;
  }
}
void loop() {

  giBattery = M5.Power.getBatteryLevel();
  M5.Lcd.setCursor(0, 0);
  M5.Lcd.printf("%3d \%",giBattery);

  if( giBatteryOld != giBattery )
  {
    // 電池へそ
    M5.Lcd.drawRoundRect(40,75,25,50,5,WHITE);
    M5.Lcd.fillRoundRect(40,75,25,50,5,WHITE);
    // 大外枠
    M5.Lcd.drawRoundRect(60,50,200,100,5,WHITE);
    M5.Lcd.fillRoundRect(60,50,200,100,5,WHITE);
    // 10%以下
    if( giBattery <= 10 )
    {
      M5.Lcd.drawRect(210,55,40,90,RED);
      M5.Lcd.fillRect(210,55,40,90,RED);
    }
    else
    {
      M5.Lcd.drawRect(210,55,40,90,BLACK);
      M5.Lcd.fillRect(210,55,40,90,BLACK);
    }
    // 50%以上
    if( giBattery >= 50 )
    {
      M5.Lcd.drawRect(165,55,40,90,BLACK);
      M5.Lcd.fillRect(165,55,40,90,BLACK);
    }
    // 75%以上
    if( giBattery >= 75 )
    {
      M5.Lcd.drawRect(120,55,40,90,BLACK);
      M5.Lcd.fillRect(120,55,40,90,BLACK);
    }
    // 90%以上
    if( giBattery >= 90 )
    {
      M5.Lcd.drawRect(75,55,40,90,BLACK);
      M5.Lcd.fillRect(75,55,40,90,BLACK);
    }
  }
  // 前回値更新
  giBatteryOld = giBattery;
}

電池っぽいな