geekcowboy.neta florea.xyz revival

Arduino and microcontrollers

A pocket game on an Arduino Uno: an OLED, two buttons and 200 lines

Arduino's own games board, the Esplora, is retired, but a small OLED screen and two buttons turn an Uno into a handheld. A complete dodge-the-blocks game with a real game loop, collision detection and a title screen, and what each part teaches.

By florea.xyz ·

For a while Arduino sold a board made for games: the Esplora, an Arduino shaped like a game controller, with a joystick, buttons and sensors built in. It is now on Arduino’s list of retired boards. You do not need it. An Uno, a small OLED screen and two pushbuttons make a perfectly good handheld, and writing a game for it teaches more about microcontrollers than most tutorials: timing without delay(), a frame loop, collision detection, random numbers on a chip with no clock, and how much a 1 KB screen buffer costs on a board with 2 KB of RAM.

The game here is Pocket Dodge: blocks fall from the top of the screen, you slide left and right to dodge them, and every block that gets past you scores a point. Every ten points they fall faster.

What you need

  • An Arduino Uno. The sketch was compiled for the R3; the R4, with sixteen times the RAM, should take it unchanged.
  • A 128×64 OLED display with an SSD1306 controller, on I2C. Adafruit’s 0.96-inch module (product 326) was $17.50 and in stock on 27 November 2026, and generic 0.96-inch SSD1306 modules cost much less. One trap: many 1.3-inch generic modules use a different controller, the SH1106, which this library does not drive. Check the listing says SSD1306.
  • Two pushbuttons and some jumper wires.

Wiring

From To Arduino
OLED GND GND
OLED VCC 5V
OLED SDA A4
OLED SCL A5
Left button D2, other leg to GND
Right button D3, other leg to GND

Most OLED modules have a regulator and accept 5 V; check yours before you plug it in. The buttons need no resistors: the sketch turns on the Uno’s internal pull-ups, so a pressed button reads LOW.

The sketch

Install Adafruit SSD1306 from the Library Manager; it brings Adafruit GFX along with it (versions 2.5.17 and 2.0.0 when this was written). Then upload:

pocket_dodge.ino

// pocket_dodge.ino: a one-screen game for an Arduino Uno, a 128x64 SSD1306 OLED and two buttons.
// Blocks fall from the top; move left and right to dodge them. Press both buttons to start a game.
// Wiring: OLED SDA to A4, SCL to A5, VCC to 5V, GND to GND. Buttons from D2 (left) and D3 (right) to GND.
// Libraries (Library Manager): Adafruit SSD1306 and Adafruit GFX. geekcowboy.net, 2026. MIT licence.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const uint8_t LEFT_PIN = 2, RIGHT_PIN = 3;     // to GND; the internal pull-ups hold them HIGH
const int16_t W = 128, H = 64;                 // the screen, in pixels
const int16_t PLAYER_W = 12, PLAYER_H = 4, PLAYER_Y = H - PLAYER_H;
const int16_t PLAYER_STEP = 3;                 // pixels per frame while a button is held
const int16_t BLOCK = 6;                       // blocks are BLOCK x BLOCK pixels
const uint8_t MAX_BLOCKS = 8;
const uint8_t MAX_SPEED = 4;                   // pixels per frame; must stay below BLOCK + PLAYER_H, or blocks could jump the player
const uint32_t FRAME_MS = 33;                  // about 30 frames a second

struct Block { int16_t x, y; bool live; };

Adafruit_SSD1306 display(W, H, &Wire, -1);     // -1: the module's reset pin is not connected
bool displayOk;
Block blocks[MAX_BLOCKS];
int16_t playerX;
uint16_t score, best;
uint8_t fallSpeed;
bool gameOver = true;                          // the title screen, until the first game starts
uint32_t rng = 2463534242UL;                   // xorshift32 state: never 0
uint32_t lastFrame;

// xorshift32: tiny and fast. The sequence is fixed for a given seed, so the game is seeded from the moment a
// human presses the buttons.
uint32_t nextRandom() {
  rng ^= rng << 13;
  rng ^= rng >> 17;
  rng ^= rng << 5;
  return rng;
}

void newGame() {
  for (Block &b : blocks) b.live = false;
  playerX = (W - PLAYER_W) / 2;
  score = 0;
  fallSpeed = 1;
  gameOver = false;
}

bool hitsPlayer(const Block &b) {
  return b.x < playerX + PLAYER_W && b.x + BLOCK > playerX && b.y < PLAYER_Y + PLAYER_H && b.y + BLOCK > PLAYER_Y;
}

// One frame of the game: move, fall, collide, score, spawn. It draws nothing, so it can be tested on a PC.
void step(bool left, bool right) {
  if (gameOver) return;
  if (left && !right) playerX = playerX > PLAYER_STEP ? playerX - PLAYER_STEP : 0;
  if (right && !left) playerX = playerX < W - PLAYER_W - PLAYER_STEP ? playerX + PLAYER_STEP : W - PLAYER_W;
  for (Block &b : blocks) {
    if (!b.live) continue;
    b.y += fallSpeed;
    if (hitsPlayer(b)) {
      gameOver = true;
      if (score > best) best = score;
      return;
    }
    if (b.y >= H) {  // off the bottom: dodged
      b.live = false;
      score++;
      if (score % 10 == 0 && fallSpeed < MAX_SPEED) fallSpeed++;
    }
  }
  if (nextRandom() % 12 == 0) {  // a new block on about one frame in twelve
    for (Block &b : blocks) {
      if (b.live) continue;
      b.x = nextRandom() % (W - BLOCK + 1);
      b.y = -BLOCK;
      b.live = true;
      break;
    }
  }
}

void draw() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  if (gameOver) {
    display.setCursor(28, 10);
    display.print(F("POCKET DODGE"));
    display.setCursor(28, 28);
    display.print(F("score "));
    display.print(score);
    display.setCursor(28, 38);
    display.print(F("best  "));
    display.print(best);
    display.setCursor(10, 54);
    display.print(F("both buttons: play"));
  } else {
    for (const Block &b : blocks)
      if (b.live) display.fillRect(b.x, b.y, BLOCK, BLOCK, SSD1306_WHITE);
    display.fillRect(playerX, PLAYER_Y, PLAYER_W, PLAYER_H, SSD1306_WHITE);
    display.setCursor(0, 0);
    display.print(score);
  }
  display.display();
}

void setup() {
  pinMode(LEFT_PIN, INPUT_PULLUP);
  pinMode(RIGHT_PIN, INPUT_PULLUP);
  Serial.begin(115200);
  Wire.begin();
  const uint8_t addresses[] = {0x3C, 0x3D};  // most 128x64 modules use 0x3C, Adafruit's default is 0x3D
  uint8_t found = 0;
  for (uint8_t a : addresses) {
    Wire.beginTransmission(a);
    if (Wire.endTransmission() == 0) {
      found = a;
      break;
    }
  }
  // begin() fails if the 1 KB screen buffer does not fit in RAM; it does not check that the display answered.
  displayOk = found && display.begin(SSD1306_SWITCHCAPVCC, found);
  if (!displayOk) {
    Serial.println(F("No SSD1306 display at 0x3C or 0x3D, or no RAM for its buffer: check SDA, SCL and power"));
    return;
  }
  draw();
}

void loop() {
  if (!displayOk) return;
  uint32_t now = millis();
  if (now - lastFrame < FRAME_MS) return;
  lastFrame = now;
  bool left = digitalRead(LEFT_PIN) == LOW, right = digitalRead(RIGHT_PIN) == LOW;
  if (gameOver) {
    if (!(left && right)) return;  // the end screen stays until both buttons are pressed
    rng ^= micros();
    if (rng == 0) rng = 1;
    newGame();
  } else {
    step(left, right);
  }
  draw();
}

The title screen appears; press both buttons together to play. When a block lands on you, the end screen shows your score and the best one since power-up; both buttons again for another go.

If the screen stays dark, open the Serial Monitor at 115200 baud. The sketch looks for the display at both usual addresses, 0x3C (most modules) and 0x3D (Adafruit’s default), and says so if neither answers.

How it works

A frame loop, not delay(). loop() runs thousands of times a second, but it only does something every 33 ms: it reads the buttons, moves everything one step and redraws the screen. That is about 30 frames a second. Timing is “now minus the last frame”, the form that keeps working when millis() wraps round after 49 days.

The game logic draws nothing. step() moves the player, moves the blocks, checks for hits, counts the score and spawns new blocks. draw() only paints what step() decided. Keeping them apart is how the game was tested on a PC without a screen, and it makes the game easier to change: a different display only touches draw().

Collision is two rectangles overlapping. A block hits the player when their x ranges overlap and their y ranges overlap. That is hitsPlayer(), four comparisons. There is one subtle rule, noted next to MAX_SPEED: a block moves several pixels per frame, so if it ever moved further in one frame than the height of the overlap zone (block plus player), it could jump straight over the player without the check catching it. At these sizes the zone is 9 pixels tall and the top speed is 4.

Random numbers on a chip with no clock. The blocks appear at random places from nextRandom(), a xorshift generator: three shifts and three XORs per number. Its sequence is fixed once you choose the starting value, so the sketch mixes in micros() at the moment you press the buttons. No human presses them at the same microsecond twice, so no two games are alike.

The screen costs half the RAM. The library keeps a copy of all 128 × 64 pixels in memory, one bit each: 1,024 bytes, half of an Uno R3’s 2 KB. That is why display.begin() can fail, and why the text is in F("..."), which leaves it in flash instead of copying it into RAM. Compiled for the R3, the sketch’s own variables, the serial and I2C buffers take 589 bytes; add the screen and about 430 bytes are left for the stack. Enough for this game, but a second big array would not fit.

Speed. Sending those 1,024 bytes over I2C takes time. The library switches the bus to 400 kHz while it sends a frame. At 9 clock pulses per byte, that is about 23 ms of transfer, before any overhead, so 30 frames a second is close to what an I2C OLED on an Uno can do. Faster games want an SPI display.

Make it yours

  • Sound. A piezo buzzer on a spare pin and tone() for a click on each point and a buzz at game over.
  • A best score that survives power-off, in the EEPROM with EEPROM.put() and EEPROM.get(). Write it only when it changes: the EEPROM is rated for about 100,000 writes per cell.
  • A joystick on A0 and A1 instead of buttons, for smooth speed instead of fixed steps.
  • More to dodge: blocks of different sizes, or ones that drift sideways. The overlap rule above still applies.

Sources