Turn an ESP32 into a portable Game Boy emulator capable of playing classic GB and GBC games. This project combines the ESP32's processing power with an SD card for game storage, delivering authentic 8-bit gaming in a compact form factor with full color support and save state functionality.
This guide provides a complete parts list, wiring diagram for connecting the display and input controls, firmware setup instructions, and step-by-step assembly. Learn how to prepare your game library, flash the emulator to the ESP32, and configure the hardware for responsive gameplay.
Wiring diagram

Assemble it in 1 step
1. Prepare your game library
With USB power disconnected, insert a FAT32 microSD card. Put legally obtained Game Boy .gb and Game Boy Color .gbc files in its top-level folder. Connect USB and press Deploy. The home screen shows the files as a 12-cartridge grid and also offers the built-in Pokemon Red. Tap a cartridge to play or its bottom-left NAME to give it a display name.
- Back up the card before formatting. Formatting erases it.
- Game Boy and Game Boy Color games are supported with native color palettes for Color games. Compatibility and speed vary by game. Maximum ROM size is 8 MiB. The library lists up to 127 card games plus the built-in game.
- Tap HOME to switch games or SAVE / LOAD to open three slots for the current game. SAVE overwrites that slot; NAME opens a touch keyboard. LOAD restores the saved moment. Slots and names persist on the card across restarts, but save states are specific to this firmware version. Previous Peanut-GB save-state slots are incompatible with this Walnut-CGB update; normal cartridge saves are retained.
- Cartridge saves are also written every 60 seconds and when leaving gameplay. Existing built-in Pokemon cartridge progress is imported if present; old session quicksaves are not compatible.
- The game view is 288 by 259 pixels. EMU reports game speed and LCD reports frames drawn. Card-loaded games may be slower than the built-in game.
- Do not remove the card while powered. Wait for Saved to card before disconnecting USB.
- Tap ICON beneath a game to cycle four built-in icon styles. Selections persist on the card. For your own artwork, put a 56 by 52 pixel uncompressed 24-bit BMP beside the ROM, with .bmp added to its full name (for example, Mario.gbc.bmp). Use builtin.bmp for the built-in game. Custom artwork takes priority; remove it from the card to use the selectable icons again.
- GBA files are not supported by this GB/GBC emulator. The display targets about 30 FPS; this is not a guarantee of full-speed emulation, especially for Color games. EMU and LCD counters report separate measured rates.
Deploy the firmware
#include "game_icons.h"
#include <Arduino.h>
#include "screen_adapter.h"
#include "cartridge_rom.h"
#include <SD.h>
#include <SPI.h>
#include <atomic>
#include <algorithm>
#include <driver/ledc.h>
#include <esp_timer.h>
#include <setjmp.h>
#define ENABLE_SOUND 0
#define WALNUT_FULL_GBC_SUPPORT 1
#define WALNUT_GB_12_COLOUR 1
#pragma GCC push_options
#pragma GCC optimize ("O3")
#include "walnut_cgb.h"
#pragma GCC pop_options
// Only the emulation task touches gb/cart RAM. Display receives complete frames.
static SPIClass sdBus(VSPI);
static uint8_t romHeader[0x150];
struct SceneCleanup { bool due(uint32_t,uint32_t){return false;} void changed(uint32_t,unsigned){} void cleaned(){} };
static gb_s gb;
static M5Canvas canvas(&M5.Display);
static uint8_t *rom, *ram;
// Reserve typical cartridge RAM before display and SD allocations fragment the heap.
static uint8_t cartridgeSaveBuffer[32768];
static size_t romSize, ramSize;
static constexpr size_t FRAME_BYTES=160*144;
static uint8_t *drawing, *latest;
static uint16_t displayPalette[64];
// Short cross-core memory sections must not sleep for a FreeRTOS tick per row.
static portMUX_TYPE frameLock = portMUX_INITIALIZER_UNLOCKED;
static std::atomic<uint8_t> buttons{0};
static std::atomic<bool> paused{false}, cleanRequested{false}, fault{false};
static std::atomic<uint32_t> emulatedFrames{0}, lastInputAt{0};
static std::atomic<uint8_t> injectedButtons{0};
static bool isDemo=false;
static uint8_t latestArea=0; // paired with latest pixels under frameLock
static const char* areaNames[]={"VILLAGE", "FOREST", "LAKESIDE", "LEFT HOUSE", "RIGHT HOUSE"};
static uint32_t generation = 0;
static bool dirty = false;
static String savePath;
static char title[17];
static constexpr int GX=16, GY=48, GW=288, GH=259;
// Persistent save slots. Only the emulation task reads/writes snapshots.
static String quickPath;
static uint16_t pixel(const uint8_t* frame, int index) { return reinterpret_cast<const uint16_t*>(frame)[index]; }
static std::atomic<uint8_t> stateRequest{0}, slotStatus{0};
static bool slotValid=false;
struct Key { int x,y,w,h; uint8_t bit; const char* label; };
static const Key keys[] = {
{52,336,52,44,JOYPAD_UP,"UP"}, {52,424,52,44,JOYPAD_DOWN,"DN"},
{0,380,52,44,JOYPAD_LEFT,"<"}, {104,380,52,44,JOYPAD_RIGHT,">"},
{246,336,74,74,JOYPAD_A,"A"}, {166,376,74,74,JOYPAD_B,"B"},
{104,454,74,26,JOYPAD_SELECT,"SELECT"}, {184,454,78,26,JOYPAD_START,"START"}
};
struct Game { String path, name; uint8_t icon=0; };
static Game games[128]; static int gameCount=0, activeGame=-1, page=0;
static std::atomic<int> launchGame{-1};
static std::atomic<bool> busy{false};
static int selectedSlot=0;
static String slotNames[3];
static bool embedded=true;
static bool gameReady=false;
static File gameFile;
static constexpr int CACHE_COUNT=32;
static constexpr unsigned CACHE_BYTES=4096;
static constexpr unsigned PINNED_PAGES=16384/CACHE_BYTES;
static int cacheCount=0;
static uint8_t* bankCache[CACHE_COUNT]={};
static uint32_t cacheMisses=0;
static int cacheBanks[CACHE_COUNT];
static uint32_t cacheAge[CACHE_COUNT]={};
static uint32_t cacheClock=0;
static int lastCache=-1;
// Direct page lookup avoids scanning the cache on every emulated ROM read.
static int8_t pageSlot[2048];
static jmp_buf emulatorRecovery;
static uint8_t* cachedRomBank(uint32_t bank) {
if(bank>=2048) return nullptr;
int hit=pageSlot[bank];
if(hit>=0) {
// O(1) lookup and age update, even across interrupt/banked-ROM jumps.
cacheAge[hit]=++cacheClock;
return bankCache[hit];
}
unsigned i=bank<PINNED_PAGES?bank:PINNED_PAGES;
if(bank>=PINNED_PAGES) for(int j=PINNED_PAGES;j<cacheCount;++j) {
if(cacheBanks[j]<0) { i=j; break; }
if(cacheAge[j]<cacheAge[i]) i=j;
}
if(cacheBanks[i]>=0) pageSlot[cacheBanks[i]]=-1;
++cacheMisses;
if(!gameFile.seek(bank*CACHE_BYTES) || gameFile.read(bankCache[i],CACHE_BYTES)!=CACHE_BYTES) {
Serial.printf("ROM read failed: bank %u\n",unsigned(bank));
fault.store(true); paused.store(true); return nullptr;
}
cacheBanks[i]=bank; cacheAge[i]=++cacheClock; pageSlot[bank]=int8_t(i);
if(bank>=PINNED_PAGES) lastCache=i;
return bankCache[i];
}
static uint32_t gameHash=0;
enum View { HOME, PLAY, SLOTS, KEYBOARD, ICONS };
static View view=HOME, returnView=HOME;
static bool uiDirty=true, namingGame=false;
static int iconGame=0;
static String editName, uiMessage;
static String metaPath(int n) { return games[n].path+".name"; }
static String slotPath(int slot) { return savePath+".slot"+String(slot+1); }
static String readName(String path, String fallback) {
File f=SD.open(path,FILE_READ); if(!f) return fallback;
String n=f.readStringUntil('\n'); f.close(); n.trim(); return n.length()?n.substring(0,24):fallback;
}
static void readSlotNames() {
for(int i=0;i<3;++i) slotNames[i]=readName(slotPath(i)+".name",String("Slot ")+String(i+1));
}
static void scanGames() {
games[gameCount++]={"", "Pokemon Red (built-in)"};
File root=SD.open("/");
for(File f=root.openNextFile(); f && gameCount<128; f=root.openNextFile()) {
String path=f.name(); if(!path.startsWith("/")) path="/"+path;
String lower=path; lower.toLowerCase();
if(!f.isDirectory() && !path.startsWith("/.") && (lower.endsWith(".gb") || lower.endsWith(".gbc"))) {
String base=path.substring(1,path.length()-(lower.endsWith(".gbc")?4:3));
games[gameCount++]={path,readName(path+".name",base)};
}
f.close();
}
root.close(); games[0].name=readName("/builtin.name",games[0].name);
for(int i=0;i<gameCount;++i) {
String path=i==0?String("/builtin.icon"):games[i].path+".icon";
games[i].icon=readName(path,"0").toInt()%12;
}
}
static bool inside(int x,int y,int rx,int ry,int w,int h) {
return x>=rx && x<rx+w && y>=ry && y<ry+h;
}
static uint8_t readRom(gb_s*, uint_fast32_t a) {
if(embedded) return a<sizeof cartridgeROM ? cartridgeROM[a] : 0xff;
if(a>=romSize) return 0xff;
uint8_t* bank=cachedRomBank(a/CACHE_BYTES);
return bank?bank[a%CACHE_BYTES]:0xff;
}
static uint16_t readRom16(gb_s* g,uint_fast32_t a) {
if(embedded && a+1<sizeof cartridgeROM) return uint16_t(cartridgeROM[a]) | (uint16_t(cartridgeROM[a+1])<<8);
if(!embedded && a+1<romSize && (a&(CACHE_BYTES-1))<CACHE_BYTES-1) { uint8_t* p=cachedRomBank(a/CACHE_BYTES); if(p) {p+=a&(CACHE_BYTES-1); return uint16_t(p[0]) | (uint16_t(p[1])<<8);} }
return uint16_t(readRom(g,a)) | (uint16_t(readRom(g,a+1))<<8);
}
static uint32_t readRom32(gb_s* g,uint_fast32_t a) {
if(embedded && a+3<sizeof cartridgeROM) { const uint8_t* p=cartridgeROM+a; return uint32_t(p[0]) | (uint32_t(p[1])<<8) | (uint32_t(p[2])<<16) | (uint32_t(p[3])<<24); }
if(!embedded && a+3<romSize && (a&(CACHE_BYTES-1))<CACHE_BYTES-3) { uint8_t* p=cachedRomBank(a/CACHE_BYTES); if(p) {p+=a&(CACHE_BYTES-1); return uint32_t(p[0]) | (uint32_t(p[1])<<8) | (uint32_t(p[2])<<16) | (uint32_t(p[3])<<24);} }
return uint32_t(readRom16(g,a)) | (uint32_t(readRom16(g,a+2))<<16);
}
static uint8_t readRam(gb_s*, uint_fast32_t a) { return a<ramSize ? ram[a] : 0xff; }
static void writeRam(gb_s*, uint_fast32_t a,uint8_t v) {
if(a<ramSize && ram[a]!=v) { ram[a]=v; dirty=true; }
}
static void error(gb_s*, gb_error_e e, uint16_t a) {
Serial.printf("Emulator error %d at %04x\n", int(e), a);
fault.store(true); paused.store(true);
longjmp(emulatorRecovery,1); // Exit invalid CPU execution, keep the worker alive for another game.
}
static void line(gb_s*, const uint8_t* pixels, uint_fast8_t y) {
if(y>=144) return;
// Lock only while publishing a scanline, not while executing the CPU.
portENTER_CRITICAL(&frameLock);
// Keep palette indices rather than expanding every pixel in RAM.
memcpy(drawing+y*160,pixels,160);
static const uint16_t dmg[]={0x9e29,0x8d88,0x3326,0x11c3};
// Palette changes normally occur at frame boundaries. Avoid 64 copies
// on every scanline; publish the palette with the completed frame.
if(y==143) for(int i=0;i<64;++i) displayPalette[i]=gb.cgb.cgbMode?gb.cgb.fixPalette[i]:dmg[i&3];
if(y==143) {
// A single shared RGB frame avoids a second 46 KiB allocation.
latestArea=isDemo?gb.wram[1]:0; ++generation;
}
portEXIT_CRITICAL(&frameLock);
}
static void save() {
if(!dirty || !ramSize) return;
String tmp=savePath+".tmp";
File f=SD.open(tmp,"w");
if(!f) { Serial.println("Cannot open save"); return; }
bool ok=f.write(ram,ramSize)==ramSize; f.close();
if(ok && (!SD.exists(savePath) || SD.remove(savePath)) && SD.rename(tmp,savePath)) { dirty=false; Serial.println("Cartridge RAM saved"); }
else Serial.println("Save failed; RAM remains dirty");
}
static void reportMemory() {
const uint32_t heap=ESP.getHeapSize(), freeHeap=ESP.getFreeHeap();
const uint32_t psram=ESP.getPsramSize(), freePsram=ESP.getFreePsram();
const uint32_t flash=ESP.getFlashChipSize(), firmware=ESP.getSketchSize();
const size_t fs=SD.totalBytes(), usedFs=SD.usedBytes();
Serial.printf("MEM internal-heap used=%u total=%u (%.2f%%) free=%u min-free=%u largest=%u\n",
heap-freeHeap,heap,heap?100.0*(heap-freeHeap)/heap:0.0,freeHeap,
ESP.getMinFreeHeap(),ESP.getMaxAllocHeap());
Serial.printf("MEM PSRAM used=%u total=%u (%.2f%%) free=%u\n",
psram-freePsram,psram,psram?100.0*(psram-freePsram)/psram:0.0,freePsram);
Serial.printf("MEM firmware=%u physical-flash=%u (%.2f%%)\n",
firmware,flash,flash?100.0*firmware/flash:0.0);
Serial.printf("MEM filesystem used=%u total=%u (%.2f%%)\n",
unsigned(usedFs),unsigned(fs),fs?100.0*usedFs/fs:0.0);
}
static bool loadGame(int index) {
gameReady=false; save(); gameFile.close();
if(ram && ram!=cartridgeSaveBuffer) free(ram);
ram=nullptr; ramSize=0;
activeGame=index; embedded=games[index].path.length()==0;
memset(pageSlot,-1,sizeof pageSlot);
for(int &n:cacheBanks) n=-1;
lastCache=-1; cacheClock=0; cacheMisses=0; memset(cacheAge,0,sizeof cacheAge);
if(embedded) { romSize=sizeof cartridgeROM; memcpy(romHeader,cartridgeROM,sizeof romHeader); }
else {
if(!cacheCount) {
// Separate banks can use fragmented free heap; retain room for SD and saves.
for(int i=0;i<CACHE_COUNT;++i) {
if(i>=int(PINNED_PAGES+1) && ESP.getFreeHeap()<24576+CACHE_BYTES) break;
bankCache[i]=static_cast<uint8_t*>(malloc(CACHE_BYTES));
if(!bankCache[i]) break;
++cacheCount;
}
}
if(cacheCount<int(PINNED_PAGES+1)) { uiMessage="Not enough ROM cache RAM"; return false; }
gameFile=SD.open(games[index].path,FILE_READ);
if(!gameFile || gameFile.read(romHeader,sizeof romHeader)!=sizeof romHeader) { uiMessage="Cannot read game"; return false; }
romSize=gameFile.size();
}
rom=romHeader;
if(romSize>8*1024*1024 || rom[0x148]>8 || rom[0x149]>5 || romSize!=(size_t(32768)<<rom[0x148])) { uiMessage="Unsupported GB/GBC ROM"; return false; }
// gb_init does not clear every work register, RAM byte or palette cache.
// Starting a different cartridge must not inherit the previous game's state.
memset(&gb,0,sizeof gb);
int init=gb_init(&gb,readRom,readRom16,readRom32,readRam,writeRam,error,nullptr);
if(init!=GB_INIT_NO_ERROR) { uiMessage=init==GB_INIT_INVALID_CHECKSUM?"Invalid ROM checksum":"Unsupported cartridge type"; return false; }
if(gb_get_save_size_s(&gb,&ramSize)!=0) { uiMessage="Invalid cartridge RAM size"; return false; }
if(ramSize) { ram=ramSize<=sizeof cartridgeSaveBuffer ? cartridgeSaveBuffer : static_cast<uint8_t*>(malloc(ramSize)); if(!ram) { ramSize=0; uiMessage="Not enough save RAM"; return false; } memset(ram,255,ramSize); }
gameHash=2166136261u;
// Hash complete content, so equal titles cannot mix save files.
if(embedded) { for(size_t i=0;i<romSize;++i) gameHash=(gameHash^cartridgeROM[i])*16777619u; }
else { uint8_t buf[512]; gameFile.seek(0); while(gameFile.available()) { int n=gameFile.read(buf,sizeof buf); for(int i=0;i<n;++i) gameHash=(gameHash^buf[i])*16777619u; } }
static uint32_t builtinHash=0;
if(!builtinHash) {
builtinHash=2166136261u;
for(size_t i=0;i<sizeof cartridgeROM;++i) builtinHash=(builtinHash^cartridgeROM[i])*16777619u;
}
if(!embedded && romSize==sizeof cartridgeROM && gameHash==builtinHash) {
embedded=true; gameFile.close();
Serial.println("Identical built-in ROM: using flash, no SD reads during gameplay");
}
char path[40]; snprintf(path,sizeof path,"/save-%08lx.sav",(unsigned long)gameHash); savePath=path;
if(ramSize) { File f=SD.open(savePath,FILE_READ); if(f && f.size()==ramSize) f.read(ram,ramSize); f.close(); }
if(embedded && ramSize && !SD.exists(savePath)) {
uint32_t legacy=2166136261u; for(size_t i=0;i<sizeof romHeader;++i) legacy=(legacy^romHeader[i])*16777619u;
char old[40]; snprintf(old,sizeof old,"/save-%08lx.sav",(unsigned long)legacy);
File f=SD.open(old,FILE_READ); if(f && f.size()==ramSize) f.read(ram,ramSize); f.close();
}
// The core resets raw CGB palettes but leaves its converted palette cache
// untouched. Initialize that cache too, before the first LCD scanline.
for(unsigned i=0;i<64;++i) gb.cgb.fixPalette[i]=0xffff;
Serial.printf("Cartridge mode: %s; ROM %u bytes; save RAM %u bytes\n",
gb.cgb.cgbMode?"Game Boy Color":"Game Boy",unsigned(romSize),unsigned(ramSize));
Serial.printf("ROM cache: %d pages (%u bytes)\n",cacheCount,unsigned(cacheCount*CACHE_BYTES));
gameReady=true; dirty=false; gb_get_rom_name(&gb,title); gb_init_lcd(&gb,line); gb.direct.frame_skip=0; gb.direct.interlace=0;
memset(drawing,0,FRAME_BYTES);
portENTER_CRITICAL(&frameLock); memcpy(latest,drawing,FRAME_BYTES); ++generation; portEXIT_CRITICAL(&frameLock);
fault.store(false); readSlotNames(); uiMessage=""; return true;
}
struct SaveHeader { uint32_t magic, version, hash, stateSize, ramBytes; };
static void handleSlot(bool writing) {
String path=slotPath(selectedSlot), tmp=path+".tmp";
if(!gameReady || SD.cardType()==CARD_NONE) {
Serial.println("Save/load: SD card unavailable or no game running");
slotStatus.store(4); return;
}
bool ok=false;
SaveHeader h={0x56425333,2,gameHash,sizeof gb,uint32_t(ramSize)};
if(writing) {
SD.remove(tmp); File f=SD.open(tmp,FILE_WRITE);
ok=f && f.write((uint8_t*)&h,sizeof h)==sizeof h && f.write((uint8_t*)&gb,sizeof gb)==sizeof gb;
if(ok && ramSize) ok=f.write(ram,ramSize)==ramSize;
if(ok) ok=f.write(drawing,FRAME_BYTES)==FRAME_BYTES;
f.flush(); f.close();
if(ok) { SD.remove(path+".bak"); if(SD.exists(path)) ok=SD.rename(path,path+".bak"); if(ok) ok=SD.rename(tmp,path); }
save();
} else {
File f=SD.open(path,FILE_READ); SaveHeader check{};
ok=f && f.read((uint8_t*)&check,sizeof check)==sizeof check && memcmp(&h,&check,sizeof h)==0 && f.size()==sizeof h+sizeof gb+ramSize+FRAME_BYTES;
// Validate readability with a small buffer, not a second full emulator.
// A duplicate CGB state can exceed the remaining contiguous ESP32 heap.
uint8_t probe[512];
while(ok && f.available()) {
size_t n=std::min(size_t(f.available()),sizeof probe);
ok=f.read(probe,n)==n;
}
if(ok) ok=f.seek(sizeof h);
// Callbacks are firmware addresses, never portable save data.
auto romRead=gb.gb_rom_read;
auto romRead16=gb.gb_rom_read_16bit;
auto romRead32=gb.gb_rom_read_32bit;
auto ramRead=gb.gb_cart_ram_read;
auto ramWrite=gb.gb_cart_ram_write;
auto onError=gb.gb_error;
auto serialTx=gb.gb_serial_tx;
auto serialRx=gb.gb_serial_rx;
auto bootRead=gb.gb_bootrom_read;
auto lcdLine=gb.display.lcd_draw_line;
if(ok) {
ok=f.read((uint8_t*)&gb,sizeof gb)==sizeof gb;
gb.gb_rom_read=romRead; gb.gb_rom_read_16bit=romRead16; gb.gb_rom_read_32bit=romRead32;
gb.gb_cart_ram_read=ramRead; gb.gb_cart_ram_write=ramWrite;
gb.gb_error=onError; gb.gb_serial_tx=serialTx; gb.gb_serial_rx=serialRx;
gb.gb_bootrom_read=bootRead; gb.display.lcd_draw_line=lcdLine; gb.direct.priv=nullptr;
if(ok && ramSize) ok=f.read(ram,ramSize)==ramSize;
if(ok) ok=f.read(drawing,FRAME_BYTES)==FRAME_BYTES;
if(ok) {
gb.direct.joypad=0xff; dirty=true;
portENTER_CRITICAL(&frameLock);
memcpy(latest,drawing,FRAME_BYTES);
static const uint16_t dmg[]={0x9e29,0x8d88,0x3326,0x11c3};
for(int i=0;i<64;++i) displayPalette[i]=gb.cgb.cgbMode?gb.cgb.fixPalette[i]:dmg[i&3];
++generation; portEXIT_CRITICAL(&frameLock);
} else {
// A card removed during the second read must not run partial CPU state.
gameReady=false; paused.store(true);
}
}
f.close();
}
Serial.printf("Slot %d %s: %s\n",selectedSlot+1,writing?"save":"load",ok?"OK":"failed (missing/incompatible file or card I/O)");
slotStatus.store(ok?(writing?1:2):3);
}
static void emulatorTask(void*) {
int64_t next=esp_timer_get_time(); uint32_t lastSave=millis();
for(;;) {
int launch=launchGame.exchange(-1);
if(launch>=0) { bool ok=loadGame(launch); Serial.printf("Game launch: %s %s; free RAM %u\n",games[launch].name.c_str(),ok?"ready":uiMessage.c_str(),ESP.getFreeHeap()); busy.store(false); next=esp_timer_get_time(); }
uint8_t request=stateRequest.exchange(0);
if(request==1 || request==2) { handleSlot(request==1); busy.store(false); next=esp_timer_get_time(); }
if(request==3) { save(); busy.store(false); }
if(paused.load() || !gameReady) { next=esp_timer_get_time(); vTaskDelay(pdMS_TO_TICKS(10)); continue; }
gb.direct.joypad=uint8_t(~buttons.load());
if(setjmp(emulatorRecovery)) {
gameReady=false;
busy.store(false);
next=esp_timer_get_time();
continue;
}
const int64_t frameStart=esp_timer_get_time();
// Keep emulated time at the original clock. If rendering is expensive,
// drop LCD refreshes, never CPU instructions or game logic.
static unsigned renderPhase=0;
gb.display.lcd_draw_line=(renderPhase++%2==0)?line:nullptr;
gb.direct.frame_skip=0;
// This library release disables its dual-fetch safety checks internally.
// CGB bank switching / HDMA needs the non-prefetch execution path.
if(gb.cgb.cgbMode) gb_run_frame(&gb);
else gb_run_frame_dualfetch(&gb);
++emulatedFrames;
// Keep LCD output at half the native rate (about 30 FPS).
// The old adaptive divisor could silently reduce output to 10 FPS.
static uint32_t perfAt=0, perfFrames=0, perfMisses=0;
if(millis()-perfAt>=3000) {
uint32_t now=millis(), frames=emulatedFrames.load();
Serial.printf("PERF emu=%.1f fps ROM misses=%u cache=%d frame=%u us free=%u\n",
(frames-perfFrames)*1000.0f/(now-perfAt),cacheMisses-perfMisses,cacheCount,
unsigned(esp_timer_get_time()-frameStart),ESP.getFreeHeap());
perfAt=now; perfFrames=frames; perfMisses=cacheMisses;
}
static uint32_t demoReportAt=0;
if(isDemo && buttons.load() && millis()-demoReportAt>=250) {
Serial.printf("DEMO area=%u panel=%u quest=%u sprite x=%u y=%u feet=%u,%u\n",
unsigned(gb.wram[1]),unsigned(gb.wram[3]),unsigned(gb.wram[4]),
unsigned(gb.oam[1]),unsigned(gb.oam[0]),
unsigned(gb.oam[1]-7),unsigned(gb.oam[0]-9));
demoReportAt=millis();
}
// Save only after controls are released, avoiding SD writes during action.
// Explicit HOME / SAVE also flushes cartridge RAM.
if(millis()-lastSave>=60000 && !buttons.load()) { save(); lastSave=millis(); next=esp_timer_get_time(); }
next+=16743; // DMG 59.7275 Hz, independent of slow panel refreshes.
int64_t wait=next-esp_timer_get_time();
if(wait>1000) vTaskDelay(pdMS_TO_TICKS(uint32_t(wait/1000)));
else { vTaskDelay(1); if(wait < -100000) next=esp_timer_get_time(); }
}
}
static void text(const char* s,int x,int y,int size=2) {
canvas.setTextSize(size); canvas.setCursor(x,y); canvas.print(s);
}
// Startup only: no emulator/input tasks run until this finite sequence ends.
// Monochrome motion, no alternating full-screen flashes; touch skips the show.
static void startupAnimation() {
M5.Display.fillScreen(TFT_WHITE);
M5.Display.setTextColor(TFT_BLACK,TFT_WHITE);
M5.Display.setTextSize(2); M5.Display.setCursor(20,100);
M5.Display.println("VIBE BOY / SD"); delay(500);
}
static void fatal(const char* message) {
Serial.println(message);
M5.Display.setEpdMode(m5gfx::epd_mode_t::epd_text);
M5.Display.fillScreen(TFT_WHITE); M5.Display.setTextColor(TFT_BLACK,TFT_WHITE);
M5.Display.setTextSize(2); M5.Display.setCursor(20,40); M5.Display.println(message);
M5.Display.display(); M5.Display.waitDisplay();
while(true) delay(1000);
}
void setup() {
Serial.begin(115200); delay(500);
setCpuFrequencyMhz(240);
auto cfg=M5.config(); cfg.clear_display=false;
cfg.internal_imu=false; cfg.internal_rtc=false; cfg.internal_mic=false; cfg.internal_spk=false;
M5.begin(cfg);
drawing=static_cast<uint8_t*>(calloc(FRAME_BYTES,1));
latest=drawing; // Shared frame protected by frameLock.
if(!drawing || !latest) fatal("Frame allocation failed");
// Portrait handheld layout: screen above controls, like the reference photo.
M5.Display.setAutoDisplay(false); M5.Display.setRotation(0);
if(M5.Display.width()!=320 || M5.Display.height()!=480) fatal("Expected 320x480 TFT");
// UI draws directly to the TFT; only packed game frames use RAM.
sdBus.begin(18,19,23,5);
if(!SD.begin(5,sdBus,10000000)) fatal("Insert FAT32 SD card, then restart");
scanGames(); paused.store(true);
if(xTaskCreatePinnedToCore(emulatorTask,"gameboy",12288,nullptr,1,nullptr,0)!=pdPASS) fatal("Task allocation failed");
}
static constexpr uint16_t SHELL=0x0843, BEZEL=0x0000, INK=0x0021, WINE=0xf81f, BLUE=0x07ff;
static void label(String s,int x,int y,int size=1) {
M5.Display.setTextSize(size); M5.Display.setTextColor(BLUE,SHELL); M5.Display.setCursor(x,y); M5.Display.print(s);
}
static void button(String s,int x,int y,int w,int h) {
M5.Display.fillRoundRect(x,y+2,w,h-2,8,BEZEL);
M5.Display.fillRoundRect(x,y,w,h-3,8,0x08c8);
M5.Display.drawRoundRect(x-1,y-1,w+2,h-1,9,0x981f);
M5.Display.drawRoundRect(x,y,w,h-3,8,0xfd20); label(s,x+6,y+h/2-4);
}
// Icon pixels are native RGB565 words, not pre-swapped display bytes.
// Use the explicit pixel type so gameplay byte-order settings cannot alter them.
// Neon icon shelf, drawn only when the library changes.
static void neonBox(int x,int y,int w,int h,uint16_t edge) {
M5.Display.drawRoundRect(x-3,y-3,w+6,h+6,10,0x6816);
M5.Display.drawRoundRect(x-2,y-2,w+4,h+4,9,0x981f);
M5.Display.drawRoundRect(x-1,y-1,w+2,h+2,8,edge);
M5.Display.fillRoundRect(x,y,w,h,7,0x0846);
M5.Display.drawRoundRect(x,y,w,h,7,edge);
M5.Display.drawRoundRect(x+2,y+2,w-4,h-4,5,0xfd20);
}
static bool drawCover(const String& path,int x,int y) {
File f=SD.open(path,FILE_READ); if(!f) return false;
uint8_t h[54];
if(f.read(h,54)!=54 || h[0]!='B' || h[1]!='M') { f.close(); return false; }
auto u32=[&](int n){return uint32_t(h[n])|(uint32_t(h[n+1])<<8)|(uint32_t(h[n+2])<<16)|(uint32_t(h[n+3])<<24);};
if(u32(18)!=56 || u32(22)!=52 || h[28]!=24 || u32(30)!=0) { f.close(); return false; }
uint8_t bytes[168]; uint16_t colors[56];
for(int row=0;row<52;++row) {
if(!f.seek(u32(10)+(51-row)*168) || f.read(bytes,168)!=168) { f.close(); return false; }
for(int i=0;i<56;++i) colors[i]=((bytes[i*3+2]&248)<<8)|((bytes[i*3+1]&252)<<3)|(bytes[i*3]>>3);
M5.Display.pushImage(x,y+row,56,1,reinterpret_cast<const lgfx::rgb565_t*>(colors));
}
f.close(); return true;
}
// Static pixel scenery: no animation work competes with the emulator.
static void pixelLandscape() {
M5.Display.fillRect(0,454,320,26,0x0843);
for(int n=0;n<9;++n) {
int x=n*40-10;
M5.Display.fillTriangle(x,474,x+20,455-(n%3)*3,x+40,474,0x3296);
M5.Display.fillTriangle(x+13,462-(n%3)*3,x+20,455-(n%3)*3,x+27,462-(n%3)*3,0xbfff);
}
M5.Display.fillRect(0,472,320,4,0x07e0);
M5.Display.fillRect(0,476,320,4,0x5124);
for(int x=4;x<320;x+=16) M5.Display.fillRect(x,477,6,2,0xb326);
for(int n=0;n<5;++n) {
int x=20+n*64;
M5.Display.fillRect(x,465,3,7,0x07e0);
M5.Display.fillRect(x-2,463,7,3,n%2?0xffe0:0xf81f);
}
}
// Six roomy cards per page; redraw only when the home view changes.
static void drawCartridge(int index,int x,int y) {
const uint16_t gold=0xfd20, purple=0x981f, panel=0x1087;
bool current=index==activeGame;
M5.Display.fillRoundRect(x,y+3,146,84,10,0x0000);
M5.Display.fillRoundRect(x,y,146,84,10,panel);
M5.Display.drawRoundRect(x,y,146,84,10,current?gold:purple);
M5.Display.drawRoundRect(x+2,y+2,142,80,8,current?gold:0x4010);
M5.Display.pushImage(x+6,y+6,56,52,reinterpret_cast<const lgfx::rgb565_t*>(gameIcons[games[index].icon%12]));
String name=games[index].name;
M5.Display.setTextSize(1); M5.Display.setTextColor(TFT_WHITE,panel);
M5.Display.setCursor(x+68,y+9); M5.Display.print(name.substring(0,12));
M5.Display.setCursor(x+68,y+21); M5.Display.print(name.length()>24?name.substring(12,23)+"~":name.substring(12));
M5.Display.setTextColor(current?gold:0xb59f,panel);
M5.Display.setCursor(x+68,y+36); M5.Display.print(current?"LAST PLAYED":games[index].path.endsWith(".gbc")?"GB COLOR":"GAME BOY");
M5.Display.fillRoundRect(x+68,y+47,70,14,4,0x4010);
M5.Display.fillTriangle(x+75,y+50,x+75,y+58,x+81,y+54,gold);
M5.Display.setTextColor(gold,0x4010); M5.Display.setCursor(x+87,y+51); M5.Display.print("PLAY");
M5.Display.drawFastHLine(x+6,y+64,134,0x4010);
M5.Display.setTextColor(0xd5bf,panel);
M5.Display.setCursor(x+20,y+71); M5.Display.print("NAME");
M5.Display.setCursor(x+96,y+71); M5.Display.print("ICON");
M5.Display.drawFastVLine(x+73,y+68,11,0x4010);
}
static void drawMenu() {
M5.Display.fillScreen(SHELL);
if(view==HOME) {
M5.Display.fillScreen(0x0002);
M5.Display.fillRect(0,0,320,20,0x0846);
M5.Display.setTextSize(1); M5.Display.setTextColor(0xbfff,0x0846);
M5.Display.setCursor(9,6); M5.Display.print("POCKET ARCADE / GB + GBC");
M5.Display.setCursor(259,6); M5.Display.printf("%d GAMES",gameCount);
for(int y=21;y<94;++y) M5.Display.drawFastHLine(0,y,320,y<60?0x1809:0x1006);
M5.Display.drawFastHLine(12,91,296,0xfd20);
for(int n=0;n<35;++n) M5.Display.fillRect((n*79)%320,23+(n*17)%62,1,1,0xadff);
M5.Display.setTextSize(3); M5.Display.setTextColor(0x981f);
M5.Display.setCursor(47,34); M5.Display.print("GAME BOY");
M5.Display.setTextColor(0xfd20); M5.Display.setCursor(45,32); M5.Display.print("GAME BOY");
M5.Display.setTextSize(1); M5.Display.setTextColor(TFT_WHITE);
M5.Display.setCursor(55,72); M5.Display.print("YOUR NEXT ADVENTURE AWAITS");
if(!gameCount) {
neonBox(20,145,280,130,BLUE);
M5.Display.setTextColor(TFT_WHITE); M5.Display.setCursor(40,169);
M5.Display.print("YOUR NEXT ADVENTURE STARTS HERE");
M5.Display.setCursor(40,200); M5.Display.print("Put .gb / .gbc games on your");
M5.Display.setCursor(40,218); M5.Display.print("FAT32 SD card, then restart.");
M5.Display.setCursor(40,249); M5.Display.print("GBA games are not supported.");
}
for(int r=0;r<6;++r) { int i=page*6+r; if(i<gameCount) drawCartridge(i,10+(r%2)*154,103+(r/2)*92); }
neonBox(8,386,82,29,0xfd20); neonBox(230,386,82,29,0x981f);
M5.Display.setTextSize(1); M5.Display.setTextColor(TFT_WHITE);
M5.Display.setCursor(25,397); M5.Display.print("< PREV");
M5.Display.setCursor(247,397); M5.Display.print("NEXT >");
M5.Display.setCursor(126,397); M5.Display.printf("%d / %d",page+1,std::max(1,(gameCount+5)/6));
neonBox(8,425,148,27,0xffe0); neonBox(164,425,148,27,0x981f);
M5.Display.setCursor(55,434); M5.Display.printf("%d GAMES",gameCount);
M5.Display.setCursor(205,434); M5.Display.print(gameReady?"RESUME":"SD LIBRARY");
pixelLandscape();
if(uiMessage.length()) { M5.Display.fillRect(0,454,320,17,0x0002); M5.Display.setTextColor(0xffe0); M5.Display.setCursor(4,458); M5.Display.print(uiMessage.substring(0,51)); }
} else if(view==ICONS) {
M5.Display.fillScreen(0x0002);
M5.Display.setTextSize(2); M5.Display.setTextColor(0xffe0);
M5.Display.setCursor(14,18); M5.Display.print("CHOOSE GAME ICON");
M5.Display.setTextSize(1); M5.Display.setCursor(14,48);
M5.Display.print(games[iconGame].name.substring(0,40));
for(int i=0;i<12;++i) {
int x=7+(i%4)*79,y=90+(i/4)*92;
neonBox(x,y,68,66,games[iconGame].icon==i?0xffe0:0x981f);
M5.Display.pushImage(x+6,y+7,56,52,reinterpret_cast<const lgfx::rgb565_t*>(gameIcons[i]));
}
button("BACK WITHOUT CHANGING",8,420,304,44);
} else if(view==SLOTS) {
label("3 SAVE SLOTS",12,12,2);
for(int i=0;i<3;++i) {
label(slotNames[i].substring(0,24),12,62+i*105,2);
button("SAVE",8,92+i*105,94,48); button("LOAD",108,92+i*105,94,48); button("NAME",208,92+i*105,104,48);
}
label(uiMessage,12,382); button("BACK TO GAME",8,420,304,48);
} else if(view==KEYBOARD) {
label("NAME (24 characters)",8,12); label(editName,8,40,2);
const char* chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_.";
for(int i=0;i<40;++i) button(String(chars[i]),(i%8)*40,100+(i/8)*52,39,48);
button("DELETE",8,370,94,44); button("CANCEL",108,370,94,44); button("DONE",208,370,104,44);
}
}
// One continuous cross perimeter: no rectangle edges through the junction.
static void drawPadOutline() {
const int xs[]={52,103,103,155,155,103,103,52,52,0,0,52};
const int ys[]={336,336,380,380,423,423,467,467,423,423,380,380};
for(int i=0;i<12;++i) {
int j=(i+1)%12;
M5.Display.drawLine(xs[i],ys[i],xs[j],ys[j],i<6?BLUE:WINE);
}
}
static void drawPadArrow(int i,bool down) {
const Key &k=keys[i];
int cx=k.x+(k.w-1)/2,cy=k.y+(k.h-1)/2+(down?2:0);
// Symmetric bounds keep each arrow centered, including its tip.
if(i==0) M5.Display.fillTriangle(cx,cy-9,cx-10,cy+9,cx+10,cy+9,SHELL);
if(i==1) M5.Display.fillTriangle(cx,cy+9,cx-10,cy-9,cx+10,cy-9,SHELL);
if(i==2) M5.Display.fillTriangle(cx-9,cy,cx+9,cy-10,cx+9,cy+10,SHELL);
if(i==3) M5.Display.fillTriangle(cx+9,cy,cx-9,cy-10,cx-9,cy+10,SHELL);
}
// Decorative shell is drawn only on entering gameplay, not every frame.
static void drawHandheld(const String &fps) {
M5.Display.fillScreen(SHELL);
M5.Display.fillRoundRect(4,4,312,330,16,BEZEL);
M5.Display.drawRoundRect(3,3,314,332,17,0x981f);
M5.Display.drawRoundRect(5,5,310,328,15,0xfd20);
M5.Display.fillRect(GX-3,GY-3,GW+6,GH+6,INK);
M5.Display.setTextColor(0x4d1d,BEZEL); M5.Display.setTextSize(1);
M5.Display.setCursor(8,12); M5.Display.print("HOME");
M5.Display.setCursor(106,12); M5.Display.print("SAVE/LOAD");
M5.Display.drawFastHLine(8,28,304,WINE);
label("POCKET",112,337,1);
// Molded speaker-style decoration only; this does not enable audio.
for(int n=0;n<4;++n) M5.Display.drawLine(271+n*10,461,275+n*10,475,0x3296);
// Recessed molded wells around the original large touch areas.
M5.Display.fillRoundRect(161,349,159,104,38,0x0064);
M5.Display.drawRoundRect(161,349,159,104,38,0x08c8);
// Classic shell controls; enlarged hitboxes unchanged.
M5.Display.fillRoundRect(0,380,156,44,4,INK);
M5.Display.fillRoundRect(52,336,52,132,4,INK);
M5.Display.fillRoundRect(2,382,152,38,3,0x0862);
M5.Display.fillRoundRect(55,339,46,126,3,0x0862);
M5.Display.drawFastHLine(5,383,46,0x2188);
M5.Display.drawFastHLine(56,340,43,0x2188);
M5.Display.fillCircle(78,402,17,INK);
M5.Display.drawCircle(78,402,14,BLUE);
drawPadOutline();
for(int i=0;i<4;++i) drawPadArrow(i,false);
for(int i=4;i<6;++i) {
const Key &k=keys[i];
M5.Display.drawCircle(k.x+k.w/2,k.y+k.h/2,38,0x981f);
M5.Display.drawCircle(k.x+k.w/2,k.y+k.h/2,37,0xfd20);
M5.Display.fillCircle(k.x+k.w/2,k.y+k.h/2,36,INK);
uint16_t face=k.label[0]=='B'?BLUE:WINE;
M5.Display.fillCircle(k.x+k.w/2,k.y+k.h/2-2,32,face);
M5.Display.drawCircle(k.x+k.w/2,k.y+k.h/2-2,30,k.label[0]=='B'?0x8dff:0xcace);
M5.Display.setTextColor(INK,face); M5.Display.setTextSize(2);
M5.Display.setCursor(k.x+k.w/2-6,k.y+k.h/2-10); M5.Display.print(k.label);
}
for(int i=6;i<8;++i) {
const Key &k=keys[i];
M5.Display.fillRoundRect(k.x+5,k.y,k.w-10,12,6,BEZEL);
label(k.label,k.x+8,k.y+15);
}
M5.Display.setTextColor(0x4d1d,BEZEL); M5.Display.setTextSize(1);
M5.Display.setCursor(8,323); M5.Display.print(fps);
}
// Three-step press/release tween. Only changing controls are redrawn;
// no delays, full-screen buffers, or perpetual animation during gameplay.
static uint8_t padDepth[8]={};
static uint32_t padTick=0;
static void animatePads(uint8_t held,uint8_t old) {
const uint32_t now=millis();
const bool step=uint32_t(now-padTick)>=24;
if(step) padTick=now;
bool ringDirty=false;
for(int i=0;i<8;++i) {
const Key &k=keys[i];
bool down=held&k.bit, changed=(held^old)&k.bit;
uint8_t target=down?3:0, previous=padDepth[i];
if(step || changed) {
if(padDepth[i]<target) ++padDepth[i];
else if(padDepth[i]>target) --padDepth[i];
}
if(previous==padDepth[i] && !changed) continue;
int depth=padDepth[i];
uint16_t glow=depth==3?0xffe0:depth==2?0xfd20:depth==1?0xc99f:0x981f;
if(i<4) {
uint16_t face=depth? (depth==3?0x4010:0x2810):0x0862;
M5.Display.fillRoundRect(k.x+3,k.y+3,k.w-6,k.h-6,3,face);
uint16_t edge=depth?glow:0x2188;
if(i<2) {
int tip=i==0?k.y+4:k.y+k.h-5;
M5.Display.drawFastHLine(k.x+5,tip,k.w-10,edge);
} else {
int tip=i==2?k.x+4:k.x+k.w-5;
M5.Display.drawFastVLine(tip,k.y+5,k.h-10,edge);
}
drawPadArrow(i,depth>=2);
ringDirty=true;
} else if(i<6) {
int cx=k.x+k.w/2,cy=k.y+k.h/2;
uint16_t face=k.label[0]=='B'?(depth==3?0x0273:depth?0x05bb:BLUE)
:(depth==3?0x8015:depth?0xc01b:WINE);
M5.Display.drawCircle(cx,cy,38,glow);
M5.Display.drawCircle(cx,cy,37,depth?glow:0xfd20);
M5.Display.fillCircle(cx,cy,36,INK);
int offset=depth-2, radius=32-depth;
M5.Display.fillCircle(cx,cy+offset,radius,face);
M5.Display.drawCircle(cx,cy+offset,radius-2,depth?glow:(k.label[0]=='B'?0x8dff:0xcace));
// Specular glint slides down as the face sinks into its well.
M5.Display.drawFastHLine(cx-10,cy+offset-radius+7,20,depth?glow:0xffff);
M5.Display.setTextColor(INK,face); M5.Display.setTextSize(2);
M5.Display.setCursor(cx-6,cy-8+offset); M5.Display.print(k.label);
} else {
M5.Display.fillRect(k.x+4,k.y,k.w-8,14,SHELL);
M5.Display.fillRoundRect(k.x+5,k.y+depth,k.w-10,12-depth,6,depth?0x2810:BEZEL);
M5.Display.drawRoundRect(k.x+5,k.y+depth,k.w-10,12-depth,6,glow);
M5.Display.drawFastHLine(k.x+12,k.y+depth+2,k.w-24,depth?0xffe0:0x2188);
}
}
if(ringDirty) {
uint8_t depth=0;
for(int i=0;i<4;++i) if(padDepth[i]>depth) depth=padDepth[i];
// Keep all light on the ring, never through the D-pad center.
M5.Display.fillCircle(78,402,17,INK);
M5.Display.drawCircle(78,402,16,depth?0x981f:INK);
M5.Display.drawCircle(78,402,14,depth==3?0xffe0:depth?0xfd20:BLUE);
}
}
static void beginName(bool game,int n) {
namingGame=game;
selectedSlot=n; editName=game?games[n].name:slotNames[n]; returnView=view; view=KEYBOARD; uiDirty=true;
}
void loop() {
static uint32_t renderedGeneration=0; static bool initial=true;
static uint32_t lastRender=0, fpsAt=0, emuAt=0, lcdAt=0, shown=0;
static String fps="EMU 0 / LCD 0";
static uint8_t drawnButtons=0;
static bool waitRelease=false;
if(busy.load()) { delay(5); return; }
if(view==PLAY && gameReady && !uiMessage.length() && paused.load() && !fault.load()) { paused.store(false); initial=true; uiDirty=true; }
M5.update();
auto &t=M5.Touch.point;
int tx=16+t.x*3/5, ty=t.y*3/5;
if(waitRelease) { if(!t.down) waitRelease=false; t.newPress=false; t.down=false; }
if(view==PLAY) {
uint8_t held=0;
if(!waitRelease && t.down) for(size_t i=0;i<M5.Touch.getCount();++i) {
const auto &finger=M5.Touch.getDetail(i);
int fx=16+finger.x*3/5, fy=finger.y*3/5;
for(auto &k:keys) if(inside(fx,fy,k.x,k.y,k.w,k.h)) held|=k.bit;
}
buttons.store(held);
if(t.newPress && ty<30 && tx<196) {
paused.store(true); buttons.store(0); busy.store(true); stateRequest.store(3);
view=tx<90?HOME:SLOTS; uiMessage=""; uiDirty=true;
}
} else {
buttons.store(0);
if(t.newPress) {
if(view==HOME) {
if(ty>=103 && ty<379) {
int col=std::min(1,std::max(0,(tx-10)/154)), row=(ty-103)/92;
int x=10+col*154, y=103+row*92, n=page*6+row*2+col;
if(n<gameCount && inside(tx,ty,x,y,146,84)) {
if(ty>=y+64 && tx>=x+73) {
iconGame=n; view=ICONS; uiDirty=true;
} else if(ty>=y+64) beginName(true,n);
else { paused.store(true); busy.store(true); launchGame.store(n); waitRelease=true; view=PLAY; initial=true; uiDirty=true; }
}
} else if(ty>=386 && ty<415) {
if(tx<90 && page>0) --page;
else if(tx>=230 && (page+1)*6<gameCount) ++page;
uiDirty=true;
} else if(ty>=425 && ty<452 && tx>=164 && gameReady) { view=PLAY; initial=true; uiDirty=true; }
} else if(view==ICONS) {
if(ty>=90 && ty<366 && tx>=7) {
int col=(tx-7)/79,row=(ty-90)/92;
int n=row*4+col;
if(col<4 && n<12 && inside(tx,ty,7+col*79,90+row*92,68,66)) {
String path=iconGame==0?String("/builtin.icon"):games[iconGame].path+".icon";
File f=SD.open(path,"w");
if(f) { f.print(n); f.close(); uiMessage="Icon saved"; }
else uiMessage="Icon changed; SD unavailable for saving";
games[iconGame].icon=n; view=HOME; uiDirty=true;
}
} else if(ty>=420) { view=HOME; uiDirty=true; }
} else if(view==SLOTS) {
for(int i=0;i<3;++i) if(ty>=92+i*105 && ty<140+i*105) {
if(tx>=208) beginName(false,i);
else { selectedSlot=i; busy.store(true); slotStatus.store(0); stateRequest.store(tx<104?1:2); uiMessage="Working..."; uiDirty=true; }
}
if(ty>=420) { uiMessage=""; view=gameReady?PLAY:HOME; waitRelease=true; initial=true; uiDirty=true; }
} else if(view==KEYBOARD) {
if(ty>=100 && ty<360) { int n=((ty-100)/52)*8+tx/40; if(n<40 && editName.length()<24) editName+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_."[n]; uiDirty=true; }
if(ty>=370 && ty<414) {
if(tx<104) { if(editName.length()) editName.remove(editName.length()-1); }
else if(tx<204) view=returnView;
else if(editName.length()) {
String path=namingGame?(selectedSlot==0?String("/builtin.name"):metaPath(selectedSlot)):slotPath(selectedSlot)+".name";
SD.remove(path+".tmp"); File f=SD.open(path+".tmp",FILE_WRITE); bool ok=f && f.print(editName)==editName.length(); f.close();
if(ok) { SD.remove(path); ok=SD.rename(path+".tmp",path); }
if(ok) { if(namingGame) games[selectedSlot].name=editName; else slotNames[selectedSlot]=editName; view=returnView; }
} uiDirty=true;
}
}
}
}
if(view!=PLAY) {
if(view==SLOTS) { uint8_t status=slotStatus.exchange(0); if(status) {uiMessage=status==1?"Saved to card":status==2?"Loaded":status==4?"SD card unavailable":"Empty, incompatible or SD error";uiDirty=true;} }
if(uiDirty) { drawMenu(); uiDirty=false; } delay(4); return;
}
if(fault.load()) {
paused.store(true); buttons.store(0); uiMessage="Game stopped: ROM/core error";
view=HOME; uiDirty=true; return;
}
if(uiMessage.length()) { paused.store(true); view=HOME; uiDirty=true; return; }
if(millis()-fpsAt>=1000) {
uint32_t count=emulatedFrames.load(), now=millis();
fps="EMU "+String((count-emuAt)*1000.0f/(now-fpsAt),1)+" LCD "+String((shown-lcdAt)*1000.0f/(now-fpsAt),1);
fpsAt=now; emuAt=count; lcdAt=shown;
M5.Display.fillRect(0,322,320,12,BEZEL); M5.Display.setTextColor(0x4d1d,BEZEL); M5.Display.setTextSize(1); M5.Display.setCursor(8,323); M5.Display.print(fps);
}
if(initial || uiDirty) {
drawHandheld(fps); drawnButtons=0; memset(padDepth,0,sizeof padDepth); uiDirty=false; initial=true;
}
uint8_t heldNow=buttons.load();
animatePads(heldNow,drawnButtons); drawnButtons=heldNow;
// Limit display updates to 30 FPS without slowing Game Boy emulation.
if(uint32_t(micros()-lastRender)<33334) {delay(1);return;}
// Snapshot each row briefly; never block emulation for the SPI transfer.
portENTER_CRITICAL(&frameLock); uint32_t currentGeneration=generation;
portEXIT_CRITICAL(&frameLock);
int minX=0,minY=0,maxX=159,maxY=143;
if(!initial && currentGeneration==renderedGeneration) { delay(1); return; }
if(maxX>=0) {
lastRender=micros();
static uint16_t row[GW];
static uint32_t displayedHashes[144];
uint16_t palette[64];
portENTER_CRITICAL(&frameLock);
memcpy(palette,displayPalette,sizeof palette);
portEXIT_CRITICAL(&frameLock);
uint32_t paletteHash=2166136261u;
for(uint16_t c:palette) paletteHash=(paletteHash^c)*16777619u;
M5.Display.startWrite();
for(int y=0;y<144;++y) {
uint32_t hash=2166136261u;
uint8_t source[160];
// Only copy under the cross-core lock. Color expansion and hashing must
// not stall the emulator with interrupts disabled for every pixel.
portENTER_CRITICAL(&frameLock);
memcpy(source,latest+y*160,sizeof source);
portEXIT_CRITICAL(&frameLock);
hash=paletteHash;
for(int x=0;x<160;x+=4) {
uint32_t packed; memcpy(&packed,source+x,4);
hash=(hash^packed)*16777619u;
}
if(!initial && displayedHashes[y]==hash) continue;
displayedHashes[y]=hash;
for(int x=0;x<GW;++x) row[x]=palette[source[x*160/GW]&63];
int top=GY+(y*GH+143)/144;
int bottom=GY+((y+1)*GH+143)/144;
M5.Display.setAddrWindow(GX,top,GW,bottom-top);
for(int n=top;n<bottom;++n) M5.Display.writePixels(row,GW,true);
}
M5.Display.endWrite(); renderedGeneration=currentGeneration; ++shown;
}
initial=false; delay(1);
}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.




