My goal: make the "M5" button behave like the power button.
The "M5" button is more user friendly.
This code runs once, puts the M5Stick C Plus into deep sleep, then the "M5" button wakes it up:
#include <M5StickCPlus.h>
//seconds
const int timeout = 10;
hw_timer_t * timer = NULL;
bool go_to_sleep = false;
void IRAM_ATTR onTimer()
{
Serial.println("onTimer called");
go_to_sleep = true;
}
void setup() {
sleep_wake();
M5.begin();
M5.Lcd.fillScreen(BLACK);
set_backlight();
setCpuFrequencyMhz(80);
timer = timerBegin(0, 80, true);
timerAttachInterrupt(timer, &onTimer, true);
timerAlarmWrite(timer, timeout * 1000 * 1000, true);
timerAlarmEnable(timer);
M5.Lcd.setCursor(0, 35, 4);
battery_display();
}
void loop() {
delay(1000);
sleep_check();
}
void sleep_check(void)
{
if(go_to_sleep == true) {
deep_sleep();
}
}
void set_backlight(void)
{
M5.Axp.ScreenBreath(8);
}
void clear_txt(void)
{
M5.Lcd.fillScreen(BLACK);
}
void battery_display(void)
{
M5.Lcd.setCursor(20, 20, 4);
M5.Lcd.setTextSize(2);
M5.Lcd.printf("%d%%", (int) battery_level());
M5.Lcd.print("\n");
M5.Lcd.setTextSize(1);
M5.Lcd.printf("%fV", M5.Axp.GetBatVoltage());
}
double battery_level(void)
{
uint16_t vbatData = M5.Axp.GetVbatData();
double vbat = vbatData * 1.1 / 1000;
double percentage = 100.0 * ((vbat - 3.0) / (4.07 - 3.0));
return min(percentage, 100);
}
void sleep_wake(void)
{
pinMode(GPIO_NUM_37, INPUT_PULLUP);
esp_sleep_enable_ext0_wakeup(GPIO_NUM_37, LOW);
}
void backlight_off(void)
{
delay(1000);
M5.Axp.ScreenBreath(0);
}
void deep_sleep(void) {
clear_txt();
M5.Lcd.setCursor(0, 30, 2);
M5.Lcd.printf("Deep sleep\n");
delay(1000);
clear_txt();
backlight_off();
delay(3900);
clear_txt();
// if I use this function, I can't wake it up with the M5 button anymore
// M5.Axp.DeepSleep();
// this works
esp_deep_sleep_start();
}
Right now it does nothing, it only prints the battery level and goes to sleep after 10 seconds.
If I unplug the device when fully charged (4.1V), then press the "M5" button once in a while (less than once an hour), I noticed a battery life of about 12 hours, which is way too little.
I imagine that if I actually make it do stuff (like connecting to WiFi and perform a HTTP request), it would last even less.
Is this correct? Can I improve it somehow?
Thanks