commit ddff48d05b1e8f07eb0d4892d7aaf943af14ca26 Author: DESKTOP-PUHFO60\dsx2016 Date: Tue Oct 27 21:16:13 2026 +0800 Add INMP441 WAV recorder for CYD 2.8/3.5. Record 16 kHz mono PCM to microSD /rec, with level meter and DAC2 playback. Co-authored-by: Cursor diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39ce04d --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch +*.pyc +__pycache__/ +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..8ff01a6 --- /dev/null +++ b/README.md @@ -0,0 +1,88 @@ +# CYD INMP441 录音 + +ESP32 Cheap Yellow Display + INMP441(I2S)→ microSD **WAV 录音**,支持 DAC 回放。 + +默认 **2.8" ESP32-2432S028R**;可选 **3.5" ESP32-3248S035C**(`cyd_35r`)。 +引脚约定见同目录 [CYD_PROJECT_GUIDE.md](../CYD_PROJECT_GUIDE.md);麦克风接线参考 [inmp441test](../inmp441test)。 + +## 硬件 + +| 项目 | 2.8" · 2432S028R | 3.5" C · 3248S035C | +|------|------------------|---------------------| +| 屏驱 | ILI9341 | ST7796 | +| 触控 | XPT2046 SoftSPI | GT911 Wire1(SDA33/SCL32/INT21/RST25) | +| 背光 TFT_BL | **GPIO21** | **GPIO27** | +| INMP441 WS | **GPIO22**(CN1/P3) | **GPIO22** | +| INMP441 SCK | **GPIO27**(CN1) | **GPIO21**(CN1;勿占 27=BL) | +| INMP441 SD | **GPIO35**(P3,仅输入) | **GPIO35** | +| microSD | CS5 / SCK18 / MISO19 / MOSI23 | 同左 | +| 喇叭 | **GPIO26**(DAC2,P4) | 同左 | + +接线: + +| INMP441 | CYD | +|---------|-----| +| VDD | 3.3V(CN1) | +| GND | GND | +| L/R | GND(左声道,勿悬空) | +| WS | IO22 | +| SCK | IO27(2.8)/ IO21(3.5) | +| SD | IO35(P3) | + +> 不要接 5V;不要占用背光脚。I2S 需要三根信号线(22 + 27/21 + 35)。 +> **3.5C**:`SCK=GPIO21` 与 GT911 INT 同脚;固件先完成触控选址,再把 21 交给 I2S,触控仅轮询。 + +## 功能 + +- 触控 **REC / STOP**:录制 16 kHz / 16-bit 单声道 PCM WAV 到 `/rec/Rxxxx.WAV` +- 最长约 **120 秒**(自动停) +- 实时电平条(近似 dB,与 inmp441test 同一换算) +- **PLAY / STOP**:用板载喇叭(GPIO26)回放最近一条录音 +- 短按顶部标题栏切换背光 4 档 +- 需插入 **FAT32 microSD** + +## 构建与烧录 + +依赖 [PlatformIO](https://platformio.org/)。 + +```bash +pio run -e cyd_28r -t upload # 2.8" +pio run -e cyd_35r -t upload # 3.5C +pio device monitor -b 115200 +``` + +### 预编译固件 + +| 板型 | 目录 | +|------|------| +| 2.8" | [`firmware/cyd_28r/`](firmware/cyd_28r/) | +| 3.5" | [`firmware/cyd_35r/`](firmware/cyd_35r/) | + +```powershell +cd firmware\cyd_28r # 或 cyd_35r +.\flash.ps1 +``` + +重新打包: + +```powershell +.\firmware\export_from_build.ps1 +.\firmware\export_from_build.ps1 -Env cyd_35r +``` + +## 项目结构 + +``` +platformio.ini +include/pins.h lv_conf.h touch.h sdcard.h recorder.h player.h +src/main.cpp touch.cpp sdcard.cpp recorder.cpp player.cpp +scripts/exclude_lvgl_asm.py +firmware/ +README.md +``` + +## 变更记录 + +| 日期 | 说明 | +|------|------| +| 2026-10-27 | 初版:INMP441 → microSD WAV 录音 + DAC 回放;双板 `cyd_28r` / `cyd_35r` | diff --git a/firmware/README.md b/firmware/README.md new file mode 100644 index 0000000..d15ab35 --- /dev/null +++ b/firmware/README.md @@ -0,0 +1,26 @@ +# 预编译固件(可随时刷写) + +| 目录 | 板子 | INMP441 | 背光 | +|------|------|---------|------| +| [`cyd_28r/`](cyd_28r/) | ESP32-2432S028R(ILI9341) | WS=22 / SCK=27 / SD=35 | GPIO21 | +| [`cyd_35r/`](cyd_35r/) | ESP32-3248S035C(ST7796 + GT911) | WS=22 / SCK=21 / SD=35 | GPIO27 | + +版本信息见各目录 `VERSION.txt`。引脚约定见 [`../CYD_PROJECT_GUIDE.md`](../../CYD_PROJECT_GUIDE.md)。 + +录音写入 microSD `/rec/Rxxxx.WAV`;回放经 GPIO26 DAC2。 + +## 直接刷写 + +```powershell +cd firmware\cyd_28r # 或 cyd_35r +.\flash.ps1 +# .\flash.ps1 -Port COM3 +``` + +## 从源码重新打包 + +```powershell +.\firmware\export_from_build.ps1 +.\firmware\export_from_build.ps1 -Env cyd_35r +.\firmware\export_from_build.ps1 -SkipBuild +``` diff --git a/firmware/cyd_28r/VERSION.txt b/firmware/cyd_28r/VERSION.txt new file mode 100644 index 0000000..43434c1 --- /dev/null +++ b/firmware/cyd_28r/VERSION.txt @@ -0,0 +1,18 @@ +name: CYD inmp441recondtest (cyd_28r) +git: unknown +date: 2026-10-27 +board: ESP32-2432S028R (ILI9341) +inmp441: WS=GPIO22 SCK=GPIO27 SD=GPIO35 +tft_bl: GPIO21 +audio: record WAV /rec + play DAC2 GPIO26 +flash_size: 4MB +offsets: + 0x1000 bootloader.bin + 0x8000 partitions.bin + 0xe000 boot_app0.bin + 0x10000 firmware.bin +sha256: + bootloader.bin 3D234A7471F67B013686DABD4DEE7C1FA915C9928463616A94BC9297ACF1ABF8 + boot_app0.bin F94C5D786A7A8FAB06AC5D10E33BF37711A6697636DC037559EA19CC410A17F0 + firmware.bin 8BDD28C452BF7406295B7E76FDC387917FE6BF223BE0FD18B6988BABD4EFF12E + partitions.bin 0A8B5720E7B77FF11F1462458C3A509DEE79224E5279898F26D6A2E3AE0517B7 diff --git a/firmware/cyd_28r/boot_app0.bin b/firmware/cyd_28r/boot_app0.bin new file mode 100644 index 0000000..13562ca Binary files /dev/null and b/firmware/cyd_28r/boot_app0.bin differ diff --git a/firmware/cyd_28r/bootloader.bin b/firmware/cyd_28r/bootloader.bin new file mode 100644 index 0000000..d592359 Binary files /dev/null and b/firmware/cyd_28r/bootloader.bin differ diff --git a/firmware/cyd_28r/firmware.bin b/firmware/cyd_28r/firmware.bin new file mode 100644 index 0000000..8ace0f0 Binary files /dev/null and b/firmware/cyd_28r/firmware.bin differ diff --git a/firmware/cyd_28r/flash.bat b/firmware/cyd_28r/flash.bat new file mode 100644 index 0000000..bf983b3 --- /dev/null +++ b/firmware/cyd_28r/flash.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0flash.ps1" %* +exit /b %ERRORLEVEL% diff --git a/firmware/cyd_28r/flash.ps1 b/firmware/cyd_28r/flash.ps1 new file mode 100644 index 0000000..dc3b4ed --- /dev/null +++ b/firmware/cyd_28r/flash.ps1 @@ -0,0 +1,84 @@ +# Flash archived CYD INMP441 WAV recorder firmware (no rebuild needed) +# Usage: +# .\flash.ps1 +# .\flash.ps1 -Port COM5 +# .\flash.ps1 -Port COM5 -Baud 460800 + +param( + [string]$Port = "", + [int]$Baud = 921600 +) + +$ErrorActionPreference = "Stop" +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $here + +function Find-Esptool { + $pio = Get-Command pio -ErrorAction SilentlyContinue + if ($pio) { + $pkg = Join-Path $env:USERPROFILE ".platformio\packages\tool-esptoolpy\esptool.py" + if (Test-Path $pkg) { return @{ Kind = "py"; Path = $pkg } } + } + $py = Get-Command python -ErrorAction SilentlyContinue + if ($py) { + try { + & python -c "import esptool" 2>$null + if ($LASTEXITCODE -eq 0) { return @{ Kind = "mod"; Path = "esptool" } } + } catch {} + } + $esp = Get-Command esptool.py -ErrorAction SilentlyContinue + if ($esp) { return @{ Kind = "py"; Path = $esp.Source } } + return $null +} + +if (-not $Port) { + $ports = @() + try { + Add-Type -AssemblyName System.IO.Ports -ErrorAction SilentlyContinue | Out-Null + $ports = [System.IO.Ports.SerialPort]::GetPortNames() | Sort-Object + } catch {} + if (-not $ports -or $ports.Count -eq 0) { + $ports = Get-CimInstance Win32_SerialPort -ErrorAction SilentlyContinue | + Select-Object -ExpandProperty DeviceID | Sort-Object + } + if (-not $ports -or $ports.Count -eq 0) { + Write-Error "No serial ports found. Plug in the CYD USB cable, then retry with -Port COMx" + } + if ($ports.Count -eq 1) { + $Port = $ports[0] + } else { + Write-Host "Available ports: $($ports -join ', ')" + $Port = $ports[-1] + Write-Host "Using last port: $Port (override with -Port)" + } +} + +$tool = Find-Esptool +if (-not $tool) { + Write-Error "esptool not found. Install PlatformIO (`pio`) or: pip install esptool" +} + +$argsCommon = @( + "--chip", "esp32", + "--port", $Port, + "--baud", "$Baud", + "--before", "default_reset", + "--after", "hard_reset", + "write_flash", "-z", + "--flash_mode", "dio", + "--flash_freq", "40m", + "--flash_size", "4MB", + "0x1000", "bootloader.bin", + "0x8000", "partitions.bin", + "0xe000", "boot_app0.bin", + "0x10000", "firmware.bin" +) + +Write-Host "Flashing $here -> $Port @ $Baud" +if ($tool.Kind -eq "mod") { + & python -m esptool @argsCommon +} else { + & python $tool.Path @argsCommon +} +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +Write-Host "Done. Open serial monitor at 115200 if needed." diff --git a/firmware/cyd_28r/meta.json b/firmware/cyd_28r/meta.json new file mode 100644 index 0000000..0c90483 --- /dev/null +++ b/firmware/cyd_28r/meta.json @@ -0,0 +1,7 @@ +{ + "boardId": "esp32-2432s028", + "name": "CYD INMP441 WAV recorder", + "summary": "Record INMP441 audio to microSD as WAV; play via DAC2", + "description": "INMP441 on WS=GPIO22 / SCK=GPIO27 / SD=GPIO35. Saves 16 kHz mono PCM to /rec/Rxxxx.WAV. Playback on GPIO26. Requires FAT32 microSD.", + "tags": ["record", "inmp441", "i2s", "wav", "sd", "mic"] +} diff --git a/firmware/cyd_28r/partitions.bin b/firmware/cyd_28r/partitions.bin new file mode 100644 index 0000000..21800fa Binary files /dev/null and b/firmware/cyd_28r/partitions.bin differ diff --git a/firmware/cyd_35r/VERSION.txt b/firmware/cyd_35r/VERSION.txt new file mode 100644 index 0000000..8f4e311 --- /dev/null +++ b/firmware/cyd_35r/VERSION.txt @@ -0,0 +1,18 @@ +name: CYD inmp441recondtest (cyd_35r) +git: unknown +date: 2026-10-27 +board: ESP32-3248S035 (ST7796 + GT911) +inmp441: WS=GPIO22 SCK=GPIO21 SD=GPIO35 +tft_bl: GPIO27 +audio: record WAV /rec + play DAC2 GPIO26 +flash_size: 4MB +offsets: + 0x1000 bootloader.bin + 0x8000 partitions.bin + 0xe000 boot_app0.bin + 0x10000 firmware.bin +sha256: + bootloader.bin 3D234A7471F67B013686DABD4DEE7C1FA915C9928463616A94BC9297ACF1ABF8 + boot_app0.bin F94C5D786A7A8FAB06AC5D10E33BF37711A6697636DC037559EA19CC410A17F0 + firmware.bin 0AFB4B303FDC198E8216D0BEEEC1BC8C9776E7BAE21FC798C4861C2FB2F6B0AC + partitions.bin 0A8B5720E7B77FF11F1462458C3A509DEE79224E5279898F26D6A2E3AE0517B7 diff --git a/firmware/cyd_35r/boot_app0.bin b/firmware/cyd_35r/boot_app0.bin new file mode 100644 index 0000000..13562ca Binary files /dev/null and b/firmware/cyd_35r/boot_app0.bin differ diff --git a/firmware/cyd_35r/bootloader.bin b/firmware/cyd_35r/bootloader.bin new file mode 100644 index 0000000..d592359 Binary files /dev/null and b/firmware/cyd_35r/bootloader.bin differ diff --git a/firmware/cyd_35r/firmware.bin b/firmware/cyd_35r/firmware.bin new file mode 100644 index 0000000..393a971 Binary files /dev/null and b/firmware/cyd_35r/firmware.bin differ diff --git a/firmware/cyd_35r/flash.bat b/firmware/cyd_35r/flash.bat new file mode 100644 index 0000000..bf983b3 --- /dev/null +++ b/firmware/cyd_35r/flash.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0flash.ps1" %* +exit /b %ERRORLEVEL% diff --git a/firmware/cyd_35r/flash.ps1 b/firmware/cyd_35r/flash.ps1 new file mode 100644 index 0000000..af94a7c --- /dev/null +++ b/firmware/cyd_35r/flash.ps1 @@ -0,0 +1,84 @@ +# Flash archived CYD INMP441 WAV recorder firmware for 3.5C (no rebuild needed) +# Usage: +# .\flash.ps1 +# .\flash.ps1 -Port COM5 +# .\flash.ps1 -Port COM5 -Baud 460800 + +param( + [string]$Port = "", + [int]$Baud = 921600 +) + +$ErrorActionPreference = "Stop" +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $here + +function Find-Esptool { + $pio = Get-Command pio -ErrorAction SilentlyContinue + if ($pio) { + $pkg = Join-Path $env:USERPROFILE ".platformio\packages\tool-esptoolpy\esptool.py" + if (Test-Path $pkg) { return @{ Kind = "py"; Path = $pkg } } + } + $py = Get-Command python -ErrorAction SilentlyContinue + if ($py) { + try { + & python -c "import esptool" 2>$null + if ($LASTEXITCODE -eq 0) { return @{ Kind = "mod"; Path = "esptool" } } + } catch {} + } + $esp = Get-Command esptool.py -ErrorAction SilentlyContinue + if ($esp) { return @{ Kind = "py"; Path = $esp.Source } } + return $null +} + +if (-not $Port) { + $ports = @() + try { + Add-Type -AssemblyName System.IO.Ports -ErrorAction SilentlyContinue | Out-Null + $ports = [System.IO.Ports.SerialPort]::GetPortNames() | Sort-Object + } catch {} + if (-not $ports -or $ports.Count -eq 0) { + $ports = Get-CimInstance Win32_SerialPort -ErrorAction SilentlyContinue | + Select-Object -ExpandProperty DeviceID | Sort-Object + } + if (-not $ports -or $ports.Count -eq 0) { + Write-Error "No serial ports found. Plug in the CYD USB cable, then retry with -Port COMx" + } + if ($ports.Count -eq 1) { + $Port = $ports[0] + } else { + Write-Host "Available ports: $($ports -join ', ')" + $Port = $ports[-1] + Write-Host "Using last port: $Port (override with -Port)" + } +} + +$tool = Find-Esptool +if (-not $tool) { + Write-Error "esptool not found. Install PlatformIO (`pio`) or: pip install esptool" +} + +$argsCommon = @( + "--chip", "esp32", + "--port", $Port, + "--baud", "$Baud", + "--before", "default_reset", + "--after", "hard_reset", + "write_flash", "-z", + "--flash_mode", "dio", + "--flash_freq", "40m", + "--flash_size", "4MB", + "0x1000", "bootloader.bin", + "0x8000", "partitions.bin", + "0xe000", "boot_app0.bin", + "0x10000", "firmware.bin" +) + +Write-Host "Flashing $here -> $Port @ $Baud" +if ($tool.Kind -eq "mod") { + & python -m esptool @argsCommon +} else { + & python $tool.Path @argsCommon +} +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +Write-Host "Done. Open serial monitor at 115200 if needed." diff --git a/firmware/cyd_35r/meta.json b/firmware/cyd_35r/meta.json new file mode 100644 index 0000000..cd6cb7c --- /dev/null +++ b/firmware/cyd_35r/meta.json @@ -0,0 +1,7 @@ +{ + "boardId": "esp32-3248s035", + "name": "CYD INMP441 WAV recorder (3.5C)", + "summary": "Record INMP441 audio to microSD as WAV; play via DAC2", + "description": "INMP441 on WS=GPIO22 / SCK=GPIO21 / SD=GPIO35. TFT_BL=27. Saves 16 kHz mono PCM to /rec/Rxxxx.WAV. Playback on GPIO26. Requires FAT32 microSD.", + "tags": ["record", "inmp441", "i2s", "wav", "sd", "mic", "3.5"] +} diff --git a/firmware/cyd_35r/partitions.bin b/firmware/cyd_35r/partitions.bin new file mode 100644 index 0000000..21800fa Binary files /dev/null and b/firmware/cyd_35r/partitions.bin differ diff --git a/firmware/export_from_build.ps1 b/firmware/export_from_build.ps1 new file mode 100644 index 0000000..cb9e33f --- /dev/null +++ b/firmware/export_from_build.ps1 @@ -0,0 +1,74 @@ +# Export firmware bins from PlatformIO build. +# Default: 2.8" (cyd_28r -> firmware/cyd_28r) +# 3.5": .\firmware\export_from_build.ps1 -Env cyd_35r + +param( + [switch]$SkipBuild, + [ValidateSet("cyd_28r", "cyd_35r")] + [string]$Env = "cyd_28r" +) + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +Set-Location $root + +$env:Path = "C:\Users\dsx2016\AppData\Local\Programs\Python\Python312\Scripts;" + $env:Path + +if (-not $SkipBuild) { + pio run -e $Env + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +} + +$src = Join-Path $root (".pio\build\" + $Env) +if ($Env -eq "cyd_35r") { + $dstName = "cyd_35r" + $boardLine = "board: ESP32-3248S035 (ST7796 + GT911)" + $micLine = "inmp441: WS=GPIO22 SCK=GPIO21 SD=GPIO35" + $blLine = "tft_bl: GPIO27" +} else { + $dstName = "cyd_28r" + $boardLine = "board: ESP32-2432S028R (ILI9341)" + $micLine = "inmp441: WS=GPIO22 SCK=GPIO27 SD=GPIO35" + $blLine = "tft_bl: GPIO21" +} +$dst = Join-Path $root ("firmware\" + $dstName) +New-Item -ItemType Directory -Force -Path $dst | Out-Null + +foreach ($f in @("bootloader.bin", "partitions.bin", "firmware.bin")) { + $p = Join-Path $src $f + if (-not (Test-Path $p)) { Write-Error "Missing build artifact: $p — build with: pio run -e $Env" } + Copy-Item $p $dst -Force +} + +$bootApp = Join-Path $env:USERPROFILE ".platformio\packages\framework-arduinoespressif32\tools\partitions\boot_app0.bin" +if (-not (Test-Path $bootApp)) { + Write-Error "boot_app0.bin not found under PlatformIO packages" +} +Copy-Item $bootApp (Join-Path $dst "boot_app0.bin") -Force + +$git = "" +try { $git = (git -C $root rev-parse --short HEAD).Trim() } catch { $git = "unknown" } +$date = Get-Date -Format "yyyy-MM-dd" +$hashes = Get-ChildItem (Join-Path $dst "*.bin") | Get-FileHash -Algorithm SHA256 +$lines = @( + "name: CYD inmp441recondtest ($dstName)", + "git: $git", + "date: $date", + $boardLine, + $micLine, + $blLine, + "audio: record WAV /rec + play DAC2 GPIO26", + "flash_size: 4MB", + "offsets:", + " 0x1000 bootloader.bin", + " 0x8000 partitions.bin", + " 0xe000 boot_app0.bin", + " 0x10000 firmware.bin", + "sha256:" +) +foreach ($h in $hashes) { + $lines += (" {0,-15} {1}" -f (Split-Path $h.Path -Leaf), $h.Hash) +} +$lines | Set-Content -Encoding utf8 (Join-Path $dst "VERSION.txt") + +Write-Host "Exported -> $dst (env=$Env git=$git)" diff --git a/include/lv_conf.h b/include/lv_conf.h new file mode 100644 index 0000000..6c23cfa --- /dev/null +++ b/include/lv_conf.h @@ -0,0 +1,86 @@ +#ifndef LV_CONF_H +#define LV_CONF_H + +#include + +#define LV_COLOR_DEPTH 16 + +#define LV_MEM_SIZE (48 * 1024U) +#define LV_DEF_REFR_PERIOD 16 +#define LV_DPI_DEF 130 + +/* ESP32 无 Helium,关掉以免 .S 汇编被错误预处理 */ +#define LV_USE_DRAW_SW_ASM LV_DRAW_SW_ASM_NONE + +#define LV_USE_OS LV_OS_NONE +#define LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN +#define LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN +#define LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN + +#define LV_USE_LOG 0 +#define LV_USE_ASSERT_NULL 1 +#define LV_USE_ASSERT_MALLOC 1 + +#define LV_FONT_MONTSERRAT_12 1 +#define LV_FONT_MONTSERRAT_14 1 +#define LV_FONT_MONTSERRAT_16 1 +#define LV_FONT_MONTSERRAT_20 1 +#define LV_FONT_MONTSERRAT_24 1 +#define LV_FONT_MONTSERRAT_28 1 +#define LV_FONT_MONTSERRAT_32 1 +#define LV_FONT_MONTSERRAT_40 1 +#define LV_FONT_DEFAULT &lv_font_montserrat_14 + +#define LV_USE_FLOAT 1 +#define LV_USE_MATRIX 0 + +#define LV_USE_LABEL 1 +#define LV_LABEL_TEXT_SELECTION 0 +#define LV_LABEL_LONG_TXT_HINT 1 + +#define LV_USE_ARC 1 +#define LV_USE_BAR 1 +#define LV_USE_BTN 1 +#define LV_USE_BUTTON 1 +#define LV_USE_IMG 1 +#define LV_USE_IMAGE 1 +#define LV_USE_LINE 1 +#define LV_USE_SLIDER 1 +#define LV_USE_SWITCH 1 +#define LV_USE_TEXTAREA 0 +#define LV_USE_CHECKBOX 0 +#define LV_USE_DROPDOWN 0 +#define LV_USE_ROLLER 0 +#define LV_USE_TABLE 0 +#define LV_USE_CALENDAR 0 +#define LV_USE_CHART 1 +#define LV_USE_KEYBOARD 0 +#define LV_USE_LIST 0 +#define LV_USE_MENU 0 +#define LV_USE_MSGBOX 0 +#define LV_USE_SPAN 0 +#define LV_USE_SPINBOX 0 +#define LV_USE_SPINNER 1 +#define LV_USE_TABVIEW 0 +#define LV_USE_TILEVIEW 0 +#define LV_USE_WIN 0 +#define LV_USE_LED 1 +#define LV_USE_SCALE 1 + +#define LV_USE_THEME_DEFAULT 1 +#define LV_THEME_DEFAULT_DARK 1 +#define LV_THEME_DEFAULT_GROW 0 +#define LV_THEME_DEFAULT_TRANSITION_TIME 80 + +#define LV_USE_FLEX 1 +#define LV_USE_GRID 1 + +#define LV_USE_TFT_ESPI 1 + +#define LV_USE_OBSERVER 0 +#define LV_USE_SYSMON 0 +#define LV_USE_PROFILER 0 +#define LV_USE_DEMO_WIDGETS 0 +#define LV_USE_DEMO_BENCHMARK 0 + +#endif /* LV_CONF_H */ diff --git a/include/pins.h b/include/pins.h new file mode 100644 index 0000000..9ed7645 --- /dev/null +++ b/include/pins.h @@ -0,0 +1,37 @@ +#pragma once + +/* CYD + INMP441 record pin truth — see ../CYD_PROJECT_GUIDE.md */ + +#if defined(CYD_BOARD_3248S035) + /* 3.5C ESP32-3248S035C: BL=27; free peripheral pair is 22+21 */ + #define TFT_BL_PIN 27 + #define I2S_WS_PIN 22 + #define I2S_SCK_PIN 21 + #define I2S_SD_PIN 35 + #define SCREEN_WIDTH 480 + #define SCREEN_HEIGHT 320 + #define CYD_GT911_SDA 33 + #define CYD_GT911_SCL 32 + #define CYD_GT911_INT 21 + #define CYD_GT911_RST 25 +#else + /* 2.8 ESP32-2432S028R: BL=21; free peripheral pair is 22+27; SD on P3 IO35 */ + #define TFT_BL_PIN 21 + #define I2S_WS_PIN 22 + #define I2S_SCK_PIN 27 + #define I2S_SD_PIN 35 + #define SCREEN_WIDTH 320 + #define SCREEN_HEIGHT 240 + #define CYD_TOUCH_IRQ 36 + #define CYD_TOUCH_MOSI 32 + #define CYD_TOUCH_MISO 39 + #define CYD_TOUCH_CLK 25 + #define CYD_TOUCH_CS 33 +#endif + +/* On-board microSD (VSPI) + speaker amp (DAC2 only — never GPIO25) */ +#define SD_MISO 19 +#define SD_MOSI 23 +#define SD_SCK 18 +#define SD_CS 5 +#define SPEAKER_PIN 26 diff --git a/include/player.h b/include/player.h new file mode 100644 index 0000000..504665b --- /dev/null +++ b/include/player.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +void player_init(void); +bool player_play(const char *path); +void player_stop(void); +bool player_is_playing(void); +const char *player_status(void); +void player_tick(void); /* stream next chunk to DAC */ diff --git a/include/recorder.h b/include/recorder.h new file mode 100644 index 0000000..9ece44d --- /dev/null +++ b/include/recorder.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#define REC_SAMPLE_RATE 16000 +#define REC_MAX_SECONDS 120 + +bool recorder_mic_init(void); +bool recorder_start(void); +void recorder_stop(void); +bool recorder_is_active(void); +float recorder_level_db(void); /* smoothed approx dBFS+offset, or NAN */ +uint32_t recorder_elapsed_ms(void); +uint32_t recorder_bytes_written(void); +const char *recorder_last_path(void); /* e.g. /rec/R0003.WAV */ +const char *recorder_status(void); +void recorder_tick(void); /* call from loop; drains I2S → SD */ diff --git a/include/sdcard.h b/include/sdcard.h new file mode 100644 index 0000000..e7c6c88 --- /dev/null +++ b/include/sdcard.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +bool sd_init(void); +void sd_deinit(void); +bool sd_ready(void); +uint64_t sd_free_bytes(void); +uint64_t sd_total_bytes(void); diff --git a/include/touch.h b/include/touch.h new file mode 100644 index 0000000..788ec0f --- /dev/null +++ b/include/touch.h @@ -0,0 +1,6 @@ +#pragma once + +#include + +void touch_init(); +void touch_read_cb(lv_indev_t *indev, lv_indev_data_t *data); diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..6cc608d --- /dev/null +++ b/platformio.ini @@ -0,0 +1,90 @@ +; CYD LVGL INMP441 WAV recorder (microSD) +; 2.8: WS=22 SCK=27 SD=35 BL=21; 3.5C: WS=22 SCK=21 SD=35 BL=27 +; see ../CYD_PROJECT_GUIDE.md +[platformio] +default_envs = cyd_28r + +[env] +platform = espressif32@6.9.0 +board = esp32dev +framework = arduino +monitor_speed = 115200 +upload_speed = 921600 +board_build.partitions = min_spiffs.csv +lib_deps = + lvgl/lvgl@9.2.2 + bodmer/TFT_eSPI@2.5.43 + https://github.com/PaulStoffregen/XPT2046_Touchscreen.git +extra_scripts = pre:scripts/exclude_lvgl_asm.py +build_flags = + -D CORE_DEBUG_LEVEL=0 + -D USER_SETUP_LOADED=1 + -D USE_HSPI_PORT=1 + -D ILI9341_2_DRIVER=1 + -D TFT_WIDTH=240 + -D TFT_HEIGHT=320 + -D TFT_MISO=12 + -D TFT_MOSI=13 + -D TFT_SCLK=14 + -D TFT_CS=15 + -D TFT_DC=2 + -D TFT_RST=-1 + -D TFT_BL=21 + -D TFT_BACKLIGHT_ON=HIGH + -D SPI_FREQUENCY=40000000 + -D SPI_READ_FREQUENCY=20000000 + -D LOAD_GLCD=1 + -D LOAD_FONT2=0 + -D LOAD_FONT4=0 + -D LOAD_FONT6=0 + -D LOAD_FONT7=0 + -D LOAD_FONT8=0 + -D LOAD_GFXFF=0 + -D SMOOTH_FONT=0 + -D TOUCH_CS=-1 + -D LV_CONF_INCLUDE_SIMPLE=1 + -I include + +; 标准 CYD 2.8" 电阻触控 (ILI9341) +[env:cyd_28r] +build_flags = + ${env.build_flags} + +; 颜色反相版本(若画面色偏/发白可改用此环境) +[env:cyd_28r_inv] +build_flags = + ${env.build_flags} + -D TFT_INVERSION_ON=1 + +; USB-C 双口 / 7789 变体 +[env:cyd_28_st7789] +build_flags = + ${env.build_flags} + -U ILI9341_2_DRIVER + -D ST7789_DRIVER=1 + -D TFT_RGB_ORDER=TFT_BGR + -D TFT_INVERSION_ON=1 + +; Optional 3.5" CYD ESP32-3248S035C (ST7796 + GT911 capacitive). Default remains cyd_28r. +; Build: pio run -e cyd_35r +; Keep TOUCH_CS=-1 — GPIO33 is GT911 SDA, not resistive touch CS. +; TFT_BL=27 (not 21 — 21 is GT911 INT / I2S SCK). GT911 uses Wire1. +[env:cyd_35r] +lib_deps = + lvgl/lvgl@9.2.2 + bodmer/TFT_eSPI@2.5.43 +build_flags = + ${env.build_flags} + -UILI9341_2_DRIVER + -DST7796_DRIVER=1 + -UTFT_WIDTH + -UTFT_HEIGHT + -DTFT_WIDTH=320 + -DTFT_HEIGHT=480 + -UTFT_BL + -DTFT_BL=27 + -DCYD_BOARD_3248S035=1 + -DSUPPORT_TRANSACTIONS + -DTFT_RGB_ORDER=TFT_BGR + -ULV_MEM_SIZE + -DLV_MEM_SIZE=32768 diff --git a/scripts/exclude_lvgl_asm.py b/scripts/exclude_lvgl_asm.py new file mode 100644 index 0000000..5200ba1 --- /dev/null +++ b/scripts/exclude_lvgl_asm.py @@ -0,0 +1,13 @@ +"""Exclude LVGL Helium/Neon .S files that break ESP32 (xtensa) builds.""" +import shutil +from pathlib import Path + +Import("env") # type: ignore # noqa: F821 + +LIBDEPS = Path(env["PROJECT_LIBDEPS_DIR"]) / env["PIOENV"] / "lvgl" # type: ignore # noqa: F821 + +for sub in ("draw/sw/blend/helium", "draw/sw/blend/neon"): + target = LIBDEPS / "src" / sub + if target.exists(): + shutil.rmtree(target, ignore_errors=True) + print(f"Removed LVGL ASM path: {target}") diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..101a0ad --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,451 @@ +/** + * CYD LVGL INMP441 WAV recorder + * 2.8 (2432S028R): WS=22 SCK=27 SD=35, TFT_BL=21 + * 3.5C (3248S035C): WS=22 SCK=21 SD=35, TFT_BL=27 — see ../CYD_PROJECT_GUIDE.md + * + * Record mono 16 kHz PCM WAV to microSD /rec/Rxxxx.WAV + * Playback via DAC2 GPIO26 only (never GPIO25). + */ + +#include +#include +#include +#include +#include + +#include "pins.h" +#include "touch.h" +#include "sdcard.h" +#include "recorder.h" +#include "player.h" + +#if defined(CYD_BOARD_3248S035) +#define DRAW_BUF_SIZE (SCREEN_WIDTH * SCREEN_HEIGHT / 20 * (LV_COLOR_DEPTH / 8)) +#else +#define DRAW_BUF_SIZE (SCREEN_WIDTH * SCREEN_HEIGHT / 10 * (LV_COLOR_DEPTH / 8)) +#endif + +#if defined(CYD_BOARD_3248S035) +#define UI_M 12 +#define UI_G 10 +#define UI_BTN_H 52 +#define UI_BAR_H 18 +#else +#define UI_M 8 +#define UI_G 6 +#define UI_BTN_H 40 +#define UI_BAR_H 14 +#endif + +static const lv_color_t COL_BG = lv_color_hex(0x0A1018); +static const lv_color_t COL_PANEL = lv_color_hex(0x121C2A); +static const lv_color_t COL_EDGE = lv_color_hex(0x1E2C40); +static const lv_color_t COL_TEXT = lv_color_hex(0xF2F5FA); +static const lv_color_t COL_MUTED = lv_color_hex(0x7E90A8); +static const lv_color_t COL_ACCENT = lv_color_hex(0x3DBF8C); +static const lv_color_t COL_OK = lv_color_hex(0x4CAF7A); +static const lv_color_t COL_WARN = lv_color_hex(0xE6B84D); +static const lv_color_t COL_BAD = lv_color_hex(0xE05A5A); +static const lv_color_t COL_REC = lv_color_hex(0xE04545); +static const lv_color_t COL_ARC_BG = lv_color_hex(0x243247); + +static uint32_t draw_buf[DRAW_BUF_SIZE / 4]; + +static lv_obj_t *lbl_status; +static lv_obj_t *lbl_uptime; +static lv_obj_t *lbl_hint; +static lv_obj_t *lbl_time; +static lv_obj_t *lbl_file; +static lv_obj_t *lbl_level; +static lv_obj_t *lbl_sd; +static lv_obj_t *led_status; +static lv_obj_t *bar_level; +static lv_obj_t *btn_rec; +static lv_obj_t *lbl_rec; +static lv_obj_t *btn_play; +static lv_obj_t *lbl_play; + +static uint8_t bright_level = 2; +static const uint8_t BRIGHT_PWM[4] = {40, 90, 160, 255}; +static uint32_t hint_until_ms = 0; +static uint32_t last_ui_ms = 0; +static bool mic_ok = false; +static bool card_ok = false; + +static void set_backlight(uint8_t level) { + bright_level = level & 0x03; + ledcWrite(0, BRIGHT_PWM[bright_level]); +} + +static void show_hint(const char *text, uint32_t ms) { + lv_label_set_text(lbl_hint, text); + lv_obj_remove_flag(lbl_hint, LV_OBJ_FLAG_HIDDEN); + lv_obj_move_foreground(lbl_hint); + hint_until_ms = millis() + ms; +} + +static const char *basename_of(const char *path) { + if (!path || !path[0]) return "-"; + const char *p = strrchr(path, '/'); + return p ? p + 1 : path; +} + +static void touchscreen_read(lv_indev_t *indev, lv_indev_data_t *data) { + static bool was_pressed = false; + static uint32_t press_ms = 0; + static bool consumed = false; + + touch_read_cb(indev, data); + + if (data->state == LV_INDEV_STATE_PRESSED) { + if (!was_pressed) { + was_pressed = true; + press_ms = millis(); + consumed = false; + } + } else if (was_pressed) { + was_pressed = false; + uint32_t held = millis() - press_ms; + if (!consumed && held < 350) { + /* Brightness only if press was not on a button — LVGL already handled + * buttons; use short idle-area taps via header region. */ + if (data->point.y < 28) { + set_backlight((bright_level + 1) & 0x03); + char buf[24]; + lv_snprintf(buf, sizeof(buf), "brightness %u/3", (unsigned)bright_level); + show_hint(buf, 900); + } + } + } +} + +static lv_obj_t *make_panel(lv_obj_t *parent, int x, int y, int w, int h) { + lv_obj_t *p = lv_obj_create(parent); + lv_obj_set_pos(p, x, y); + lv_obj_set_size(p, w, h); + lv_obj_set_style_bg_color(p, COL_PANEL, 0); + lv_obj_set_style_bg_opa(p, LV_OPA_COVER, 0); + lv_obj_set_style_border_color(p, COL_EDGE, 0); + lv_obj_set_style_border_width(p, 1, 0); + lv_obj_set_style_radius(p, 12, 0); + lv_obj_set_style_pad_all(p, 8, 0); + lv_obj_clear_flag(p, LV_OBJ_FLAG_SCROLLABLE); + return p; +} + +static void style_btn(lv_obj_t *btn, lv_color_t bg) { + lv_obj_set_style_bg_color(btn, bg, 0); + lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0); + lv_obj_set_style_radius(btn, 12, 0); + lv_obj_set_style_border_width(btn, 0, 0); + lv_obj_set_style_shadow_width(btn, 0, 0); + lv_obj_set_ext_click_area(btn, 8); +} + +static void on_rec_clicked(lv_event_t *e) { + (void)e; + if (player_is_playing()) { + player_stop(); + show_hint("stopped play", 800); + } + + if (recorder_is_active()) { + recorder_stop(); + show_hint("saved", 1200); + } else { + if (!card_ok && !sd_init()) { + show_hint("insert microSD", 2000); + return; + } + card_ok = sd_ready(); + if (!recorder_start()) { + show_hint(recorder_status(), 2000); + return; + } + show_hint("recording…", 1000); + } +} + +static void on_play_clicked(lv_event_t *e) { + (void)e; + if (recorder_is_active()) { + show_hint("stop REC first", 1200); + return; + } + if (player_is_playing()) { + player_stop(); + show_hint("stopped", 800); + return; + } + const char *path = recorder_last_path(); + if (!path || !path[0]) { + show_hint("no recording", 1200); + return; + } + if (!player_play(path)) { + show_hint(player_status(), 1500); + return; + } + show_hint("playing", 800); +} + +static void create_ui(void) { + lv_obj_t *scr = lv_screen_active(); + lv_obj_set_style_bg_color(scr, COL_BG, 0); + lv_obj_set_style_bg_opa(scr, LV_OPA_COVER, 0); + lv_obj_clear_flag(scr, LV_OBJ_FLAG_SCROLLABLE); + + lv_obj_t *title = lv_label_create(scr); + lv_label_set_text(title, "RECORD"); + lv_obj_set_style_text_font(title, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_color(title, COL_TEXT, 0); + lv_obj_set_pos(title, UI_M, 4); + + lbl_uptime = lv_label_create(scr); + lv_label_set_text(lbl_uptime, "up 00:00"); + lv_obj_set_style_text_font(lbl_uptime, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_uptime, COL_MUTED, 0); + lv_obj_align_to(lbl_uptime, title, LV_ALIGN_OUT_RIGHT_MID, 8, 1); + + led_status = lv_led_create(scr); + lv_obj_set_size(led_status, 9, 9); + lv_obj_align(led_status, LV_ALIGN_TOP_RIGHT, -UI_M, 6); + lv_led_set_color(led_status, COL_WARN); + lv_led_on(led_status); + + lbl_status = lv_label_create(scr); + lv_label_set_text(lbl_status, "INIT"); + lv_obj_set_style_text_font(lbl_status, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_status, COL_MUTED, 0); + lv_obj_align(lbl_status, LV_ALIGN_TOP_RIGHT, -(UI_M + 16), 4); + + lbl_hint = lv_label_create(scr); + lv_label_set_text(lbl_hint, ""); + lv_obj_set_style_text_font(lbl_hint, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_hint, COL_WARN, 0); + lv_obj_set_style_bg_color(lbl_hint, COL_BG, 0); + lv_obj_set_style_bg_opa(lbl_hint, LV_OPA_COVER, 0); + lv_obj_set_style_pad_hor(lbl_hint, 6, 0); + lv_obj_align(lbl_hint, LV_ALIGN_TOP_MID, 0, 4); + lv_obj_add_flag(lbl_hint, LV_OBJ_FLAG_HIDDEN); + + const int content_w = SCREEN_WIDTH - 2 * UI_M; + const int y0 = 28; + + lv_obj_t *p_main = make_panel(scr, UI_M, y0, content_w, + SCREEN_HEIGHT - y0 - UI_M); + + lbl_time = lv_label_create(p_main); + lv_label_set_text(lbl_time, "00:00"); + lv_obj_set_style_text_font(lbl_time, &lv_font_montserrat_28, 0); + lv_obj_set_style_text_color(lbl_time, COL_TEXT, 0); + lv_obj_align(lbl_time, LV_ALIGN_TOP_LEFT, 0, 0); + + lbl_level = lv_label_create(p_main); + lv_label_set_text(lbl_level, "--.- dB"); + lv_obj_set_style_text_font(lbl_level, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_color(lbl_level, COL_MUTED, 0); + lv_obj_align(lbl_level, LV_ALIGN_TOP_RIGHT, 0, 8); + + bar_level = lv_bar_create(p_main); + lv_obj_set_size(bar_level, content_w - 16, UI_BAR_H); + lv_obj_align(bar_level, LV_ALIGN_TOP_MID, 0, 40); + lv_bar_set_range(bar_level, 30, 110); + lv_bar_set_value(bar_level, 30, LV_ANIM_OFF); + lv_obj_set_style_bg_color(bar_level, COL_ARC_BG, LV_PART_MAIN); + lv_obj_set_style_bg_opa(bar_level, LV_OPA_COVER, LV_PART_MAIN); + lv_obj_set_style_radius(bar_level, 6, LV_PART_MAIN); + lv_obj_set_style_bg_color(bar_level, COL_ACCENT, LV_PART_INDICATOR); + lv_obj_set_style_radius(bar_level, 6, LV_PART_INDICATOR); + + lbl_file = lv_label_create(p_main); + lv_label_set_text(lbl_file, "file: -"); + lv_obj_set_style_text_font(lbl_file, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_file, COL_MUTED, 0); + lv_obj_align(lbl_file, LV_ALIGN_TOP_LEFT, 0, 40 + UI_BAR_H + 10); + + lbl_sd = lv_label_create(p_main); + lv_label_set_text(lbl_sd, "SD: -"); + lv_obj_set_style_text_font(lbl_sd, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_sd, COL_MUTED, 0); + lv_obj_align(lbl_sd, LV_ALIGN_TOP_LEFT, 0, 40 + UI_BAR_H + 28); + + const int btn_y = 40 + UI_BAR_H + 52; + const int btn_w = (content_w - 16 - UI_G) / 2; + + btn_rec = lv_button_create(p_main); + lv_obj_set_size(btn_rec, btn_w, UI_BTN_H); + lv_obj_align(btn_rec, LV_ALIGN_TOP_LEFT, 0, btn_y); + style_btn(btn_rec, COL_REC); + lv_obj_add_event_cb(btn_rec, on_rec_clicked, LV_EVENT_CLICKED, nullptr); + lbl_rec = lv_label_create(btn_rec); + lv_label_set_text(lbl_rec, "REC"); + lv_obj_set_style_text_font(lbl_rec, &lv_font_montserrat_16, 0); + lv_obj_set_style_text_color(lbl_rec, COL_TEXT, 0); + lv_obj_center(lbl_rec); + + btn_play = lv_button_create(p_main); + lv_obj_set_size(btn_play, btn_w, UI_BTN_H); + lv_obj_align(btn_play, LV_ALIGN_TOP_RIGHT, 0, btn_y); + style_btn(btn_play, COL_ACCENT); + lv_obj_add_event_cb(btn_play, on_play_clicked, LV_EVENT_CLICKED, nullptr); + lbl_play = lv_label_create(btn_play); + lv_label_set_text(lbl_play, "PLAY"); + lv_obj_set_style_text_font(lbl_play, &lv_font_montserrat_16, 0); + lv_obj_set_style_text_color(lbl_play, COL_TEXT, 0); + lv_obj_center(lbl_play); + + lv_obj_t *hint2 = lv_label_create(p_main); + lv_label_set_text(hint2, "tap header: brightness | max 120s"); + lv_obj_set_style_text_font(hint2, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(hint2, COL_MUTED, 0); + lv_obj_align(hint2, LV_ALIGN_BOTTOM_MID, 0, 0); +} + +static void refresh_ui(void) { + char buf[48]; + uint32_t up = millis() / 1000; + lv_snprintf(buf, sizeof(buf), "up %02lu:%02lu bl%u", + (unsigned long)(up / 60), (unsigned long)(up % 60), + (unsigned)bright_level); + lv_label_set_text(lbl_uptime, buf); + + if (hint_until_ms && (int32_t)(millis() - hint_until_ms) >= 0) { + hint_until_ms = 0; + lv_obj_add_flag(lbl_hint, LV_OBJ_FLAG_HIDDEN); + } + + const bool rec = recorder_is_active(); + const bool play = player_is_playing(); + + if (rec) { + uint32_t ms = recorder_elapsed_ms(); + lv_snprintf(buf, sizeof(buf), "%02lu:%02lu", + (unsigned long)(ms / 60000), + (unsigned long)((ms / 1000) % 60)); + lv_label_set_text(lbl_time, buf); + lv_obj_set_style_text_color(lbl_time, COL_REC, 0); + lv_label_set_text(lbl_rec, "STOP"); + lv_obj_set_style_bg_color(btn_rec, COL_WARN, 0); + lv_label_set_text(lbl_status, "REC"); + lv_led_set_color(led_status, COL_REC); + } else if (play) { + lv_label_set_text(lbl_time, "PLAY"); + lv_obj_set_style_text_color(lbl_time, COL_ACCENT, 0); + lv_label_set_text(lbl_rec, "REC"); + lv_obj_set_style_bg_color(btn_rec, COL_REC, 0); + lv_label_set_text(lbl_play, "STOP"); + lv_obj_set_style_bg_color(btn_play, COL_WARN, 0); + lv_label_set_text(lbl_status, "PLAY"); + lv_led_set_color(led_status, COL_ACCENT); + } else { + lv_label_set_text(lbl_time, "00:00"); + lv_obj_set_style_text_color(lbl_time, COL_TEXT, 0); + lv_label_set_text(lbl_rec, "REC"); + lv_obj_set_style_bg_color(btn_rec, COL_REC, 0); + lv_label_set_text(lbl_play, "PLAY"); + lv_obj_set_style_bg_color(btn_play, COL_ACCENT, 0); + if (!mic_ok) { + lv_label_set_text(lbl_status, "NO MIC"); + lv_led_set_color(led_status, COL_BAD); + } else if (!card_ok) { + lv_label_set_text(lbl_status, "NO SD"); + lv_led_set_color(led_status, COL_WARN); + } else { + lv_label_set_text(lbl_status, "READY"); + lv_led_set_color(led_status, COL_OK); + } + } + + float db = recorder_level_db(); + if (!isnan(db)) { + lv_snprintf(buf, sizeof(buf), "%.0f dB", db); + lv_label_set_text(lbl_level, buf); + int v = (int)lroundf(constrain(db, 30.0f, 110.0f)); + lv_bar_set_value(bar_level, v, LV_ANIM_OFF); + lv_color_t c = (db < 70) ? COL_ACCENT : ((db < 90) ? COL_WARN : COL_BAD); + lv_obj_set_style_bg_color(bar_level, c, LV_PART_INDICATOR); + lv_obj_set_style_text_color(lbl_level, c, 0); + } else { + lv_label_set_text(lbl_level, "-- dB"); + } + + lv_snprintf(buf, sizeof(buf), "file: %s", basename_of(recorder_last_path())); + lv_label_set_text(lbl_file, buf); + + if (card_ok) { + uint64_t free_mb = sd_free_bytes() / (1024ULL * 1024ULL); + uint64_t tot_mb = sd_total_bytes() / (1024ULL * 1024ULL); + lv_snprintf(buf, sizeof(buf), "SD: %llu/%llu MB free 16kHz WAV", + (unsigned long long)free_mb, (unsigned long long)tot_mb); + lv_label_set_text(lbl_sd, buf); + lv_obj_set_style_text_color(lbl_sd, COL_MUTED, 0); + } else { + lv_label_set_text(lbl_sd, "SD: not mounted — insert card"); + lv_obj_set_style_text_color(lbl_sd, COL_BAD, 0); + } +} + +void setup() { + Serial.begin(115200); + delay(200); + + ledcSetup(0, 5000, 8); + ledcAttachPin(TFT_BL_PIN, 0); + set_backlight(2); + + Serial.println("CYD LVGL INMP441 WAV Recorder"); + Serial.printf("LVGL %d.%d.%d WS=%d SCK=%d SD=%d BL=%d spk=%d\n", + lv_version_major(), lv_version_minor(), lv_version_patch(), + I2S_WS_PIN, I2S_SCK_PIN, I2S_SD_PIN, TFT_BL_PIN, SPEAKER_PIN); + + /* 3.5: GT911 may pulse INT(=21) during addr select; release before I2S SCK. */ + touch_init(); + + card_ok = sd_init(); + mic_ok = recorder_mic_init(); + player_init(); + + Serial.println(mic_ok ? "I2S mic OK" : "I2S mic FAIL — check wiring"); + Serial.println(card_ok ? "SD OK" : "SD FAIL — insert FAT32 microSD"); +#if defined(CYD_BOARD_3248S035) + Serial.println("3.5C: SCK=GPIO21 (shared GT911 INT; touch is poll-only)"); +#endif + + lv_init(); + +#if defined(CYD_BOARD_3248S035) + lv_display_t *disp = lv_tft_espi_create(320, 480, draw_buf, sizeof(draw_buf)); +#else + lv_display_t *disp = lv_tft_espi_create(240, 320, draw_buf, sizeof(draw_buf)); +#endif + lv_display_set_rotation(disp, LV_DISPLAY_ROTATION_270); + + lv_indev_t *indev = lv_indev_create(); + lv_indev_set_type(indev, LV_INDEV_TYPE_POINTER); + lv_indev_set_read_cb(indev, touchscreen_read); + lv_indev_set_display(indev, disp); + + create_ui(); + if (!mic_ok) show_hint("mic init fail", 3000); + else if (!card_ok) show_hint("insert microSD", 3000); + + refresh_ui(); +} + +void loop() { + /* Drain mic (and write WAV while recording) often enough for DMA. */ + recorder_tick(); + recorder_tick(); + player_tick(); + + uint32_t now = millis(); + if (now - last_ui_ms >= 100) { + last_ui_ms = now; + refresh_ui(); + } + + lv_timer_handler(); + lv_tick_inc(5); + delay(5); +} diff --git a/src/player.cpp b/src/player.cpp new file mode 100644 index 0000000..c0025b0 --- /dev/null +++ b/src/player.cpp @@ -0,0 +1,261 @@ +/** + * Stream 16-bit mono/stereo PCM WAV → DAC2 (GPIO26) only. + * Never touches GPIO25 (touch CLK / GT911 RST). + */ + +#include "player.h" +#include "pins.h" +#include "sdcard.h" + +#include +#include +#include +#include +#include +#include + +static File play_file; +static volatile bool playing = false; +static volatile bool stop_req = false; +static const char *status = "idle"; +static TaskHandle_t play_task = nullptr; +static char play_path[48] = ""; +static uint8_t volume = 45; + +static void release_dac(void) { + dac_output_disable(DAC_CHANNEL_1); + dac_output_disable(DAC_CHANNEL_2); + pinMode(SPEAKER_PIN, OUTPUT); + digitalWrite(SPEAKER_PIN, LOW); +} + +static bool read_u16(File &f, uint16_t &v) { + uint8_t b[2]; + if (f.read(b, 2) != 2) return false; + v = (uint16_t)b[0] | ((uint16_t)b[1] << 8); + return true; +} + +static bool read_u32(File &f, uint32_t &v) { + uint8_t b[4]; + if (f.read(b, 4) != 4) return false; + v = (uint32_t)b[0] | ((uint32_t)b[1] << 8) | ((uint32_t)b[2] << 16) | + ((uint32_t)b[3] << 24); + return true; +} + +static uint8_t scale_u8(int16_t s16) { + int c = ((int)s16 * (int)volume) / 100; + c = (c * 40) / 100; + int o = 128 + (c / 256); + if (o < 0) o = 0; + if (o > 255) o = 255; + return (uint8_t)o; +} + +static bool open_and_parse(const char *path, uint16_t *channels, uint16_t *bits, + uint32_t *sample_rate, uint32_t *data_left) { + play_file = SD.open(path, FILE_READ); + if (!play_file) { + status = "open fail"; + return false; + } + + uint32_t tag = 0; + if (!read_u32(play_file, tag) || tag != 0x46464952) { + play_file.close(); + status = "not RIFF"; + return false; + } + uint32_t riff_size = 0; + read_u32(play_file, riff_size); + (void)riff_size; + if (!read_u32(play_file, tag) || tag != 0x45564157) { + play_file.close(); + status = "not WAVE"; + return false; + } + + bool got_fmt = false; + bool got_data = false; + *channels = 1; + *bits = 16; + *sample_rate = 16000; + *data_left = 0; + + while (play_file.available() >= 8) { + uint32_t ckid = 0, cksize = 0; + if (!read_u32(play_file, ckid) || !read_u32(play_file, cksize)) break; + + if (ckid == 0x20746D66) { + uint16_t audio_fmt = 0; + read_u16(play_file, audio_fmt); + read_u16(play_file, *channels); + read_u32(play_file, *sample_rate); + uint32_t byte_rate = 0; + uint16_t block_align = 0; + read_u32(play_file, byte_rate); + (void)byte_rate; + read_u16(play_file, block_align); + (void)block_align; + read_u16(play_file, *bits); + if (cksize > 16) { + play_file.seek(play_file.position() + (cksize - 16)); + } + if (audio_fmt != 1 && audio_fmt != 0xFFFE) { + play_file.close(); + status = "not PCM"; + return false; + } + got_fmt = true; + } else if (ckid == 0x61746164) { + *data_left = cksize; + got_data = true; + break; + } else { + play_file.seek(play_file.position() + cksize + (cksize & 1)); + } + } + + if (!got_fmt || !got_data || *data_left == 0) { + play_file.close(); + status = "bad WAV"; + return false; + } + if (*bits != 16 && *bits != 8) { + play_file.close(); + status = "bits?"; + return false; + } + if (*channels < 1 || *channels > 2) { + play_file.close(); + status = "ch?"; + return false; + } + return true; +} + +static void play_task_fn(void * /*arg*/) { + uint16_t channels = 1; + uint16_t bits = 16; + uint32_t sample_rate = 16000; + uint32_t data_left = 0; + + if (!open_and_parse(play_path, &channels, &bits, &sample_rate, &data_left)) { + playing = false; + vTaskDelete(nullptr); + return; + } + + if (sample_rate < 4000) sample_rate = 4000; + if (sample_rate > 48000) sample_rate = 48000; + const uint32_t period_us = 1000000UL / sample_rate; + + dac_output_disable(DAC_CHANNEL_1); + dac_output_enable(DAC_CHANNEL_2); + dac_output_voltage(DAC_CHANNEL_2, 128); + + status = "play"; + Serial.printf("PLAY %s %uHz %ubit %uch\n", play_path, (unsigned)sample_rate, + (unsigned)bits, (unsigned)channels); + + uint32_t next_us = micros(); + while (!stop_req && data_left > 0) { + int32_t mono = 0; + for (uint16_t c = 0; c < channels; c++) { + if (bits == 8) { + int b = play_file.read(); + if (b < 0) { + data_left = 0; + break; + } + data_left--; + mono += (b - 128) * 256; + } else { + uint16_t s; + if (!read_u16(play_file, s) || data_left < 2) { + data_left = 0; + break; + } + data_left -= 2; + mono += (int16_t)s; + } + } + if (channels == 2) mono /= 2; + + dac_output_voltage(DAC_CHANNEL_2, scale_u8((int16_t)mono)); + + next_us += period_us; + int32_t wait = (int32_t)(next_us - micros()); + if (wait > 0) { + delayMicroseconds((uint32_t)wait); + } else if (wait < -2000) { + next_us = micros(); + } + } + + if (play_file) play_file.close(); + release_dac(); + playing = false; + status = stop_req ? "stopped" : "done"; + play_task = nullptr; + vTaskDelete(nullptr); +} + +void player_init(void) { + release_dac(); + status = "idle"; +} + +void player_stop(void) { + if (!playing && !play_task) { + release_dac(); + return; + } + stop_req = true; + for (int i = 0; i < 50 && play_task; i++) { + delay(10); + } + if (play_file) play_file.close(); + playing = false; + play_task = nullptr; + release_dac(); + status = "stopped"; +} + +bool player_is_playing(void) { return playing; } + +const char *player_status(void) { return status; } + +bool player_play(const char *path) { + player_stop(); + if (!path || !path[0]) { + status = "no file"; + return false; + } + if (!sd_ready() && !sd_init()) { + status = "no SD"; + return false; + } + + strncpy(play_path, path, sizeof(play_path) - 1); + play_path[sizeof(play_path) - 1] = '\0'; + stop_req = false; + playing = true; + status = "start"; + + BaseType_t ok = + xTaskCreatePinnedToCore(play_task_fn, "wavdac", 4096, nullptr, 4, + &play_task, 0); + if (ok != pdPASS) { + playing = false; + play_task = nullptr; + status = "task fail"; + return false; + } + return true; +} + +void player_tick(void) { + /* playback runs in its own task */ +} diff --git a/src/recorder.cpp b/src/recorder.cpp new file mode 100644 index 0000000..a628d3e --- /dev/null +++ b/src/recorder.cpp @@ -0,0 +1,322 @@ +/** + * INMP441 I2S → 16-bit mono PCM WAV on microSD (/rec/Rxxxx.WAV) + * Stereo DMA slots: pick louder even/odd (ESP32 L/R vs mic L/R often inverted). + */ + +#include "recorder.h" +#include "pins.h" +#include "sdcard.h" + +#include +#include +#include +#include +#include +#include + +#define I2S_PORT I2S_NUM_0 +#define DMA_BUF_COUNT 8 +#define DMA_BUF_LEN 256 +#define READ_SAMPLES 512 +#define MIC_DB_OFFSET 120.0f +#define EMA_ALPHA 0.35f +#define WAV_HDR_SIZE 44 +#define REC_DIR "/rec" + +static int32_t i2s_raw[READ_SAMPLES]; +static int16_t pcm_out[READ_SAMPLES / 2 + 8]; + +static bool mic_ok = false; +static bool recording = false; +static File rec_file; +static char last_path[40] = ""; +static char status_buf[32] = "idle"; +static uint32_t data_bytes = 0; +static uint32_t start_ms = 0; +static float level_db = NAN; +static uint16_t next_index = 1; +static int preferred_slot = -1; /* -1=auto, 0=even, 1=odd */ + +static void write_u16(File &f, uint16_t v) { + uint8_t b[2] = {(uint8_t)(v & 0xFF), (uint8_t)(v >> 8)}; + f.write(b, 2); +} + +static void write_u32(File &f, uint32_t v) { + uint8_t b[4] = {(uint8_t)(v & 0xFF), (uint8_t)((v >> 8) & 0xFF), + (uint8_t)((v >> 16) & 0xFF), (uint8_t)((v >> 24) & 0xFF)}; + f.write(b, 4); +} + +static void write_wav_header(File &f, uint32_t pcm_bytes) { + const uint32_t sample_rate = REC_SAMPLE_RATE; + const uint16_t channels = 1; + const uint16_t bits = 16; + const uint32_t byte_rate = sample_rate * channels * (bits / 8); + const uint16_t block_align = channels * (bits / 8); + + f.seek(0); + f.write((const uint8_t *)"RIFF", 4); + write_u32(f, 36 + pcm_bytes); + f.write((const uint8_t *)"WAVE", 4); + f.write((const uint8_t *)"fmt ", 4); + write_u32(f, 16); + write_u16(f, 1); /* PCM */ + write_u16(f, channels); + write_u32(f, sample_rate); + write_u32(f, byte_rate); + write_u16(f, block_align); + write_u16(f, bits); + f.write((const uint8_t *)"data", 4); + write_u32(f, pcm_bytes); +} + +static void ensure_rec_dir(void) { + if (!SD.exists(REC_DIR)) { + SD.mkdir(REC_DIR); + } +} + +static uint16_t scan_next_index(void) { + ensure_rec_dir(); + uint16_t max_n = 0; + File root = SD.open(REC_DIR); + if (!root || !root.isDirectory()) { + if (root) root.close(); + return 1; + } + File f = root.openNextFile(); + while (f) { + const char *name = f.name(); + /* SD lib may return "/rec/R0001.WAV" or "R0001.WAV" */ + const char *base = strrchr(name, '/'); + base = base ? base + 1 : name; + if (base[0] == 'R' || base[0] == 'r') { + int n = atoi(base + 1); + if (n > 0 && (uint16_t)n > max_n) max_n = (uint16_t)n; + } + f = root.openNextFile(); + } + root.close(); + return (uint16_t)(max_n + 1); +} + +bool recorder_mic_init(void) { + i2s_config_t cfg = {}; + cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX); + cfg.sample_rate = REC_SAMPLE_RATE; + cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT; + cfg.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT; + cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S; + cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; + cfg.dma_buf_count = DMA_BUF_COUNT; + cfg.dma_buf_len = DMA_BUF_LEN; + cfg.use_apll = false; + cfg.tx_desc_auto_clear = false; + cfg.fixed_mclk = 0; + + i2s_pin_config_t pins = {}; + pins.bck_io_num = I2S_SCK_PIN; + pins.ws_io_num = I2S_WS_PIN; + pins.data_out_num = I2S_PIN_NO_CHANGE; + pins.data_in_num = I2S_SD_PIN; + + if (i2s_driver_install(I2S_PORT, &cfg, 0, NULL) != ESP_OK) { + strncpy(status_buf, "i2s fail", sizeof(status_buf)); + return false; + } + if (i2s_set_pin(I2S_PORT, &pins) != ESP_OK) { + strncpy(status_buf, "i2s pin", sizeof(status_buf)); + return false; + } + i2s_zero_dma_buffer(I2S_PORT); + mic_ok = true; + strncpy(status_buf, "ready", sizeof(status_buf)); + Serial.printf("I2S mic WS=%d SCK=%d SD=%d @%u Hz\n", I2S_WS_PIN, I2S_SCK_PIN, + I2S_SD_PIN, (unsigned)REC_SAMPLE_RATE); + return true; +} + +bool recorder_start(void) { + if (recording) return true; + if (!mic_ok) { + strncpy(status_buf, "no mic", sizeof(status_buf)); + return false; + } + if (!sd_ready() && !sd_init()) { + strncpy(status_buf, "no SD", sizeof(status_buf)); + return false; + } + if (sd_free_bytes() < 64 * 1024) { + strncpy(status_buf, "SD full", sizeof(status_buf)); + return false; + } + + next_index = scan_next_index(); + ensure_rec_dir(); + snprintf(last_path, sizeof(last_path), "%s/R%04u.WAV", REC_DIR, + (unsigned)next_index); + + if (SD.exists(last_path)) { + SD.remove(last_path); + } + + rec_file = SD.open(last_path, FILE_WRITE); + if (!rec_file) { + strncpy(status_buf, "open fail", sizeof(status_buf)); + last_path[0] = '\0'; + return false; + } + + /* Placeholder header; finalize on stop. */ + uint8_t zeros[WAV_HDR_SIZE] = {0}; + if (rec_file.write(zeros, WAV_HDR_SIZE) != WAV_HDR_SIZE) { + rec_file.close(); + strncpy(status_buf, "hdr fail", sizeof(status_buf)); + return false; + } + + data_bytes = 0; + start_ms = millis(); + preferred_slot = -1; + level_db = NAN; + recording = true; + strncpy(status_buf, "REC", sizeof(status_buf)); + Serial.printf("REC start %s\n", last_path); + return true; +} + +void recorder_stop(void) { + if (!recording) return; + recording = false; + + if (rec_file) { + write_wav_header(rec_file, data_bytes); + rec_file.flush(); + rec_file.close(); + } + + uint32_t sec = data_bytes / (REC_SAMPLE_RATE * 2); + Serial.printf("REC stop %s bytes=%lu (~%lus)\n", last_path, + (unsigned long)data_bytes, (unsigned long)sec); + strncpy(status_buf, "saved", sizeof(status_buf)); +} + +bool recorder_is_active(void) { return recording; } + +float recorder_level_db(void) { return level_db; } + +uint32_t recorder_elapsed_ms(void) { + if (!recording) return 0; + return millis() - start_ms; +} + +uint32_t recorder_bytes_written(void) { return data_bytes; } + +const char *recorder_last_path(void) { return last_path; } + +const char *recorder_status(void) { return status_buf; } + +static float ema(float prev, float sample) { + if (isnan(prev)) return sample; + return prev + EMA_ALPHA * (sample - prev); +} + +void recorder_tick(void) { + if (!mic_ok) return; + + size_t bytes_read = 0; + /* Non-blocking when idle; short wait while recording so LVGL stays responsive. */ + esp_err_t err = + i2s_read(I2S_PORT, (void *)i2s_raw, sizeof(i2s_raw), &bytes_read, + recording ? pdMS_TO_TICKS(8) : 0); + if (err != ESP_OK || bytes_read < sizeof(int32_t) * 32) { + return; + } + + int n = (int)(bytes_read / sizeof(int32_t)); + if (n < 32) return; + + /* Unpack 24-bit left-justified. */ + static int32_t unpacked[READ_SAMPLES]; + for (int i = 0; i < n; i++) { + unpacked[i] = i2s_raw[i] >> 8; + } + + double mean_even = 0.0, mean_odd = 0.0; + int n_even = 0, n_odd = 0; + for (int i = 0; i < n; i++) { + if ((i & 1) == 0) { + mean_even += unpacked[i]; + n_even++; + } else { + mean_odd += unpacked[i]; + n_odd++; + } + } + if (n_even < 8 || n_odd < 8) return; + mean_even /= (double)n_even; + mean_odd /= (double)n_odd; + + double sum_even = 0.0, sum_odd = 0.0; + for (int i = 0; i < n; i++) { + double v; + if ((i & 1) == 0) { + v = (double)unpacked[i] - mean_even; + sum_even += v * v; + } else { + v = (double)unpacked[i] - mean_odd; + sum_odd += v * v; + } + } + double rms_even = sqrt(sum_even / (double)n_even); + double rms_odd = sqrt(sum_odd / (double)n_odd); + + if (preferred_slot < 0) { + preferred_slot = (rms_even >= rms_odd) ? 0 : 1; + } + const int slot = preferred_slot; + const double mean = (slot == 0) ? mean_even : mean_odd; + const double rms = (slot == 0) ? rms_even : rms_odd; + + if (rms >= 1.0) { + float dbfs = 20.0f * log10f((float)rms / 8388607.0f); + float db = dbfs + MIC_DB_OFFSET; + if (db < 0.0f) db = 0.0f; + if (db > 140.0f) db = 140.0f; + level_db = ema(level_db, db); + } else { + level_db = ema(level_db, 0.0f); + } + + if (!recording) return; + + /* Convert selected slot → int16 PCM */ + int out_n = 0; + for (int i = slot; i < n; i += 2) { + int32_t v = unpacked[i] - (int32_t)mean; + /* 24-bit → 16-bit with headroom (>> 8) */ + int32_t s = v >> 8; + if (s > 32767) s = 32767; + if (s < -32768) s = -32768; + pcm_out[out_n++] = (int16_t)s; + } + + if (out_n > 0) { + size_t want = (size_t)out_n * sizeof(int16_t); + size_t wr = rec_file.write((const uint8_t *)pcm_out, want); + if (wr != want) { + Serial.println("REC write error — stopping"); + strncpy(status_buf, "write err", sizeof(status_buf)); + recorder_stop(); + return; + } + data_bytes += (uint32_t)wr; + } + + if (recorder_elapsed_ms() >= (uint32_t)REC_MAX_SECONDS * 1000U) { + Serial.println("REC max duration — auto stop"); + strncpy(status_buf, "max time", sizeof(status_buf)); + recorder_stop(); + } +} diff --git a/src/sdcard.cpp b/src/sdcard.cpp new file mode 100644 index 0000000..fbee266 --- /dev/null +++ b/src/sdcard.cpp @@ -0,0 +1,54 @@ +#include "sdcard.h" +#include "pins.h" + +#include +#include +#include +#include + +static SPIClass sd_spi(VSPI); +static bool g_ready = false; + +bool sd_init(void) { + if (g_ready) return true; + + pinMode(SD_CS, OUTPUT); + digitalWrite(SD_CS, HIGH); +#if !defined(CYD_BOARD_3248S035) + /* Keep XPT2046 CS high so SD SPI does not steal the bus. */ + pinMode(CYD_TOUCH_CS, OUTPUT); + digitalWrite(CYD_TOUCH_CS, HIGH); +#endif + + sd_spi.begin(SD_SCK, SD_MISO, SD_MOSI, SD_CS); + if (!SD.begin(SD_CS, sd_spi, 25000000)) { + g_ready = false; + Serial.println("SD mount FAIL"); + return false; + } + + g_ready = true; + Serial.printf("SD OK total=%llu free=%llu\n", + (unsigned long long)SD.totalBytes(), + (unsigned long long)(SD.totalBytes() - SD.usedBytes())); + return true; +} + +void sd_deinit(void) { + if (g_ready) { + SD.end(); + g_ready = false; + } +} + +bool sd_ready(void) { return g_ready; } + +uint64_t sd_free_bytes(void) { + if (!g_ready) return 0; + return SD.totalBytes() - SD.usedBytes(); +} + +uint64_t sd_total_bytes(void) { + if (!g_ready) return 0; + return SD.totalBytes(); +} diff --git a/src/touch.cpp b/src/touch.cpp new file mode 100644 index 0000000..542862a --- /dev/null +++ b/src/touch.cpp @@ -0,0 +1,195 @@ +#include "touch.h" + +#include + +/** + * 2.8": XPT2046 resistive SoftSPI bus (CS33). + * 3.5C (3248S035C): GT911 capacitive on Wire1 SDA33/SCL32/INT21/RST25. + * Feed coords are always native panel 320x480 for LVGL ROTATION_270. + * Wire1 keeps GT911 off the INMP441 pins (WS22 / SCK21). After touch_init(), + * main claims GPIO21 as I2S BCK — touch stays poll-only (no INT IRQ). + * TFT_BL=27 on 3.5C. + */ + +static int16_t clampi(int32_t v, int32_t lo, int32_t hi) { + if (v < lo) return (int16_t)lo; + if (v > hi) return (int16_t)hi; + return (int16_t)v; +} + +#if defined(CYD_BOARD_3248S035) + +#include + +/* Native panel size — not UI landscape SCREEN_* (480x320). */ +static constexpr int16_t PANEL_W = 320; +static constexpr int16_t PANEL_H = 480; + +#define CYD_GT911_SDA 33 +#define CYD_GT911_SCL 32 +#define CYD_GT911_INT 21 +#define CYD_GT911_RST 25 + +/* Minimal GT911 — no config rewrite (TAMC setResolution can hang Wire). */ +static uint8_t s_gt_addr = 0x5D; +static constexpr uint16_t GT_POINT_INFO = 0x814E; +static constexpr uint16_t GT_POINT_1 = 0x814F; + +static bool gt_write8(uint16_t reg, uint8_t val) { + Wire1.beginTransmission(s_gt_addr); + Wire1.write((uint8_t)(reg >> 8)); + Wire1.write((uint8_t)(reg & 0xFF)); + Wire1.write(val); + return Wire1.endTransmission() == 0; +} + +static bool gt_read(uint16_t reg, uint8_t *buf, uint8_t len) { + Wire1.beginTransmission(s_gt_addr); + Wire1.write((uint8_t)(reg >> 8)); + Wire1.write((uint8_t)(reg & 0xFF)); + if (Wire1.endTransmission(false) != 0) { + return false; + } + const uint8_t n = Wire1.requestFrom(s_gt_addr, len); + if (n != len) { + return false; + } + for (uint8_t i = 0; i < len; i++) { + buf[i] = Wire1.read(); + } + return true; +} + +static bool gt_probe(uint8_t addr) { + Wire1.beginTransmission(addr); + return Wire1.endTransmission() == 0; +} + +/* TAMC-compatible address select: INT low => 0x5D, INT high => 0x14 */ +static void gt_hw_reset(bool addr_0x14) { + pinMode(CYD_GT911_INT, OUTPUT); + pinMode(CYD_GT911_RST, OUTPUT); + digitalWrite(CYD_GT911_INT, LOW); + digitalWrite(CYD_GT911_RST, LOW); + delay(10); + digitalWrite(CYD_GT911_INT, addr_0x14 ? HIGH : LOW); + delay(1); + digitalWrite(CYD_GT911_RST, HIGH); + delay(5); + digitalWrite(CYD_GT911_INT, LOW); + delay(50); + /* BL=27. Release INT(21) before main reuses it as INMP441 I2S SCK. */ + pinMode(CYD_GT911_INT, INPUT); + delay(50); +} + +static bool gt_find_addr() { + for (uint8_t a : {uint8_t(0x5D), uint8_t(0x14)}) { + if (gt_probe(a)) { + s_gt_addr = a; + return true; + } + } + return false; +} + +void touch_init() { + Serial.println("Touch: GT911 I2C capacitive (3.5C) minimal Wire1"); + Wire1.begin(CYD_GT911_SDA, CYD_GT911_SCL); + Wire1.setClock(100000); +#if defined(WIRE_HAS_TIMEOUT) || defined(ESP32) + Wire1.setTimeOut(50); +#endif + + if (!gt_find_addr()) { + Serial.println("GT911 not found — hw reset 0x5D"); + gt_hw_reset(false); + if (!gt_find_addr()) { + Serial.println("GT911 not found — hw reset 0x14"); + gt_hw_reset(true); + gt_find_addr(); + } + } + + Serial.printf("GT911 probe 0x5D=%s 0x14=%s using=0x%02X\n", + gt_probe(0x5D) ? "OK" : "no", gt_probe(0x14) ? "OK" : "no", + s_gt_addr); + Serial.printf("GT911 SDA=%d SCL=%d INT=%d RST=%d\n", CYD_GT911_SDA, + CYD_GT911_SCL, CYD_GT911_INT, CYD_GT911_RST); +} + +void touch_read_cb(lv_indev_t * /*indev*/, lv_indev_data_t *data) { + uint8_t info = 0; + + if (!gt_read(GT_POINT_INFO, &info, 1)) { + data->state = LV_INDEV_STATE_RELEASED; + return; + } + + const uint8_t touches = info & 0x0F; + const bool buffered = (info & 0x80) != 0; + + if (!buffered || touches == 0) { + if (buffered) { + gt_write8(GT_POINT_INFO, 0); + } + data->state = LV_INDEV_STATE_RELEASED; + return; + } + + uint8_t pt[7]; + if (!gt_read(GT_POINT_1, pt, 7)) { + gt_write8(GT_POINT_INFO, 0); + data->state = LV_INDEV_STATE_RELEASED; + return; + } + gt_write8(GT_POINT_INFO, 0); + + const int16_t raw_x = (int16_t)(pt[1] | (pt[2] << 8)); + const int16_t raw_y = (int16_t)(pt[3] | (pt[4] << 8)); + + /* Native 320x480 → LVGL 270. UI ≈ (H-1-raw_y, raw_x). */ + const int16_t nx = clampi(raw_x, 0, PANEL_W - 1); + const int16_t ny = clampi(raw_y, 0, PANEL_H - 1); + data->point.x = (int16_t)((PANEL_W - 1) - nx); + data->point.y = (int16_t)((PANEL_H - 1) - ny); + data->state = LV_INDEV_STATE_PRESSED; +} + +#else + +#include +#include + +#define XPT2046_IRQ 36 +#define XPT2046_MOSI 32 +#define XPT2046_MISO 39 +#define XPT2046_CLK 25 +#define XPT2046_CS 33 + +/* 2.8 UI landscape feed (unchanged from prior main.cpp). */ +static constexpr int16_t UI_W = 320; +static constexpr int16_t UI_H = 240; + +static SPIClass touchscreenSPI = SPIClass(VSPI); +static XPT2046_Touchscreen touchscreen(XPT2046_CS, XPT2046_IRQ); + +void touch_init() { + touchscreenSPI.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS); + touchscreen.begin(touchscreenSPI); + touchscreen.setRotation(2); + Serial.println("Touch: XPT2046 resistive (2.8)"); +} + +void touch_read_cb(lv_indev_t * /*indev*/, lv_indev_data_t *data) { + if (touchscreen.tirqTouched() && touchscreen.touched()) { + TS_Point p = touchscreen.getPoint(); + data->point.x = map(p.y, 240, 3800, 1, UI_W); + data->point.y = map(p.x, 200, 3700, UI_H, 1); + data->state = LV_INDEV_STATE_PRESSED; + } else { + data->state = LV_INDEV_STATE_RELEASED; + } +} + +#endif