// =====================================================================
// LED Bike Race - ESP32-S3 version (DevKitC-1)
// - Pins moved to S3, all adjacent on the left header: 4,5,6,7,15
// - Buzzer removed
// - ledsPerPass (edit mode value) is saved to flash and survives reboot
//
// Arduino IDE settings:
// Board: ESP32S3 Dev Module
// USB CDC On Boot: Enabled (to see Serial on the USB port)
// FastLED: version 3.9 or newer
// =====================================================================
#include <FastLED.h>
#include <Preferences.h>
// ===================== CONFIG =====================
#define NUM_LEDS 144
#define CHIPSET WS2811
#define COLOR_ORDER RGB
#define BRIGHTNESS 128
// ===== ESP32-S3 Pins (left header, consecutive, next to 3V3) =====
#define SENSOR_PIN_A 4
#define LED_PIN_A 5
#define SENSOR_PIN_B 6
#define LED_PIN_B 7
#define BUTTON_PIN 15 // push button to GND (INPUT_PULLUP)
// ===== Behavior =====
int ledsPerPass = 3;
const int MIN_LEDS_PER_PASS = 1;
const int MAX_LEDS_PER_PASS = 6;
const unsigned long COOLDOWN_MS = 60;
// ===== Saved settings (flash) =====
Preferences prefs;
const char *PREFS_NS = "bikerace";
const char *PREFS_KEY_LPP = "lpp";
// ===== Edit mode =====
const unsigned long ENTER_PREVIEW_HOLD_MS = 15000; // 15 sec
const unsigned long ENTER_EDIT_HOLD_MS = 10000; // 10 sec
const unsigned long EDIT_IDLE_TIMEOUT_MS = 12000; // must be > ENTER_EDIT_HOLD_MS
// ===== Tail =====
const uint8_t TRAIL_DECAY = 24;
// ===== Speed learning =====
const int SPEED_SAMPLES = 3;
// ===== Debug =====
#define DEBUG 1
const unsigned long DEBUG_EVERY_MS = 1000;
unsigned long lastDebugMs = 0;
// ===== Timeout / Replay / Finish =====
const unsigned long STOP_BOTH_MS = 10000; // both started, both stopped -> replay flow
const unsigned long STOP_SINGLE_WITH_IDLE_MS = 10000; // only one ever started, then stopped -> replay flow
const unsigned long START_IDLE_TIMEOUT_MS = 20000; // start pressed but nobody moved -> back to idle
const unsigned long WIN_STAGE_MS = 5000; // show winner, then auto-new game
const unsigned long COUNTDOWN_STEP_MS = 700; // 3,2,1 timing
const unsigned long REPLAY_STEP_MS = 100; // replay speed
const unsigned long POST_REPLAY_WAIT_MS = 10000; // hold result after replay
// ===== Button Debounce =====
const unsigned long BUTTON_DEBOUNCE_MS = 35;
bool btnStable = HIGH;
bool btnLastStable = HIGH;
bool btnLastReading = HIGH;
unsigned long btnLastChangeMs = 0;
bool btnPressActive = false;
unsigned long btnPressedAt = 0;
bool btnLongActionFired = false;
// ===== Edit timing =====
unsigned long editLastActionAt = 0;
bool editConfirmFlashPending = false;
bool previewReleaseFlashDone = false;
// ===== Sleep/Idle indicator =====
const int SLEEP_LED_IDX = 1; // LED #2 (index 1)
const unsigned long SLEEP_STEP_MS = 60; // slow update
unsigned long sleepNextAt = 0;
// ===== Countdown =====
unsigned long countdownStepAt = 0;
uint8_t countdownPhase = 0; // 0=3(far), 1=2(mid), 2=1(near), 3=go
// ===== Replay flow =====
unsigned long replayWaitUntil = 0;
unsigned long replayNextStepAt = 0;
unsigned long postWaitUntil = 0;
int replayTargetA = 0;
int replayTargetB = 0;
int replayPosA = 0;
int replayPosB = 0;
// ===== Race start / finish timing =====
unsigned long raceStartedAt = 0;
unsigned long finishUntil = 0;
// ===================== LED BUFFERS =====================
static CRGB ledsA[NUM_LEDS];
static CRGB ledsB[NUM_LEDS];
// ===================== STATE MACHINE =====================
enum GameState {
STATE_IDLE,
STATE_COUNTDOWN,
STATE_RACE,
STATE_REPLAY_WAIT,
STATE_REPLAY_RUN,
STATE_POST_WAIT,
STATE_FINISH,
STATE_EDIT_PREVIEW,
STATE_EDIT_MODE
};
GameState gameState = STATE_IDLE;
// ===================== RACE STATE =====================
int winnerId = 0; // 0=none, 1=A, 2=B
// ===================== TRACK =====================
struct Track {
int id; // 1=A, 2=B
int sensorPin;
CRGB *leds;
bool lastMagnetState;
unsigned long lastEdgeMs; // last REAL pedal edge time (activity)
unsigned long lastLapMs;
int currentIndex;
bool everMoved;
// speed learning
unsigned long speedSamples[SPEED_SAMPLES - 1];
int speedSampleCount;
unsigned long avgLapTime;
// step scheduler
bool stepping;
int stepsLeft;
unsigned long stepDelay;
unsigned long nextStepAt;
// win animation
bool inWin;
uint8_t winPhase;
uint8_t winRep;
int winDot;
unsigned long winUntil;
unsigned long winNextAt;
// lose animation
bool inLose;
unsigned long loseNextAt;
};
Track trackA;
Track trackB;
// ===================== PROTOTYPES =====================
static inline CRGB trkColorByTrack(int trackId);
void trkInit(Track &t, int id, int sensorPin, CRGB *ledsPtr, unsigned long now);
void trkStartWin(Track &t, unsigned long now);
bool trkUpdateWin(Track &t, unsigned long now);
void trkStartLose(Track &t, unsigned long now);
bool trkUpdateLose(Track &t, unsigned long now);
static inline void trkStepOne(Track &t);
void trkOnEdge(Track &t, unsigned long now);
bool trkUpdate(Track &t, unsigned long now);
void startRaceOver(int winner, unsigned long now);
void resetRace(unsigned long now);
void startCountdown(unsigned long now);
bool updateCountdown(unsigned long now);
void enterRaceFromCountdown(unsigned long now);
bool updateSleepIdle(unsigned long now);
void updateButton(unsigned long now);
bool handleStopLogic(unsigned long now);
bool handleNoActivityTimeout(unsigned long now);
void renderReplayDisplay(int uptoA, int uptoB);
bool renderReplayWaitDisplay();
void renderCountdownThirds(uint8_t phase);
void startReplayWait(unsigned long now);
bool updateReplayWait(unsigned long now);
bool updateReplayRun(unsigned long now);
bool updatePostWait(unsigned long now);
void enterEditPreview(unsigned long now);
void enterEditMode(unsigned long now);
bool updateEditPreview(unsigned long now);
bool updateEditMode(unsigned long now);
void renderEditValue(int value);
void cycleLedsPerPass(unsigned long now);
void leaveToIdle(unsigned long now);
void flashEditValueOnce(unsigned long now);
void loadSettings();
void saveSettings();
static inline void dbgEdge(const Track &t, unsigned long dt);
static inline void dbgFinish(int winner);
static inline void dbgReset();
// ===================== SETTINGS (flash) =====================
void loadSettings() {
prefs.begin(PREFS_NS, true); // read-only
int v = prefs.getInt(PREFS_KEY_LPP, ledsPerPass);
prefs.end();
ledsPerPass = constrain(v, MIN_LEDS_PER_PASS, MAX_LEDS_PER_PASS);
#if DEBUG
Serial.print("Loaded ledsPerPass=");
Serial.println(ledsPerPass);
#endif
}
void saveSettings() {
prefs.begin(PREFS_NS, false);
if (prefs.getInt(PREFS_KEY_LPP, -1) != ledsPerPass) {
prefs.putInt(PREFS_KEY_LPP, ledsPerPass);
#if DEBUG
Serial.print("Saved ledsPerPass=");
Serial.println(ledsPerPass);
#endif
}
prefs.end();
}
// ===================== COLOR =====================
static inline CRGB trkColorByTrack(int trackId) {
if (trackId == 1) return CRGB(0, 255, 0);
return CRGB(0, 0, 255);
}
// ===================== DEBUG HELPERS =====================
static inline void dbgEdge(const Track &t, unsigned long dt) {
#if DEBUG
Serial.print("EDGE T");
Serial.print(t.id);
Serial.print(" dt=");
Serial.print(dt);
Serial.print(" idx=");
Serial.print(t.currentIndex);
Serial.print(" stepDelay=");
Serial.print(t.stepDelay);
Serial.print(" avg=");
Serial.println(t.avgLapTime);
#endif
}
static inline void dbgFinish(int winner) {
#if DEBUG
Serial.print("FINISH! winner=T");
Serial.println(winner);
#endif
}
static inline void dbgReset() {
#if DEBUG
Serial.println("RESET -> IDLE");
#endif
}
// ===================== IDLE SLEEP =====================
bool updateSleepIdle(unsigned long now) {
if (gameState != STATE_IDLE) return false;
if ((long)(now - sleepNextAt) < 0) return false;
uint16_t phase = (now / 35) % 512;
uint8_t b = (phase < 256) ? phase : (511 - phase);
b = constrain(b, 10, 70);
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
ledsA[SLEEP_LED_IDX] = CRGB(0, b, 0);
ledsB[SLEEP_LED_IDX] = CRGB(0, 0, b);
sleepNextAt = now + SLEEP_STEP_MS;
return true;
}
// ===================== WIN =====================
void trkStartWin(Track &t, unsigned long now) {
t.inWin = true;
t.winPhase = 0;
t.winRep = 0;
t.winDot = 0;
t.winNextAt = now;
t.winUntil = now + WIN_STAGE_MS;
}
bool trkUpdateWin(Track &t, unsigned long now) {
if (!t.inWin) return false;
if (t.winPhase == 0) {
if ((long)(now - t.winNextAt) < 0) return false;
for (int i = 0; i < NUM_LEDS; i++) t.leds[i].fadeToBlackBy(70);
const uint8_t WIN_TAIL = 5;
for (int k = 0; k < WIN_TAIL; k++) {
int idx = t.winDot - k;
if (idx < 0) idx += NUM_LEDS;
CRGB c = trkColorByTrack(t.id);
uint8_t scale = 255 - (k * (255 / WIN_TAIL));
c.nscale8_video(scale);
t.leds[idx] += c;
}
t.winDot++;
t.winNextAt = now + 8;
if (t.winDot >= NUM_LEDS) {
t.winDot = 0;
t.winRep++;
t.winNextAt = now + 30;
if (t.winRep >= 3) t.winPhase = 1;
}
return true;
}
if (t.winPhase == 1) {
if ((long)(now - t.winNextAt) < 0) return false;
uint16_t phase = (now / 6) % 512;
uint8_t b = (phase < 256) ? phase : (511 - phase);
b = constrain(b, 40, 255);
CRGB c = trkColorByTrack(t.id);
c.nscale8_video(b);
fill_solid(t.leds, NUM_LEDS, c);
t.winNextAt = now + 20;
if ((long)(now - t.winUntil) >= 0) {
t.inWin = false;
}
return true;
}
t.inWin = false;
return true;
}
// ===================== LOSE =====================
void trkStartLose(Track &t, unsigned long now) {
t.inLose = true;
t.loseNextAt = now;
}
bool trkUpdateLose(Track &t, unsigned long now) {
if (!t.inLose) return false;
if ((long)(now - t.loseNextAt) < 0) return false;
uint16_t phase = (now / 10) % 512;
uint8_t b = (phase < 256) ? phase : (511 - phase);
b = constrain(b, 20, 110);
for (int i = 0; i < NUM_LEDS; i++) {
if ((i % 5) < 3) t.leds[i] = CRGB(b, 0, 0);
else t.leds[i] = CRGB::Black;
}
t.loseNextAt = now + 25;
return true;
}
// ===================== RACE CONTROL =====================
void startRaceOver(int winner, unsigned long now) {
winnerId = winner;
dbgFinish(winnerId);
trackA.stepping = false;
trackB.stepping = false;
if (winnerId == 1) {
trkStartWin(trackA, now);
trkStartLose(trackB, now);
} else {
trkStartWin(trackB, now);
trkStartLose(trackA, now);
}
finishUntil = now + WIN_STAGE_MS;
gameState = STATE_FINISH;
}
void resetRace(unsigned long now) {
dbgReset();
winnerId = 0;
trackA.currentIndex = 0;
trackB.currentIndex = 0;
trackA.everMoved = false;
trackB.everMoved = false;
trackA.stepping = false;
trackB.stepping = false;
trackA.inWin = false;
trackB.inWin = false;
trackA.inLose = false;
trackB.inLose = false;
fill_solid(trackA.leds, NUM_LEDS, CRGB::Black);
fill_solid(trackB.leds, NUM_LEDS, CRGB::Black);
trackA.lastLapMs = now;
trackB.lastLapMs = now;
trackA.lastEdgeMs = now;
trackB.lastEdgeMs = now;
trackA.speedSampleCount = 0;
trackB.speedSampleCount = 0;
trackA.avgLapTime = 0;
trackB.avgLapTime = 0;
replayWaitUntil = 0;
replayNextStepAt = 0;
postWaitUntil = 0;
replayTargetA = 0;
replayTargetB = 0;
replayPosA = 0;
replayPosB = 0;
raceStartedAt = 0;
finishUntil = 0;
countdownStepAt = 0;
countdownPhase = 0;
sleepNextAt = now;
}
void startCountdown(unsigned long now) {
resetRace(now);
gameState = STATE_COUNTDOWN;
countdownPhase = 0;
countdownStepAt = now;
#if DEBUG
Serial.println("START -> COUNTDOWN");
#endif
}
void renderCountdownThirds(uint8_t phase) {
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
const int third = NUM_LEDS / 3;
const int nearStart = 0;
const int midStart = third;
const int farStart = third * 2;
CRGB cA = trkColorByTrack(1);
CRGB cB = trkColorByTrack(2);
auto fillRange = [&](int start, int end) {
for (int i = start; i < end; i++) {
ledsA[i] = cA;
ledsB[i] = cB;
}
};
if (phase == 0) {
fillRange(farStart, NUM_LEDS);
} else if (phase == 1) {
fillRange(midStart, farStart);
} else if (phase == 2) {
fillRange(nearStart, midStart);
} else {
for (int i = 0; i < 3 && i < NUM_LEDS; i++) {
ledsA[i] = cA;
ledsB[i] = cB;
}
}
}
bool updateCountdown(unsigned long now) {
if (gameState != STATE_COUNTDOWN) return false;
if ((long)(now - countdownStepAt) < 0) return false;
if (countdownPhase <= 3) {
renderCountdownThirds(countdownPhase);
countdownPhase++;
countdownStepAt = now + COUNTDOWN_STEP_MS;
return true;
}
enterRaceFromCountdown(now);
return true;
}
void enterRaceFromCountdown(unsigned long now) {
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
for (int i = 0; i < 3 && i < NUM_LEDS; i++) {
ledsA[i] = trkColorByTrack(1);
ledsB[i] = trkColorByTrack(2);
}
raceStartedAt = now;
gameState = STATE_RACE;
#if DEBUG
Serial.println("COUNTDOWN -> RACE");
#endif
}
// ===================== ONE LED STEP (during race) =====================
static inline void trkStepOne(Track &t) {
for (int i = 0; i < NUM_LEDS; i++) {
t.leds[i].fadeToBlackBy(TRAIL_DECAY);
}
t.leds[t.currentIndex] = trkColorByTrack(t.id);
t.currentIndex++;
}
// ===================== MAGNET EDGE =====================
void trkOnEdge(Track &t, unsigned long now) {
t.everMoved = true;
t.lastEdgeMs = now;
unsigned long dt = now - t.lastLapMs;
t.lastLapMs = now;
if (t.speedSampleCount > 0 && t.speedSampleCount < SPEED_SAMPLES) {
t.speedSamples[t.speedSampleCount - 1] = dt;
}
if (t.speedSampleCount < SPEED_SAMPLES) t.speedSampleCount++;
if (t.speedSampleCount == SPEED_SAMPLES && t.avgLapTime == 0) {
unsigned long sum = 0;
for (int i = 0; i < SPEED_SAMPLES - 1; i++) sum += t.speedSamples[i];
t.avgLapTime = sum / (SPEED_SAMPLES - 1);
}
unsigned long baseTime = (t.avgLapTime > 0) ? t.avgLapTime : dt;
unsigned long sd = (baseTime / ledsPerPass) / 2;
sd = constrain(sd, 10UL, 30UL);
t.stepDelay = sd;
t.stepsLeft = ledsPerPass;
t.stepping = true;
t.nextStepAt = now;
dbgEdge(t, dt);
}
// ===================== UPDATE TRACK =====================
bool trkUpdate(Track &t, unsigned long now) {
bool changed = false;
if (gameState == STATE_FINISH) {
if (t.inWin) changed |= trkUpdateWin(t, now);
if (t.inLose) changed |= trkUpdateLose(t, now);
return changed;
}
if (gameState != STATE_RACE) return false;
bool magnetDetected = (digitalRead(t.sensorPin) == LOW);
if (magnetDetected && !t.lastMagnetState) {
if (!t.stepping && (now - t.lastEdgeMs) >= COOLDOWN_MS) {
trkOnEdge(t, now);
changed = true;
}
}
t.lastMagnetState = magnetDetected;
if (t.stepping && (long)(now - t.nextStepAt) >= 0) {
while (t.stepping && (long)(now - t.nextStepAt) >= 0) {
if (t.currentIndex >= NUM_LEDS) {
startRaceOver(t.id, now);
changed = true;
break;
}
trkStepOne(t);
changed = true;
t.stepsLeft--;
if (t.stepsLeft <= 0) {
t.stepping = false;
break;
}
t.nextStepAt += t.stepDelay;
if ((long)(now - t.nextStepAt) > 1000) t.nextStepAt = now;
}
}
#if DEBUG
if (gameState == STATE_RACE && (long)(now - lastDebugMs) >= 0) {
lastDebugMs = now + DEBUG_EVERY_MS;
Serial.print("STAT A idx=");
Serial.print(trackA.currentIndex);
Serial.print(" step=");
Serial.print(trackA.stepping);
Serial.print(" ever=");
Serial.print(trackA.everMoved);
Serial.print(" | B idx=");
Serial.print(trackB.currentIndex);
Serial.print(" step=");
Serial.print(trackB.stepping);
Serial.print(" ever=");
Serial.print(trackB.everMoved);
Serial.print(" | idleA=");
Serial.print(now - trackA.lastEdgeMs);
Serial.print(" idleB=");
Serial.println(now - trackB.lastEdgeMs);
}
#endif
return changed;
}
// ===================== REPLAY FLOW =====================
void renderReplayDisplay(int uptoA, int uptoB) {
uptoA = constrain(uptoA, 0, NUM_LEDS);
uptoB = constrain(uptoB, 0, NUM_LEDS);
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
CRGB cA = trkColorByTrack(1);
CRGB cB = trkColorByTrack(2);
if (!trackA.everMoved) {
for (int i = 0; i < 3 && i < NUM_LEDS; i++) ledsA[i] = cA;
} else {
for (int i = 0; i < uptoA; i++) ledsA[i] = cA;
}
if (!trackB.everMoved) {
for (int i = 0; i < 3 && i < NUM_LEDS; i++) ledsB[i] = cB;
} else {
for (int i = 0; i < uptoB; i++) ledsB[i] = cB;
}
}
bool renderReplayWaitDisplay() {
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
const int tail = 5;
bool changed = false;
if (!trackA.everMoved) {
CRGB cA = trkColorByTrack(1);
for (int i = 0; i < 3 && i < NUM_LEDS; i++) ledsA[i] = cA;
changed = true;
} else if (trackA.currentIndex > 0) {
int head = trackA.currentIndex - 1;
for (int k = 0; k < tail; k++) {
int idx = head - k;
if (idx < 0) break;
CRGB c = trkColorByTrack(1);
uint8_t scale = 255 - (k * (255 / tail));
c.nscale8_video(scale);
ledsA[idx] += c;
}
changed = true;
}
if (!trackB.everMoved) {
CRGB cB = trkColorByTrack(2);
for (int i = 0; i < 3 && i < NUM_LEDS; i++) ledsB[i] = cB;
changed = true;
} else if (trackB.currentIndex > 0) {
int head = trackB.currentIndex - 1;
for (int k = 0; k < tail; k++) {
int idx = head - k;
if (idx < 0) break;
CRGB c = trkColorByTrack(2);
uint8_t scale = 255 - (k * (255 / tail));
c.nscale8_video(scale);
ledsB[idx] += c;
}
changed = true;
}
return changed;
}
void startReplayWait(unsigned long now) {
replayTargetA = constrain(trackA.currentIndex, 0, NUM_LEDS);
replayTargetB = constrain(trackB.currentIndex, 0, NUM_LEDS);
trackA.stepping = false;
trackB.stepping = false;
replayPosA = 0;
replayPosB = 0;
replayNextStepAt = now;
renderReplayDisplay(0, 0);
#if DEBUG
Serial.print("REPLAY_RUN start targetA=");
Serial.print(replayTargetA);
Serial.print(" targetB=");
Serial.println(replayTargetB);
#endif
gameState = STATE_REPLAY_RUN;
}
bool updateReplayWait(unsigned long now) {
if (gameState != STATE_REPLAY_WAIT) return false;
renderReplayWaitDisplay();
if ((long)(now - replayWaitUntil) < 0) return true;
replayPosA = 0;
replayPosB = 0;
replayNextStepAt = now;
renderReplayDisplay(0, 0);
#if DEBUG
Serial.println("REPLAY_WAIT -> REPLAY_RUN");
#endif
gameState = STATE_REPLAY_RUN;
return true;
}
bool updateReplayRun(unsigned long now) {
if (gameState != STATE_REPLAY_RUN) return false;
if ((long)(now - replayNextStepAt) < 0) return false;
if (replayPosA < replayTargetA) replayPosA++;
if (replayPosB < replayTargetB) replayPosB++;
renderReplayDisplay(replayPosA, replayPosB);
replayNextStepAt = now + REPLAY_STEP_MS;
if (replayPosA >= replayTargetA && replayPosB >= replayTargetB) {
postWaitUntil = now + POST_REPLAY_WAIT_MS;
#if DEBUG
Serial.println("REPLAY_RUN done -> POST_WAIT");
#endif
gameState = STATE_POST_WAIT;
}
return true;
}
bool updatePostWait(unsigned long now) {
if (gameState != STATE_POST_WAIT) return false;
renderReplayDisplay(replayTargetA, replayTargetB);
if ((long)(now - postWaitUntil) < 0) return true;
#if DEBUG
Serial.println("POST_WAIT done -> IDLE");
#endif
resetRace(now);
gameState = STATE_IDLE;
return true;
}
// ===================== EDIT MODE =====================
void renderEditValue(int value) {
value = constrain(value, MIN_LEDS_PER_PASS, MAX_LEDS_PER_PASS);
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
int startIdx = (NUM_LEDS / 2) - (value / 2);
startIdx = constrain(startIdx, 0, NUM_LEDS - value);
for (int i = 0; i < value; i++) {
ledsA[startIdx + i] = trkColorByTrack(1);
ledsB[startIdx + i] = trkColorByTrack(2);
}
}
void flashEditValueOnce(unsigned long now) {
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
FastLED.show();
delay(120);
renderEditValue(ledsPerPass);
FastLED.show();
}
void leaveToIdle(unsigned long now) {
saveSettings(); // keep the edited value after power off
resetRace(now);
gameState = STATE_IDLE;
editConfirmFlashPending = false;
previewReleaseFlashDone = false;
}
void enterEditPreview(unsigned long now) {
resetRace(now);
gameState = STATE_EDIT_PREVIEW;
editLastActionAt = now;
editConfirmFlashPending = true;
previewReleaseFlashDone = false;
renderEditValue(ledsPerPass);
#if DEBUG
Serial.print("ENTER EDIT PREVIEW, ledsPerPass=");
Serial.println(ledsPerPass);
#endif
}
void enterEditMode(unsigned long now) {
gameState = STATE_EDIT_MODE;
editLastActionAt = now;
editConfirmFlashPending = false;
flashEditValueOnce(now);
#if DEBUG
Serial.print("ENTER EDIT MODE, ledsPerPass=");
Serial.println(ledsPerPass);
#endif
}
void cycleLedsPerPass(unsigned long now) {
ledsPerPass++;
if (ledsPerPass > MAX_LEDS_PER_PASS) ledsPerPass = MIN_LEDS_PER_PASS;
editLastActionAt = now;
renderEditValue(ledsPerPass);
#if DEBUG
Serial.print("EDIT VALUE -> ");
Serial.println(ledsPerPass);
#endif
}
bool updateEditPreview(unsigned long now) {
if (gameState != STATE_EDIT_PREVIEW) return false;
renderEditValue(ledsPerPass);
if ((now - editLastActionAt) >= EDIT_IDLE_TIMEOUT_MS) {
#if DEBUG
Serial.println("EDIT PREVIEW timeout -> IDLE");
#endif
leaveToIdle(now);
return true;
}
return true;
}
bool updateEditMode(unsigned long now) {
if (gameState != STATE_EDIT_MODE) return false;
renderEditValue(ledsPerPass);
if ((now - editLastActionAt) >= EDIT_IDLE_TIMEOUT_MS) {
#if DEBUG
Serial.println("EDIT MODE timeout -> IDLE");
#endif
leaveToIdle(now);
return true;
}
return true;
}
// ===================== STOP / TIMEOUT LOGIC =====================
bool handleStopLogic(unsigned long now) {
if (gameState != STATE_RACE) return false;
unsigned long idleA = now - trackA.lastEdgeMs;
unsigned long idleB = now - trackB.lastEdgeMs;
if (trackA.everMoved && trackB.everMoved) {
if (idleA >= STOP_BOTH_MS && idleB >= STOP_BOTH_MS) {
#if DEBUG
Serial.println("Both started, then both stopped -> replay flow");
#endif
startReplayWait(now);
return true;
}
return false;
}
if (trackA.everMoved && !trackB.everMoved && idleA >= STOP_SINGLE_WITH_IDLE_MS) {
#if DEBUG
Serial.println("Only A moved, B never started, A stopped -> replay flow");
#endif
startReplayWait(now);
return true;
}
if (!trackA.everMoved && trackB.everMoved && idleB >= STOP_SINGLE_WITH_IDLE_MS) {
#if DEBUG
Serial.println("Only B moved, A never started, B stopped -> replay flow");
#endif
startReplayWait(now);
return true;
}
return false;
}
bool handleNoActivityTimeout(unsigned long now) {
if (gameState != STATE_RACE) return false;
if (trackA.everMoved || trackB.everMoved) return false;
if ((now - raceStartedAt) < START_IDLE_TIMEOUT_MS) return false;
#if DEBUG
Serial.println("No activity after start -> back to IDLE");
#endif
resetRace(now);
gameState = STATE_IDLE;
return true;
}
// ===================== INIT =====================
void trkInit(Track &t, int id, int sensorPin, CRGB *ledsPtr, unsigned long now) {
t.id = id;
t.sensorPin = sensorPin;
t.leds = ledsPtr;
t.lastMagnetState = false;
t.lastEdgeMs = now;
t.lastLapMs = now;
t.currentIndex = 0;
t.everMoved = false;
for (int i = 0; i < SPEED_SAMPLES - 1; i++) t.speedSamples[i] = 0;
t.speedSampleCount = 0;
t.avgLapTime = 0;
t.stepping = false;
t.stepsLeft = 0;
t.stepDelay = 80;
t.nextStepAt = now;
t.inWin = false;
t.winPhase = 0;
t.winRep = 0;
t.winDot = 0;
t.winUntil = 0;
t.winNextAt = now;
t.inLose = false;
t.loseNextAt = now;
}
// ===================== BUTTON (debounced) =====================
void updateButton(unsigned long now) {
bool reading = digitalRead(BUTTON_PIN);
if (reading != btnLastReading) {
btnLastReading = reading;
btnLastChangeMs = now;
}
if ((now - btnLastChangeMs) >= BUTTON_DEBOUNCE_MS) {
btnStable = reading;
}
// press started
if (btnLastStable == HIGH && btnStable == LOW) {
btnPressActive = true;
btnPressedAt = now;
btnLongActionFired = false;
if (gameState == STATE_EDIT_PREVIEW || gameState == STATE_EDIT_MODE) {
editLastActionAt = now;
}
#if DEBUG
Serial.print("BUTTON DOWN. state=");
Serial.println((int)gameState);
#endif
}
// while holding
if (btnStable == LOW && btnPressActive) {
unsigned long heldMs = now - btnPressedAt;
if (gameState == STATE_EDIT_PREVIEW || gameState == STATE_EDIT_MODE) {
editLastActionAt = now;
}
if (!btnLongActionFired) {
if (gameState == STATE_IDLE && heldMs >= ENTER_PREVIEW_HOLD_MS) {
enterEditPreview(now);
btnLongActionFired = true;
} else if (gameState == STATE_EDIT_PREVIEW && heldMs >= ENTER_EDIT_HOLD_MS) {
enterEditMode(now);
btnLongActionFired = true;
}
}
}
// release
if (btnLastStable == LOW && btnStable == HIGH) {
unsigned long heldMs = now - btnPressedAt;
#if DEBUG
Serial.print("BUTTON UP after ");
Serial.print(heldMs);
Serial.print(" ms. state=");
Serial.println((int)gameState);
#endif
if (!btnLongActionFired) {
if (gameState == STATE_EDIT_MODE) {
cycleLedsPerPass(now);
} else if (gameState == STATE_EDIT_PREVIEW) {
editLastActionAt = now;
} else {
startCountdown(now);
}
} else {
if (gameState == STATE_EDIT_PREVIEW) {
if (!previewReleaseFlashDone) {
flashEditValueOnce(now);
previewReleaseFlashDone = true;
}
editLastActionAt = now;
} else if (gameState == STATE_EDIT_MODE) {
editLastActionAt = now;
}
}
btnPressActive = false;
btnPressedAt = 0;
btnLongActionFired = false;
}
btnLastStable = btnStable;
}
// ===================== SETUP/LOOP =====================
void setup() {
Serial.begin(115200);
delay(300); // give native USB a moment
pinMode(SENSOR_PIN_A, INPUT_PULLUP);
pinMode(SENSOR_PIN_B, INPUT_PULLUP);
pinMode(BUTTON_PIN, INPUT_PULLUP);
loadSettings();
FastLED.addLeds<CHIPSET, LED_PIN_A, COLOR_ORDER>(ledsA, NUM_LEDS);
FastLED.addLeds<CHIPSET, LED_PIN_B, COLOR_ORDER>(ledsB, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
fill_solid(ledsA, NUM_LEDS, CRGB::Black);
fill_solid(ledsB, NUM_LEDS, CRGB::Black);
FastLED.show();
unsigned long now = millis();
trkInit(trackA, 1, SENSOR_PIN_A, ledsA, now);
trkInit(trackB, 2, SENSOR_PIN_B, ledsB, now);
gameState = STATE_IDLE;
sleepNextAt = now;
#if DEBUG
Serial.println("ESP32-S3 ready. STATE_IDLE: LED #2 breathing. Press BUTTON to start.");
#endif
}
void loop() {
unsigned long now = millis();
updateButton(now);
bool changed = false;
if (gameState == STATE_IDLE) {
changed |= updateSleepIdle(now);
} else if (gameState == STATE_COUNTDOWN) {
changed |= updateCountdown(now);
} else if (gameState == STATE_RACE) {
changed |= trkUpdate(trackA, now);
changed |= trkUpdate(trackB, now);
changed |= handleStopLogic(now);
changed |= handleNoActivityTimeout(now);
} else if (gameState == STATE_REPLAY_WAIT) {
changed |= updateReplayWait(now);
} else if (gameState == STATE_REPLAY_RUN) {
changed |= updateReplayRun(now);
} else if (gameState == STATE_POST_WAIT) {
changed |= updatePostWait(now);
} else if (gameState == STATE_FINISH) {
changed |= trkUpdate(trackA, now);
changed |= trkUpdate(trackB, now);
if ((long)(now - finishUntil) >= 0) {
#if DEBUG
Serial.println("FINISH timeout -> auto new countdown");
#endif
startCountdown(now);
changed = true;
}
} else if (gameState == STATE_EDIT_PREVIEW) {
changed |= updateEditPreview(now);
} else if (gameState == STATE_EDIT_MODE) {
changed |= updateEditMode(now);
}
if (changed) {
FastLED.show();
}
}