Community project

ESP32 Touch Game Launcher

Photo of ESP32 Touch Game Launcher
Generated with AI

milessealy212

Published November 17, 2026

This project turns an ESP32 into a handheld touch-screen game launcher with a customizable home screen interface. The device features a TFT display, capacitive touch input, adjustable brightness, and optional PIN lock protection to keep games secure.

The guide provides a complete wiring diagram, parts list, and step-by-step assembly instructions to build the handheld board and connect USB power. Firmware is included with support for touch calibration, display rotation, brightness control, and a preference system to save user settings.

Wiring diagram

Wiring diagram for ESP32 Touch Game Launcher
Loading diagram…

Assemble it in 2 steps

1. Prepare the handheld board

Use the ESP32-2432S028R with the ILI9341 display. Its screen, touchscreen and RGB LED are already wired on the board. No external wires or buttons are needed. For Music, insert a FAT32 microSD card into the onboard slot with MP3 or WAV files in its root folder before powering on.

  • Keep the display in portrait orientation.
  • Page 3 contains Walkie-Chat. Open it on both nearby boards running this firmware to exchange broadcast messages on channel 1 without a router.
  • Router Wi-Fi pauses while Walkie-Chat is open and reconnects when you return Home. Previously synchronized time continues running offline.
  • Tap Type Message to use the existing QWERTY layouts, then Send. Drag the chat feed up or down to browse the last 20 messages.
  • Turn Test Bot ON for simulated replies after one second. These replies are local, not proof that another board received your message.
  • The onboard blue LED briefly lights for incoming messages. No external parts or wiring are required.
  • Broadcast chat is unencrypted. Do not send passwords or sensitive information; a sent message has no delivery confirmation.
  • To connect Wi-Fi, open Page 2, Settings, Wi-Fi Setup. Enter your 2.4 GHz network name and password with the touch keyboard, then tap Connect. Credentials are saved on the board and reconnect after restart.
  • The abc, ABC and Symbols key cycles keyboard layouts. Show reveals the password; Delete removes one character. Wi-Fi is paused while Music is open.
  • Put Bluetooth headphones or a speaker in pairing mode, open Music on Page 2, tap Scan / Connect BT, then tap its name.
  • Tap SD Tracks to browse songs. Prev and Next change tracks; the volume slider controls Bluetooth audio.
  • Music pauses Wi-Fi until you return Home. Clock and weather reconnect afterwards.
  • The browser lists up to 64 tracks and 24 Bluetooth devices, with list paging buttons.
  • Use standard PCM WAV or MP3 files. Do not remove the card while Music is open.

2. Connect USB power

Place the board on a non-conductive surface and connect a USB data cable to its USB socket. This project uses USB power, not a battery.

  • Do not connect a bare lithium battery directly to the board's power pins.

Deploy the firmware

#include <AudioGeneratorMP3.h>
#include <Arduino.h>
#include <esp_arduino_version.h>
#include <SPI.h>
#include <TFT_eSPI.h>

#include <Preferences.h>
#include <math.h>
#include <WiFi.h>
#include <time.h>
#include <esp_timer.h>
TFT_eSPI tft;
TFT_eSprite g(&tft);
SPIClass touchSPI(VSPI);
struct Point { int x,y; };
class TouchDriver {
public:
 uint8_t transfer(uint8_t v){uint8_t r=0;for(int b=7;b>=0;b--){digitalWrite(25,LOW);digitalWrite(32,(v>>b)&1);digitalWrite(25,HIGH);r=(r<<1)|digitalRead(39);}digitalWrite(25,LOW);return r;}
 void begin(SPIClass &) { pinMode(25,OUTPUT);pinMode(32,OUTPUT);pinMode(39,INPUT);digitalWrite(25,LOW);pinMode(33,OUTPUT);digitalWrite(33,HIGH);pinMode(36,INPUT); }
 void setRotation(int) {}
 int sample(uint8_t cmd) { transfer(cmd);return ((transfer(0)<<8)|transfer(0))>>3; }
 Point getPoint() { digitalWrite(33,LOW);int x=sample(0xD0),y=sample(0x90);sample(0xD0);digitalWrite(33,HIGH);return {x,y}; }
 bool touched() { return digitalRead(36)==LOW; }
} touch;
Preferences prefs;
const uint16_t BG=0x1084, WHITE=0xffff;
float cal[6];
int homePage=0,brightness=3;
bool darkMode=true;
bool quickOpen=false,quickSwallow=false,brightnessPending=false;
int sliderDuty=-1;
bool locked=true,pinEnabled=false;
bool lockPinStage=false,lockTouchSwallow=false;
uint32_t lockTransition=0;
String lockPin="1234",pinEntry="",lockMessage="";
int slideStart=-1;
uint8_t failedPinAttempts=0;
const uint8_t brightnessDuty[4]={32,96,180,255};
void applyBrightness(){
#if ESP_ARDUINO_VERSION_MAJOR >= 3
 ledcWrite(21,sliderDuty>=0?sliderDuty:brightnessDuty[brightness]);
#else
 ledcWrite(0,sliderDuty>=0?sliderDuty:brightnessDuty[brightness]);
#endif
}
void beginBrightness(){
#if ESP_ARDUINO_VERSION_MAJOR >= 3
 ledcAttach(21,5000,8);
#else
 ledcSetup(0,5000,8);ledcAttachPin(21,0);
#endif
 applyBrightness();
}
// New apps use the existing calibrated touchscreen and display sprite.
uint8_t canvas[240*202];
const uint16_t paintColors[]={0x0000,0xf800,0x001f,0x07e0,0xffff};
int paint=0,prevX=-1,prevY=-1,flashMode=4;
String calcEntry="0"; double calcStored=0; char calcOp=0;
bool calcNew=true,calcError=false;
void rgbOff(){for(int p:{4,16,17})digitalWrite(p,HIGH);}
void flashlight(int mode){
 flashMode=mode;rgbOff();
 if(mode==1)digitalWrite(4,LOW);
 if(mode==2)digitalWrite(16,LOW);
 if(mode==3)digitalWrite(17,LOW);
 if(mode==0){
#if ESP_ARDUINO_VERSION_MAJOR >= 3
 ledcWrite(21,255);
#else
 ledcWrite(0,255);
#endif
 }else applyBrightness();
}
int app=0,score=0; bool dirty=true,ended=false,started=false,wasDown=false;
uint32_t tick=0,second=0,hideAt=0;
float bird=150,vel=0,pipeX=240; int gap=150; bool passed=false;
float bx=120,by=230,dx=2.1,dy=-2.7; int paddle=120; bool bricks[24];
int cells[9],outcome=0; int cards[12],first=-1,last=-1,moves=0; bool matched[12];
void text(String s,int x,int y,int size=1,uint16_t c=WHITE){g.setTextColor(c);g.setTextSize(size);g.drawString(s,x,y);}
void reset(int a){app=a;score=0;ended=false;started=false;dirty=true;bird=150;vel=0;pipeX=240;gap=random(110,230);passed=false;bx=120;by=230;dx=2.1;dy=-2.7;paddle=120;outcome=0;first=last=-1;hideAt=0;moves=0;for(int i=0;i<24;i++)bricks[i]=true;for(int i=0;i<9;i++)cells[i]=0;for(int i=0;i<12;i++){cards[i]=i/2;matched[i]=false;}for(int i=11;i>0;i--){int j=random(i+1);int v=cards[i];cards[i]=cards[j];cards[j]=v;}}
#include "tetris.h"
#include "minesweeper.h"
int result(){const int lines[8][3]={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};for(auto &l:lines)if(cells[l[0]]&&cells[l[0]]==cells[l[1]]&&cells[l[1]]==cells[l[2]])return cells[l[0]];for(int v:cells)if(!v)return 0;return 3;}
int minimax(bool ai){int r=result();if(r)return r==2?10:r==1?-10:0;int best=ai?-100:100;for(int i=0;i<9;i++)if(!cells[i]){cells[i]=ai?2:1;int v=minimax(!ai);cells[i]=0;best=ai?max(best,v):min(best,v);}return best;}
void aiMove(){int best=-100,choice=-1;for(int i=0;i<9;i++)if(!cells[i]){cells[i]=2;int v=minimax(false);cells[i]=0;if(v>best){best=v;choice=i;}}if(choice>=0)cells[choice]=2;outcome=result();}
void calculateKey(int k){
 const char* keys[]={"7","8","9","/","4","5","6","*","1","2","3","-","C","0","=","+"};
 char c=keys[k][0];
 if(c=='C'){calcEntry="0";calcStored=0;calcOp=0;calcNew=true;calcError=false;}
 else if(c>='0'&&c<='9'){
  if(calcNew||calcError){calcEntry="";calcNew=false;calcError=false;}
  if(calcEntry=="0")calcEntry="";
  if(calcEntry.length()<12)calcEntry+=c;
 }else if(!calcError){
  double v=calcEntry.toDouble();
  if(calcOp&&!calcNew){
   if(calcOp=='+')v=calcStored+v;
   if(calcOp=='-')v=calcStored-v;
   if(calcOp=='*')v=calcStored*v;
   if(calcOp=='/'){if(v==0)calcError=true;else v=calcStored/v;}
  }
  if(!isfinite(v)||fabs(v)>999999999999.0)calcError=true;
  if(calcError){calcEntry="Error";calcOp=0;}
  else{char buf[32];snprintf(buf,sizeof(buf),"%.9g",v);calcEntry=buf;calcStored=v;calcOp=c=='='?0:c;}
  calcNew=true;
 }
 dirty=true;
}
void paintAt(int x,int y){
 if(prevX<0){prevX=x;prevY=y;}
 int steps=max(abs(x-prevX),abs(y-prevY));
 for(int i=0;i<=steps;i++){
  int px=steps?prevX+(x-prevX)*i/steps:x,py=steps?prevY+(y-prevY)*i/steps:y;
  int radius=paint==4?7:2;
  for(int yy=max(112,py-radius);yy<=min(313,py+radius);yy++)
   for(int xx=max(0,px-radius);xx<=min(239,px+radius);xx++)canvas[(yy-112)*240+xx]=paint;
 }
 prevX=x;prevY=y;dirty=true;
}
// Networking owns no display or touch resources. Results cross a small queue.
char WIFI_SSID[33]="YOUR_WIFI_NAME";
char WIFI_PASSWORD[65]="YOUR_WIFI_PASSWORD";
struct WifiCredentials { char ssid[33]; char password[65]; };
QueueHandle_t wifiQueue;
struct WifiConnectResult { bool connected; char ip[16]; int status; };
QueueHandle_t wifiResultQueue;
int wifiErrorStatus=6;
int wifiConnectState=0; // idle, connecting, connected, failed
String wifiConnectingSSID,wifiConnectedIP;
uint32_t wifiFeedbackUntil=0;
String wifiName,wifiPass;
int wifiField=0,wifiKeys=0;
bool wifiShow=false;
const char* keyboardRows[3][4]={
 {"1234567890","qwertyuiop","asdfghjkl-","zxcvbnm._@"},
 {"1234567890","QWERTYUIOP","ASDFGHJKL_","ZXCVBNM.-@"},
 {"!@#$%^&*()","[]{}<>/\\|=","+_-:;\"'?,.","0123456789"}
};
int clockTab=0;
bool stopwatchRunning=false;
int64_t stopwatchAccum=0,stopwatchStart=0;
int64_t stopwatchMs(){return (stopwatchAccum+(stopwatchRunning?esp_timer_get_time()-stopwatchStart:0))/1000;}
volatile bool manualClock=false;
int savedHour=12,savedMinute=0,savedSecond=0,savedMonth=1,savedDay=1,savedYear=2026;
uint32_t clockMillis=0,lastTouchMillis=0,screenTimeoutMs=0;
uint32_t clockEditMillis=0,clockPersistMillis=0;
bool clockSavePending=false;
struct SavedClock { int hour,minute,second,month,day,year; };
void loadClock(){
 SavedClock value={12,0,0,1,1,2026};
 if(prefs.getBytesLength("offlineClock")==sizeof(value)){
  prefs.getBytes("offlineClock",&value,sizeof(value));manualClock=true;
 }
 savedHour=constrain(value.hour,0,23);savedMinute=constrain(value.minute,0,59);
 savedSecond=constrain(value.second,0,59);savedMonth=constrain(value.month,1,12);
 savedDay=constrain(value.day,1,31);savedYear=constrain(value.year,2020,2099);
 clockMillis=clockPersistMillis=lastTouchMillis=millis();
 screenTimeoutMs=prefs.getUInt("screenTimeoutMs",0); // Zero preserves disabled timeout.
}
void advanceOfflineClock(){
 uint32_t now=millis(),seconds=(uint32_t)(now-clockMillis)/1000;
 if(!manualClock){clockMillis=now;return;}
 if(seconds){
  clockMillis+=seconds*1000;
  uint32_t total=savedHour*3600U+savedMinute*60U+savedSecond+seconds;
  uint32_t days=total/86400U;total%=86400U;
  savedHour=total/3600;savedMinute=(total/60)%60;savedSecond=total%60;
  while(days--){
   static const int monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
   int limit=monthDays[constrain(savedMonth,1,12)-1];
   if(savedMonth==2&&savedYear%4==0&&(savedYear%100!=0||savedYear%400==0))++limit;
   if(++savedDay>limit){savedDay=1;if(++savedMonth>12){savedMonth=1;if(++savedYear>2099)savedYear=2020;}}
  }
  dirty=true;
 }
}
bool readClock(struct tm &t){
 if(!manualClock)return getLocalTime(&t,0);
 t={};t.tm_hour=savedHour;t.tm_min=savedMinute;t.tm_sec=savedSecond;
 t.tm_mon=savedMonth-1;t.tm_mday=savedDay;t.tm_year=savedYear-1900;t.tm_isdst=-1;
 // Gregorian weekday using integer arithmetic, never mktime/system-clock writes.
 static const int offsets[]={0,3,2,5,0,3,5,1,4,6,2,4};
 int y=savedYear-(savedMonth<3);
 t.tm_wday=(y+y/4-y/100+y/400+offsets[constrain(savedMonth,1,12)-1]+savedDay)%7;
 return true;
}
void persistClock(bool touching){
 uint32_t now=millis();
 if(!manualClock||touching)return;
 if((clockSavePending&&now-clockEditMillis>=750)||now-clockPersistMillis>=60000){
  SavedClock value={savedHour,savedMinute,savedSecond,savedMonth,savedDay,savedYear};
  // Main-loop NVS write: no ISR, interrupt masking, or radio/display lock held.
  if(prefs.putBytes("offlineClock",&value,sizeof(value))==sizeof(value)){
   clockSavePending=false;clockPersistMillis=now;
  }
 }
}
bool timerRunning=false,timerAlert=false;
int64_t timerPreset=60000,timerRemaining=60000,timerStarted=0;
int timerLedPhase=-1;
int64_t countdownMs(){return timerRunning?max((int64_t)0,timerRemaining-(esp_timer_get_time()-timerStarted)/1000):timerRemaining;}
void clearTimerAlert(){if(timerAlert){timerAlert=false;timerLedPhase=-1;flashlight(flashMode);}}
void adjustClock(int row,int delta){
 if(row<0||row>=6)return;
 advanceOfflineClock();
 if(!manualClock){
  struct tm t={};
  if(readClock(t)){savedHour=t.tm_hour;savedMinute=t.tm_min;savedSecond=t.tm_sec;
   savedMonth=constrain(t.tm_mon+1,1,12);savedDay=constrain(t.tm_mday,1,31);savedYear=constrain(t.tm_year+1900,2020,2099);}
 }
 delta=delta<0?-1:1;
 if(row==0)savedHour=(savedHour+delta+24)%24;
 if(row==1)savedMinute=(savedMinute+delta+60)%60;
 if(row==2)savedHour=(savedHour+12)%24;
 if(row==3)savedMonth=(savedMonth-1+delta+12)%12+1;
 if(row==4)savedDay=(savedDay-1+delta+31)%31+1;
 if(row==5)savedYear=constrain(savedYear+delta,2020,2099);
 savedSecond=0;manualClock=true;
 clockMillis=clockEditMillis=lastTouchMillis=millis();clockSavePending=true;dirty=true;
}
#include "music.h"
#include "chat.h"
void networkTask(void*){
 WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(true);WiFi.begin(WIFI_SSID,WIFI_PASSWORD);
 uint32_t reconnectAt=millis();bool chatActive=false;
 for(;;){
  if(musicRequested){vTaskDelay(pdMS_TO_TICKS(200));continue;}
  xSemaphoreTake(radioLock,portMAX_DELAY);
  if(musicRequested){xSemaphoreGive(radioLock);continue;}
  if(chatRequested&&!chatActive){
   WiFi.setAutoReconnect(false);WiFi.disconnect(false,false);WiFi.mode(WIFI_STA);
   esp_err_t result=esp_wifi_set_channel(1,WIFI_SECOND_CHAN_NONE);
   if(result==ESP_OK)result=esp_now_init();
   if(result==ESP_OK){esp_now_peer_info_t peer={};memcpy(peer.peer_addr,chatBroadcast,6);peer.channel=1;peer.ifidx=WIFI_IF_STA;peer.encrypt=false;
    result=esp_now_add_peer(&peer);if(result==ESP_OK)result=esp_now_register_recv_cb(chatReceive);
    if(result!=ESP_OK)esp_now_deinit();
   }
   chatReady=result==ESP_OK;chatActive=true;chatStatus=chatReady?"Channel 1 - no router needed":"Radio init failed; reopen app";dirty=true;
  }
  if(!chatRequested&&chatActive){esp_now_deinit();chatReady=false;chatActive=false;WiFi.setAutoReconnect(true);WiFi.begin(WIFI_SSID,WIFI_PASSWORD);}
  if(chatActive){xSemaphoreGive(radioLock);vTaskDelay(pdMS_TO_TICKS(50));continue;}
  WifiCredentials credentials;
  if(wifiQueue&&xQueueReceive(wifiQueue,&credentials,0)==pdTRUE){
   // Reset both radio users before attempting the supplied credentials.
   esp_now_deinit();chatReady=false;chatActive=false;
   WiFi.setAutoReconnect(false);
   WiFi.disconnect(true);
   WiFi.mode(WIFI_OFF);
   delay(200);
   WiFi.mode(WIFI_STA);
   WiFi.setSleep(false);
   WiFi.begin(credentials.ssid,credentials.password);
   uint32_t started=millis();
   while(WiFi.status()!=WL_CONNECTED && millis()-started<10000){
    vTaskDelay(pdMS_TO_TICKS(100));
   }
   int finalStatus=(int)WiFi.status(); // Capture before cleanup changes the status.
   WifiConnectResult result={finalStatus==WL_CONNECTED,{0},finalStatus};
   if(result.connected){
    memcpy(WIFI_SSID,credentials.ssid,sizeof(WIFI_SSID));
    memcpy(WIFI_PASSWORD,credentials.password,sizeof(WIFI_PASSWORD));
    Preferences storage;storage.begin("arcade",false);
    storage.putString("ssid",WIFI_SSID);storage.putString("wifiPass",WIFI_PASSWORD);storage.end();
    WiFi.localIP().toString().toCharArray(result.ip,sizeof(result.ip));
    WiFi.setAutoReconnect(true);
    if(!manualClock)configTzTime("EST5EDT,M3.2.0,M11.1.0", "pool.ntp.org", "time.nist.gov");
   }else WiFi.disconnect(false,false);
   xQueueOverwrite(wifiResultQueue,&result);
   reconnectAt=millis();
   xSemaphoreGive(radioLock);
   vTaskDelay(pdMS_TO_TICKS(100));
   continue;
  }
  uint32_t now=millis();
  if(WiFi.status()!=WL_CONNECTED){
   if(WiFi.getAutoReconnect()&&now-reconnectAt>=30000){WiFi.reconnect();reconnectAt=now;}
  }
  xSemaphoreGive(radioLock);
  vTaskDelay(pdMS_TO_TICKS(1000));
 }
}
void tap(int x,int y,bool edge){
 lastTouchMillis=millis();
 if(quickSwallow)return;
 if(!locked&&app!=12){
  if(quickOpen){
   if(y>=94&&y<=144){
    int duty=constrain(16+(x-20)*239/200,16,255);
    if(sliderDuty!=duty){sliderDuty=duty;applyBrightness();brightnessPending=true;dirty=true;}
   }else if(edge&&((y<30)||(y>=276&&y<316))){quickOpen=false;quickSwallow=true;dirty=true;}
   return;
  }
  if(edge&&y<25&&x>=118&&x<140){quickOpen=true;dirty=true;return;}
 }

 if(locked||app==12){
  if(locked){
   if(lockTouchSwallow)return;
   if(!lockPinStage){
    // A tap also covers the beginning of an upward swipe. Consume the
    // whole gesture so it cannot accidentally enter the first PIN digit.
    if(edge){
     pinEntry="";lockMessage="";lockTouchSwallow=true;
     if(pinEnabled){lockPinStage=true;lockTransition=millis();}
     else {locked=false;failedPinAttempts=0;}
     dirty=true;
    }
    return;
   }
   if(lockTransition&&millis()-lockTransition<180)return;
   if(edge&&y>=28&&y<66){
    lockPinStage=false;pinEntry="";lockMessage="";
    lockTouchSwallow=true;dirty=true;return;
   }
  }
  if(!edge)return;
  if(app==12&&y<55&&x<70){app=5;pinEntry="";dirty=true;return;}
  if(app==12&&y>=58&&y<96){pinEnabled=!pinEnabled;prefs.putBool("pinEnabled",pinEnabled);dirty=true;return;}
  if(y>=132&&y<308){
   int row=(y-132)/44,col=x/80;
   if(row<3){if(pinEntry.length()<4)pinEntry+=char('1'+row*3+col);}
   else if(col==0){if(locked)pinEntry=pinEntry.substring(0,pinEntry.length()?pinEntry.length()-1:0);else pinEntry="";lockMessage="";}
   else if(col==1){if(pinEntry.length()<4)pinEntry+='0';}
   else if(pinEntry.length()==4){
    if(app==12){lockPin=pinEntry;prefs.putString("lockPin",lockPin);pinEntry="";lockMessage="PIN saved";}
    else if(pinEntry==lockPin){locked=false;failedPinAttempts=0;pinEntry="";lockMessage="";}
    else {
     pinEntry="";lockMessage="Incorrect PIN";
     if(++failedPinAttempts>=5){
      failedPinAttempts=0;locked=false;app=5;quickOpen=false;
      slideStart=-1;lockMessage="";
     }
    }
   }
   dirty=true;
  }
  return;
 }
 if(app==0&&edge&&y<25&&x>=140&&x<191){locked=true;lockPinStage=false;lockTransition=0;failedPinAttempts=0;pinEntry="";lockMessage="";slideStart=-1;dirty=true;return;}

 if(app==11){
  if(!edge)return;
  if(x<70&&y<50){reset(0);return;}
  if(wifiConnectState==1)return;
  if(y>=58&&y<91)wifiField=0;
  else if(y>=94&&y<127)wifiField=1;
  else if(y>=130&&y<156){if(x<80)wifiKeys=(wifiKeys+1)%3;else if(x<160)wifiShow=!wifiShow;else {String &v=wifiField?wifiPass:wifiName;if(v.length())v.remove(v.length()-1);}}
  else if(y>=162&&y<274){int row=(y-162)/28,col=x/24;String &v=wifiField?wifiPass:wifiName;if(v.length()<(wifiField?64:32))v+=keyboardRows[wifiKeys][row][col];}
  else if(y>=278&&y<315){
   if(x<72){String &v=wifiField?wifiPass:wifiName;if(v.length()<(wifiField?64:32))v+=' ';}
   else if(x<144){(wifiField?wifiPass:wifiName)="";}
   else if(wifiName.length()&&wifiQueue){wifiPass.trim();WifiCredentials c={};wifiName.toCharArray(c.ssid,sizeof(c.ssid));wifiPass.toCharArray(c.password,sizeof(c.password));chatRequested=false;wifiConnectingSSID=wifiName;wifiConnectState=1;wifiFeedbackUntil=0;xQueueOverwrite(wifiQueue,&c);}
  }
  dirty=true;return;
 }

 if(app&&edge&&x<70&&y<50){if(app==13){chatRequested=false;chatCompose=false;botAt=0;}if(app==10){musicRequested=false;musicPlaying=false;}if(app==8){rgbOff();applyBrightness();}prevX=prevY=-1;reset(0);return;}
 if(app==0){
  if(!edge)return;
  if(y>=289){homePage=min(2,x/80);dirty=true;return;}
  if(homePage==0&&y>=75&&y<283){int col=x>=120,row=(y-75)/69;int slot=row*2+col;if(slot<4)reset(1+slot);else if(slot==4){app=14;tetReset();}else if(slot==5){app=15;msReset();}}
  else if(homePage==1&&y>=75&&y<282){
   int col=x>=120,row=(y-75)/69;int slot=row*2+col;if(slot>=6)return;app=5+slot;dirty=true;
   if(app==8)flashlight(4);
   if(app==10){musicRequested=true;musicDevices=false;trackPage=0;}
  }
  else if(homePage==2&&x>=12&&x<114&&y>=75&&y<173){app=13;chatRequested=true;chatCompose=false;dirty=true;}
  return;
 }
 if(app==15){msTap(x,y,edge);return;}
 if(app==14){tetTap(x,y,edge);return;}
 if(app==13){chatTap(x,y,edge);return;}
 if(app==10){
  if(!musicReady)return;
  if(y>=275&&y<315){musicVolume=constrain((x-16)*127/208,0,127);dirty=true;return;}
  if(!edge)return;
  if(y>=58&&y<94){musicDevices=true;musicCommand=1;dirty=true;return;}
  if(y>=100&&y<124){musicDevices=x<120;dirty=true;return;}
  if(y>=128&&y<218){int i=(y-128)/30+(musicDevices?devicePage:trackPage)*3;if(musicDevices){if(i<deviceCount)devicePick=i;}else if(i<trackCount){musicTrack=i;musicCommand=2;}dirty=true;return;}
  if(y>=218&&y<242){int &page=musicDevices?devicePage:trackPage;int count=musicDevices?deviceCount:trackCount;page=constrain(page+(x<120?-1:1),0,max(0,(count-1)/3));dirty=true;return;}
  if(y>=242&&y<273&&trackCount){if(x<70){musicTrack=(musicTrack+trackCount-1)%trackCount;musicCommand=2;}else if(x>=170){musicTrack=(musicTrack+1)%trackCount;musicCommand=2;}else if(!musicPlaying&&musicMessage.length()){musicCommand=2;}else musicPlaying=!musicPlaying;dirty=true;}
  return;
 }
 if(app==9){
  if(!edge)return;
  if(y>=60&&y<98){clockTab=min(2,x/80);dirty=true;return;}
  if(clockTab==0&&y>=130&&y<316&&(x<48||x>=192)){adjustClock((y-130)/31,x<48?-1:1);return;}
  if(clockTab==1){
   if(y>=110&&y<150){clearTimerAlert();timerRunning=false;timerPreset=(x<80?1:x<160?5:10)*60000LL;timerRemaining=timerPreset;}
   if(y>=230&&y<296){
    if(x<80&&!timerRunning&&timerRemaining>0){clearTimerAlert();timerStarted=esp_timer_get_time();timerRunning=true;}
    else if(x>=80&&x<160&&timerRunning){timerRemaining=countdownMs();timerRunning=false;}
    else if(x>=160){clearTimerAlert();timerRunning=false;timerRemaining=timerPreset;}
   }
   if(y>=300)clearTimerAlert();dirty=true;
  }
  if(clockTab==2&&y>=230&&y<296){
   if(x<80&&!stopwatchRunning){stopwatchStart=esp_timer_get_time();stopwatchRunning=true;}
   else if(x>=80&&x<160&&stopwatchRunning){stopwatchAccum+=esp_timer_get_time()-stopwatchStart;stopwatchRunning=false;}
   else if(x>=160){stopwatchRunning=false;stopwatchAccum=0;}
   dirty=true;
  }
  return;
 }
 if(app==6){if(edge&&y>=120&&y<312&&x>=8&&x<232)calculateKey(((y-120)/48)*4+(x-8)/56);return;}
 if(app==7){
  if(y>=112&&y<=313){paintAt(x,y);return;}
  prevX=prevY=-1;
  if(edge&&y>=59&&y<87){paint=min(x/48,4);dirty=true;}
  if(edge&&y>=88&&y<110&&x>=166){memset(canvas,4,sizeof(canvas));dirty=true;}
  return;
 }
 if(app==8){if(edge&&y>=80&&y<305){flashlight((y-80)/45);dirty=true;}return;}
 if(app==5){
  if(!edge)return;
  if(y>=160&&y<197){app=12;pinEntry="";lockMessage="";dirty=true;return;}
  if(y>=268&&y<312){wifiName=WIFI_SSID;wifiPass=WIFI_PASSWORD;wifiField=0;app=11;dirty=true;return;}
  if(y>=112&&y<154&&x>=8&&x<232){brightness=(x-8)/56;sliderDuty=-1;prefs.remove("sliderDuty");applyBrightness();prefs.putUChar("brightness",brightness);dirty=true;}
  if(y>=211&&y<257&&x>=12&&x<228){darkMode=x<120;prefs.putBool("dark",darkMode);dirty=true;}
  return;
 }
 if((app==1||app==2)&&edge){if(ended){reset(app);return;}started=true;if(app==1)vel=-4.3;}
 if(app==2&&!ended){int p=constrain(x,28,212);if(p!=paddle){paddle=p;dirty=true;}}
 if(app==3&&edge){if(outcome){reset(3);return;}if(x>=15&&x<225&&y>=75&&y<285){int i=((y-75)/70)*3+(x-15)/70;if(!cells[i]){cells[i]=1;outcome=result();if(!outcome)aiMove();dirty=true;}}}
 if(app==4&&edge){if(ended){reset(4);return;}if(hideAt)return;if(x>=12&&x<228&&y>=75&&y<279){int i=((y-75)/68)*4+(x-12)/54;if(matched[i]||i==first)return;if(first<0)first=i;else{last=i;moves++;if(cards[first]==cards[last]){matched[first]=matched[last]=true;first=last=-1;bool all=true;for(bool m:matched)all&=m;ended=all;}else hideAt=millis()+850;}dirty=true;}}
}
void update(){
 if(locked||quickOpen)return;
 if(app==15){msUpdate();return;}
 if(app==14){tetUpdate();return;}
 if(app==4&&hideAt&&(int32_t)(millis()-hideAt)>=0){hideAt=0;first=last=-1;dirty=true;}
 if(!started||ended)return;
 if(app==1){vel+=0.23;bird+=vel;pipeX-=2; if(pipeX<-38){pipeX=240;gap=random(110,230);passed=false;}if(!passed&&pipeX+38<55){score++;passed=true;}if(bird<65||bird>286||(pipeX<65&&pipeX+38>45&&(bird-9<gap-45||bird+9>gap+45)))ended=true;dirty=true;}
 if(app==2){bx+=dx;by+=dy;if(bx<5){bx=5;dx=abs(dx);}if(bx>235){bx=235;dx=-abs(dx);}if(by<65){by=65;dy=abs(dy);}if(dy>0&&by>=270&&by<=282&&abs(bx-paddle)<32){by=269;dy=-abs(dy);dx=(bx-paddle)/11.0;if(abs(dx)<0.5)dx=0.5;}for(int i=0;i<24;i++)if(bricks[i]){int x=9+(i%6)*38,y=80+(i/6)*22;if(bx+4>=x&&bx-4<=x+33&&by+4>=y&&by-4<=y+16){bricks[i]=false;dy=-dy;score++;break;}}if(by>304||score==24)ended=true;dirty=true;}
}
// Launcher-only artwork; app routing and generous touch targets are unchanged.
void launcherIcon(int id,int x,int y,uint16_t color,const char* label,uint16_t ink){
 const int cx=x+27,cy=y+27;
 g.fillRoundRect(x,y,54,54,14,color);
 uint16_t highlight=((color>>1)&0x7bef)+0x7bef;
 g.drawRoundRect(x,y,54,54,14,highlight);
 const uint16_t w=WHITE;
 switch(id){
 case 1: // Bird
  g.fillCircle(cx-2,cy,12,w);g.fillTriangle(cx+8,cy-3,cx+18,cy+2,cx+8,cy+5,0xffe0);
  g.fillCircle(cx+3,cy-4,3,color);g.fillTriangle(cx-8,cy,cx-17,cy-7,cx-15,cy+7,0xffe0);break;
 case 2: // Bricks, ball and paddle
  for(int r=0;r<2;r++)for(int c=0;c<3;c++)g.fillRoundRect(x+10+c*12,y+11+r*8,10,6,2,w);
  g.fillCircle(cx+5,cy+5,3,w);g.fillRoundRect(x+14,y+39,26,4,2,w);break;
 case 3:
  for(int i=0;i<2;i++){g.drawFastVLine(x+21+i*12,y+10,34,w);g.drawFastHLine(x+10,y+21+i*12,34,w);}
  g.drawLine(x+12,y+12,x+18,y+18,w);g.drawLine(x+18,y+12,x+12,y+18,w);g.drawCircle(x+27,y+27,4,w);break;
 case 4: // Matching cards
  g.fillRoundRect(x+11,y+13,17,27,3,w);g.fillRoundRect(x+29,y+17,15,27,3,0xffe0);
  g.fillCircle(x+19,y+26,4,color);g.fillCircle(x+36,y+30,4,color);break;
 case 5: // Gear
  for(int i=0;i<8;i++){float a=i*PI/4;int dx=roundf(cosf(a)*16),dy=roundf(sinf(a)*16);g.fillRect(cx+dx-3,cy+dy-3,7,7,w);}
  g.fillCircle(cx,cy,15,w);g.fillCircle(cx,cy,9,color);g.fillCircle(cx,cy,4,w);break;
 case 6:
  g.fillRoundRect(x+13,y+9,28,36,4,w);g.fillRect(x+17,y+13,20,7,color);
  for(int r=0;r<3;r++)for(int c=0;c<3;c++)g.fillRect(x+17+c*7,y+24+r*6,4,4,color);break;
 case 7: // Pencil
  g.fillTriangle(x+13,y+36,x+18,y+41,x+11,y+43,w);
  g.fillTriangle(x+16,y+34,x+35,y+15,x+40,y+20,w);g.fillTriangle(x+16,y+34,x+40,y+20,x+21,y+39,w);
  g.drawLine(x+11,y+46,x+42,y+46,w);break;
 case 8:
  g.fillRoundRect(x+22,y+26,11,18,3,w);g.fillTriangle(x+19,y+20,x+36,y+20,x+32,y+28,w);
  g.drawLine(cx,y+7,cx,y+15,w);g.drawLine(x+12,y+11,x+19,y+17,w);g.drawLine(x+42,y+11,x+35,y+17,w);break;
 case 9: // Analog face and digital badge
  g.fillCircle(cx,y+23,17,w);g.drawCircle(cx,y+23,14,color);
  g.drawLine(cx,y+23,cx,y+12,color);g.drawLine(cx,y+23,cx+9,y+27,color);
  g.fillCircle(cx,y+23,2,color);g.fillRoundRect(x+10,y+36,34,12,4,0x0010);
  g.setTextColor(w);g.setTextSize(1);g.drawString("12:00",x+12,y+39);break;
 case 10:
  g.fillRect(x+24,y+13,4,25,w);g.fillRect(x+38,y+10,4,23,w);
  g.fillTriangle(x+24,y+13,x+42,y+9,x+42,y+17,w);g.fillTriangle(x+24,y+13,x+42,y+17,x+24,y+21,w);
  g.fillCircle(x+20,y+38,6,w);g.fillCircle(x+34,y+33,6,w);break;
 case 13:
  g.fillRoundRect(x+10,y+12,34,26,7,w);g.fillTriangle(x+15,y+35,x+15,y+44,x+25,y+35,w);
  for(int i=0;i<3;i++)g.fillCircle(x+18+i*9,y+25,2,color);break;
 case 15: // Classic mine/flag grid inside a squircle
  for(int r=0;r<3;r++)for(int c=0;c<3;c++){g.fillRect(x+9+c*12,y+9+r*12,11,11,0xdedb);g.drawRect(x+9+c*12,y+9+r*12,11,11,0x4208);}
  g.fillCircle(x+14,y+14,3,0);g.drawLine(x+10,y+14,x+18,y+14,0);g.drawLine(x+14,y+10,x+14,y+18,0);
  g.drawFastVLine(x+36,y+23,9,0);g.fillTriangle(x+37,y+23,x+43,y+26,x+37,y+29,0xf800);
  g.setTextSize(1);g.setTextColor(0x001f);g.drawString("1",x+24,y+35);break;
 case 14:
  for(int j=0;j<4;j++){int bx=x+12+(j==0?1:j-1)*10,by=y+15+(j==0?0:10);g.fillRect(bx,by,9,9,w);g.drawRect(bx+1,by+1,7,7,0xf81f);}
  g.fillRect(x+32,y+36,9,9,0xffe0);break;
 }
 g.setTextSize(1);g.setTextColor(ink);
 g.drawString(label,cx-g.textWidth(label)/2,y+56);
}
void draw(){
 bool os=locked||app==0||app==5||app==9||app==12;
 uint16_t ink=os&&!darkMode?0x1084:WHITE;
 g.fillSprite(os&&!darkMode?0xef7d:BG);g.fillRect(0,0,240,25,os&&!darkMode?0xdedb:0x0000);char clock[24];struct tm local={};bool timeReady=readClock(local);
 if(timeReady){snprintf(clock,sizeof(clock),"%d:%02d %s",local.tm_hour%12?local.tm_hour%12:12,local.tm_min,local.tm_hour<12?"AM":"PM");}
 else snprintf(clock,sizeof(clock),"--:--");text(clock,6,7,1,ink);g.drawRect(195,6,30,13,ink);g.fillRect(225,10,3,5,ink);text("USB",200,9,1,os&&!darkMode?0x0250:0x07ff);
 if(!locked&&app!=12){g.fillRoundRect(118,2,22,21,3,0x025f);text("v",125,8);}
 if(quickOpen&&!locked){
  uint16_t panel=darkMode?0x18e3:0xef7d,fg=darkMode?WHITE:0x1084;
  g.fillRect(0,25,240,295,panel);
  text("Quick Settings",16,40,2,fg);
  int duty=sliderDuty>=0?sliderDuty:brightnessDuty[brightness];
  text("Brightness  "+String(duty*100/255)+"%",16,78,1,fg);
  g.fillRoundRect(20,115,200,8,4,0x7bef);
  int knob=20+(constrain(duty,16,255)-16)*200/239;
  g.fillRoundRect(20,115,max(1,knob-20),8,4,0x025f);g.fillCircle(knob,119,12,0x07ff);
  bool online=WiFi.status()==WL_CONNECTED;
  uint16_t wifiColor=online?0x07e0:0x7bef;
  g.drawCircle(30,173,16,wifiColor);g.drawCircle(30,173,10,wifiColor);
  g.fillRect(10,174,41,18,panel);g.fillCircle(30,173,3,wifiColor);
  text(online?"Wi-Fi connected":musicRequested?"Wi-Fi off for Music":"Wi-Fi offline",56,158,1,fg);
  text(online?WiFi.localIP().toString():"Settings > Wi-Fi Setup",56,176,1,fg);
  if(musicRequested&&musicPlaying&&trackCount&&musicTrack>=0&&musicTrack<trackCount){
   g.fillRoundRect(8,203,224,62,8,0x025f);
   text("Now Playing",18,213);
   String title=tracks[musicTrack];if(title.startsWith("/"))title=title.substring(1);
   text(title.substring(0,34),18,234);
   text("Volume: "+String(musicVolume*100/127)+"%",18,251);
  }
  g.fillRoundRect(8,280,224,32,6,0x39e7);text("Close dropdown",68,291);
  g.pushSprite(0,0);dirty=false;return;
 }
 if(locked||app==12){
  text(WiFi.status()==WL_CONNECTED?"Wi-Fi connected":"Wi-Fi offline",8,32,1,ink);
  if(app==12&&!locked){
   g.fillRoundRect(4,28,64,24,6,0x39e7);text("< Back",9,36);
   text("Lock Settings",78,36,1,ink);
   g.fillRoundRect(8,58,224,38,6,0x025f);text(pinEnabled?"PIN: ON (tap to turn off)":"PIN: OFF (tap to turn on)",16,73);
   text("Enter new PIN, then Save",14,104,1,ink);
  }else if(!lockPinStage){
   // Hide the normal status bar: the clock stage contains only Wi-Fi,
   // the centered time/date, and a discreet unlock prompt.
   uint16_t panel=darkMode?BG:0xef7d;
   g.fillSprite(panel);
   uint16_t wifiInk=WiFi.status()==WL_CONNECTED?0x07e0:0x7bef;
   g.drawCircle(120,25,15,wifiInk);g.drawCircle(120,25,9,wifiInk);
   g.fillRect(100,26,41,18,panel);g.fillCircle(120,25,3,wifiInk);
   g.setTextSize(4);g.setTextColor(ink);
   g.drawString(clock,(240-g.textWidth(clock))/2,126);
   char date[32];if(timeReady)strftime(date,sizeof(date),"%a, %b %d",&local);else snprintf(date,sizeof(date),"Open Clock to set time");
   g.setTextSize(1);g.drawString(date,(240-g.textWidth(date))/2,174);
   const char* prompt="Swipe Up or Tap to Unlock";
   g.setTextColor(darkMode?0xbdf7:0x5aeb);
   g.drawString(prompt,(240-g.textWidth(prompt))/2,286);
  }
  if((locked&&lockPinStage)||(!locked&&app==12)){
   int offset=0;
   if(locked){
    uint32_t elapsed=millis()-lockTransition;
    if(lockTransition&&elapsed<180)offset=(180-elapsed)*100/180;
    else lockTransition=0;
    g.fillSprite(darkMode?BG:0xef7d);
    g.fillRoundRect(8,28+offset,224,36,10,0x39e7);
    text("< Cancel / Back",64,40+offset);
    text("Enter your PIN",78,78+offset,1,ink);
    for(int i=0;i<4;i++){
     int cx=84+i*24;
     if(i<(int)pinEntry.length())g.fillCircle(cx,113+offset,6,ink);
     else g.drawCircle(cx,113+offset,6,ink);
    }
   }else{
    String dots="";for(unsigned i=0;i<pinEntry.length();i++)dots+='*';
    text(dots,104,118,2,ink);
   }
   const char* keys[]={"1","2","3","4","5","6","7","8","9",locked?"Backspace":"Clear","0",app==12&&!locked?"Save":"Unlock"};
   for(int i=0;i<12;i++){int x=i%3*80+4,y=132+i/3*44+offset;g.fillRoundRect(x,y,72,40,10,0x025f);text(keys[i],x+(i==9?3:i==11?6:28),y+13,i==9||i==11?1:2);}
   text(lockMessage,12,310+offset,1,ink);
  }
  g.pushSprite(0,0);dirty=false;return;
 }
 if(app==0){g.fillRoundRect(140,2,51,21,4,0x025f);text("Lock",153,8);}
 if(app){g.fillRoundRect(4,28,64,24,6,0x39e7);text("< Home",9,36);const char* names[]={"","Flappy","Bricks","Tic Tac Toe","Memory","Settings","Calculator","Sketchpad","Flashlight","Clock","Music (BT)","Wi-Fi Setup","Lock Settings","Walkie-Chat","Tetris","Minesweeper"};if(app!=15)text(names[app],78,35,1,ink);}
 else if(homePage==0){text("Pocket Arcade",18,40,2,ink);
  const char* titles[]={"Flappy","Bricks","Tic Tac Toe","Memory","Tetris","Minesweeper"};
  const int ids[]={1,2,3,4,14,15};
  const uint16_t colors[]={0x04bf,0xfba0,0x901b,0x05b5,0x481f,0x03ad};
  for(int i=0;i<6;i++)launcherIcon(ids[i],36+(i%2)*114,75+(i/2)*69,colors[i],titles[i],ink);
 }
 if(app==0&&homePage==1){
  text("Phone Apps",18,40,2,ink);
  const char* labels[]={"Settings","Calculator","Sketchpad","Flashlight","Clock","Music (BT)"};
  const uint16_t colors[]={0x6473,0x02ff,0x05ad,0xe520,0x049b,0xe82f};
  for(int i=0;i<6;i++)launcherIcon(5+i,36+(i%2)*114,75+(i/2)*69,colors[i],labels[i],ink);
 }
 if(app==0&&homePage==2){text("Offline Apps",18,40,2,ink);launcherIcon(13,36,75,0x0515,"Walkie-Chat",ink);}
 if(app==0){for(int i=0;i<3;i++){int x=4+i*80;g.fillRoundRect(x,289,72,27,6,homePage==i?0x025f:0x4a69);text("Page "+String(i+1),x+18,298);}}
 if(app==13)chatDraw();
 if(app==10){
  g.fillRoundRect(8,58,224,36,6,0x025f);text(musicBTStarted&&bt.is_connected()?"Connected":"Scan / Connect BT",20,71,1);
  text("Speakers",12,106,1,musicDevices?0xffe0:WHITE);text("SD Tracks",132,106,1,!musicDevices?0xffe0:WHITE);
  int count=musicDevices?deviceCount:trackCount,page=musicDevices?devicePage:trackPage;
  for(int row=0;row<3;row++){int i=page*3+row;g.fillRoundRect(8,128+row*30,224,28,4,0x39e7);if(i<count){String label=musicDevices?String(devices[i].name):tracks[i].substring(1);text(label.substring(0,34),12,138+row*30);}}
  if(!musicDevices&&!trackCount)text(musicMessage,12,138);
  text("< List",20,224);text("List >",177,224);
  const char* labels[]={"Prev",musicPlaying?"Pause":"Play","Next"};for(int i=0;i<3;i++){g.fillRoundRect(8+i*76,242,72,30,5,0x025f);text(labels[i],22+i*76,252);}
  text("Volume",12,280);g.fillRect(16,301,208,6,0x7bef);g.fillCircle(16+musicVolume*208/127,304,8,0x07ff);
  if(trackCount)text(tracks[musicTrack].substring(1,32),12,119);
 }
 if(app==9){
  const char* tabs[]={"Set Time","Timer","Stopwatch"};
  for(int i=0;i<3;i++){g.fillRoundRect(3+i*80,60,74,38,6,clockTab==i?0x025f:0x4a69);text(tabs[i],7+i*80,75);}
  if(clockTab==0){
   text(timeReady?String(clock):"Tap +/- to set time",8,108,1,ink);
   struct tm t=local;if(!timeReady){t.tm_year=savedYear-1900;t.tm_mon=savedMonth-1;t.tm_mday=savedDay;t.tm_hour=savedHour;}
   const char* labels[]={"Hour","Minute","AM/PM","Month","Day","Year"};
   String values[]={String(t.tm_hour%12?t.tm_hour%12:12),String(t.tm_min),t.tm_hour<12?"AM":"PM",String(t.tm_mon+1),String(t.tm_mday),String(t.tm_year+1900)};
   for(int i=0;i<6;i++){int y=130+i*31;g.fillRoundRect(4,y,42,28,5,0x025f);g.fillRoundRect(194,y,42,28,5,0x025f);text("-",20,y+6,2);text("+",207,y+6,2);text(String(labels[i])+": "+values[i],54,y+9,1,ink);}
  }else{
   if(clockTab==1){
    const char* presets[]={"1m","5m","10m"};for(int i=0;i<3;i++){g.fillRoundRect(4+i*80,110,72,40,6,0x39e7);text(presets[i],24+i*80,122,2);}
    int64_t secs=(countdownMs()+999)/1000;char value[24];snprintf(value,sizeof(value),"%02llu:%02llu",(unsigned long long)(secs/60),(unsigned long long)(secs%60));text(value,44,168,4,ink);
    text(timerAlert?"Time's up!":timerRunning?"Running":"Paused",84,211,1,ink);
    if(timerAlert)text("Tap here to dismiss alert",36,304,1,ink);
   }else{
    int64_t ms=stopwatchMs();char elapsed[32];snprintf(elapsed,sizeof(elapsed),"%02llu:%02llu:%02llu",(unsigned long long)(ms/3600000),(unsigned long long)(ms/60000%60),(unsigned long long)(ms/1000%60));
    text(elapsed,24,132,3,ink);char fraction[12];snprintf(fraction,sizeof(fraction),".%02u",(unsigned)(ms%1000/10));text(fraction,90,172,3,ink);text(stopwatchRunning?"Running":"Stopped",92,211,1,ink);
   }
   const char* labels[]={"Start",clockTab==1?"Pause":"Stop","Reset"};for(int i=0;i<3;i++){g.fillRoundRect(4+i*80,230,72,66,7,i==2?0xb800:0x025f);text(labels[i],10+i*80,254,2);}
  }
 }
 if(app==5){
  if(wifiConnectState==2 && millis()<wifiFeedbackUntil){
   g.fillRoundRect(2,25,236,31,4,0x0200);
   text("Connected! IP: "+wifiConnectedIP,5,37,1,0x07e0);
  }
  text("Screen brightness",12,77,1,ink);
  const char* levels[]={"Low","Medium","High","Max"};
  for(int i=0;i<4;i++){int x=8+i*56;g.fillRoundRect(x,112,52,42,6,brightness==i?0x025f:0x4a69);text(levels[i],x+(i==1?8:14),129);}
  g.fillRoundRect(12,160,216,37,6,0x025f);text("Lock / PIN Settings",32,173);
  g.fillRoundRect(12,211,102,46,6,darkMode?0x025f:0x4a69);text("Dark Mode",25,230);
  g.fillRoundRect(126,211,102,46,6,!darkMode?0x025f:0x4a69);text("Light Mode",137,230);
  g.fillRoundRect(12,268,216,44,6,0x025f);text("Wi-Fi Setup",62,283,2);
 }
 if(app==11){
  String status=WiFi.status()==WL_CONNECTED?"Connected: "+WiFi.localIP().toString():"Offline / connecting (2.4 GHz)";
  // Header retains the standard Home action.
  for(int i=0;i<2;i++){g.fillRoundRect(4,58+i*36,232,33,4,0x39e7);if(wifiField==i)g.drawRoundRect(4,58+i*36,232,33,4,0xffe0);String value=i?wifiPass:wifiName;if(i&&!wifiShow){value="";for(unsigned j=0;j<wifiPass.length();j++)value+='*';}text(i?"Password":"Network name",8,61+i*36);text(value.substring(value.length()>35?value.length()-35:0),8,76+i*36);}
  const char* controls[]={wifiKeys==0?"abc":wifiKeys==1?"ABC":"Symbols",wifiShow?"Hide":"Show","Delete"};
  for(int i=0;i<3;i++){g.fillRoundRect(i*80+2,130,76,26,4,0x025f);text(controls[i],i*80+10,139);}
  for(int r=0;r<4;r++)for(int c=0;c<10;c++){g.fillRoundRect(c*24+1,162+r*28,22,26,3,0x4a69);text(String(keyboardRows[wifiKeys][r][c]),c*24+6,170+r*28);}
  const char* actions[]={"Space","Clear","Connect"};for(int i=0;i<3;i++){int x=i<2?i*72:144;int w=i<2?70:94;g.fillRoundRect(x,278,w,24,4,0x025f);text(actions[i],x+8,286);}
  if(wifiConnectState==1){
   g.fillRoundRect(2,25,236,31,4,0x025f);
   text("Connecting to",8,29);text(wifiConnectingSSID.substring(0,36)+"...",8,42);
   text("Please wait (up to 10 seconds)",3,308,1,ink);
  }else if(wifiConnectState==3){
   g.fillRoundRect(2,25,236,31,4,0x7800);
   String reason;
   switch(wifiErrorStatus){
    case 0:reason="Idle / Timeout";break;
    case 1:reason="SSID Not Found";break;
    case 2:reason="Scan Complete";break;
    case 4:reason="Connection Failed";break;
    case 5:reason="Connection Lost";break;
    case 6:reason="Disconnected";break;
    case 255:reason="No Wi-Fi Shield";break;
    default:reason="Unknown Status";break;
   }
   text("Error "+String(wifiErrorStatus)+": "+reason,8,29,1,0xf800);
   text("Check password / 2.4GHz",8,42,1,0xf800);
   text("Edit details and tap Connect to retry",3,308,1,ink);
  }else text(status.substring(0,39),3,308,1,ink);
 }
 if(app==6){
  g.fillRoundRect(8,64,224,48,6,0x0000);text(calcEntry,16,80,calcEntry.length()>10?2:3);
  const char* labels[]={"7","8","9","/","4","5","6","x","1","2","3","-","C","0","=","+"};
  for(int i=0;i<16;i++){int x=8+(i%4)*56,y=120+(i/4)*48;
   g.fillRoundRect(x,y,52,44,6,i==12?0xb800:(i%4==3||i==14)?0x025f:0x4a69);text(labels[i],x+18,y+12,2);
  }
 }
 if(app==7){
  const char* labels[]={"Black","Red","Blue","Green","Erase"};
  for(int i=0;i<5;i++){g.fillRect(i*48,59,47,28,paintColors[i]);text(labels[i],i*48+5,69,1,i==4?0:WHITE);if(paint==i)g.drawRect(i*48,59,47,28,0xfd20);}
  text("Draw with your finger",4,95);g.fillRoundRect(166,88,72,22,4,0xb800);text("Clear",183,95);
  for(int y=0;y<202;y++)for(int x=0;x<240;x++)g.drawPixel(x,y+112,paintColors[canvas[y*240+x]]);
 }
 if(app==8){
  if(flashMode==0){g.fillSprite(WHITE);g.fillRoundRect(4,28,64,24,6,0x39e7);text("< Home",9,36);text("Flashlight",78,35,1,0);}
  const char* labels[]={"White Screen","Red LED","Green LED","Blue LED","Off"};
  uint16_t colors[]={0x4a69,0xb800,0x03e0,0x0018,0x39e7};
  for(int i=0;i<5;i++){g.fillRoundRect(14,80+i*45,212,40,8,colors[i]);text(labels[i],42,93+i*45,2);if(flashMode==i)g.drawRoundRect(14,80+i*45,212,40,8,0xffe0);}
 }
 if(app==15)msDraw();
 if(app==14)tetDraw();
 if(app==1){g.fillRect(0,60,240,236,0x03bf);g.fillRect(pipeX,60,38,gap-45-60,0x07e0);g.fillRect(pipeX,gap+45,38,296-gap-45,0x07e0);g.fillCircle(55,bird,9,0xffe0);g.fillCircle(58,bird-3,2,0);text("Score "+String(score),8,64);}
 if(app==2){for(int i=0;i<24;i++)if(bricks[i])g.fillRoundRect(9+(i%6)*38,80+(i/6)*22,33,16,3,0xf800+(i/6)*0x0180);g.fillRect(paddle-28,276,56,7,0x07ff);g.fillCircle(bx,by,4,WHITE);text("Score "+String(score),8,60);}
 if(app==3){for(int i=0;i<9;i++){int x=15+(i%3)*70,y=75+(i/3)*70;g.drawRoundRect(x,y,68,68,6,0x7bef);if(cells[i]==1){g.drawLine(x+18,y+18,x+50,y+50,0x07ff);g.drawLine(x+50,y+18,x+18,y+50,0x07ff);}if(cells[i]==2)g.drawCircle(x+34,y+34,20,0xfd20);}text(outcome?(outcome==1?"You win! Tap to reset":outcome==2?"AI wins. Tap to reset":"Draw! Tap to reset"):"You are X. Tap a square",8,301);}
 if(app==4){uint16_t colors[]={0xf800,0x07e0,0x001f,0xffe0,0xf81f,0x07ff};for(int i=0;i<12;i++){int x=12+(i%4)*54,y=75+(i/4)*68;bool open=matched[i]||i==first||i==last;g.fillRoundRect(x,y,48,60,6,open?colors[cards[i]]:0x39e7);text(open?String(cards[i]+1):"?",x+17,y+21,2,open?0:WHITE);}text(ended?"Matched! Tap to replay":"Moves: "+String(moves),12,298);}
 if((app==1||app==2)&&(!started||ended)){g.fillRoundRect(15,174,210,61,8,0x0000);text(ended?(app==2&&score==24?"You win!":"Game over"):"Tap to start",32,184,2);text(ended?"Tap to retry":app==1?"Tap anywhere to flap":"Drag to move paddle",28,215);}
 g.pushSprite(0,0);dirty=false;
}
// Three-point affine calibration handles reversed and swapped touch axes.
void calibrate(){const int sx[3]={25,215,25},sy[3]={65,65,285};float rx[3],ry[3];for(int i=0;i<3;i++){while(touch.touched())delay(10);tft.fillScreen(BG);tft.setTextColor(WHITE,BG);tft.setTextSize(1);tft.drawString("Touch calibration",20,10);tft.drawString("Press the cross, then release",10,30);tft.drawLine(sx[i]-12,sy[i],sx[i]+12,sy[i],WHITE);tft.drawLine(sx[i],sy[i]-12,sx[i],sy[i]+12,WHITE);while(!touch.touched())delay(10);delay(70);long x=0,y=0;int n=0;for(int j=0;j<20;j++){if(touch.touched()){auto p=touch.getPoint();x+=p.x;y+=p.y;n++;}delay(5);}if(!n){i--;continue;}rx[i]=(float)x/n;ry[i]=(float)y/n;while(touch.touched())delay(10);}
 float d=rx[0]*(ry[1]-ry[2])+rx[1]*(ry[2]-ry[0])+rx[2]*(ry[0]-ry[1]);if(abs(d)<100){calibrate();return;}for(int k=0;k<2;k++){const int *v=k?sy:sx;cal[k*3]=(v[0]*(ry[1]-ry[2])+v[1]*(ry[2]-ry[0])+v[2]*(ry[0]-ry[1]))/d;cal[k*3+1]=(v[0]*(rx[2]-rx[1])+v[1]*(rx[0]-rx[2])+v[2]*(rx[1]-rx[0]))/d;cal[k*3+2]=(v[0]*(rx[1]*ry[2]-rx[2]*ry[1])+v[1]*(rx[2]*ry[0]-rx[0]*ry[2])+v[2]*(rx[0]*ry[1]-rx[1]*ry[0]))/d;}prefs.putBytes("affine",cal,sizeof(cal));}
void setup(){for(int p:{4,16,17}){pinMode(p,OUTPUT);digitalWrite(p,HIGH);}pinMode(21,OUTPUT);digitalWrite(21,LOW);tft.init();tft.setRotation(0);digitalWrite(21,HIGH);touch.begin(touchSPI);touch.setRotation(0);prefs.begin("arcade",false);loadClock();prefs.getString("ssid",WIFI_SSID).toCharArray(WIFI_SSID,sizeof(WIFI_SSID));prefs.getString("wifiPass",WIFI_PASSWORD).toCharArray(WIFI_PASSWORD,sizeof(WIFI_PASSWORD));wifiQueue=xQueueCreate(1,sizeof(WifiCredentials));wifiResultQueue=xQueueCreate(1,sizeof(WifiConnectResult));chatQueue=xQueueCreate(4,sizeof(ChatPacket));brightness=constrain((int)prefs.getUChar("brightness",3),0,3);darkMode=prefs.getBool("dark",true);pinEnabled=prefs.getBool("pinEnabled",false);lockPin=prefs.getString("lockPin","1234");if(lockPin.length()!=4)lockPin="1234";sliderDuty=prefs.isKey("sliderDuty")?constrain((int)prefs.getUChar("sliderDuty",255),16,255):-1;beginBrightness();if(prefs.getBytesLength("affine")==sizeof(cal))prefs.getBytes("affine",cal,sizeof(cal));else calibrate();tft.fillScreen(BG);tft.drawString("Hold touch to recalibrate",12,150);uint32_t start=millis();bool hold=true;while(millis()-start<1500){if(millis()-start>250&&!touch.touched())hold=false;delay(10);}if(hold)calibrate();WiFi.mode(WIFI_STA);g.setColorDepth(8);if(!g.createSprite(240,320)){tft.fillScreen(0);tft.drawString("Not enough display memory",5,100);while(true)delay(1000);}memset(canvas,4,sizeof(canvas));randomSeed(esp_random());reset(0);radioLock=xSemaphoreCreateMutex();spiLock=xSemaphoreCreateMutex();pcm=xQueueCreate(2048,4);xTaskCreate(musicTask,"music",8192,nullptr,2,nullptr);setenv("TZ","EST5EDT,M3.2.0,M11.1.0",1);tzset();xTaskCreate(networkTask,"network",6144,nullptr,1,nullptr);}
void loop(){
 advanceOfflineClock();
 chatPoll();
 WifiConnectResult wifiResult;
 if(wifiResultQueue&&xQueueReceive(wifiResultQueue,&wifiResult,0)==pdTRUE){
  wifiConnectState=wifiResult.connected?2:3;
  wifiErrorStatus=wifiResult.status;
  if(wifiResult.connected){
   wifiConnectedIP=wifiResult.ip;wifiFeedbackUntil=millis()+8000;
   if(app==11)app=5;
  }
  dirty=true;
 }
 // Start/restart NTP on each Wi-Fi connection, independently of weather requests.
 static bool wifiWasConnected=false;
 bool wifiConnected=WiFi.status()==WL_CONNECTED;
 if(wifiConnected&&!wifiWasConnected){
  if(!manualClock)configTzTime("EST5EDT,M3.2.0,M11.1.0", "pool.ntp.org", "time.nist.gov");
  dirty=true;
 }
 wifiWasConnected=wifiConnected;
 if(timerRunning&&countdownMs()==0){timerRemaining=0;timerRunning=false;timerAlert=true;timerLedPhase=-1;dirty=true;}
 if(timerAlert){int phase=(millis()/250)%6; // RGB flashes, separated by dark intervals.
  if(phase!=timerLedPhase||blueUntil){rgbOff();if(phase%2==0)digitalWrite(phase==0?4:phase==2?16:17,LOW);timerLedPhase=phase;}
 }
 if(!locked&&app==9&&clockTab==2&&stopwatchRunning&&millis()-tick>=25)dirty=true;
 bool down=touch.touched();if(down){lastTouchMillis=millis();xSemaphoreTake(spiLock,portMAX_DELAY);auto p=touch.getPoint();xSemaphoreGive(spiLock);int x=constrain((int)(cal[0]*p.x+cal[1]*p.y+cal[2]),0,239),y=constrain((int)(cal[3]*p.x+cal[4]*p.y+cal[5]),0,319);tap(x,y,!wasDown);}if(!down){lockTouchSwallow=false;prevX=prevY=-1;chatDrag=-1;quickSwallow=false;if(brightnessPending){prefs.putUChar("sliderDuty",sliderDuty);brightnessPending=false;}}persistClock(down);
 if(!down&&!locked&&screenTimeoutMs>0&&(uint32_t)(millis()-lastTouchMillis)>=screenTimeoutMs){
  locked=true;lockPinStage=false;lockTransition=0;quickOpen=false;pinEntry="";lockMessage="";dirty=true;
 }
 wasDown=down;if(millis()-tick>=25){tick=millis();update();}if(app==10&&millis()/1000!=second)dirty=true;if(millis()/1000!=second){second=millis()/1000;dirty=true;}if(locked&&lockPinStage&&lockTransition)dirty=true;if(dirty)draw();delay(3);}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik