CRT Terminal app

This commit is contained in:
Dejvino
2026-11-11 22:03:40 +01:00
parent 1ef22cc832
commit 951c56168c
10 changed files with 1447 additions and 28 deletions
+2
View File
@@ -9,3 +9,5 @@ emulator/missilecommand-emu
emulator/seq*.bmp
emulator/mc-prefs.cfg
emulator/*-emu
emulator/*-prefs.cfg
+14
View File
@@ -23,6 +23,8 @@ examples
├─Touchpad # Read touch coordinates
├─GPSShield # GPS Shield example
├─lvgl_example # lvgl example
├─MissileCommand # arcade game
├─CrtTerminal # CRT monitor terminal emulator
└─UnitTest # Factory hardware unit testing
````
@@ -96,3 +98,15 @@ See [utilities.h](./examples//UnitTest//utilities.h)
- See [shell](./shell/)
![](./shell/T_Deck_2.png)
## SDL emulator (run sketches on your PC)
`emulator/` hosts a small SDL2 harness that runs selected example sketches
without hardware (framebuffer, keyboard, trackball and touch are emulated):
````
cd emulator
make run # MissileCommand (default)
make run APP=CrtTerminal # CRT terminal
make smoke APP=CrtTerminal # headless: N frames + BMP dump, --type "keys\n"
````
+31 -11
View File
@@ -1,32 +1,52 @@
# Local SDL2 emulator for MissileCommand (run the game on your PC)
# SDL2 emulator for T-Deck example sketches (run the app on your PC)
#
# make build ./missilecommand-emu
# make run build + launch the window
# make smoke headless test: 240 frames, dump the last frame to a BMP
# make build the MissileCommand emulator (default)
# make APP=CrtTerminal build the CRT terminal emulator
# make run [APP=...] build + launch the window
# make smoke [APP=...] headless test: N frames, dump the last frame
# make clean [APP=...] remove the binary + smoke frame
#
# The sketch is included by src/main.cpp as a single translation unit:
# -DAPP_INO='"<App>.ino"'. Apps with a sound_engine.cpp get it linked
# automatically (wildcard).
APP ?= MissileCommand
APP_DIR := ../examples/$(APP)
ifeq ($(APP),MissileCommand)
APP_TITLE := Missile Command
DEFS += -DEMU_APP_MISSILECOMMAND
endif
ifeq ($(APP),CrtTerminal)
APP_TITLE := CRT Terminal
endif
APP_TITLE ?= $(APP)
CXX ?= g++
CXXFLAGS ?= -std=gnu++17 -O2 -Wall -Wextra
SDLFLAGS := -I/usr/include/SDL2
INC := -Isrc/shim -I../examples/MissileCommand
INC := -Isrc/shim -I$(APP_DIR)
LIBS := -lSDL2 -lSDL2_ttf
GAME_DIR := ../examples/MissileCommand
DEFS += -DAPP_INO='"$(APP).ino"' -DAPP_NAME='"$(APP_TITLE)"'
SHIMS := $(wildcard src/shim/*.h) $(wildcard src/shim/driver/*.h)
EMU := missilecommand-emu
SOUND_SRC := $(wildcard $(APP_DIR)/sound_engine.cpp)
EMU := $(APP)-emu
.PHONY: all run smoke clean
all: $(EMU)
$(EMU): src/main.cpp $(GAME_DIR)/sound_engine.cpp $(GAME_DIR)/MissileCommand.ino $(SHIMS)
$(CXX) $(CXXFLAGS) $(SDLFLAGS) $(INC) \
src/main.cpp $(GAME_DIR)/sound_engine.cpp -o $@ $(LIBS)
$(EMU): src/main.cpp $(SOUND_SRC) $(APP_DIR)/$(APP).ino $(SHIMS)
$(CXX) $(CXXFLAGS) $(SDLFLAGS) $(INC) $(DEFS) \
src/main.cpp $(SOUND_SRC) -o $@ $(LIBS)
run: $(EMU)
./$(EMU)
# Headless smoke test: dummy video/audio, run N frames, save the last frame.
# Feed some keys: 'a' starts the game, arrows steer, etc. via --script.
# Feed keys via --type "text" (queued a few chars per frame).
smoke: $(EMU)
./$(EMU) --frames 240 --dump smoke_frame.bmp
+60 -11
View File
@@ -1,15 +1,15 @@
/**
* SDL2 host for the MissileCommand sketch — run the game on your PC.
* SDL2 host for T-Deck example sketches — run the app on your PC.
* The sketch is selected with -DAPP_INO (see the Makefile, APP=...).
*
* Input mapping:
* Arrow keys trackball roll (hold to keep rolling)
* Mouse wheel trackball roll (each notch = a ball pulse burst)
* Enter / right-click trackball press (fire)
* Left-click screen tap (aim + fire)
* A S D fire from left / center / right battery
* Space fire from nearest battery
* U / V volume up / down
* M mute toggle
* Enter / right-click trackball press
* Left-click screen tap
* Letters/digits keyboard device @ I2C 0x55
* Backspace/Delete keyboard device (0x08 / 0x7F)
* --type "text" queue keys programmatically (for smoke tests)
*/
#include <SDL.h>
#include <SDL_ttf.h>
@@ -19,8 +19,15 @@
#include "emu_gfx.h"
#include "emu_input.h"
// pull in the whole game as a single translation unit
#include "MissileCommand.ino"
#ifndef APP_INO
#define APP_INO "MissileCommand.ino"
#endif
#ifndef APP_NAME
#define APP_NAME "T-Deck app"
#endif
// pull in the whole sketch as a single translation unit
#include APP_INO
// ---------------------------------------------------------------------------
// Global instances declared extern in the shims
@@ -63,14 +70,22 @@ int main(int argc, char **argv)
{
long maxFrames = -1;
const char *dumpPath = nullptr;
bool autoplay = false;
const char *typeStr = nullptr;
int typeFromFrame = 30;
int dumpEvery = 0;
#ifdef EMU_APP_MISSILECOMMAND
bool autoplay = false;
#endif
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--frames") && i + 1 < argc) maxFrames = atol(argv[++i]);
else if (!strcmp(argv[i], "--dump") && i + 1 < argc) dumpPath = argv[++i];
else if (!strcmp(argv[i], "--dump-interval") && i + 1 < argc) dumpEvery = atoi(argv[++i]);
else if (!strcmp(argv[i], "--type") && i + 1 < argc) typeStr = argv[++i];
else if (!strcmp(argv[i], "--type-at") && i + 1 < argc) typeFromFrame = atoi(argv[++i]);
#ifdef EMU_APP_MISSILECOMMAND
else if (!strcmp(argv[i], "--wave") && i + 1 < argc) emuStartWaveRequest = atoi(argv[++i]);
else if (!strcmp(argv[i], "--autoplay")) autoplay = true;
#endif
}
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
@@ -79,7 +94,7 @@ int main(int argc, char **argv)
}
TTF_Init();
SDL_Window *win = SDL_CreateWindow("Missile Command — T-Deck emulator",
SDL_Window *win = SDL_CreateWindow("T-Deck emulator — " APP_NAME,
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_RESIZABLE);
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
@@ -122,6 +137,12 @@ int main(int argc, char **argv)
case SDLK_SPACE:
emu::keyboard.push_back(' ');
break;
case SDLK_BACKSPACE:
emu::keyboard.push_back(0x08);
break;
case SDLK_DELETE:
emu::keyboard.push_back(0x7F);
break;
case SDLK_ESCAPE:
running = false;
break;
@@ -203,7 +224,34 @@ int main(int argc, char **argv)
}
}
// --type: queue the string on the keyboard device like a human typing
// (one char per --type-at start, ~40 ms apart in millis time, so the
// sketch processes each key before the next arrives).
// '\n' emulates Enter: press the trackball pin for one iteration.
static const char *typeNext = nullptr;
static int typePressPin = -1;
static unsigned long lastTypeMs = 0;
if (typeStr && frame >= (uint32_t)typeFromFrame) {
if (typePressPin >= 0) {
emu::pinLevels[typePressPin] = 1; // release the Enter press
typePressPin = -1;
}
if (!typeNext) typeNext = typeStr;
const char *typeEnd = typeStr + strlen(typeStr);
if (typeNext < typeEnd && millis() - lastTypeMs >= 40) {
lastTypeMs = millis();
if (*typeNext == '\n' || *typeNext == '\r') {
typeNext++; // consume the Enter char
emu::pinLevels[BOARD_BOOT_PIN] = 0;
typePressPin = BOARD_BOOT_PIN;
} else {
emu::keyboard.push_back((uint8_t)*typeNext++);
}
}
}
// Headless test mode: start the game, wander the crosshair, keep firing.
#ifdef EMU_APP_MISSILECOMMAND
if (autoplay) {
static bool started = false;
if (!started && frame >= 5) {
@@ -215,6 +263,7 @@ int main(int argc, char **argv)
if (frame % 4 == 0) emu::pinLevels[dirPin[dir]] ^= 1;
if (frame % 75 == 0) emu::keyboard.push_back('s');
}
#endif
// fire any emulated interrupts triggered by the pin changes above
emu::dispatchIsrs();
+2 -2
View File
@@ -13,8 +13,8 @@ class Preferences {
public:
bool begin(const char *ns, bool readOnly = false)
{
(void)ns;
(void)readOnly;
snprintf(path_, sizeof(path_), "%s-prefs.cfg", ns);
map_.clear();
if (FILE *f = fopen(path_, "r")) {
char key[64];
@@ -53,5 +53,5 @@ private:
}
std::unordered_map<std::string, uint32_t> map_;
const char *path_ = "mc-prefs.cfg";
char path_[64] = "mc-prefs.cfg";
};
+971
View File
@@ -0,0 +1,971 @@
/**
* @file CrtTerminal.ino
* @brief CRT monitor terminal emulator 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"
// ---------------------------------------------------------------------------
// Hardware
// ---------------------------------------------------------------------------
TFT_eSPI tft;
TouchDrvGT911 touch;
SoundEngine sound;
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 = 33; // ~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)
{
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()
{
SndEvent e = { SND_TONE, 540, 0, 10, 8000 };
sound.play(e);
SndEvent f = { SND_TONE, 540, 0, 10, 100 };
sound.play(f);
delay(15);
}
static void sndClick()
{
SndEvent e = { SND_TONE, 660, 0, 22, 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()
{
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()
{
if (!fxOn) return;
// 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();
}
// ---------------------------------------------------------------------------
// 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");
}
attachTrackball();
}
static void bootSequence()
{
clearScreen();
SndEvent e = { SND_SWEEP, 300, 900, 320, 10000 };
sound.play(e);
bigPrintCentered("T-DECK", Y0 + 6 * CELL_H);
bigPrintCentered("CRT TERMINAL", Y0 + 11 * CELL_H);
delay(1600);
clearScreen();
static const char *lines[] = {
"*** T-DECK CRT TERMINAL ***",
"ROM BIOS 1.0 - 320X240",
"RAM TEST ......... 8192K OK",
"PHOSPHOR ......... WARMING UP",
"KEYBOARD @55 ..... ONLINE",
touchAvail ? "TOUCH GT911 ...... ONLINE" : "TOUCH GT911 ...... ABSENT",
"SOUND ............ READY",
"",
"TYPE 'HELP' FOR COMMANDS.",
"",
};
for (const char *l : lines) {
SndEvent t = { SND_TONE, 1500, 0, 10, 2500 };
sound.play(t);
writeStr(l);
writeStr("\n");
delay(110);
}
printPrompt();
}
// ---------------------------------------------------------------------------
// setup / loop
// ---------------------------------------------------------------------------
void setup()
{
hardwareInit();
buildPalette();
if (!sound.begin()) {
Serial.println("Sound engine init failed (no I2S?)");
}
// restore persisted settings
prefs.begin("crt", false);
phosMode = prefs.getUInt("phos", PH_GREEN);
if (phosMode >= PH_COUNT) phosMode = PH_GREEN;
buildPalette();
fxOn = prefs.getUInt("fx", 1) != 0;
sound.setVolume((uint8_t)prefs.getUInt("vol", 5));
bootSequence();
}
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();
fxUpdate();
// cursor blink
bool on = (now - blinkT0) % CURSOR_PERIOD < CURSOR_ON_MS;
if (on != cursorShowing || cursorDirty) {
cursorShowing = on;
cursorDirty = false;
renderCursor(on);
}
}
+222
View File
@@ -0,0 +1,222 @@
/**
* @file sound_engine.cpp
* @brief I2S speaker rendering task (8 kHz, 16-bit, mono).
*
* Based on the wiring used by examples/SimpleTone:
* BCK = GPIO7, WS = GPIO5, DOUT = GPIO6.
*
* Sounds are rendered strictly in queue order; layering is achieved by
* queueing several events back to back (e.g. a rumble sweep followed by a
* noise tail reads as one big explosion).
*/
#include "sound_engine.h"
#include "utilities.h"
#include <driver/i2s.h>
#define SND_SAMPLE_RATE 8000
#define SND_I2S_PORT I2S_NUM_0
#define SND_CHUNK 128 // samples per i2s_write call
#define SND_FADE_MS 2 // fade in/out to avoid clicks
bool SoundEngine::begin()
{
i2s_config_t cfg = {};
cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
cfg.sample_rate = SND_SAMPLE_RATE;
cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
cfg.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S;
cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
cfg.dma_buf_count = 8;
cfg.dma_buf_len = 64;
if (i2s_driver_install(SND_I2S_PORT, &cfg, 0, NULL) != ESP_OK) {
return false;
}
i2s_pin_config_t pins = {};
pins.bck_io_num = BOARD_I2S_BCK;
pins.ws_io_num = BOARD_I2S_WS;
pins.data_out_num = BOARD_I2S_DOUT;
pins.data_in_num = I2S_PIN_NO_CHANGE;
i2s_set_pin(SND_I2S_PORT, &pins);
q_ = xQueueCreate(12, sizeof(SndEvent));
if (q_ == nullptr) {
return false;
}
// Render on core 0; the game loop runs on core 1.
return xTaskCreatePinnedToCore(trampoline, "sound", 4096, this, 5, nullptr, 0) == pdTRUE;
}
void SoundEngine::play(const SndEvent &e)
{
if (q_) {
xQueueSend(q_, &e, 0); // drop instead of blocking the game
}
}
void SoundEngine::trampoline(void *arg)
{
static_cast<SoundEngine *>(arg)->task();
}
void SoundEngine::task()
{
for (;;) {
SndEvent e;
xQueueReceive(q_, &e, portMAX_DELAY);
switch (e.type) {
case SND_TONE: renderTone(e.freq, e.dur, e.amp); break;
case SND_SWEEP: renderSweep(e.freq, e.freq2, e.dur, e.amp); break;
case SND_NOISE: renderNoise(e.dur, e.amp); break;
}
// After the LAST queued event the I2S TX DMA ring would keep
// replaying its remaining ~64 ms of buffer forever — heard as the
// sound's tail (rocket sweep, melody tone) repeating endlessly.
// Zero the ring once the queue is empty (not between queued events,
// which would punch silence-gaps into back-to-back melodies).
if (uxQueueMessagesWaiting(q_) == 0) {
i2s_zero_dma_buffer(SND_I2S_PORT);
}
}
}
void SoundEngine::volumeUp()
{
if (vol_ < VOL_MAX) vol_++;
}
void SoundEngine::volumeDown()
{
if (vol_ > 0) vol_--;
}
void SoundEngine::toggleMute()
{
if (vol_ > 0) {
lastVol_ = vol_;
vol_ = 0;
} else {
vol_ = lastVol_ > 0 ? lastVol_ : VOL_MAX / 2;
}
}
// Restore a saved volume level (from NVS at boot); 0 keeps the device muted
// while lastVol_ stays at its default so unmute still works.
void SoundEngine::setVolume(uint8_t v)
{
if (v > VOL_MAX) v = VOL_MAX;
vol_ = v;
if (vol_ > 0) lastVol_ = vol_;
}
// scaled peak amplitude for the current volume level
static inline uint32_t scaledAmp(uint16_t amp, uint8_t vol)
{
return ((uint32_t)amp * vol) / SoundEngine::VOL_MAX;
}
// fade envelope over the first/last SND_FADE_MS of the whole event
static inline uint32_t envelope(uint32_t pos, uint32_t total, uint32_t fade, uint32_t amp)
{
if (fade * 2 > total) fade = total / 2;
uint32_t s = amp;
if (pos < fade) s = s * pos / fade;
uint32_t tail = total - pos;
if (tail < fade) s = s * tail / fade;
return s;
}
void SoundEngine::renderTone(uint16_t freq, uint16_t durMs, uint16_t amp)
{
static int16_t buf[SND_CHUNK];
uint32_t a = scaledAmp(amp, vol_);
if (a == 0) return;
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
if (total == 0) return;
uint32_t half = (freq > 0) ? (SND_SAMPLE_RATE / 2) / freq : 1;
if (half == 0) half = 1;
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
if (fade < 2) fade = 2;
uint32_t phase = 0;
for (uint32_t i = 0; i < total; ) {
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
for (uint32_t k = 0; k < n; k++) {
int32_t s = ((phase / half) & 1) ? (int32_t)a : -(int32_t)a;
buf[k] = (int16_t)(s * (int32_t)envelope(i + k, total, fade, 256) / 256);
phase++;
}
size_t bw;
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
i += n;
}
}
// Square wave gliding from freq0 to freq1 (Hz) over the duration.
// Phase is carried in a float cycle counter (0..1) so frequency changes
// never click.
void SoundEngine::renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp)
{
static int16_t buf[SND_CHUNK];
uint32_t a = scaledAmp(amp, vol_);
if (a == 0) return;
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
if (total == 0) return;
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
if (fade < 2) fade = 2;
float phase = 0.0f;
for (uint32_t i = 0; i < total; ) {
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
for (uint32_t k = 0; k < n; k++) {
uint32_t pos = i + k;
float f = (float)freq0 +
((float)(int16_t)(freq1 - freq0) * (float)pos) / (float)total;
if (f < 20.0f) f = 20.0f;
phase += f / (float)SND_SAMPLE_RATE;
if (phase >= 1.0f) phase -= 1.0f;
int32_t s = (phase < 0.5f) ? (int32_t)a : -(int32_t)a;
buf[k] = (int16_t)(s * (int32_t)envelope(pos, total, fade, 256) / 256);
}
size_t bw;
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
i += n;
}
}
void SoundEngine::renderNoise(uint16_t durMs, uint16_t amp)
{
static int16_t buf[SND_CHUNK];
uint32_t a = scaledAmp(amp, vol_);
if (a == 0) return;
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
if (total == 0) return;
uint32_t seed = esp_random() | 1;
for (uint32_t i = 0; i < total; ) {
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
for (uint32_t k = 0; k < n; k++) {
// xorshift32 for cheap white noise
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
int32_t signedS = (int32_t)(seed & 0xFFFF) - 32768;
// linear decay over the burst
int32_t s = (int32_t)(((int64_t)signedS * a * (int64_t)(total - i - k)) /
((int64_t)32768 * (int64_t)total));
buf[k] = (int16_t)s;
}
size_t bw;
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
i += n;
}
}
+55
View File
@@ -0,0 +1,55 @@
/**
* @file sound_engine.h
* @brief Tiny non-blocking I2S sound engine for the T-Deck speaker.
*
* A FreeRTOS task owns the I2S peripheral (speaker, I2S_NUM_0) and renders
* queued sound events one after another. The game only ever pushes events,
* so it never blocks. Event types:
*
* SND_TONE fixed square-wave beep
* SND_SWEEP square wave gliding from freq down/up to freq2 (sirens, booms)
* SND_NOISE white-noise burst with linear decay (explosions)
*/
#pragma once
#include <Arduino.h>
enum SndType : uint8_t {
SND_TONE = 0, // fixed square wave
SND_SWEEP, // square wave gliding freq -> freq2
SND_NOISE, // white noise burst
};
struct SndEvent {
SndType type;
uint16_t freq; // Hz (tone, or sweep start)
uint16_t freq2; // Hz (sweep end; ignored for tone/noise)
uint16_t dur; // duration in ms
uint16_t amp; // peak amplitude 0..32767
};
class SoundEngine {
public:
static const uint8_t VOL_MAX = 8;
bool begin();
void play(const SndEvent &e);
// Master volume, applied to every rendered sound
void volumeUp();
void volumeDown();
void toggleMute();
void setVolume(uint8_t v); // restore a saved level (0 = muted)
uint8_t volume() const { return vol_; }
private:
static void trampoline(void *arg);
void task();
void renderTone(uint16_t freq, uint16_t durMs, uint16_t amp);
void renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp);
void renderNoise(uint16_t durMs, uint16_t amp);
QueueHandle_t q_ = nullptr;
uint8_t vol_ = 5; // default: moderate
uint8_t lastVol_ = 5; // remembered for mute toggle
};
+85
View File
@@ -0,0 +1,85 @@
/**
* @file utilities.h
* @author Lewis He (lewishe@outlook.com)
* @license MIT
* @copyright Copyright (c) 2023 Shenzhen Xin Yuan Electronic Technology Co., Ltd
* @date 2023-04-11
*
*/
#pragma once
//! The board peripheral power control pin needs to be set to HIGH when using the peripheral
#define BOARD_POWERON 10
#define BOARD_I2S_WS 5
#define BOARD_I2S_BCK 7
#define BOARD_I2S_DOUT 6
#define BOARD_I2C_SDA 18
#define BOARD_I2C_SCL 8
#define BOARD_BAT_ADC 4
#define BOARD_TOUCH_INT 16
#define BOARD_KEYBOARD_INT 46
#define BOARD_SDCARD_CS 39
#define BOARD_TFT_CS 12
#define RADIO_CS_PIN 9
#define BOARD_TFT_DC 11
#define BOARD_TFT_BACKLIGHT 42
#define BOARD_SPI_MOSI 41
#define BOARD_SPI_MISO 38
#define BOARD_SPI_SCK 40
#define BOARD_TBOX_G02 2
#define BOARD_TBOX_G01 3
#define BOARD_TBOX_G04 1
#define BOARD_TBOX_G03 15
#define BOARD_ES7210_MCLK 48
#define BOARD_ES7210_LRCK 21
#define BOARD_ES7210_SCK 47
#define BOARD_ES7210_DIN 14
#define RADIO_BUSY_PIN 13
#define RADIO_RST_PIN 17
#define RADIO_DIO1_PIN 45
#define BOARD_BOOT_PIN 0
#define BOARD_BL_PIN 42
#define BOARD_GPS_TX_PIN 43
#define BOARD_GPS_RX_PIN 44
#ifndef RADIO_FREQ
#define RADIO_FREQ 868.0
#endif
#ifndef RADIO_BANDWIDTH
#define RADIO_BANDWIDTH 125.0
#endif
#ifndef RADIO_SF
#define RADIO_SF 10
#endif
#ifndef RADIO_CR
#define RADIO_CR 6
#endif
#ifndef RADIO_TX_POWER
#define RADIO_TX_POWER 22
#endif
#define DEFAULT_OPA 100
+2 -1
View File
@@ -32,7 +32,8 @@ default_envs = T-Deck
; src_dir = examples/I2SPlay
; src_dir = examples/LvglArduinoVNC_VGA
; src_dir = examples/SimpleTone
src_dir = examples/MissileCommand
src_dir = examples/CrtTerminal
; src_dir = examples/MissileCommand
;! Don't make changes