|
以下示例展示如何将电池电量按百分比分4段显示
已知5306的IIC地址为0x75,寄存器地址0x78为查询电量百分比,具体函数在M5Stack的库中查看Power.cpp,颜色显示采用了RGB565的方式
[mw_shl_code=arduino,true]#include <M5Stack.h>
#define RGB(r,g,b) (int16_t)(b + (g << 5) + (r << 11)) //RGB888转RGB565
unsigned long currentMillis;
unsigned long lastupdateMillis = 0;
int lastbattery = -1;
void displayBatteryLevel()
{
if (currentMillis - lastupdateMillis > 1000) {
int battlevel = 0;
byte retval;
Wire.beginTransmission(0x75);
Wire.write(0x78);
if (Wire.endTransmission(false) == 0 && Wire.requestFrom(0x75, 1)) {
retval = Wire.read() & 0xF0;
if (retval == 0xE0) battlevel = 25;
else if (retval == 0xC0) battlevel = 50;
else if (retval == 0x80) battlevel = 75;
else if (retval == 0x00) battlevel = 100;
}
if (lastbattery != battlevel){
M5.Lcd.fillRect(250, 5, 56, 21, RGB(31, 63, 31));
M5.Lcd.fillRect(306, 9, 4, 13, RGB(31, 63, 31));
M5.Lcd.fillRect(252, 7, 52, 17, RGB(0, 0, 0));
if (battlevel <= 25)
M5.Lcd.fillRect(253, 8, battlevel/2, 15, RGB(31, 20, 10));
else
M5.Lcd.fillRect(253, 8, battlevel/2, 15, RGB(20, 40, 31));
lastbattery = battlevel;
}
lastupdateMillis = currentMillis;
}
}
void setup() {
M5.begin();
Wire.begin();
M5.Lcd.clear();
}
void loop() {
currentMillis = millis();
displayBatteryLevel();
}[/mw_shl_code]
|
|