// Mini LED Ludo - STM32F103C8T6 (Blue Pill), Arduino / STM32duino core.
// Board: 48 WS2812 LEDs, 7-LED dice, 4 buttons, TM1637 display, buzzer.
//
// How to play:
// Setup : Red button (short) cycles 2/3/4 players, any long press starts.
// Turn : current player's button (short) rolls the dice.
// Choose : if both pieces can move, the selected one blinks.
// short press = switch piece, long press = confirm.
// Rules : 6 to leave base, 6 or a capture = roll again,
// start cells are safe, exact roll to finish.
// Win : long press any button to play again.
#include <Adafruit_NeoPixel.h>
#include <TM1637Display.h>
#include <SPI.h>
#include <string.h>
// ---- ludo_logic.h (inlined for Wokwi) ----
// ludo_logic.h - pure game rules for Mini LED Ludo (no hardware code).
// Same file compiles on the PC (for tests) and on the STM32.
#include <stdint.h>
namespace ludo {
static const uint8_t NUM_PLAYERS = 4; // 0=Red 1=Green 2=Yellow 3=Blue
static const uint8_t PIECES = 2; // pieces per player
static const uint8_t LOOP_LEN = 28; // cells on the outer path (LED 0..27)
static const int8_t IN_BASE = -1; // progress value of a piece still in base
static const int8_t LAST_LOOP = 26; // last progress value on the outer path
static const int8_t FINISH = 29; // 27,28 = home path, 29 = finish
static const uint8_t NUM_LEDS = 48;
static const uint8_t START[NUM_PLAYERS] = {1, 8, 15, 22}; // start cells (safe)
static const uint8_t HOME_BASE[NUM_PLAYERS] = {28, 31, 34, 37}; // home1, home2, finish
static const uint8_t BASE_LED[NUM_PLAYERS] = {40, 42, 44, 46}; // 2 base slots each
struct Game {
int8_t progress[NUM_PLAYERS][PIECES];
bool active[NUM_PLAYERS];
uint8_t current;
};
// 2 players sit opposite each other (Red vs Yellow), 3 = Red, Green, Yellow.
inline void reset(Game &g, uint8_t numPlayers) {
for (uint8_t p = 0; p < NUM_PLAYERS; p++) {
g.active[p] = (numPlayers >= 4) || (numPlayers == 3 && p < 3) ||
(numPlayers == 2 && (p == 0 || p == 2));
for (uint8_t i = 0; i < PIECES; i++) g.progress[p][i] = IN_BASE;
}
g.current = 0;
}
inline bool isSafeCell(uint8_t cell) {
for (uint8_t p = 0; p < NUM_PLAYERS; p++)
if (START[p] == cell) return true;
return false;
}
// Outer-path cell for a progress value 0..26.
inline uint8_t loopCell(uint8_t player, int8_t progress) {
return (uint8_t)((START[player] + progress) % LOOP_LEN);
}
// Which LED shows this piece.
inline uint8_t ledFor(uint8_t player, uint8_t piece, int8_t progress) {
if (progress == IN_BASE) return BASE_LED[player] + piece;
if (progress <= LAST_LOOP) return loopCell(player, progress);
return HOME_BASE[player] + (progress - (LAST_LOOP + 1)); // 27->+0, 28->+1, 29->+2
}
inline bool canMove(const Game &g, uint8_t p, uint8_t i, uint8_t dice) {
int8_t pr = g.progress[p][i];
if (pr == IN_BASE) return dice == 6; // need a 6 to leave base
if (pr == FINISH) return false;
return pr + dice <= FINISH; // exact roll needed to finish
}
// Bit i set = piece i can move.
inline uint8_t movableMask(const Game &g, uint8_t p, uint8_t dice) {
uint8_t m = 0;
for (uint8_t i = 0; i < PIECES; i++)
if (canMove(g, p, i, dice)) m |= (1 << i);
return m;
}
// Both movable pieces would end up in the same place -> no real choice.
inline bool sameChoice(const Game &g, uint8_t p) {
return g.progress[p][0] == g.progress[p][1];
}
// Call after the piece has landed. Sends opponents on that cell back to base.
// Returns how many pieces were captured.
inline uint8_t resolveLanding(Game &g, uint8_t p, uint8_t i) {
int8_t pr = g.progress[p][i];
if (pr < 0 || pr > LAST_LOOP) return 0; // home path is private
uint8_t cell = loopCell(p, pr);
if (isSafeCell(cell)) return 0;
uint8_t captured = 0;
for (uint8_t q = 0; q < NUM_PLAYERS; q++) {
if (q == p || !g.active[q]) continue;
for (uint8_t j = 0; j < PIECES; j++) {
int8_t qp = g.progress[q][j];
if (qp >= 0 && qp <= LAST_LOOP && loopCell(q, qp) == cell) {
g.progress[q][j] = IN_BASE;
captured++;
}
}
}
return captured;
}
// Instant move (no animation). Returns captured count.
inline uint8_t applyMove(Game &g, uint8_t p, uint8_t i, uint8_t dice) {
if (g.progress[p][i] == IN_BASE) g.progress[p][i] = 0;
else g.progress[p][i] += dice;
return resolveLanding(g, p, i);
}
inline bool hasWon(const Game &g, uint8_t p) {
for (uint8_t i = 0; i < PIECES; i++)
if (g.progress[p][i] != FINISH) return false;
return true;
}
inline uint8_t nextPlayer(const Game &g, uint8_t p) {
do { p = (p + 1) % NUM_PLAYERS; } while (!g.active[p]);
return p;
}
} // namespace ludo
// ---- end ludo_logic.h ----
using namespace ludo;
// ---------- Pins ----------
#define PIN_STRIP PA7 // SPI1 MOSI drives the WS2812 data line
#define PIN_BUZZER PB0
#define PIN_TM_CLK PB6
#define PIN_TM_DIO PB7
const uint8_t BTN_PIN[NUM_PLAYERS] = {PA0, PA1, PA2, PA3}; // Red, Green, Yellow, Blue
// Dice: 7 LEDs need only 4 pins (LEDs that always light together share a pin)
#define DICE_C PB12 // center : 1, 3, 5
#define DICE_A PB13 // top-left + bottom-right: 2..6
#define DICE_B PB14 // top-right + bottom-left: 4, 5, 6
#define DICE_M PB15 // middle-left + middle-right: 6
// ---------- Hardware objects ----------
Adafruit_NeoPixel strip(NUM_LEDS, PIN_STRIP, NEO_GRB + NEO_KHZ800);
TM1637Display display(PIN_TM_CLK, PIN_TM_DIO);
// ---------- WS2812 driver (SPI1, PA7) ----------
// The WS2812 bit timing is made by the SPI peripheral, not by delays:
// SPI at 4.5 MHz, one SPI byte per LED bit.
// LED bit 0 -> 11000000 (0.44 us high) LED bit 1 -> 11110000 (0.89 us high)
// Gaps between SPI bytes only stretch the LOW time, which WS2812 tolerates.
// (Wokwi's Blue Pill cannot simulate bit-banged WS2812 timing; this works there
// and on the real board. Later: same idea with SPI + DMA, CPU stays free.)
void ws2812Send(const uint8_t *data, uint16_t len) {
SPI.beginTransaction(SPISettings(4500000, MSBFIRST, SPI_MODE0));
noInterrupts();
for (uint16_t k = 0; k < 200; k++) { // long LOW preamble = reset pulse,
while (!(SPI1->SR & SPI_SR_TXE)) {} // also keeps the first bits from
*(volatile uint8_t *)&SPI1->DR = 0x00; // being lost in the simulator
}
for (uint16_t n = 0; n < len; n++) {
uint8_t v = data[n];
for (uint8_t bit = 0; bit < 8; bit++) {
while (!(SPI1->SR & SPI_SR_TXE)) {} // wait until TX buffer is empty
*(volatile uint8_t *)&SPI1->DR = (v & 0x80) ? 0xF0 : 0xC0;
v <<= 1;
}
}
while (SPI1->SR & SPI_SR_BSY) {} // last byte fully sent
interrupts();
(void)SPI1->DR; (void)SPI1->SR; // clear overrun flag
SPI.endTransaction();
delayMicroseconds(80); // >50 us low = latch
}
void ledShow() { ws2812Send(strip.getPixels(), NUM_LEDS * 3); }
// ---------- Colours ----------
const uint8_t COLOR[NUM_PLAYERS][3] = {
{255, 0, 0}, {0, 200, 0}, {255, 170, 0}, {0, 70, 255}
};
uint32_t playerColor(uint8_t p, uint8_t div = 1) {
return strip.Color(COLOR[p][0] / div, COLOR[p][1] / div, COLOR[p][2] / div);
}
// TM1637 segment letters for each player: r, G, Y, b
const uint8_t LETTER[NUM_PLAYERS] = {
SEG_E | SEG_G,
SEG_A | SEG_C | SEG_D | SEG_E | SEG_F,
SEG_B | SEG_C | SEG_D | SEG_F | SEG_G,
SEG_C | SEG_D | SEG_E | SEG_F | SEG_G
};
const uint8_t SEG_DASH = SEG_G;
// ---------- Buttons (debounce + short/long press) ----------
enum BtnEvent { EV_NONE, EV_SHORT, EV_LONG };
const uint16_t DEBOUNCE_MS = 25;
const uint16_t LONG_MS = 600;
struct Btn { bool stable, lastRaw, longFired; uint32_t lastEdge, pressAt; };
Btn btn[NUM_PLAYERS];
BtnEvent ev[NUM_PLAYERS];
// Returns a BtnEvent as uint8_t: Arduino's auto-generated prototypes
// break on functions that return a type declared in the sketch.
uint8_t pollButton(uint8_t i) {
Btn &b = btn[i];
bool raw = digitalRead(BTN_PIN[i]) == LOW; // pull-up: pressed = LOW
uint32_t now = millis();
if (raw != b.lastRaw) { b.lastRaw = raw; b.lastEdge = now; }
if (now - b.lastEdge >= DEBOUNCE_MS && raw != b.stable) {
b.stable = raw;
if (raw) { b.pressAt = now; b.longFired = false; }
else if (!b.longFired) return EV_SHORT;
}
if (b.stable && !b.longFired && now - b.pressAt >= LONG_MS) {
b.longFired = true;
return EV_LONG;
}
return EV_NONE;
}
void pollAllButtons() {
for (uint8_t i = 0; i < NUM_PLAYERS; i++) ev[i] = (BtnEvent)pollButton(i);
}
// ---------- Game state ----------
enum State { ST_SETUP, ST_WAIT_ROLL, ST_SELECT, ST_WIN };
State state = ST_SETUP;
Game game;
uint8_t numPlayers = 4;
uint8_t dice = 0;
int8_t selPiece = -1; // piece blinking during ST_SELECT
uint8_t selMask = 0;
bool seeded = false;
// ---------- Sound ----------
void beep(uint16_t f, uint16_t ms) { tone(PIN_BUZZER, f, ms); }
void soundCapture() { for (uint16_t f = 1500; f > 300; f -= 200) { beep(f, 40); delay(45); } }
void soundWin() {
const uint16_t n[] = {523, 659, 784, 1047, 784, 1047};
for (uint8_t i = 0; i < 6; i++) { beep(n[i], 140); delay(160); }
}
// ---------- Dice LEDs ----------
void showDice(uint8_t n) {
digitalWrite(DICE_C, n == 1 || n == 3 || n == 5);
digitalWrite(DICE_A, n >= 2);
digitalWrite(DICE_B, n >= 4);
digitalWrite(DICE_M, n == 6);
}
// ---------- 7-segment ----------
void showTurn() {
uint8_t d = (dice >= 1 && dice <= 6) ? display.encodeDigit(dice) : SEG_DASH;
uint8_t seg[4] = {LETTER[game.current], 0, 0, d};
display.setSegments(seg);
}
void showSetup() {
uint8_t seg[4] = {SEG_A | SEG_B | SEG_E | SEG_F | SEG_G, // P
SEG_D | SEG_E | SEG_F, // L
0, display.encodeDigit(numPlayers)};
display.setSegments(seg);
}
void showWin(uint8_t p) {
uint8_t seg[4] = {SEG_A | SEG_D | SEG_E | SEG_F | SEG_G, // E
SEG_C | SEG_E | SEG_G, // n
SEG_B | SEG_C | SEG_D | SEG_E | SEG_G, // d
LETTER[p]};
display.setSegments(seg);
}
// ---------- Board rendering ----------
// Sending 48 LEDs takes time, so only send when the picture changed.
uint8_t lastFrame[NUM_LEDS * 3];
void showIfChanged() {
if (memcmp(lastFrame, strip.getPixels(), sizeof(lastFrame)) == 0) return;
memcpy(lastFrame, strip.getPixels(), sizeof(lastFrame));
ledShow();
}
void render() {
uint32_t now = millis();
strip.clear();
// Faint "printed board": start cells, home paths, empty base slots
for (uint8_t p = 0; p < NUM_PLAYERS; p++) {
if (!game.active[p]) continue;
uint8_t div = (state != ST_SETUP && p == game.current) ? 6 : 25;
strip.setPixelColor(START[p], playerColor(p, div));
for (uint8_t k = 0; k < 3; k++) strip.setPixelColor(HOME_BASE[p] + k, playerColor(p, div));
for (uint8_t k = 0; k < PIECES; k++) strip.setPixelColor(BASE_LED[p] + k, playerColor(p, 40));
}
// Which players stand on each LED (bitmask)
uint8_t occ[NUM_LEDS] = {0};
bool blinkOff = ((now / 250) % 2) == 0;
for (uint8_t p = 0; p < NUM_PLAYERS; p++) {
if (!game.active[p]) continue;
for (uint8_t i = 0; i < PIECES; i++) {
if (state == ST_SELECT && p == game.current && i == selPiece && blinkOff) continue;
occ[ledFor(p, i, game.progress[p][i])] |= (1 << p);
}
}
// Draw pieces; if two colours share a safe cell, alternate them
for (uint8_t led = 0; led < NUM_LEDS; led++) {
if (!occ[led]) continue;
uint8_t list[NUM_PLAYERS], n = 0;
for (uint8_t p = 0; p < NUM_PLAYERS; p++) if (occ[led] & (1 << p)) list[n++] = p;
strip.setPixelColor(led, playerColor(list[(now / 400) % n]));
}
showIfChanged();
}
// ---------- Game flow ----------
void startGame() {
reset(game, numPlayers);
dice = 0;
showDice(0);
state = ST_WAIT_ROLL;
showTurn();
Serial.print("New game, players: "); Serial.println(numPlayers);
}
uint8_t rollDice() {
if (!seeded) { randomSeed(micros()); seeded = true; } // time of 1st press = seed
for (uint8_t k = 0; k < 12; k++) { // rolling animation
showDice(random(1, 7));
beep(900 + k * 60, 15);
delay(40 + k * 8);
}
uint8_t d = random(1, 7);
showDice(d);
return d;
}
void endTurn(bool again) {
if (!again) game.current = nextPlayer(game, game.current);
dice = 0;
state = ST_WAIT_ROLL;
showTurn();
render();
}
void movePiece(uint8_t i) {
uint8_t p = game.current;
Serial.print("P"); Serial.print(p); Serial.print(" piece "); Serial.print(i);
Serial.print(" dice "); Serial.println(dice);
if (game.progress[p][i] == IN_BASE) { // leave base
game.progress[p][i] = 0;
beep(1200, 60);
render();
delay(250);
} else { // walk cell by cell
for (uint8_t k = 0; k < dice; k++) {
game.progress[p][i]++;
beep(1400, 15);
render();
delay(180);
}
}
uint8_t captured = resolveLanding(game, p, i);
if (captured) {
Serial.println("Capture!");
uint8_t led = ledFor(p, i, game.progress[p][i]);
for (uint8_t k = 0; k < 4; k++) { // flash the cell white
strip.setPixelColor(led, strip.Color(255, 255, 255)); ledShow(); delay(80);
render(); delay(80);
}
soundCapture();
} else if (game.progress[p][i] == FINISH) {
beep(1800, 120);
}
if (hasWon(game, p)) {
state = ST_WIN;
showWin(p);
soundWin();
Serial.print("Winner: P"); Serial.println(p);
return;
}
endTurn(dice == 6 || captured > 0);
}
void handleRoll() {
dice = rollDice();
showTurn();
selMask = movableMask(game, game.current, dice);
if (selMask == 0) { // no legal move
beep(200, 300);
delay(900);
endTurn(false);
return;
}
bool onlyOne = selMask != 0b11 || sameChoice(game, game.current);
if (onlyOne) {
delay(400);
movePiece((selMask & 1) ? 0 : 1);
} else {
selPiece = 0;
state = ST_SELECT;
}
}
void winAnimation(uint8_t p) {
uint32_t now = millis();
strip.clear();
for (uint8_t k = 0; k < 4; k++) { // 4 dots chasing around the path
uint8_t led = (now / 60 + k * 7) % LOOP_LEN;
strip.setPixelColor(led, playerColor(p));
}
for (uint8_t k = 0; k < 3; k++) strip.setPixelColor(HOME_BASE[p] + k, playerColor(p));
showIfChanged();
}
// ---------- Arduino entry points ----------
void setup() {
Serial.begin(115200);
for (uint8_t i = 0; i < NUM_PLAYERS; i++) pinMode(BTN_PIN[i], INPUT_PULLUP);
pinMode(DICE_C, OUTPUT); pinMode(DICE_A, OUTPUT);
pinMode(DICE_B, OUTPUT); pinMode(DICE_M, OUTPUT);
pinMode(PIN_BUZZER, OUTPUT);
SPI.begin(); // PA7 becomes SPI1 MOSI (strip = pixel buffer only,
// strip.begin() would grab PA7 as a plain GPIO)
strip.setBrightness(80); // keep current low on the real board
display.setBrightness(5);
reset(game, numPlayers);
showSetup();
showDice(0);
Serial.println("Mini LED Ludo ready");
}
void loop() {
pollAllButtons();
switch (state) {
case ST_SETUP:
if (ev[0] == EV_SHORT) {
numPlayers = (numPlayers == 4) ? 2 : numPlayers + 1;
reset(game, numPlayers);
showSetup();
beep(1000, 30);
}
for (uint8_t i = 0; i < NUM_PLAYERS; i++)
if (ev[i] == EV_LONG) { beep(1500, 80); startGame(); break; }
render();
break;
case ST_WAIT_ROLL:
if (ev[game.current] != EV_NONE) handleRoll();
render();
break;
case ST_SELECT: {
BtnEvent e = ev[game.current];
if (e == EV_SHORT) { // switch to the other movable piece
selPiece = (selPiece + 1) % PIECES;
if (!(selMask & (1 << selPiece))) selPiece = (selPiece + 1) % PIECES;
beep(1000, 20);
} else if (e == EV_LONG) { // confirm
uint8_t i = selPiece;
selPiece = -1;
state = ST_WAIT_ROLL; // stop blinking while moving
movePiece(i);
}
if (state == ST_SELECT) render();
break;
}
case ST_WIN:
winAnimation(game.current);
for (uint8_t i = 0; i < NUM_PLAYERS; i++)
if (ev[i] == EV_LONG) {
state = ST_SETUP;
dice = 0;
showDice(0);
reset(game, numPlayers);
showSetup();
break;
}
break;
}
delay(5);
}
Loading
stm32-bluepill
stm32-bluepill