Обновить скетч manual monitor LVGL v2

This commit is contained in:
AidarKC
2026-10-16 19:56:04 +03:00
parent ae6ee5361e
commit 5ca602852f
@@ -12,7 +12,7 @@
void setup(); void setup();
void loop(); void loop();
// Dedicated LVGL v2 of the manual two-button breath monitor. // Manual Monitor LVGL V3.2: keep display awake when leaving settings with KEY1.
#define PIN_LCD_CS 12 #define PIN_LCD_CS 12
#define PIN_LCD_SCLK 38 #define PIN_LCD_SCLK 38
#define PIN_LCD_D0 4 #define PIN_LCD_D0 4
@@ -33,7 +33,7 @@ void loop();
#define PIN_I2S_MCLK 42 #define PIN_I2S_MCLK 42
static constexpr uint16_t DISP_W = 480, DISP_H = 480; static constexpr uint16_t DISP_W = 480, DISP_H = 480;
static constexpr uint32_t LVGL_TICK_MS = 2, UI_MS = 120, HOLD_PAUSE_MS = 1200; static constexpr uint32_t LVGL_TICK_MS = 2, UI_MS = 120;
static constexpr uint32_t DEBOUNCE_MS = 45, BATT_MS = 5000; static constexpr uint32_t DEBOUNCE_MS = 45, BATT_MS = 5000;
static constexpr uint32_t QUIET_START_MS = 30000, LOUD_START_MS = 60000; static constexpr uint32_t QUIET_START_MS = 30000, LOUD_START_MS = 60000;
static constexpr uint32_t SLOW_LOUD_MS = 90000, POWER_OFF_MS = 390000; static constexpr uint32_t SLOW_LOUD_MS = 90000, POWER_OFF_MS = 390000;
@@ -55,16 +55,20 @@ static Button gInhale{PIN_INHALE}, gExhale{PIN_EXHALE};
enum class Screen : uint8_t { Home, Monitor, Settings }; enum class Screen : uint8_t { Home, Monitor, Settings };
static Screen gScreen = Screen::Home; static Screen gScreen = Screen::Home;
static bool gPowerReady = false, gAudioReady = false, gTouchDown = false; static bool gPowerReady = false, gAudioReady = false, gTouchDown = false;
static bool gScreenOn = true, gPaused = false, gHaveInhale = false; static uint32_t gLastPowerLong = 0;
static uint32_t gPauseStarted = 0, gPhaseStarted = 0, gCycleStarted = 0, gLastActivity = 0, gLastUi = 0, gLastBatt = 0, gLastReminder = 0; static uint32_t gKey1WakeUntil = 0;
static bool gScreenOn = true, gPaused = false;
enum class BreathState : uint8_t { Waiting, Inhale, Exhale };
static BreathState gBreath = BreathState::Waiting;
static uint64_t gCompletedMs = 0;
static uint32_t gPhaseStarted = 0, gCycleStarted = 0, gLastActivity = 0, gLastUi = 0, gLastBatt = 0, gLastReminder = 0;
static uint8_t gLimit = 2, gTick = 3, gAlert = 10, gScreenTimeout = 1; static uint8_t gLimit = 2, gTick = 3, gAlert = 10, gScreenTimeout = 1;
static uint32_t gCycles[5] = {}; static uint8_t gCycleCount = 0, gCycleNext = 0, gShortStreak = 0; static uint32_t gCycles[5] = {}; static uint8_t gCycleCount = 0, gCycleNext = 0, gShortStreak = 0;
static lv_disp_draw_buf_t gDrawBuf; static lv_color_t *gBuf1 = nullptr, *gBuf2 = nullptr; static lv_disp_draw_buf_t gDrawBuf; static lv_color_t *gBuf1 = nullptr, *gBuf2 = nullptr;
static lv_obj_t *gRoot = nullptr, *gPhase = nullptr, *gPhaseValue = nullptr, *gAverage = nullptr, *gAverageValue = nullptr; static lv_obj_t *gRoot=nullptr, *gState=nullptr, *gPhaseTime=nullptr, *gCycleValue=nullptr;
static lv_obj_t *gElapsedValue = nullptr, *gLimitValue = nullptr, *gLastFive = nullptr, *gState = nullptr; static lv_obj_t *gAverageValue=nullptr, *gElapsedValue=nullptr, *gLimitValue=nullptr;
static lv_obj_t *gBatteryText = nullptr, *gBatteryFill = nullptr, *gBolt = nullptr; static lv_obj_t *gHistory[5]={}, *gPausedBanner=nullptr;
static bool gDirectNumbersPending = false; static lv_obj_t *gBatteryText=nullptr, *gBatteryFill=nullptr, *gBolt=nullptr;
static char gDirectPhase[16] = "0.0 s", gDirectAverage[16] = "--", gDirectElapsed[12] = "00:00", gDirectLimit[16] = "10.0 s";
static lv_color_t color(uint32_t c) { return lv_color_hex(c); } static lv_color_t color(uint32_t c) { return lv_color_hex(c); }
static void flush(lv_disp_drv_t *d, const lv_area_t *a, lv_color_t *p) { static void flush(lv_disp_drv_t *d, const lv_area_t *a, lv_color_t *p) {
@@ -76,6 +80,15 @@ static void flush(lv_disp_drv_t *d, const lv_area_t *a, lv_color_t *p) {
#endif #endif
lv_disp_flush_ready(d); lv_disp_flush_ready(d);
} }
// CO5300 QSPI: align LVGL partial-refresh rectangles to whole RGB565 pixel pairs.
// This prevents odd-width transfer regions from potentially shifting successive rows.
static void rounder(lv_disp_drv_t *d, lv_area_t *a) {
(void)d;
a->x1 &= ~1;
a->x2 |= 1;
if (a->x1 < 0) a->x1 = 0;
if (a->x2 >= DISP_W) a->x2 = DISP_W - 1;
}
static void tick(void *) { lv_tick_inc(LVGL_TICK_MS); } static void tick(void *) { lv_tick_inc(LVGL_TICK_MS); }
static void touchRead(lv_indev_drv_t *, lv_indev_data_t *d) { static void touchRead(lv_indev_drv_t *, lv_indev_data_t *d) {
int16_t x=0,y=0; bool down = gTouch.getPoint(&x,&y,1)>0; int16_t x=0,y=0; bool down = gTouch.getPoint(&x,&y,1)>0;
@@ -96,28 +109,176 @@ static void fmt(char *out,size_t n,uint32_t ms) { snprintf(out,n,"%lu.%01lu s",(
static uint32_t average() { uint64_t total=0; for(uint8_t i=0;i<gCycleCount;i++) total+=gCycles[i]; return gCycleCount ? (uint32_t)((total+gCycleCount/2)/gCycleCount) : 0; } static uint32_t average() { uint64_t total=0; for(uint8_t i=0;i<gCycleCount;i++) total+=gCycles[i]; return gCycleCount ? (uint32_t)((total+gCycleCount/2)/gCycleCount) : 0; }
static void loadSettings() { gPrefs.begin("manual-lvgl",false); gLimit=min<uint8_t>(4,gPrefs.getUChar("limit",2)); gTick=min<uint8_t>(10,gPrefs.getUChar("tick",3)); gAlert=min<uint8_t>(10,gPrefs.getUChar("alert",10)); gScreenTimeout=min<uint8_t>(3,gPrefs.getUChar("screen",1)); } static void loadSettings() { gPrefs.begin("manual-lvgl",false); gLimit=min<uint8_t>(4,gPrefs.getUChar("limit",2)); gTick=min<uint8_t>(10,gPrefs.getUChar("tick",3)); gAlert=min<uint8_t>(10,gPrefs.getUChar("alert",10)); gScreenTimeout=min<uint8_t>(3,gPrefs.getUChar("screen",1)); }
static void saveSettings() { gPrefs.putUChar("limit",gLimit); gPrefs.putUChar("tick",gTick); gPrefs.putUChar("alert",gAlert); gPrefs.putUChar("screen",gScreenTimeout); } static void saveSettings() { gPrefs.putUChar("limit",gLimit); gPrefs.putUChar("tick",gTick); gPrefs.putUChar("alert",gAlert); gPrefs.putUChar("screen",gScreenTimeout); }
static void initPower() { gPowerReady=gPower.begin(Wire,AXP2101_SLAVE_ADDRESS,PIN_I2C_SDA,PIN_I2C_SCL); if(!gPowerReady)return; gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); gPower.setChargeTargetVoltage(3); gPower.clearIrqStatus(); gPower.enableBattDetection(); gPower.enableBattVoltageMeasure(); gPower.enableVbusVoltageMeasure(); } static void initPower() { gPowerReady=gPower.begin(Wire,AXP2101_SLAVE_ADDRESS,PIN_I2C_SDA,PIN_I2C_SCL); if(!gPowerReady)return; gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); gPower.setChargeTargetVoltage(3); gPower.setPowerKeyPressOffTime(XPOWERS_POWEROFF_10S);
// AXP2101 IRQ hold threshold: 0=1s, 1=1.5s, 2=2s, 3=2.5s (reg 0x27, bits 5:4).
Wire.beginTransmission(AXP2101_SLAVE_ADDRESS); Wire.write(0x27);
if(Wire.endTransmission(false)==0 && Wire.requestFrom((uint8_t)AXP2101_SLAVE_ADDRESS,(uint8_t)1)==1){
uint8_t reg=Wire.read(); Wire.beginTransmission(AXP2101_SLAVE_ADDRESS);
Wire.write(0x27);Wire.write((uint8_t)((reg & ~0x30u)|0x10u));Wire.endTransmission();
}
gPower.clearIrqStatus(); gPower.enableIRQ(XPOWERS_AXP2101_PKEY_SHORT_IRQ | XPOWERS_AXP2101_PKEY_LONG_IRQ); gPower.enableBattDetection(); gPower.enableBattVoltageMeasure(); gPower.enableVbusVoltageMeasure(); }
static int battery() { if(!gPowerReady || !gPower.isBatteryConnect())return -1; int percent=constrain(gPower.getBatteryPercent(),0,100); uint16_t mv=gPower.getBattVoltage(); if(percent==0 && mv>=3300) return constrain((int)((mv-3300UL)*100UL/900UL),1,100); return percent; } static int battery() { if(!gPowerReady || !gPower.isBatteryConnect())return -1; int percent=constrain(gPower.getBatteryPercent(),0,100); uint16_t mv=gPower.getBattVoltage(); if(percent==0 && mv>=3300) return constrain((int)((mv-3300UL)*100UL/900UL),1,100); return percent; }
static void initAudio() { pinMode(PIN_PA,OUTPUT); digitalWrite(PIN_PA,HIGH); gI2s.setPins(PIN_I2S_BCLK,PIN_I2S_LRCK,PIN_I2S_DOUT,PIN_I2S_DIN,PIN_I2S_MCLK); if(!gI2s.begin(I2S_MODE_STD,16000,I2S_DATA_BIT_WIDTH_16BIT,I2S_SLOT_MODE_STEREO,I2S_STD_SLOT_BOTH))return; es8311_handle_t h=es8311_create(0,ES8311_ADDRRES_0); if(!h)return; es8311_clock_config_t c={false,false,true,4096000,16000}; gAudioReady=es8311_init(h,&c,ES8311_RESOLUTION_16,ES8311_RESOLUTION_16)==ESP_OK; if(gAudioReady){es8311_voice_volume_set(h,100,nullptr);es8311_voice_mute(h,false);} } static void initAudio() { pinMode(PIN_PA,OUTPUT); digitalWrite(PIN_PA,HIGH); gI2s.setPins(PIN_I2S_BCLK,PIN_I2S_LRCK,PIN_I2S_DOUT,PIN_I2S_DIN,PIN_I2S_MCLK); if(!gI2s.begin(I2S_MODE_STD,16000,I2S_DATA_BIT_WIDTH_16BIT,I2S_SLOT_MODE_STEREO,I2S_STD_SLOT_BOTH))return; es8311_handle_t h=es8311_create(0,ES8311_ADDRRES_0); if(!h)return; es8311_clock_config_t c={false,false,true,4096000,16000}; gAudioReady=es8311_init(h,&c,ES8311_RESOLUTION_16,ES8311_RESOLUTION_16)==ESP_OK; if(gAudioReady){es8311_voice_volume_set(h,100,nullptr);es8311_voice_mute(h,false);} }
static void beep(uint16_t hz,uint16_t count,int16_t amp) { if(!gAudioReady||amp<=0)return; static int16_t buf[1600*2]; count=min<uint16_t>(count,1600); for(uint16_t i=0;i<count;i++){int16_t v=(int16_t)(sinf(6.2831853f*hz*i/16000.0f)*amp);buf[i*2]=v;buf[i*2+1]=v;} gI2s.write((uint8_t *)buf,count*4); } static void beep(uint16_t hz,uint16_t count,int16_t amp) { if(!gAudioReady||amp<=0)return; static int16_t buf[1600*2]; count=min<uint16_t>(count,1600); for(uint16_t i=0;i<count;i++){int16_t v=(int16_t)(sinf(6.2831853f*hz*i/16000.0f)*amp);buf[i*2]=v;buf[i*2+1]=v;} gI2s.write((uint8_t *)buf,count*4); }
static void quiet() { beep(880,480,TICK_VOLUME[gTick]); } static void loud(){beep(1200,1600,ALERT_VOLUME[gAlert]);} static void quiet() { beep(880,480,TICK_VOLUME[gTick]); } static void loud(){beep(1200,1600,ALERT_VOLUME[gAlert]);}
static void batteryUi() { if(!gBatteryText)return; int p=battery(); char t[8]; snprintf(t,sizeof(t),p<0?"--":"%d%%",p); lv_label_set_text(gBatteryText,t); if(gBatteryFill)lv_obj_set_width(gBatteryFill,p>0?max(2,min(26,p*26/100)):0); if(gBolt)lv_obj_set_style_opa(gBolt,(gPowerReady&&gPower.isCharging())?LV_OPA_COVER:LV_OPA_TRANSP,0); } static void batteryUi() { if(!gBatteryText)return; int p=battery(); char t[8]; snprintf(t,sizeof(t),p<0?"--":"%d%%",p); lv_label_set_text(gBatteryText,t); if(gBatteryFill)lv_obj_set_width(gBatteryFill,p>0?max(2,min(26,p*26/100)):0); if(gBolt)lv_obj_set_style_opa(gBolt,(gPowerReady&&gPower.isCharging())?LV_OPA_COVER:LV_OPA_TRANSP,0); }
static void topBar(const char *title) { label(gRoot,title,&lv_font_montserrat_24,0xFFFFFF); lv_obj_align(lv_obj_get_child(gRoot,0),LV_ALIGN_TOP_LEFT,26,20); gBatteryText=label(gRoot,"--",&lv_font_montserrat_16,0xC9D3DE); lv_obj_set_pos(gBatteryText,297,22); if(gPowerReady){static const lv_point_t bolt[]={{6,0},{1,9},{5,9},{2,18},{10,7},{6,7}};gBolt=lv_line_create(gRoot);lv_line_set_points(gBolt,bolt,6);lv_obj_set_pos(gBolt,337,17);lv_obj_set_style_line_width(gBolt,2,0);lv_obj_set_style_line_color(gBolt,color(0xFFD34D),0);lv_obj_set_style_line_rounded(gBolt,true,0);} lv_obj_t *b=lv_obj_create(gRoot);lv_obj_set_pos(b,349,24);lv_obj_set_size(b,32,16);lv_obj_set_style_bg_opa(b,LV_OPA_TRANSP,0);lv_obj_set_style_border_color(b,color(0xC9D3DE),0);lv_obj_set_style_border_width(b,2,0);lv_obj_set_style_radius(b,4,0);lv_obj_clear_flag(b,LV_OBJ_FLAG_SCROLLABLE); lv_obj_t *cap=lv_obj_create(gRoot);lv_obj_set_pos(cap,381,28);lv_obj_set_size(cap,4,8);lv_obj_set_style_bg_color(cap,color(0xC9D3DE),0);lv_obj_set_style_border_width(cap,0,0);lv_obj_set_style_radius(cap,2,0); gBatteryFill=lv_obj_create(gRoot);lv_obj_set_pos(gBatteryFill,352,27);lv_obj_set_size(gBatteryFill,2,10);lv_obj_set_style_bg_color(gBatteryFill,color(0x38B26D),0);lv_obj_set_style_border_width(gBatteryFill,0,0);lv_obj_set_style_radius(gBatteryFill,2,0); batteryUi(); } static void topBar(const char *title) { label(gRoot,title,&lv_font_montserrat_24,0xFFFFFF); lv_obj_align(lv_obj_get_child(gRoot,0),LV_ALIGN_TOP_LEFT,26,49); gBatteryText=label(gRoot,"--",&lv_font_montserrat_16,0xC9D3DE); lv_obj_set_pos(gBatteryText,297,51); if(gPowerReady){static const lv_point_t bolt[]={{6,0},{1,9},{5,9},{2,18},{10,7},{6,7}};gBolt=lv_line_create(gRoot);lv_line_set_points(gBolt,bolt,6);lv_obj_set_pos(gBolt,337,46);lv_obj_set_style_line_width(gBolt,2,0);lv_obj_set_style_line_color(gBolt,color(0xFFD34D),0);lv_obj_set_style_line_rounded(gBolt,true,0);} lv_obj_t *b=lv_obj_create(gRoot);lv_obj_set_pos(b,349,53);lv_obj_set_size(b,32,16);lv_obj_set_style_bg_opa(b,LV_OPA_TRANSP,0);lv_obj_set_style_border_color(b,color(0xC9D3DE),0);lv_obj_set_style_border_width(b,2,0);lv_obj_set_style_radius(b,4,0);lv_obj_clear_flag(b,LV_OBJ_FLAG_SCROLLABLE); lv_obj_t *cap=lv_obj_create(gRoot);lv_obj_set_pos(cap,381,57);lv_obj_set_size(cap,4,8);lv_obj_set_style_bg_color(cap,color(0xC9D3DE),0);lv_obj_set_style_border_width(cap,0,0);lv_obj_set_style_radius(cap,2,0); gBatteryFill=lv_obj_create(gRoot);lv_obj_set_pos(gBatteryFill,352,56);lv_obj_set_size(gBatteryFill,2,10);lv_obj_set_style_bg_color(gBatteryFill,color(0x38B26D),0);lv_obj_set_style_border_width(gBatteryFill,0,0);lv_obj_set_style_radius(gBatteryFill,2,0); batteryUi(); }
static void clearUi() { lv_obj_clean(lv_scr_act()); gRoot=lv_scr_act(); lv_obj_set_style_bg_color(gRoot,color(0x08111B),0);lv_obj_set_style_bg_opa(gRoot,LV_OPA_COVER,0);lv_obj_set_style_pad_all(gRoot,0,0); gBatteryText=gBatteryFill=gBolt=nullptr; } static void clearUi() { lv_obj_clean(lv_scr_act()); gRoot=lv_scr_act(); lv_obj_set_style_bg_color(gRoot,color(0x08111B),0);lv_obj_set_style_bg_opa(gRoot,LV_OPA_COVER,0);lv_obj_set_style_pad_all(gRoot,0,0); gBatteryText=gBatteryFill=gBolt=nullptr; }
static void drawDirectNumber(int x,int y,int w,int h,const char *text,uint16_t textColor,uint8_t size) { gfx->fillRect(x+2,y+2,w-4,h-4,0x142331); gfx->setFont(); gfx->setTextSize(size); gfx->setTextColor(textColor); int tx=x+(w-(int)strlen(text)*6*size)/2; gfx->setCursor(max(x+6,tx),y+(h-8*size)/2+7*size); gfx->print(text); } static void legend() {
static void drawDirectNumbers() { if(!gDirectNumbersPending || gScreen!=Screen::Monitor || !gScreenOn)return; drawDirectNumber(24,202,204,88,gDirectPhase,0xFFFF,4); drawDirectNumber(252,202,204,88,gDirectAverage,0xFFFF,4); drawDirectNumber(24,306,204,72,gDirectElapsed,0xFFFF,4); drawDirectNumber(252,306,204,72,gDirectLimit,0xFFE0,4); gDirectNumbersPending=false; } lv_obj_t *l=label(gRoot,"INHALE",&lv_font_montserrat_14,0x38B26D);lv_obj_set_pos(l,24,12);
static void enterMonitor(lv_event_t *) { gScreen=Screen::Monitor; gLastActivity=millis(); clearUi(); topBar("MANUAL MONITOR"); lv_obj_t *hero=panel(24,72,432,112,0x102A36); gState=label(hero,"READY",&lv_font_montserrat_28,0x4FB3FF);lv_obj_align(gState,LV_ALIGN_TOP_MID,0,18); lv_obj_t *hint=label(hero,"KEY2: INHALE KEY3: EXHALE",&lv_font_montserrat_14,0xB8C7D2);lv_obj_align(hint,LV_ALIGN_BOTTOM_MID,0,-17); lv_obj_t *a=panel(24,202,204,88);gPhaseValue=label(a,"",&lv_font_montserrat_32,0xFFFFFF); lv_obj_t *b=panel(252,202,204,88);gAverageValue=label(b,"",&lv_font_montserrat_32,0xFFFFFF); lv_obj_t *c=panel(24,306,204,72);gElapsedValue=label(c,"",&lv_font_montserrat_28,0xFFFFFF); lv_obj_t *d=panel(252,306,204,72);gLimitValue=label(d,"",&lv_font_montserrat_28,0xFFD34D); lv_obj_t *last=panel(24,394,432,60);gLastFive=label(last,"HISTORY: --",&lv_font_montserrat_16,0xD7E3EA);lv_obj_align(gLastFive,LV_ALIGN_CENTER,0,0); gDirectNumbersPending=true; } l=label(gRoot,"SETTINGS",&lv_font_montserrat_14,0xC9D3DE);lv_obj_align(l,LV_ALIGN_TOP_MID,0,12);
l=label(gRoot,"EXHALE",&lv_font_montserrat_14,0x4FB3FF);lv_obj_align(l,LV_ALIGN_TOP_RIGHT,-24,12);
}
static lv_obj_t *metric(int x,int y,const char *caption,uint32_t valueColor) {
lv_obj_t *p=panel(x,y,204,100);lv_obj_t *l=label(p,caption,&lv_font_montserrat_14,0x9EB4C2);
lv_obj_align(l,LV_ALIGN_TOP_MID,0,7);
l=label(p,"--",&lv_font_montserrat_28,valueColor);lv_obj_align(l,LV_ALIGN_CENTER,0,12);
return l;
}
static void enterMonitor(lv_event_t *) {
gScreen=Screen::Monitor;gLastActivity=millis();clearUi();legend();topBar("MANUAL MONITOR");
lv_obj_t *hero=panel(24,92,432,73,0x102A36);
gState=label(hero,"WAITING",&lv_font_montserrat_28,0x4FB3FF);
gPhaseTime=label(hero,"",&lv_font_montserrat_28,0xFFFFFF);
gCycleValue=metric(24,182,"CYCLE",0xFFFFFF);
gAverageValue=metric(252,182,"AVG 5",0xFFFFFF);
gElapsedValue=metric(24,298,"ELAPSED",0xFFFFFF);
gLimitValue=metric(252,298,"LIMIT",0xFFD34D);
lv_obj_t *history=panel(24,413,432,53);
lv_obj_t *title=label(history,"HISTORY",&lv_font_montserrat_14,0xC9D3DE);lv_obj_set_pos(title,7,3);
for(int i=0;i<5;i++){gHistory[i]=label(history,"--",&lv_font_montserrat_16,0xFFFFFF);
lv_obj_set_pos(gHistory[i],78+i*68,3);}
}
static void home(lv_event_t *); static void settings(lv_event_t *); static void home(lv_event_t *); static void settings(lv_event_t *);
static lv_obj_t *button(lv_obj_t *p,const char *text,int x,int y,int w,int h,uint32_t bg,lv_event_cb_t cb) { lv_obj_t *b=lv_btn_create(p);lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h);card(b,bg);lv_obj_add_event_cb(b,cb,LV_EVENT_CLICKED,nullptr);lv_obj_t *l=label(b,text,&lv_font_montserrat_20,0xFFFFFF);lv_obj_center(l);return b; } static lv_obj_t *button(lv_obj_t *p,const char *text,int x,int y,int w,int h,uint32_t bg,lv_event_cb_t cb) { lv_obj_t *b=lv_btn_create(p);lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h);card(b,bg);lv_obj_add_event_cb(b,cb,LV_EVENT_CLICKED,nullptr);lv_obj_t *l=label(b,text,&lv_font_montserrat_20,0xFFFFFF);lv_obj_center(l);return b; }
static void home(lv_event_t *) { gScreen=Screen::Home;clearUi();topBar("BREATH MONITOR");lv_obj_t *intro=panel(24,78,432,84,0x102A36);lv_obj_t *i=label(intro,"Two external buttons",&lv_font_montserrat_22,0xFFFFFF);lv_obj_align(i,LV_ALIGN_TOP_MID,0,14);i=label(intro,"Manual breathing cadence monitor",&lv_font_montserrat_14,0xB8C7D2);lv_obj_align(i,LV_ALIGN_BOTTOM_MID,0,-14);button(gRoot,"START MANUAL MONITOR",24,188,432,82,0x28775E,enterMonitor);button(gRoot,"SETTINGS",24,290,208,58,0x214D69,settings);button(gRoot,"ABOUT",248,290,208,58,0x403C68,[](lv_event_t *){});lv_obj_t *h=panel(24,374,432,70);i=label(h,"Hold EXHALE to pause / resume",&lv_font_montserrat_16,0xFFD34D);lv_obj_align(i,LV_ALIGN_TOP_MID,0,12);i=label(h,"Screen can turn off; measurement continues",&lv_font_montserrat_14,0xB8C7D2);lv_obj_align(i,LV_ALIGN_BOTTOM_MID,0,-12); } static void home(lv_event_t *) {enterMonitor(nullptr);}
static void settingChanged(lv_event_t *e){uint8_t *v=(uint8_t *)lv_event_get_user_data(e);*v=lv_slider_get_value(lv_event_get_target(e));saveSettings();} static void settingChanged(lv_event_t *e){uint8_t *v=(uint8_t *)lv_event_get_user_data(e);*v=lv_slider_get_value(lv_event_get_target(e));saveSettings();}
static void settings(lv_event_t *) {gScreen=Screen::Settings;clearUi();topBar("SETTINGS");lv_obj_t *list=lv_obj_create(gRoot);lv_obj_set_pos(list,20,68);lv_obj_set_size(list,440,352);card(list,0x10202D);lv_obj_set_style_pad_all(list,16,0);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN);lv_obj_set_style_pad_row(list,18,0);struct Item{const char *name;uint8_t *v;uint8_t max;};Item items[]={{"Breath limit",&gLimit,4},{"Cycle tick",&gTick,10},{"Alert volume",&gAlert,10},{"Screen timeout",&gScreenTimeout,3}};for(auto &it:items){lv_obj_t *row=lv_obj_create(list);lv_obj_set_size(row,400,66);card(row,0x172C3C);lv_obj_t *n=label(row,it.name,&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(n,12,8);lv_obj_t *s=lv_slider_create(row);lv_obj_set_pos(s,12,34);lv_obj_set_size(s,376,18);lv_slider_set_range(s,0,it.max);lv_slider_set_value(s,*it.v,LV_ANIM_OFF);lv_obj_add_event_cb(s,settingChanged,LV_EVENT_VALUE_CHANGED,it.v);}button(gRoot,"BACK",150,430,180,38,0x214D69,home);} static void refresh();
static void toggleSettingsFromKey(){ if(gScreen==Screen::Monitor) settings(nullptr); else if(gScreen==Screen::Settings) enterMonitor(nullptr); } static void settings(lv_event_t *) {
static void addCycle(uint32_t ms){gCycles[gCycleNext]=ms;gCycleNext=(gCycleNext+1)%5;if(gCycleCount<5)gCycleCount++;uint32_t a=average();if(a && a<LIMITS[gLimit]*1000UL){gShortStreak=min<uint8_t>(5,gShortStreak+1);for(uint8_t i=0;i<gShortStreak;i++){loud();delay(80);}}else gShortStreak=0;} gScreen=Screen::Settings;clearUi();legend();topBar("SETTINGS");
static void phase(bool inhale){uint32_t now=millis();if(gPaused)return;if(inhale){if(gHaveInhale)return;gHaveInhale=true;gPhaseStarted=now;if(!gCycleStarted)gCycleStarted=now;quiet();}else{if(!gHaveInhale)return;uint32_t cycle=now-gCycleStarted;addCycle(cycle);gHaveInhale=false;gCycleStarted=now;gPhaseStarted=now;quiet();}gLastReminder=now;} if(gPaused){gPausedBanner=label(gRoot,"PAUSED",&lv_font_montserrat_20,0xFFD34D);
static void togglePause(){uint32_t now=millis();if(!gPaused){gPaused=true;gPauseStarted=now;}else{uint32_t delta=now-gPauseStarted;if(gPhaseStarted)gPhaseStarted+=delta;if(gCycleStarted)gCycleStarted+=delta;gLastReminder+=delta;gPaused=false;}gLastActivity=now;} lv_obj_align(gPausedBanner,LV_ALIGN_TOP_MID,0,32);}
static void poll(Button &b,bool inhale){uint32_t now=millis();bool raw=digitalRead(b.pin)==LOW;if(raw!=b.raw){b.raw=raw;b.changed=now;}if(b.stable==b.raw||now-b.changed<DEBOUNCE_MS)return;b.stable=b.raw;if(b.stable){b.pressed=now;gLastActivity=now;if(!gScreenOn){gScreenOn=true;gfx->setBrightness(220);}if(gScreen==Screen::Monitor&&inhale)phase(true);return;}uint32_t held=now-b.pressed;if(inhale&&held>=HOLD_PAUSE_MS){toggleSettingsFromKey();return;}if(gScreen!=Screen::Monitor)return;if(!inhale&&held>=HOLD_PAUSE_MS)togglePause();else if(!inhale)phase(false);} lv_obj_t *list=lv_obj_create(gRoot);lv_obj_set_pos(list,20,91);lv_obj_set_size(list,440,334);
static void refresh(){if(gScreen!=Screen::Monitor)return;uint32_t now=millis(),phaseMs=gPhaseStarted&&!gPaused?now-gPhaseStarted:0;char s[100]; if(gPaused)lv_label_set_text(gState,"PAUSED");else if(!gHaveInhale)lv_label_set_text(gState,"WAITING FOR INHALE");else lv_label_set_text(gState,"INHALE - PRESS EXHALE");fmt(gDirectPhase,sizeof(gDirectPhase),phaseMs);uint32_t a=average();if(a)fmt(gDirectAverage,sizeof(gDirectAverage),a);else snprintf(gDirectAverage,sizeof(gDirectAverage),"--");snprintf(gDirectLimit,sizeof(gDirectLimit),"%u.%01u s",LIMITS[gLimit],0);uint32_t elapsed=gCycleStarted&&!gPaused?now-gCycleStarted:0;snprintf(gDirectElapsed,sizeof(gDirectElapsed),"%02lu:%02lu",(unsigned long)(elapsed/60000),(unsigned long)((elapsed/1000)%60));size_t used=snprintf(s,sizeof(s),"HISTORY:");for(uint8_t i=0;i<gCycleCount&&used<sizeof(s);i++){uint8_t j=(gCycleNext+5-gCycleCount+i)%5;used+=snprintf(s+used,sizeof(s)-used," %lu.%01lu",(unsigned long)(gCycles[j]/1000),(unsigned long)((gCycles[j]%1000)/100));}if(!gCycleCount)snprintf(s,sizeof(s),"HISTORY: --");lv_label_set_text(gLastFive,s);gDirectNumbersPending=true;} card(list,0x10202D);lv_obj_set_style_pad_all(list,10,0);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN);
static void reminders(){if(gScreen!=Screen::Monitor||gPaused||!gPhaseStarted)return;uint32_t now=millis(),age=now-gPhaseStarted;if(age<QUIET_START_MS||now-gLastReminder<((age<SLOW_LOUD_MS)?5000:15000))return;gLastReminder=now;if(age<LOUD_START_MS)quiet();else if(age<POWER_OFF_MS)loud();else{gfx->setBrightness(0);if(gPowerReady)gPower.shutdown();esp_deep_sleep_start();}} lv_obj_set_style_pad_row(list,9,0);
void setup(){Serial.begin(115200);Wire.begin(PIN_I2C_SDA,PIN_I2C_SCL);initPower();pinMode(PIN_INHALE,INPUT_PULLUP);pinMode(PIN_EXHALE,INPUT_PULLUP);initAudio();gfx->begin();gBus->writeC8D8(0x36,0xA0);gfx->setBrightness(220);gTouch.setPins(PIN_TP_INT,-1);gTouch.begin(Wire,0x5A,PIN_I2C_SDA,PIN_I2C_SCL);gTouch.setMaxCoordinates(DISP_W,DISP_H);gTouch.setSwapXY(true);gTouch.setMirrorXY(true,false);loadSettings();lv_init();gBuf1=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);gBuf2=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);lv_disp_draw_buf_init(&gDrawBuf,gBuf1,gBuf2,DISP_W*40);static lv_disp_drv_t dd;lv_disp_drv_init(&dd);dd.hor_res=DISP_W;dd.ver_res=DISP_H;dd.flush_cb=flush;dd.draw_buf=&gDrawBuf;lv_disp_drv_register(&dd);static lv_indev_drv_t id;lv_indev_drv_init(&id);id.type=LV_INDEV_TYPE_POINTER;id.read_cb=touchRead;lv_indev_drv_register(&id);const esp_timer_create_args_t ta={.callback=&tick,.name="lvgl_tick"};esp_timer_handle_t timer;esp_timer_create(&ta,&timer);esp_timer_start_periodic(timer,LVGL_TICK_MS*1000);gLastActivity=millis();home(nullptr);} struct Item{const char *name;uint8_t *v;uint8_t max;};
void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();}if(now-gLastBatt>=BATT_MS){gLastBatt=now;batteryUi();}uint32_t timeout=SCREEN_TIMEOUTS[gScreenTimeout];if(gScreenOn&&timeout&&now-gLastActivity>=timeout){gScreenOn=false;gfx->setBrightness(0);}lv_timer_handler();drawDirectNumbers();delay(5);} Item items[]={{"Breath limit",&gLimit,4},{"Cycle tick",&gTick,10},{"Alert volume",&gAlert,10},{"Screen timeout",&gScreenTimeout,3}};
for(auto &it:items){lv_obj_t *row=lv_obj_create(list);lv_obj_set_size(row,400,67);card(row,0x172C3C);
lv_obj_t *n=label(row,it.name,&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(n,12,6);
lv_obj_t *sl=lv_slider_create(row);lv_obj_set_pos(sl,12,36);lv_obj_set_size(sl,376,16);
lv_slider_set_range(sl,0,it.max);lv_slider_set_value(sl,*it.v,LV_ANIM_OFF);
lv_obj_add_event_cb(sl,settingChanged,LV_EVENT_VALUE_CHANGED,it.v);
}
button(gRoot,"BACK",150,435,180,36,0x214D69,[](lv_event_t *){
if(gPaused){gPaused=false;gBreath=BreathState::Waiting;}enterMonitor(nullptr);
});
}
// PMU power key can blank the AMOLED independently of our timeout flag.
// Explicitly wake the panel for any accepted KEY1 action.
static void wakeDisplayFromKey1() {
gLastActivity=millis();
gKey1WakeUntil=gLastActivity+1500;
gScreenOn=true;
gfx->setBrightness(220);
}
static void keyShort(){
wakeDisplayFromKey1();
if(gScreen==Screen::Settings){if(gPaused){gPaused=false;gBreath=BreathState::Waiting;}enterMonitor(nullptr);}
else settings(nullptr);
}
static void keyLong(){
wakeDisplayFromKey1();
if(!gPaused){gPaused=true;gBreath=BreathState::Waiting;gCycleStarted=0;gPhaseStarted=0;}
settings(nullptr);
}
// Key1 is PMU PWRON (AXP2101), not a GPIO. Handle short/long PMU IRQs.
static void pollPowerKey(){
if(!gPowerReady)return;
gPower.getIrqStatus();
bool longPress=gPower.isPekeyLongPressIrq();
bool shortPress=gPower.isPekeyShortPressIrq();
if(longPress||shortPress){gPower.clearIrqStatus();wakeDisplayFromKey1();
if(longPress){gLastPowerLong=millis();keyLong();}
else if(millis()-gLastPowerLong>750)keyShort();}
}
static void addCycle(uint32_t ms){
if(!ms)return;
gCompletedMs+=ms;gCycles[gCycleNext]=ms;gCycleNext=(gCycleNext+1)%5;
if(gCycleCount<5)gCycleCount++;
uint32_t a=average();if(a && a<LIMITS[gLimit]*1000UL){
gShortStreak=min<uint8_t>(5,gShortStreak+1);
for(uint8_t i=0;i<gShortStreak;i++){loud();delay(80);}
}else gShortStreak=0;
}
static void phase(bool inhale){
if(gPaused)return;
uint32_t now=millis();
if(inhale){
if(gBreath==BreathState::Inhale)return;
if(gBreath==BreathState::Exhale)addCycle(now-gCycleStarted);
gBreath=BreathState::Inhale;gCycleStarted=now;gPhaseStarted=now;quiet();
}else{
if(gBreath!=BreathState::Inhale)return;
gBreath=BreathState::Exhale;gPhaseStarted=now;quiet();
}
gLastReminder=now;
}
static void poll(Button &b,bool inhale){
uint32_t now=millis();bool raw=digitalRead(b.pin)==LOW;
if(raw!=b.raw){b.raw=raw;b.changed=now;}
if(b.stable==b.raw||now-b.changed<DEBOUNCE_MS)return;
b.stable=b.raw;if(b.stable){b.pressed=now;gLastActivity=now;
if(!gScreenOn){gScreenOn=true;gfx->setBrightness(220);}
phase(inhale);
}
}
static void refresh(){
if(gScreen!=Screen::Monitor)return;
uint32_t now=millis();char t[24];
const char *state=gBreath==BreathState::Waiting?"WAITING":gBreath==BreathState::Inhale?"INHALE":"EXHALE";
lv_label_set_text(gState,state);
lv_obj_set_style_text_color(gState,color(gBreath==BreathState::Inhale?0x38B26D:0x4FB3FF),0);
if(gBreath==BreathState::Waiting)lv_label_set_text(gPhaseTime,"");
else{fmt(t,sizeof(t),now-gPhaseStarted);lv_label_set_text(gPhaseTime,t);}
// Center phase and white phase timer as one horizontal group.
lv_obj_update_layout(gState);lv_obj_update_layout(gPhaseTime);
int w=lv_obj_get_width(gState)+(gBreath==BreathState::Waiting?0:14+lv_obj_get_width(gPhaseTime));
lv_obj_set_pos(gState,(432-w)/2,14);
lv_obj_set_pos(gPhaseTime,(432-w)/2+lv_obj_get_width(gState)+14,14);
lv_obj_align(gCycleValue,LV_ALIGN_CENTER,0,12);
lv_obj_align(gAverageValue,LV_ALIGN_CENTER,0,12);
lv_obj_align(gElapsedValue,LV_ALIGN_CENTER,0,12);
lv_obj_align(gLimitValue,LV_ALIGN_CENTER,0,12);
uint32_t cycle=gBreath==BreathState::Waiting?0:now-gCycleStarted;
fmt(t,sizeof(t),cycle);lv_label_set_text(gCycleValue,t);
if(gCycleCount){fmt(t,sizeof(t),average());lv_label_set_text(gAverageValue,t);}
else lv_label_set_text(gAverageValue,"--");
uint64_t seconds=gCompletedMs/1000;
if(seconds>=3600)snprintf(t,sizeof(t),"%llu:%02llu:%02llu",
(unsigned long long)(seconds/3600),(unsigned long long)((seconds/60)%60),(unsigned long long)(seconds%60));
else snprintf(t,sizeof(t),"%02llu:%02llu",(unsigned long long)(seconds/60),(unsigned long long)(seconds%60));
lv_label_set_text(gElapsedValue,t);
snprintf(t,sizeof(t),"%u.0 s",LIMITS[gLimit]);lv_label_set_text(gLimitValue,t);
for(uint8_t i=0;i<5;i++){
if(i<gCycleCount){uint8_t index=(gCycleNext+5-gCycleCount+i)%5;
snprintf(t,sizeof(t),"%lu.%01lu",(unsigned long)(gCycles[index]/1000),
(unsigned long)((gCycles[index]%1000)/100));}
else snprintf(t,sizeof(t),"--");
lv_label_set_text(gHistory[i],t);
}
lv_obj_align(gCycleValue,LV_ALIGN_CENTER,0,12);
lv_obj_align(gAverageValue,LV_ALIGN_CENTER,0,12);
lv_obj_align(gElapsedValue,LV_ALIGN_CENTER,0,12);
lv_obj_align(gLimitValue,LV_ALIGN_CENTER,0,12);
// LVGL owns all drawing; do not overwrite its tiles through direct GFX writes.
}
static void reminders(){
if(gPaused||gBreath==BreathState::Waiting||gScreen!=Screen::Monitor)return;
uint32_t now=millis(),age=now-gPhaseStarted;
if(age<QUIET_START_MS||now-gLastReminder<((age<SLOW_LOUD_MS)?5000:15000))return;
gLastReminder=now;
if(age<LOUD_START_MS)quiet();else if(age<POWER_OFF_MS)loud();
else{gfx->setBrightness(0);if(gPowerReady)gPower.shutdown();esp_deep_sleep_start();}
}
void setup(){Serial.begin(115200);Wire.begin(PIN_I2C_SDA,PIN_I2C_SCL);initPower();pinMode(PIN_INHALE,INPUT_PULLUP);pinMode(PIN_EXHALE,INPUT_PULLUP);initAudio();gfx->begin();gBus->writeC8D8(0x36,0xA0);gfx->setBrightness(220);gTouch.setPins(PIN_TP_INT,-1);gTouch.begin(Wire,0x5A,PIN_I2C_SDA,PIN_I2C_SCL);gTouch.setMaxCoordinates(DISP_W,DISP_H);gTouch.setSwapXY(true);gTouch.setMirrorXY(true,false);loadSettings();lv_init();gBuf1=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);gBuf2=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);lv_disp_draw_buf_init(&gDrawBuf,gBuf1,gBuf2,DISP_W*40);static lv_disp_drv_t dd;lv_disp_drv_init(&dd);dd.hor_res=DISP_W;dd.ver_res=DISP_H;dd.flush_cb=flush;dd.rounder_cb=rounder;dd.draw_buf=&gDrawBuf;lv_disp_drv_register(&dd);static lv_indev_drv_t id;lv_indev_drv_init(&id);id.type=LV_INDEV_TYPE_POINTER;id.read_cb=touchRead;lv_indev_drv_register(&id);const esp_timer_create_args_t ta={.callback=&tick,.name="lvgl_tick"};esp_timer_handle_t timer;esp_timer_create(&ta,&timer);esp_timer_start_periodic(timer,LVGL_TICK_MS*1000);gLastActivity=millis();enterMonitor(nullptr);}
void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);pollPowerKey();reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();}if(now-gLastBatt>=BATT_MS){gLastBatt=now;batteryUi();}uint32_t timeout=SCREEN_TIMEOUTS[gScreenTimeout];if(gScreenOn&&gScreen!=Screen::Settings&&(int32_t)(now-gKey1WakeUntil)>=0&&timeout&&now-gLastActivity>=timeout){gScreenOn=false;gfx->setBrightness(0);}lv_timer_handler();if((int32_t)(millis()-gKey1WakeUntil)<0){gScreenOn=true;gfx->setBrightness(220);}delay(5);}