Lessons and the learning game

Build an electronic chessboard

A chessboard that knows where every piece is, on an Uno: reed switches under the squares, move detection, the rules, LED hints and a small engine.

The board

Every lesson opens on the same wiring:

  • The squares: sixteen reed switches, one under each square from c3 to f6, the middle of the board. A magnet in a piece's base closes its reed.
  • The expander: an MCP23017 at 0x20, one reed on each of its 16 inputs, pull-ups on. A full board is four of them, at 0x20 to 0x23.
  • The lights: a 16 x 8 WS2812 panel whose left 8 x 8 is the board's 64 LEDs.

The bench board wires the middle sixteen squares for real, and the sketches keep the other 48 in software. Moves anywhere can be typed in the same from-to form the reeds produce (e2e4). The catalog lists this course on an ESP32; it is built on the Uno, which has room for the rules and the engine.

How it works

Sensing. One reed per expander pin: closed reads 0, open reads 1, and the sketch reads all sixteen in one I2C transaction. One reed per pin means no ghosting; an 8 by 8 matrix would need a diode at every square.

Moves. A square must read the same for 60 ms before it counts. A lift and a place on another square is a move; a lift and a place on the same square is no move; two lifts and a place on one of them is a capture.

Rules. A 0x88 board of 128 bytes, where any square with a bit of 0x88 set is off the board. Moves are generated per piece, and each is made and unmade to check the mover's king is not left attacked. No legal moves is checkmate if in check, stalemate if not. Castling and en passant are left out, and pawns always promote to a queen.

Hints. Pieces lit dim (white for white, red for black), the last move in blue, and a chosen piece's legal squares in green.

The engine. Material (pawn 100, knight 320, bishop 330, rook 500, queen 900) plus a center bonus, searched with negamax and alpha-beta pruning three plies deep, captures first. It never misses a free piece and does not make plans: each extra ply costs around six times the work and more RAM than the Uno has.

The course

Build an electronic chessboard gets there in six lessons, each a sketch on the same wiring:

  1. Reed square matrix: reeds, an MCP23017 and the LEDs.
  2. Move detection: lifts, places, captures and debouncing.
  3. Legal moves: the 0x88 board, check, checkmate and stalemate.
  4. LED hints: the position, the last move and legal squares in light.
  5. A chess engine: negamax with alpha-beta, three plies.
  6. Project: play the board: reed moves, typed moves, hints and the engine.

Every step but the last is checked against the running circuit.