ESP32 game console: build a mini handheld with an OLED and Snake
A pocket game console sounds like a big project. It is not. You need an ESP32 dev board, a 0.96 inch SSD1306 OLED, five push buttons and a passive buzzer. Put them on a breadboard and you have a DIY handheld game console that fits in your hand.
This guide gives you the parts list, a wiring table with safe pins and a complete ESP32 Snake game sketch. The snake grows when it eats, speeds up as you score and beeps when you eat or crash. Once Snake works, the free OLED Block Coder gives you more games, such as a dino-style runner and a Pong-style paddle game, built with drag and drop blocks.
Quick answer. Wire the OLED to GPIO 21 (SDA) and GPIO 22 (SCL). Wire five buttons from GPIO 32, 33, 25, 26 and 27 to GND, and a passive buzzer from GPIO 14 to GND. Install the esp32 board package, Adafruit SSD1306 and Adafruit GFX. Pick ESP32 Dev Module and upload the sketch below. Press A to play.
Parts for the ESP32 game console
Prices change between sellers and pack sizes, so the table shows typical US ranges.
| Part | Notes | Typical price (US) |
|---|---|---|
| ESP32 dev board | ESP32 DevKit V1 or any board with an ESP32-WROOM-32 module (30 or 38 pins) | Usually $5 to $12 |
| OLED screen | 0.96 inch SSD1306, 128x64 pixels, I2C, 4 pins (VCC, GND, SCL, SDA) | Usually $4 to $8 |
| 5 tactile buttons | 6 mm or 12 mm push buttons: UP, DOWN, LEFT, RIGHT and A | Usually under $1 each |
| Passive piezo buzzer | Must be passive, so it can play different tones | Usually under $1 |
| Breadboard or perfboard | Breadboard to test, perfboard if you want to solder a sturdy handheld | Usually $3 to $8 |
| Jumper wires | Male to male for a breadboard, or thin solid wire for perfboard | Usually $3 to $7 a pack |
| USB power bank | Any small phone power bank and a USB cable that carries data and power | You may already own one |
Optional battery parts for a true handheld: a protected 3.7 V LiPo cell, a LiPo charger module, a 5 V boost module and a small slide switch. The battery section below explains why you need the boost module.
Wiring the OLED, buttons and buzzer
The OLED talks to the ESP32 over I2C. That is a two-wire bus: SDA carries data and SCL carries the clock. Each button connects one GPIO pin to GND. The sketch turns on the ESP32's internal pull-up resistors, so the pin reads HIGH when the button is up and LOW when you press it. You do not need any extra resistors.
| Part | Part pin | ESP32 pin |
|---|---|---|
| OLED | VCC | 3V3 |
| OLED | GND | GND |
| OLED | SDA | GPIO 21 |
| OLED | SCL | GPIO 22 |
| Button UP | one leg / other leg | GPIO 32 / GND |
| Button DOWN | one leg / other leg | GPIO 33 / GND |
| Button LEFT | one leg / other leg | GPIO 25 / GND |
| Button RIGHT | one leg / other leg | GPIO 26 / GND |
| Button A (START) | one leg / other leg | GPIO 27 / GND |
| Passive buzzer | + / − | GPIO 14 / GND |
On a four-leg tactile button, use two legs on opposite corners. Legs on the same side are often joined inside the button, and then it reads as pressed all the time.
Why these pins? ESP32 pins to avoid
Some ESP32 pins have jobs at boot, and a button on them can stop the board from starting. The table above avoids:
- Strapping pins 0, 2, 12 and 15 (and also 5). The ESP32 reads these at power on to decide how to boot. GPIO 0 held LOW puts the board in download mode. GPIO 12 sets the flash voltage, and the wrong level can stop it from booting at all.
- GPIO 34 to 39 are input only and have no internal pull-up resistors. A button on them would need an external resistor, so it is easier to skip them.
- GPIO 6 to 11 connect to the flash chip inside the module. Never use them.
- GPIO 1 and 3 are the USB serial lines used for uploads and the Serial Monitor.
Espressif lists these limits in its ESP32 GPIO documentation.
Install the board package and libraries
- In the Arduino IDE, open Boards Manager, search for esp32 and install the package by Espressif Systems. Version 3.x of this core includes
tone(), which the sketch uses for sound. - Open Sketch → Include Library → Manage Libraries, search for Adafruit SSD1306 and click Install.
- When it asks about dependencies, click Install All. That adds the Adafruit GFX Library, which has the text and shape functions.
- Go to Tools → Board and pick ESP32 Dev Module. Then pick your port under Tools → Port.
New to this screen? The Arduino OLED display tutorial for the SSD1306 covers the basics.
The complete ESP32 Snake game sketch
Copy the whole sketch into a new file. The pin numbers and the OLED address are at the top, so you can change them in one place if your wiring is different.
// ESP32 Mini Console: Snake on a 128x64 SSD1306 OLED (I2C)
// Board: ESP32 Dev Module (Arduino-ESP32 core 3.x)
// Libraries: Adafruit SSD1306 + Adafruit GFX
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_W 128
#define SCREEN_H 64
#define OLED_ADDR 0x3C // try 0x3D if the screen stays black
// ---- Pins (buttons go to GND, no resistors needed) ----
const uint8_t BTN_UP = 32;
const uint8_t BTN_DOWN = 33;
const uint8_t BTN_LEFT = 25;
const uint8_t BTN_RIGHT = 26;
const uint8_t BTN_A = 27; // A / START
const uint8_t BUZZER_PIN = 14; // passive buzzer
Adafruit_SSD1306 display(SCREEN_W, SCREEN_H, &Wire, -1);
// ---- Play area: 31 x 12 cells of 4x4 pixels, below the score bar ----
const int CELL = 4;
const int COLS = 31;
const int ROWS = 12;
const int AREA_X = 2; // pixel x of cell (0,0)
const int AREA_Y = 12; // pixel y of cell (0,0)
const int MAX_LEN = 128; // longest snake we store
// ---- Speed ----
const int START_STEP_MS = 180; // time between moves at the start
const int MIN_STEP_MS = 70; // fastest the snake can go
const int SPEED_UP_MS = 4; // faster by this much per food
enum State { MENU, PLAYING, GAME_OVER };
State state = MENU;
uint8_t snakeX[MAX_LEN];
uint8_t snakeY[MAX_LEN];
int snakeLen = 0;
uint8_t dir = 1; // last move: 0 up, 1 right, 2 down, 3 left
uint8_t nextDir = 1; // direction for the next move
const int8_t DX[4] = { 0, 1, 0, -1 };
const int8_t DY[4] = { -1, 0, 1, 0 };
uint8_t foodX = 0, foodY = 0;
unsigned int score = 0;
unsigned int best = 0; // kept in RAM, resets when power is off
int stepMs = START_STEP_MS;
unsigned long lastStep = 0;
unsigned long gameOverAt = 0;
bool aWasDown = false;
bool isDown(uint8_t pin) {
return digitalRead(pin) == LOW; // INPUT_PULLUP: pressed = LOW
}
// True only on the loop where A changes from up to down
bool aPressed() {
bool down = isDown(BTN_A);
bool pressed = down && !aWasDown;
aWasDown = down;
return pressed;
}
void beep(unsigned int freq, unsigned long ms) {
tone(BUZZER_PIN, freq, ms);
}
void centerText(const char *text, int y, uint8_t size) {
display.setTextSize(size);
int w = strlen(text) * 6 * size; // 6 px per character at size 1
display.setCursor((SCREEN_W - w) / 2, y);
display.print(text);
}
bool onSnake(int x, int y) {
for (int i = 0; i < snakeLen; i++) {
if (snakeX[i] == x && snakeY[i] == y) return true;
}
return false;
}
void placeFood() {
// 372 cells and at most 128 snake parts, so a free cell always exists
int x, y;
do {
x = random(COLS);
y = random(ROWS);
} while (onSnake(x, y));
foodX = x;
foodY = y;
}
void resetGame() {
snakeLen = 3;
for (int i = 0; i < snakeLen; i++) {
snakeX[i] = COLS / 2 - i; // head in the middle, body to the left
snakeY[i] = ROWS / 2;
}
dir = 1;
nextDir = 1;
score = 0;
stepMs = START_STEP_MS;
placeFood();
lastStep = millis();
}
void readDirection() {
int wanted = -1;
if (isDown(BTN_UP)) wanted = 0;
else if (isDown(BTN_RIGHT)) wanted = 1;
else if (isDown(BTN_DOWN)) wanted = 2;
else if (isDown(BTN_LEFT)) wanted = 3;
// Ignore the opposite of the last move, so the snake never reverses into itself
if (wanted >= 0 && wanted != (dir + 2) % 4) nextDir = wanted;
}
void drawCell(int cx, int cy, bool filled) {
int px = AREA_X + cx * CELL;
int py = AREA_Y + cy * CELL;
if (filled) display.fillRect(px, py, CELL - 1, CELL - 1, SSD1306_WHITE);
else display.drawRect(px, py, CELL - 1, CELL - 1, SSD1306_WHITE);
}
void drawGame() {
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.print("SCORE ");
display.print(score);
display.setCursor(80, 0);
display.print("BEST ");
display.print(best);
display.drawRect(0, 10, SCREEN_W, SCREEN_H - 10, SSD1306_WHITE); // walls
drawCell(foodX, foodY, false); // food = hollow square
for (int i = 0; i < snakeLen; i++) drawCell(snakeX[i], snakeY[i], true);
display.display();
}
void drawMenu() {
display.clearDisplay();
centerText("ESP32 MINI CONSOLE", 4, 1);
centerText("SNAKE", 20, 2);
centerText("Press A", 44, 1);
display.setCursor(40, 56);
display.print("Best: ");
display.print(best);
display.display();
}
void drawGameOver() {
display.clearDisplay();
centerText("GAME OVER", 4, 2);
display.setTextSize(1);
display.setCursor(34, 26);
display.print("Score: ");
display.print(score);
display.setCursor(34, 38);
display.print("Best: ");
display.print(best);
centerText("Press A", 54, 1);
display.display();
}
void endGame() {
state = GAME_OVER;
gameOverAt = millis();
if (score > best) best = score;
beep(196, 400); // low tone for a crash
drawGameOver();
}
void stepSnake() {
dir = nextDir;
int nx = snakeX[0] + DX[dir];
int ny = snakeY[0] + DY[dir];
// Hit a wall?
if (nx < 0 || nx >= COLS || ny < 0 || ny >= ROWS) {
endGame();
return;
}
bool eating = (nx == foodX && ny == foodY);
bool grow = eating && snakeLen < MAX_LEN;
// Hit itself? If the snake does not grow, the tail moves away
// this step, so the last part does not count.
int checkLen = grow ? snakeLen : snakeLen - 1;
for (int i = 0; i < checkLen; i++) {
if (snakeX[i] == nx && snakeY[i] == ny) {
endGame();
return;
}
}
if (grow) snakeLen++;
for (int i = snakeLen - 1; i > 0; i--) { // move every part one place back
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] = nx;
snakeY[0] = ny;
if (eating) {
score++;
beep(1047, 40); // short high beep
stepMs = START_STEP_MS - (int)score * SPEED_UP_MS;
if (stepMs < MIN_STEP_MS) stepMs = MIN_STEP_MS;
placeFood();
}
}
void setup() {
Serial.begin(115200);
pinMode(BTN_UP, INPUT_PULLUP);
pinMode(BTN_DOWN, INPUT_PULLUP);
pinMode(BTN_LEFT, INPUT_PULLUP);
pinMode(BTN_RIGHT, INPUT_PULLUP);
pinMode(BTN_A, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
Wire.begin(21, 22); // SDA = GPIO 21, SCL = GPIO 22
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("SSD1306 not found. Check wiring and address.");
for (;;) delay(1000);
}
display.setTextColor(SSD1306_WHITE);
drawMenu();
}
void loop() {
bool aNow = aPressed(); // read A on every loop
if (state == MENU) {
if (aNow) {
randomSeed(micros()); // press timing makes a good seed
resetGame();
state = PLAYING;
drawGame();
}
} else if (state == PLAYING) {
readDirection(); // read the arrows on every loop
if (millis() - lastStep >= (unsigned long)stepMs) {
lastStep = millis();
stepSnake();
if (state == PLAYING) drawGame();
}
} else { // GAME_OVER
if (aNow && millis() - gameOverAt > 500) {
resetGame();
state = PLAYING;
drawGame();
}
}
}
What you should see: "ESP32 MINI CONSOLE", a big "SNAKE" title, "Press A" and your best score. Press A and a short snake appears in a walled box, with the score at the top. The food is a small hollow square. Eat it for a quick beep. Hit a wall or your tail and you hear a low tone and see the game over screen.
A note on testing. This sketch compiles for ESP32 Dev Module with the Arduino-ESP32 3.x core, and I checked the logic line by line, but I have not run this exact sketch on hardware yet. If something does not behave, the troubleshooting list covers the most likely causes.
How the ESP32 Snake code works
Every small game follows the same pattern: read the buttons, update the game, then draw one frame.
The grid and the snake arrays
The top 10 pixel rows hold the score bar. Below that, the play area is a grid of 31 columns and 12 rows of 4 by 4 pixel cells. Each snake part is drawn as a 3 by 3 square, so you see a thin gap between parts.
The snake lives in two arrays, snakeX and snakeY, with the head at index 0. They hold up to
128 parts in just 256 bytes of RAM. On each move, every part copies the position of the part in front of it, and the
head moves one cell. When the snake eats, the length goes up by one before that copy, so the old tail stays put. That
is how the snake grows.
Timing with millis(), not delay()
The snake only moves when stepMs milliseconds have passed since the last move: 180 ms at the start, 4 ms
less for each food, down to 70 ms. The game gets faster as you eat but never becomes impossible.
During a delay(), the ESP32 cannot read the buttons, so quick taps get lost. With
millis(), the buttons are read on every pass of the loop, and the last valid press waits in
nextDir until the next move.
Buttons and the no-reverse rule
Each button pin uses INPUT_PULLUP, so digitalRead() returns LOW when it is pressed. If you
press the direction opposite to the last move, the code ignores it. Otherwise a snake moving right could turn left
into its own neck. The check uses dir, the move that already happened, so even two very fast taps (UP,
then LEFT) cannot reverse the snake.
The A button should act once per press, not every loop while you hold it. aPressed() only returns true
on the loop where the button changes from up to down. On the game over screen, the sketch also waits half a second,
so a press made while crashing does not restart the game by accident.
Food and collisions
placeFood() picks a random cell and tries again if the snake is on it. There are 372 cells and at most
128 snake parts, so it always finds a free cell quickly.
Before the head moves, the code checks for a wall (the new cell is outside the grid) and for the body. One detail: if the snake is not growing this step, the tail leaves its cell at the same time, so the head may move into it.
Sound with tone()
tone(pin, frequency, duration) plays a square wave on the buzzer pin for the given time and returns right
away, so the game does not pause. The sketch plays 1047 Hz for 40 ms when you eat and 196 Hz for 400 ms when you
crash. The Arduino tone() reference
explains the function. For full melodies, such as a start-up jingle, see the guide to
Arduino buzzer songs and code.
Saving the best score
The best score is a normal variable, so it resets when you unplug the console. To keep it, use the Preferences library that comes with the ESP32 board package. It stores small values in flash:
#include <Preferences.h>
Preferences prefs;
// in setup(), after display.begin():
prefs.begin("console", false);
best = prefs.getUInt("best", 0);
// in endGame(), replace the best line with:
if (score > best) {
best = score;
prefs.putUInt("best", best); // only write when the record is beaten
}
Writing only when the record is beaten keeps flash writes to a minimum.
Add more games: dino runner and Pong
A console needs more than one game. The quickest way to get them is the free OLED Block Coder, a drag and drop editor for SSD1306 and SH1106 screens. Its game templates include:
- Dino runner: press to jump over the obstacles. Each one you pass adds a point. It shows gravity with a speed variable, a ground line and box collision.
- Pong, one player: hold the button to move the paddle up, let go to move it down, and keep the ball in play.
- Pong, 2 players: two buttons per paddle, a score for each player and a serve after each point.
- Snake: a simpler one-button version with a fixed length, good for learning how direction works.
You test each game in the browser with on-screen buttons, then copy the Arduino sketch. Two things to know first. The Block Coder writes sketches for the U8g2 library, not Adafruit SSD1306, so install U8g2 too (the two can sit side by side). And the templates use pin 2 for the button. GPIO 2 is a strapping pin on the ESP32, so change the pin on the button block to 27 (the A button). For 2-player Pong, use 32, 33, 25 and 26.
A menu to pick the game
Flashing a new sketch for every game works, but a real console has a menu. Put each game in its own functions, such
as snakeReset(), snakeUpdate() and snakeDraw(), then the same for the runner
and Pong. Add a MENU state that lists the games. UP and DOWN move a frame around a name, and A starts
that game. When a game ends, A takes you back to the menu.
Pick one library for the whole console. Most calls map directly: U8g2's drawBox is Adafruit's
fillRect and drawFrame is drawRect. The guide to
building an Arduino OLED menu with buttons shows the menu
step by step, and the one-button Arduino OLED game guide has
a full runner written with Adafruit SSD1306, including ESP32 pins.
Battery power, done safely
The easiest way to make the console portable is a USB power bank. Plug it into the ESP32's USB port and you are done. The board's own regulator makes 3.3 V for the chip and the OLED. Some power banks switch off when the current draw is very low. If yours does, try a different one.
A built-in battery is nicer, but there is a trap. A single LiPo cell gives about 3.7 V (4.2 V when full). Do not wire it to the 5V or VIN pin and expect a stable 3.3 V. The regulator on most ESP32 dev boards is a linear type, often an AMS1117, and it needs its input well above 3.3 V. From a LiPo the 3.3 V rail sags, and the ESP32 can reset during a burst of current.
Two setups that work:
- LiPo + charger module + 5 V boost module. The charger module charges the cell from USB. The boost module turns the cell voltage into a steady 5 V, which you feed into the 5V or VIN pin through a slide switch. Some modules combine charging and boosting on one small board.
- An ESP32 board with a built-in LiPo charger. Several Feather-style and similar boards have a battery connector and charging circuit on board, so you plug the cell straight in.
LiPo safety. Buy cells with a built-in protection circuit. Never puncture, bend or crush a LiPo, and do not use one that has puffed up. Check the polarity of the connector before you plug it in, because the red and black wires are not always in the same place. Charge only with a proper LiPo charger, and do not leave a new build charging unattended.
An OLED only uses power for lit pixels, and a Snake screen is mostly black, which helps battery life. The guide to OLED power consumption and battery life shows how to estimate run time.
A 3D printed case idea
Once everything works, move it to perfboard: OLED in the middle, the four arrows as a cross on the left and A on the right. Measure your own parts with calipers, because ESP32 boards vary in length and USB port position. Leave a window for the screen, holes for the buttons, a slot for the USB cable and room for the battery. A two-part case held with small screws is easy to open later. For a name plate or a label like "MINI CONSOLE" on the lid, the free Text to STL tool turns any text into a printable 3D model.
Troubleshooting the ESP32 game console
- Problem: the OLED stays blank. Why: wrong wiring or the wrong address. Fix: check that SDA goes to GPIO 21 and SCL to GPIO 22, and that VCC goes to 3V3. Open the Serial Monitor at 115200 baud. If it says "SSD1306 not found", change
OLED_ADDRto0x3D. The SSD1306 blank screen fix guide has an I2C scanner sketch. - Problem: a button does nothing, or acts as if always pressed. Why: the button is turned the wrong way, or it goes to the wrong pin. Fix: use two legs on opposite corners (or rotate the button 90 degrees), make sure the other leg goes to GND, and check that the pin in the code matches your wire.
- Problem: the board will not boot or will not upload. Why: something is connected to a strapping pin such as 0, 2, 12 or 15. Fix: move that wire to one of the safe pins in the wiring table. If the upload still hangs at "Connecting...", hold the BOOT button on the board until it starts.
- Problem: the buzzer is silent or only clicks. Why: it is an active buzzer, or it is wired backwards. Fix: use a passive buzzer, and connect its + leg to GPIO 14. An active buzzer has its own oscillator and cannot follow
tone(). - Problem: random resets or a frozen screen. Why: weak power. Fix: try a different USB cable and port, or a better power bank. On battery, use a 5 V boost module as described above. Thin or long cables can drop the voltage enough to reset the ESP32.
- Problem: the picture is shifted or shows noise on one side. Why: the screen is a 1.3 inch SH1106, not an SSD1306. Fix: see the FAQ below.
Frequently asked questions
Can I use an Arduino Uno instead of an ESP32?
Yes, with a few changes. Wire the OLED to A4 (SDA) and A5 (SCL), call Wire.begin() with no pin numbers, and move the buttons and buzzer to free pins such as D2 to D6 and D8. The game fits, but the screen buffer takes half of the Uno's 2 KB of RAM, so there is little room left for extra games.
Will this work with a 1.3 inch SH1106 OLED?
Not with the Adafruit SSD1306 library as it is. Use the Adafruit SH110X library with Adafruit_SH1106G and SH110X_WHITE, or switch to U8g2, which supports both chips. The game logic stays the same.
How do I save the high score on an ESP32?
Use the Preferences library that comes with the ESP32 board package. Read the best score with getUInt() in setup() and write it with putUInt() only when a player beats it. The value stays in flash after you unplug the console.
How do I add more games to the console?
Give each game its own reset, update and draw functions, then add a menu screen where UP and DOWN pick a game and A starts it. The Dino and Pong templates in the free OLED Block Coder are good starting points for the logic.
Do I need a passive or an active buzzer?
A passive buzzer. The sketch uses tone() to play different pitches, and only a passive buzzer can follow that signal. An active buzzer has its own oscillator and plays one fixed beep.
Sources: Adafruit SSD1306 library (GitHub), Adafruit GFX graphics library guide, Espressif ESP32 GPIO documentation and the Arduino tone() reference.
Related guides
- Arduino OLED game: one-button runner on an SSD1306
- ESP32 OLED animation guide
- Arduino OLED menu with buttons
- ESP32 desk robot with OLED eyes and touch moods
- Arduino buzzer songs and code
- Arduino OLED display tutorial (I2C SSD1306)
Free tools: Lithophane Maker for flat, curved, heart, round and cylinder lamp lithophanes, the Shadow Box Lamp Generator for wall shadow lamps, Text to STL for names and keychains, and 3MF to Web to show your prints on a website. See all tools.