Files
lilygo-t-deck/examples/NoiseSensor/NoiseSensor.ino
T
Dejvino b8de153e5a Fix microphone stereo detection on the T-Deck Plus
I2S_CHANNEL_FMT_ALL_LEFT copies a single channel into every slot, so
both microphones read the same signal and the balance stayed at zero.
Use I2S_CHANNEL_FMT_MULTIPLE (the real TDM mode) instead.

The board only fits two of the four ES7210 mic footprints, but the
schematic carries all four. Rather than hardcode MIC1/MIC3, the detector
now measures the TDM slots and locks onto the two that carry signal,
treating the lower slot as the left microphone. Equal maximum gain is
applied to all inputs so the pair amplifies consistently.

Also widen the balance range (claps produce only a few dB of difference
between the closely spaced mics) and recalibrate loudness to the dBFS
range seen with 37.5 dB analog gain.
2026-11-12 14:04:31 +01:00

1115 lines
34 KiB
Arduino

/**
* @file NoiseSensor.ino
* @brief Aliens-like motion sensor emulator via sound array for the LilyGo T-Deck (ESP32-S3).
*
* A green-phosphor (P1-style) terminal drawn with TFT_eSPI pixels: a 53x26
* character grid rendered from a built-in 5x7 bitmap font, with CRT dressing:
* - scanlines (every 3rd row drawn dim)
* - a rolling interference band with a bright phosphor halo
* - occasional single-row horizontal jitter
* - selectable phosphor: green / amber / white (B&W TV)
*
* Input:
* Keyboard : type commands, Backspace erases, Enter submits
* Trackball press : submits the line (like Enter)
* Screen tap : submits the line
*
* Commands (try 'help'):
* help clear echo ver uptime mem fortune dir
* banner beep phos crt vol
*
* Rendering: everything is a character grid, so the effects can repaint any
* row at any time (they only need the grid, no frame buffer). Glyph pixels
* are drawn as fillRect runs, which is SPI-friendly on the device.
*/
#include <Arduino.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <Wire.h>
#include <Preferences.h>
#include "utilities.h"
#include "TouchDrvGT911.hpp"
#include "sound_engine.h"
#include "sound_detector.h"
// ---------------------------------------------------------------------------
// Hardware
// ---------------------------------------------------------------------------
TFT_eSPI tft;
TouchDrvGT911 touch;
SoundEngine sound;
SoundDetector soundDetector;
Preferences prefs;
static bool touchAvail = false;
// ---------------------------------------------------------------------------
// Screen / grid geometry (rotation 1 -> 320x240)
// ---------------------------------------------------------------------------
static const int CELL_W = 6; // 5 px glyph + 1 px gap
static const int CELL_H = 9; // 7 px glyph + 2 px gap
static const int COLS = 53; // 53 * 6 = 318 px
static const int ROWS = 26; // 26 * 9 = 234 px
static const int X0 = 1;
static const int Y0 = 3;
static const int SCR_W = 320;
static const int SCR_H = 240;
static const int LINE_BUF = COLS - 3; // room for "> " + cursor cell
// ---------------------------------------------------------------------------
// CRT look: phosphor palettes {R,G,B} + brightness levels (0..255)
// ---------------------------------------------------------------------------
enum Phos : uint8_t { PH_GREEN = 0, PH_AMBER = 1, PH_WHITE = 2, PH_COUNT };
static const uint8_t PHOS_RGB[PH_COUNT][3] = {
{ 90, 255, 140 }, // P1 green phosphor
{ 255, 170, 60 }, // P3 amber
{ 215, 228, 255 }, // B&W TV white
};
static const char *PHOS_NAME[PH_COUNT] = { "P1 GREEN", "P3 AMBER", "B&W TV" };
static uint8_t phosMode = PH_GREEN;
// Brightness levels, packed as RGB565 on demand
static const int LV_BRIGHT = 255; // glyph core
static const int LV_MID = 170; // cursor block
static const int LV_GLOW = 60; // band halo / interference line
static const int LV_SCAN = 160; // glyph pixels on scanline rows
static uint16_t C_BG, C_BRIGHT, C_MID, C_GLOW, C_SCAN;
static uint16_t shadeRGB(const uint8_t *rgb, int lv)
{
int r = (rgb[0] * lv) / 255;
int g = (rgb[1] * lv) / 255;
int b = (rgb[2] * lv) / 255;
return (uint16_t)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
}
static void buildPalette()
{
const uint8_t *rgb = PHOS_RGB[phosMode];
C_BG = 0x0000; // true black behind the glass
C_BRIGHT = shadeRGB(rgb, LV_BRIGHT);
C_MID = shadeRGB(rgb, LV_MID);
C_GLOW = shadeRGB(rgb, LV_GLOW);
C_SCAN = shadeRGB(rgb, LV_SCAN);
}
// ---------------------------------------------------------------------------
// 5x7 bitmap font, ASCII 32..126 (classic terminal font).
// Each byte is one glyph column, bit i (LSB) = row i (top to bottom).
// ---------------------------------------------------------------------------
static const uint8_t FONT5X7[95][5] = {
{0x00,0x00,0x00,0x00,0x00}, // ' '
{0x00,0x00,0x5F,0x00,0x00}, // '!'
{0x00,0x07,0x00,0x07,0x00}, // '"'
{0x14,0x7F,0x14,0x7F,0x14}, // '#'
{0x24,0x2A,0x7F,0x2A,0x12}, // '$'
{0x23,0x13,0x08,0x64,0x62}, // '%'
{0x36,0x49,0x55,0x22,0x50}, // '&'
{0x00,0x05,0x03,0x00,0x00}, // '\''
{0x00,0x1C,0x22,0x41,0x00}, // '('
{0x00,0x41,0x22,0x1C,0x00}, // ')'
{0x14,0x08,0x3E,0x08,0x14}, // '*'
{0x08,0x08,0x3E,0x08,0x08}, // '+'
{0x00,0x50,0x30,0x00,0x00}, // ','
{0x08,0x08,0x08,0x08,0x08}, // '-'
{0x00,0x60,0x60,0x00,0x00}, // '.'
{0x20,0x10,0x08,0x04,0x02}, // '/'
{0x3E,0x51,0x49,0x45,0x3E}, // '0'
{0x00,0x42,0x7F,0x40,0x00}, // '1'
{0x42,0x61,0x51,0x49,0x46}, // '2'
{0x21,0x41,0x45,0x4B,0x31}, // '3'
{0x18,0x14,0x12,0x7F,0x10}, // '4'
{0x27,0x45,0x45,0x45,0x39}, // '5'
{0x3C,0x4A,0x49,0x49,0x30}, // '6'
{0x01,0x71,0x09,0x05,0x03}, // '7'
{0x36,0x49,0x49,0x49,0x36}, // '8'
{0x06,0x49,0x49,0x29,0x1E}, // '9'
{0x00,0x36,0x36,0x00,0x00}, // ':'
{0x00,0x56,0x36,0x00,0x00}, // ';'
{0x00,0x08,0x14,0x22,0x41}, // '<'
{0x14,0x14,0x14,0x14,0x14}, // '='
{0x41,0x22,0x14,0x08,0x00}, // '>'
{0x02,0x01,0x51,0x09,0x06}, // '?'
{0x32,0x49,0x79,0x41,0x3E}, // '@'
{0x7E,0x11,0x11,0x11,0x7E}, // 'A'
{0x7F,0x49,0x49,0x49,0x36}, // 'B'
{0x3E,0x41,0x41,0x41,0x22}, // 'C'
{0x7F,0x41,0x41,0x22,0x1C}, // 'D'
{0x7F,0x49,0x49,0x49,0x41}, // 'E'
{0x7F,0x09,0x09,0x01,0x01}, // 'F'
{0x3E,0x41,0x49,0x49,0x7A}, // 'G'
{0x7F,0x08,0x08,0x08,0x7F}, // 'H'
{0x00,0x41,0x7F,0x41,0x00}, // 'I'
{0x20,0x40,0x41,0x3F,0x01}, // 'J'
{0x7F,0x08,0x14,0x22,0x41}, // 'K'
{0x7F,0x40,0x40,0x40,0x40}, // 'L'
{0x7F,0x02,0x0C,0x02,0x7F}, // 'M'
{0x7F,0x04,0x08,0x10,0x7F}, // 'N'
{0x3E,0x41,0x41,0x41,0x3E}, // 'O'
{0x7F,0x09,0x09,0x09,0x06}, // 'P'
{0x3E,0x41,0x51,0x21,0x5E}, // 'Q'
{0x7F,0x09,0x09,0x09,0x79}, // 'R'
{0x46,0x49,0x49,0x49,0x31}, // 'S'
{0x01,0x01,0x7F,0x01,0x01}, // 'T'
{0x3F,0x40,0x40,0x40,0x3F}, // 'U'
{0x1F,0x20,0x40,0x20,0x1F}, // 'V'
{0x3F,0x40,0x38,0x40,0x3F}, // 'W'
{0x63,0x14,0x08,0x14,0x63}, // 'X'
{0x07,0x08,0x70,0x08,0x07}, // 'Y'
{0x61,0x51,0x49,0x45,0x43}, // 'Z'
{0x00,0x7F,0x41,0x41,0x00}, // '['
{0x02,0x04,0x08,0x10,0x20}, // '\'
{0x00,0x41,0x41,0x7F,0x00}, // ']'
{0x04,0x02,0x01,0x02,0x04}, // '^'
{0x40,0x40,0x40,0x40,0x40}, // '_'
{0x01,0x02,0x04,0x00,0x00}, // '`'
{0x20,0x54,0x54,0x54,0x78}, // 'a'
{0x7F,0x48,0x44,0x44,0x38}, // 'b'
{0x38,0x44,0x44,0x44,0x20}, // 'c'
{0x38,0x44,0x44,0x48,0x7F}, // 'd'
{0x38,0x54,0x54,0x54,0x18}, // 'e'
{0x08,0x7E,0x09,0x01,0x02}, // 'f'
{0x0C,0x52,0x52,0x52,0x3E}, // 'g'
{0x7F,0x08,0x04,0x04,0x78}, // 'h'
{0x00,0x44,0x7D,0x40,0x00}, // 'i'
{0x20,0x40,0x44,0x3D,0x00}, // 'j'
{0x7F,0x10,0x28,0x44,0x00}, // 'k'
{0x00,0x41,0x7F,0x40,0x00}, // 'l'
{0x7C,0x04,0x18,0x04,0x78}, // 'm'
{0x7C,0x08,0x04,0x04,0x78}, // 'n'
{0x38,0x44,0x44,0x44,0x38}, // 'o'
{0x7C,0x14,0x14,0x14,0x08}, // 'p'
{0x08,0x14,0x14,0x18,0x7C}, // 'q'
{0x7C,0x08,0x04,0x04,0x08}, // 'r'
{0x48,0x54,0x54,0x54,0x20}, // 's'
{0x04,0x3E,0x44,0x40,0x20}, // 't'
{0x3C,0x40,0x40,0x20,0x7C}, // 'u'
{0x1C,0x20,0x40,0x20,0x1C}, // 'v'
{0x3C,0x40,0x30,0x40,0x3C}, // 'w'
{0x44,0x28,0x10,0x28,0x44}, // 'x'
{0x0C,0x50,0x50,0x50,0x3C}, // 'y'
{0x44,0x64,0x54,0x4C,0x44}, // 'z'
{0x00,0x08,0x36,0x41,0x00}, // '{'
{0x00,0x00,0x7F,0x00,0x00}, // '|'
{0x00,0x41,0x36,0x08,0x00}, // '}'
{0x08,0x08,0x2A,0x1C,0x08}, // '~'
};
// ---------------------------------------------------------------------------
// Terminal state
// ---------------------------------------------------------------------------
static char grid[ROWS][COLS];
static int curCol = 0, curRow = 0; // next cell to write
static char lineBuf[LINE_BUF + 1];
static int lineLen = 0;
static const uint32_t FRAME_MS = 50; // ~30 fps
static const uint32_t INPUT_GRACE_MS = 1200;
static const uint32_t CURSOR_ON_MS = 420;
static const uint32_t CURSOR_PERIOD = 700;
// CRT effects
static bool fxOn = true;
static float bandY = -24.0f; // top of the rolling band (px)
static const float BAND_SPEED = 0.55f; // px / frame
static const int BAND_H = 18; // band height (px)
static bool bandRows[ROWS]; // which cell rows the band covers
static int lineLastY = -1; // interference line y last frame
static int jitterRow = -1, jitterOff = 0; // active row jitter
static uint32_t jitterUntil = 0;
static uint32_t nextJitterMs = 0;
// Cursor blink
static bool cursorShowing = false;
static bool cursorDirty = true;
static uint32_t blinkT0 = 0;
// ---------------------------------------------------------------------------
// Low-level rendering
// ---------------------------------------------------------------------------
static void renderGlyphRuns(int x, int y, char ch, uint16_t color, bool scanDim)
{
if (ch < 32 || ch > 126) ch = '?';
const uint8_t *g = FONT5X7[ch - 32];
for (int ry = 0; ry < 7; ry++) {
int rx = 0;
while (rx < 5) {
if (g[rx] & (1 << ry)) {
int len = 1;
while (rx + len < 5 && (g[rx + len] & (1 << ry))) len++;
uint16_t col = color;
if (scanDim && ((y + ry) % 3) == 2) col = C_SCAN;
tft.fillRect(x + rx, y + ry, len, 1, col);
rx += len;
} else {
rx++;
}
}
}
}
// Repaint one grid cell: black background, then the glyph.
static void renderCell(int col, int row, int xoff, bool inBand)
{
if (col < 0 || col >= COLS || row < 0 || row >= ROWS) return;
int x = X0 + col * CELL_W + xoff;
int y = Y0 + row * CELL_H;
tft.fillRect(x, y, CELL_W, CELL_H, C_BG);
char ch = grid[row][col];
if (ch == ' ') return;
if (inBand) {
// phosphor halo: slightly enlarged dim copy behind the glyph
renderGlyphRuns(x - 1, y - 1, ch, C_GLOW, false);
renderGlyphRuns(x - 1, y + 1, ch, C_GLOW, false);
}
renderGlyphRuns(x, y, ch, C_BRIGHT, true);
}
static void renderRow(int row, int xoff)
{
bool inBand = fxOn && bandRows[row];
for (int c = 0; c < COLS; c++) renderCell(c, row, xoff, inBand);
if (row == curRow) cursorDirty = true;
}
static void renderAll()
{
for (int r = 0; r < ROWS; r++) renderRow(r, 0);
}
// Block cursor: filled cell with the glyph knocked out in background color.
static void renderCursor(bool on)
{
if (curCol < 0 || curCol >= COLS || curRow < 0 || curRow >= ROWS) return;
int x = X0 + curCol * CELL_W;
int y = Y0 + curRow * CELL_H;
tft.fillRect(x, y, CELL_W, CELL_H, C_BG);
if (on) {
tft.fillRect(x, y, 5, 7, C_MID);
char ch = grid[curRow][curCol];
if (ch != ' ') renderGlyphRuns(x, y, ch, C_BG, false);
} else {
char ch = grid[curRow][curCol];
if (ch != ' ') {
bool inBand = fxOn && bandRows[curRow];
if (inBand) {
renderGlyphRuns(x - 1, y - 1, ch, C_GLOW, false);
renderGlyphRuns(x - 1, y + 1, ch, C_GLOW, false);
}
renderGlyphRuns(x, y, ch, C_BRIGHT, true);
}
}
}
// Big text (2x scale) drawn straight to the glass (used by boot + 'banner')
static int bigTextWidth(const char *s)
{
return (int)strlen(s) * (5 * 2 + 2) - 2;
}
static void bigPrintAt(const char *s, int x, int y)
{
for (int i = 0; s[i]; i++) {
if (s[i] == ' ') { x += 5 * 2 + 2; continue; }
if (s[i] < 32 || s[i] > 126) continue;
const uint8_t *g = FONT5X7[s[i] - 32];
for (int cx = 0; cx < 5; cx++) {
for (int ry = 0; ry < 7; ry++) {
if (g[cx] & (1 << ry)) {
tft.fillRect(x + cx * 2, y + ry * 2, 2, 2, C_BRIGHT);
}
}
}
x += 5 * 2 + 2;
}
}
static void bigPrintCentered(const char *s, int y)
{
bigPrintAt(s, (SCR_W - bigTextWidth(s)) / 2, y);
}
// ---------------------------------------------------------------------------
// Grid / text output
// ---------------------------------------------------------------------------
static void scrollUp()
{
memmove(&grid[0], &grid[1], sizeof(grid) - COLS);
memset(&grid[ROWS - 1][0], ' ', COLS);
renderAll();
}
static void newline()
{
curCol = 0;
curRow++;
if (curRow >= ROWS) {
curRow = ROWS - 1;
scrollUp();
}
cursorDirty = true;
sndBlip();
}
static void putChar(char ch)
{
return;
if (ch == '\n') { newline(); return; }
if (ch < 32 || ch > 126) ch = '?';
grid[curRow][curCol] = ch;
renderCell(curCol, curRow, 0, fxOn && bandRows[curRow]);
sndBlip();
curCol++;
if (curCol >= COLS) newline();
}
static void writeStr(const char *s)
{
for (int i = 0; s[i]; i++) putChar(s[i]);
}
static void clearScreen()
{
tft.fillScreen(C_BG);
tft.drawRect(0, 0, SCR_W, SCR_H, C_GLOW);
memset(grid, ' ', sizeof(grid));
curCol = curRow = 0;
memset(bandRows, 0, sizeof(bandRows));
lineLastY = -1;
cursorDirty = true;
}
static void printPrompt()
{
writeStr("> ");
}
// ---------------------------------------------------------------------------
// Sound helpers
// ---------------------------------------------------------------------------
static void sndBlip()
{
// Keep the device's own radar ping out of the microphone detector.
soundDetector.suppress(200);
SndEvent e = { SND_TONE, 540, 0, 10, 8000 };
sound.play(e);
delay(15);
}
static void sndClick()
{
soundDetector.suppress(200);
SndEvent e = { SND_TONE, 660, 0, 152, 5000 };
sound.play(e);
}
static void sndBell()
{
SndEvent e = { SND_TONE, 1250, 0, 70, 9000 };
sound.play(e);
}
static void sndError()
{
SndEvent a = { SND_TONE, 240, 0, 90, 12000 };
SndEvent b = { SND_TONE, 170, 0, 130, 12000 };
sound.play(a);
sound.play(b);
}
// ---------------------------------------------------------------------------
// Input handling
// ---------------------------------------------------------------------------
static void execute(char *line); // shell (defined below)
static volatile uint32_t tbClicks;
static void IRAM_ATTR tbIsrClick() { tbClicks++; }
static void attachTrackball()
{
pinMode(BOARD_BOOT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BOARD_BOOT_PIN), tbIsrClick, FALLING);
}
static uint32_t lastSubmitMs = 0;
static void submitLine()
{
return;
uint32_t now = millis();
if (now - lastSubmitMs < 150) return; // soft repeat guard
lastSubmitMs = now;
lineBuf[lineLen] = 0;
if (cursorShowing) renderCursor(false);
newline();
if (lineLen > 0) execute(lineBuf);
else sndClick();
lineLen = 0;
printPrompt();
cursorDirty = true;
}
static void addChar(char c)
{
if (lineLen >= LINE_BUF) { sndBell(); return; }
if (cursorShowing) renderCursor(false);
grid[curRow][curCol] = c;
renderCell(curCol, curRow, 0, fxOn && bandRows[curRow]);
lineBuf[lineLen++] = c;
curCol++;
if (curCol >= COLS) newline();
blinkT0 = millis(); // restart blink phase
cursorShowing = true;
renderCursor(true);
}
static void backspace()
{
if (lineLen == 0) { sndBell(); return; }
curCol--;
lineLen--;
lineBuf[lineLen] = 0;
grid[curRow][curCol] = ' ';
renderCell(curCol, curRow, 0, fxOn && bandRows[curRow]);
blinkT0 = millis();
cursorShowing = true;
renderCursor(true);
}
static void handleKey(char k)
{
if (k == '\n' || k == '\r') { submitLine(); return; }
if (k == 0x08 || k == 0x7F) { backspace(); return; }
if (k >= 32 && k <= 126) addChar(k);
}
static void pollKeyboard()
{
// drain everything the keyboard controller has buffered (a fast typist
// must never lose keys to the frame pacing)
Wire.requestFrom((uint8_t)0x55, (uint8_t)1);
while (Wire.available() > 0) {
char k = (char)Wire.read();
if (k != 0) handleKey(k);
}
}
static void pollClick()
{
if (tbClicks == 0) return;
// submit only after the ball is released again: contact bounce fires
// several FALLING edges while the pin is low, and this way they can't
// double-submit — nor can a quick second press be swallowed by a timer
if (digitalRead(BOARD_BOOT_PIN) != HIGH) return;
tbClicks = 0;
submitLine();
}
static void pollTouch()
{
if (!touchAvail) return;
static bool wasDown = false;
if (!touch.isPressed()) { wasDown = false; return; }
if (wasDown) return;
int16_t x[1], y[1];
if (touch.getPoint(x, y, 1) > 0) {
wasDown = true;
submitLine();
}
}
// ---------------------------------------------------------------------------
// CRT effects
// ---------------------------------------------------------------------------
static bool rowInBand(int row)
{
int yTop = Y0 + row * CELL_H;
int yBot = yTop + CELL_H;
return bandY < yBot && (bandY + BAND_H) > yTop;
}
static void fxUpdate()
{
// rolling band: repaint rows it enters / leaves (halo boost)
bandY += BAND_SPEED;
if (bandY > SCR_H) {
bandY = -BAND_H;
memset(bandRows, 0, sizeof(bandRows));
}
for (int r = 0; r < ROWS; r++) {
bool in = rowInBand(r);
if (in != bandRows[r]) {
bandRows[r] = in;
renderRow(r, 0);
}
}
// interference line: a 1 px bright trace riding the band
int ly = (int)(bandY + BAND_H / 2);
if (ly < 0 || ly >= SCR_H) return;
if (ly != lineLastY) {
int orow = (lineLastY - Y0) / CELL_H;
if (orow >= 0 && orow < ROWS) renderRow(orow, 0);
lineLastY = ly;
}
tft.drawRect(0, 0, SCR_W, SCR_H, C_GLOW);
tft.fillRect(0, ly, SCR_W, 1, C_GLOW);
if (cursorShowing && curRow == (ly - Y0) / CELL_H) renderCursor(true);
// occasional single-row jitter (sync wobble)
uint32_t now = millis();
if (jitterRow >= 0) {
if ((int32_t)(now - jitterUntil) >= 0) {
renderRow(jitterRow, 0);
jitterRow = -1;
}
} else if (now >= nextJitterMs) {
nextJitterMs = now + 1800 + random(0, 2600);
int r = random(0, ROWS);
if (r != curRow) {
jitterRow = r;
jitterOff = (random(0, 2) == 0) ? 1 : -1;
jitterUntil = now + 90;
renderRow(r, jitterOff);
}
}
}
static void setFx(bool on)
{
if (fxOn == on) return;
fxOn = on;
if (on) {
bandY = -BAND_H;
memset(bandRows, 0, sizeof(bandRows));
lineLastY = -1;
nextJitterMs = millis() + 2000;
} else {
jitterRow = -1;
}
renderAll();
}
// Origin of the scanner (bottom center of the screen)
#define RADAR_ORIGIN_X 160
#define RADAR_ORIGIN_Y 260
#define MAX_RADIUS 210
// Colors (16-bit RGB565)
#define C_BLACK 0x0000
#define C_GLOW 0x07E0 // Bright CRT Green
#define C_DIM_GRN 0x0320 // Dark Phosphor Green
#define C_WHITE 0xFFFF
struct RadarBlip {
float angle; // Radians (-PI/4 to +PI/4: 0 is straight ahead)
float distance; // Normalized 0.0 (near) to 1.0 (far boundary)
uint8_t alpha; // Decay intensity (0 - 255)
bool active;
};
#define RADAR_CX 160
#define RADAR_CY 120
#define MAX_BLIPS 5
RadarBlip blips[MAX_BLIPS];
// Sweep line parameters (sweeps back and forth across the front wedge)
float sweepAngle = -M_PI / 4.0; // Start at -45 degrees (left)
int sweepDirection = 1; // 1 = sweeping right, -1 = sweeping left
const float SWEEP_SPEED = 0.04; // Adjust sweep rate
void initRadar() {
for (int i = 0; i < MAX_BLIPS; i++) {
blips[i].active = false;
}
}
// Index of the blip currently driven by the microphone. Reused every frame so
// a continuous sound slides around instead of filling all MAX_BLIPS slots.
static int liveBlip = -1;
static int allocBlip() {
for (int i = 0; i < MAX_BLIPS; i++) {
if (!blips[i].active) return i;
}
return -1;
}
// lrBalance: -1.0 (far left) to +1.0 (far right)
// loudness: 0.0 (quiet/far) to 1.0 (loud/near)
static void placeBlip(int i, float lrBalance, float loudness) {
if (i < 0) return;
blips[i].active = true;
// Map L/R balance to forward-facing wedge (-45 deg to +45 deg)
blips[i].angle = constrain(lrBalance, -1.0f, 1.0f) * (M_PI / 4.0f);
// Loudness maps to distance: loudest is near origin, quiet is near edge
blips[i].distance = constrain(1.0f - loudness, 0.15f, 0.95f);
blips[i].alpha = 255;
}
// One-shot blip (manual trigger / future events)
void triggerBlip(float lrBalance, float loudness) {
placeBlip(allocBlip(), lrBalance, loudness);
sndClick();
}
// Continuous update from the dual-microphone detector.
static void updateSoundBlip(float lrBalance, float loudness) {
if (liveBlip < 0 || !blips[liveBlip].active) {
liveBlip = allocBlip();
}
placeBlip(liveBlip, lrBalance, loudness);
}
static void drawArc(float r, uint32_t color) {
for (float a = -M_PI / 4.0; a <= M_PI / 4.0; a += 0.05) {
int ax = RADAR_ORIGIN_X + (int)(r * sin(a));
int ay = RADAR_ORIGIN_Y - (int)(r * cos(a));
tft.drawPixel(ax, ay, color);
}
}
void radarUpdate() {
// 1. Draw Forward-Facing Sector Grid (Distance Arcs)
// 50m, 100m, 150m, 200m equivalent scale lines
for (int r = 50; r <= MAX_RADIUS; r += 50) {
// Draw arc segments within the -45 to +45 degree wedge
drawArc(r, C_DIM_GRN);
}
// 2. Draw Vector Boundary Lines (-45°, 0° Center, +45°)
int xLeft = RADAR_ORIGIN_X + (int)(MAX_RADIUS * sin(-M_PI / 4.0));
int yLeft = RADAR_ORIGIN_Y - (int)(MAX_RADIUS * cos(-M_PI / 4.0));
int xRight = RADAR_ORIGIN_X + (int)(MAX_RADIUS * sin(M_PI / 4.0));
int yRight = RADAR_ORIGIN_Y - (int)(MAX_RADIUS * cos(M_PI / 4.0));
tft.drawLine(RADAR_ORIGIN_X, RADAR_ORIGIN_Y, xLeft, yLeft, C_DIM_GRN);
tft.drawLine(RADAR_ORIGIN_X, RADAR_ORIGIN_Y, xRight, yRight, C_DIM_GRN);
tft.drawLine(RADAR_ORIGIN_X, RADAR_ORIGIN_Y, RADAR_ORIGIN_X, RADAR_ORIGIN_Y - MAX_RADIUS, C_DIM_GRN); // Center line
// 3. Update & Draw Oscillating Forward Sweep Line
/*sweepAngle += SWEEP_SPEED * sweepDirection;
if (sweepAngle >= M_PI / 4.0) {
sweepAngle = M_PI / 4.0;
sweepDirection = -1; // Reverse sweep direction
} else if (sweepAngle <= -M_PI / 4.0) {
sweepAngle = -M_PI / 4.0;
sweepDirection = 1;
}
int sx = RADAR_ORIGIN_X + (int)(MAX_RADIUS * sin(sweepAngle));
int sy = RADAR_ORIGIN_Y - (int)(MAX_RADIUS * cos(sweepAngle));
tft.drawLine(RADAR_ORIGIN_X, RADAR_ORIGIN_Y, sx, sy, C_GLOW);*/
sweepAngle += 10.0f;//SWEEP_SPEED;
if (sweepAngle > MAX_RADIUS * 2) {
sweepAngle = 0;
sndBlip();
} else if (sweepAngle < MAX_RADIUS) {
drawArc(sweepAngle, C_GLOW);
}
// Feed the live microphone measurement into the blip layer. Balance moves
// it left/right; loudness pulls it toward the centre (closer target).
SoundReading snd = soundDetector.read();
if (snd.active) {
updateSoundBlip(snd.balance, snd.loudness);
}
// 4. Render Active Target Blips with Phosphor Decay
for (int i = 0; i < MAX_BLIPS; i++) {
if (blips[i].active) {
float r = blips[i].distance * MAX_RADIUS;
// 0 angle = straight up (forward), negative = left, positive = right
int bx = RADAR_ORIGIN_X + (int)(r * sin(blips[i].angle));
int by = RADAR_ORIGIN_Y - (int)(r * cos(blips[i].angle));
// Render blip core and outer glow
if (blips[i].alpha > 128) {
tft.fillCircle(bx, by, 4, C_WHITE);
tft.drawCircle(bx, by, 7, C_GLOW);
} else {
tft.drawCircle(bx, by, 4, C_GLOW);
}
// Decay blip intensity over time
if (blips[i].alpha > 15) {
blips[i].alpha -= 15;
} else {
blips[i].active = false;
}
}
}
}
// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------
static void cmdHelp()
{
writeStr("COMMANDS:\n");
writeStr("help clear echo ver uptime\n");
writeStr("mem fortune dir banner beep\n");
writeStr("phos <green|amber|white>\n");
writeStr("crt <on|off> vol <n|+|->\n");
}
static void cmdVer()
{
writeStr("CRTTERM v1.0 - T-Deck CRT\n");
writeStr("PHOSPHOR: ");
writeStr(PHOS_NAME[phosMode]);
writeStr("\n");
}
static void cmdUptime()
{
uint32_t s = millis() / 1000;
uint32_t d = s / 86400; s %= 86400;
uint32_t h = s / 3600; s %= 3600;
uint32_t m = s / 60; s %= 60;
char buf[48];
snprintf(buf, sizeof(buf), "UP %luD %02lu:%02lu:%02lu\n",
(unsigned long)d, (unsigned long)h, (unsigned long)m, (unsigned long)s);
writeStr(buf);
}
static void cmdMem()
{
#ifdef EMULATOR
writeStr("HEAP 247K/8192K (EMU)\n");
#else
char buf[64];
snprintf(buf, sizeof(buf), "HEAP %uK/%uK\n",
(unsigned)(ESP.getFreeHeap() / 1024),
(unsigned)(ESP.getHeapSize() / 1024));
writeStr(buf);
#endif
}
static const char *FORTUNES[] = {
"IT IS NOW SAFE TO TURN OFF",
"YOUR COMPUTER.",
"",
"REAL TERMINALS FLICKER.",
"IT BUILDS CHARACTER.",
"",
"THERE IS NO PLACE LIKE",
"0x0000:0000.",
"",
"PC LOAD LETTER",
"",
"THE CAKE IS A LIE.",
"",
"LOADING REALITY... 42%",
"",
"GREEN PHOSPHOR NEVER DIES,",
"IT JUST FADES TO DIM.",
"",
"IT'S NOT A BUG, IT'S AN",
"UNDOCUMENTED FEATURE.",
"",
"INSERT COIN TO CONTINUE.",
};
static void cmdFortune()
{
int n = sizeof(FORTUNES) / sizeof(FORTUNES[0]);
// fortunes come in 3-line blocks (text, text, blank)
int block = random(0, n / 3);
for (int i = 0; i < 3; i++) {
writeStr(FORTUNES[block * 3 + i]);
writeStr("\n");
}
}
static void cmdDir()
{
writeStr("TAPE DIRECTORY:\n");
writeStr("BASIC.BIN 12K\n");
writeStr("ADVENTURE.BIN 34K\n");
writeStr("STARFIELD.BIN 8K\n");
writeStr("MONITOR.ROM 64K\n");
writeStr("4 FILE(S), 8192K FREE\n");
}
static void cmdBanner()
{
bigPrintCentered("T-DECK", Y0 + 7 * CELL_H);
bigPrintCentered("CRT", Y0 + 12 * CELL_H);
SndEvent e = { SND_SWEEP, 220, 880, 260, 12000 };
sound.play(e);
delay(1500);
clearScreen();
writeStr("*** T-DECK CRT TERMINAL ***\n");
}
static void cmdBeep(const char *args)
{
int n = atoi(args);
if (n < 1) n = 1;
if (n > 5) n = 5;
for (int i = 0; i < n; i++) {
SndEvent e = { SND_TONE, 880, 0, 110, 14000 };
sound.play(e);
delay(140);
}
}
// case-insensitive compare (avoids strcasecmp portability differences)
static bool eqIgnoreCase(const char *a, const char *b)
{
while (*a && *b) {
if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return false;
a++; b++;
}
return *a == 0 && *b == 0;
}
static void cmdPhos(const char *args)
{
if (eqIgnoreCase(args, "green") || eqIgnoreCase(args, "p1")) phosMode = PH_GREEN;
else if (eqIgnoreCase(args, "amber") || eqIgnoreCase(args, "p3")) phosMode = PH_AMBER;
else if (eqIgnoreCase(args, "white") || eqIgnoreCase(args, "bw")) phosMode = PH_WHITE;
else {
writeStr("USAGE: PHOS <GREEN|AMBER|WHITE>\n");
return;
}
buildPalette();
tft.fillScreen(C_BG);
memset(bandRows, 0, sizeof(bandRows));
lineLastY = -1;
renderAll();
writeStr("PHOSPHOR: ");
writeStr(PHOS_NAME[phosMode]);
writeStr("\n");
prefs.begin("crt", false);
prefs.putUInt("phos", phosMode);
}
static void cmdCrt(const char *args)
{
if (eqIgnoreCase(args, "off")) {
setFx(false);
writeStr("CRT FX: OFF\n");
} else if (eqIgnoreCase(args, "on")) {
setFx(true);
writeStr("CRT FX: ON\n");
} else {
writeStr("USAGE: CRT <ON|OFF>\n");
}
prefs.begin("crt", false);
prefs.putUInt("fx", fxOn ? 1 : 0);
}
static void cmdVol(const char *args)
{
if (*args == 0) {
writeStr("USAGE: VOL <0-8|+|->\n");
return;
}
if (strcmp(args, "+") == 0) {
sound.volumeUp();
} else if (strcmp(args, "-") == 0) {
sound.volumeDown();
} else {
int v = atoi(args);
if (v < 0) v = 0;
if (v > SoundEngine::VOL_MAX) v = SoundEngine::VOL_MAX;
sound.setVolume((uint8_t)v);
}
char buf[24];
snprintf(buf, sizeof(buf), "VOL %u/%u\n", sound.volume(), SoundEngine::VOL_MAX);
writeStr(buf);
prefs.begin("crt", false);
prefs.putUInt("vol", sound.volume());
}
static void execute(char *line)
{
// trim leading spaces
while (*line == ' ') line++;
if (*line == 0) return;
// split command / args
char *args = line;
while (*args && *args != ' ') args++;
if (*args) {
*args = 0;
args++;
while (*args == ' ') args++;
}
// lowercase the command
for (char *p = line; *p; p++) *p = (char)tolower((unsigned char)*p);
if (strcmp(line, "help") == 0) cmdHelp();
else if (strcmp(line, "clear") == 0 || strcmp(line, "cls") == 0) clearScreen();
else if (strcmp(line, "echo") == 0) { writeStr(args); writeStr("\n"); }
else if (strcmp(line, "ver") == 0) cmdVer();
else if (strcmp(line, "uptime") == 0) cmdUptime();
else if (strcmp(line, "mem") == 0) cmdMem();
else if (strcmp(line, "fortune") == 0) cmdFortune();
else if (strcmp(line, "dir") == 0 || strcmp(line, "ls") == 0) cmdDir();
else if (strcmp(line, "banner") == 0) cmdBanner();
else if (strcmp(line, "beep") == 0) cmdBeep(args);
else if (strcmp(line, "phos") == 0) cmdPhos(args);
else if (strcmp(line, "crt") == 0) cmdCrt(args);
else if (strcmp(line, "vol") == 0) cmdVol(args);
else {
writeStr("?SYNTAX ERROR\n");
writeStr("TRY 'HELP'\n");
sndError();
}
}
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
static void setBrightness(uint8_t level)
{
// ESP32-S3 LEDC-attached backlight: same bit-banged stepping as UnitTest
static uint8_t blLevel = 255;
static const uint8_t steps = 16;
if (level == 0) {
digitalWrite(BOARD_BL_PIN, 1);
blLevel = steps;
delayMicroseconds(30);
}
int from = steps - blLevel;
int to = steps - level;
int num = (steps + to - from) % steps;
for (int i = 0; i < num; i++) {
digitalWrite(BOARD_BL_PIN, 0);
digitalWrite(BOARD_BL_PIN, 1);
}
blLevel = level;
}
static void hardwareInit()
{
Serial.begin(115200);
Serial.println("T-Deck CRT Terminal");
pinMode(BOARD_POWERON, OUTPUT);
digitalWrite(BOARD_POWERON, HIGH);
// CS lines high during init
pinMode(BOARD_SDCARD_CS, OUTPUT);
pinMode(RADIO_CS_PIN, OUTPUT);
pinMode(BOARD_TFT_CS, OUTPUT);
digitalWrite(BOARD_SDCARD_CS, HIGH);
digitalWrite(RADIO_CS_PIN, HIGH);
digitalWrite(BOARD_TFT_CS, HIGH);
pinMode(BOARD_SPI_MISO, INPUT_PULLUP);
SPI.begin(BOARD_SPI_SCK, BOARD_SPI_MISO, BOARD_SPI_MOSI);
tft.begin();
tft.setRotation(1);
tft.fillScreen(TFT_BLACK);
pinMode(BOARD_BL_PIN, OUTPUT);
for (int i = 0; i <= 16; ++i) {
setBrightness(i);
delay(20);
}
// I2C: touch + keyboard share the bus
Wire.begin(BOARD_I2C_SDA, BOARD_I2C_SCL);
touch.setPins(-1, BOARD_TOUCH_INT);
touchAvail = touch.begin(Wire);
if (touchAvail) {
touch.setMaxCoordinates(tft.width(), tft.height());
touch.setSwapXY(true);
touch.setMirrorXY(false, true);
Serial.println("GT911 touch ready");
} else {
Serial.println("No GT911 touch found");
}
// NOTE: GPIO0 (trackball centre / BOOT) is unavailable while the ES7210
// microphones are running, and leaving its interrupt enabled causes
// spurious captures. Keep it detached; the microphone radar does not need
// the trackball.
// attachTrackball();
}
static void bootSequence()
{
clearScreen();
SndEvent e = { SND_SWEEP, 300, 900, 320, 10000 };
sound.play(e);
bigPrintCentered("T-DECK", Y0 + 6 * CELL_H);
bigPrintCentered("MOTION SENSOR", Y0 + 11 * CELL_H);
delay(1600);
clearScreen();
}
// ---------------------------------------------------------------------------
// setup / loop
// ---------------------------------------------------------------------------
void setup()
{
hardwareInit();
buildPalette();
if (!sound.begin()) {
Serial.println("Sound engine init failed (no I2S?)");
}
// restore persisted settings
prefs.begin("motion-sensor", false);
phosMode = prefs.getUInt("phos", PH_GREEN);
if (phosMode >= PH_COUNT) phosMode = PH_GREEN;
buildPalette();
//sound.setVolume((uint8_t)prefs.getUInt("vol", 5));
sound.setVolume((uint8_t)5);
bootSequence();
initRadar();
if (!soundDetector.begin(16000)) {
Serial.println("Sound detector init failed (ES7210 mics)");
} else {
Serial.println("Sound detector ready (dual mics, slots auto-detected)");
}
}
void loop()
{
// swallow all input right after power-up/reset
uint32_t now = millis();
if (now < INPUT_GRACE_MS) {
tbClicks = 0;
delay(1);
return;
}
static uint32_t nextFrame = 0;
if ((int32_t)(now - nextFrame) < 0) {
delay(1);
return;
}
nextFrame = now + FRAME_MS;
// clicks / taps first: they submit the line as it stood when the user
// pressed Enter — chars typed afterwards belong on the next line
pollClick();
pollTouch();
pollKeyboard();
clearScreen();
//fxUpdate();
radarUpdate();
}