commit 59b85fb7dce9034851c613726a89b70e6cded618 Author: DESKTOP-PUHFO60\dsx2016 Date: Tue Oct 27 20:49:12 2026 +0800 Add INMP441 sound-level meter for CYD 2.8/3.5. I2S mic on WS22/SCK27(SD35) with LVGL dB gauge, peak/min-max and firmware pack. Co-authored-by: Cursor diff --git a/.cursor/rules/git-and-docs.mdc b/.cursor/rules/git-and-docs.mdc new file mode 100644 index 0000000..8cd4cb7 --- /dev/null +++ b/.cursor/rules/git-and-docs.mdc @@ -0,0 +1,14 @@ +--- +description: 每次改动必须提交 Git 并更新文档 +alwaysApply: true +--- + +# Git 与文档 + +对本项目做任何功能、行为或配置改动后,在结束本次任务前必须: + +1. **更新文档**:至少更新 `README.md` 的「功能 / 硬件 / 变更记录」中受影响部分;行为变更写进变更记录表。 +2. **提交 Git**:`git add` 相关文件后 `git commit`(按仓库既有 message 风格;中英文均可,说明 why)。 +3. **不要**在未提交的情况下声称任务已完成。 + +例外:用户明确说「先别提交」或「不要改文档」时,以用户当次指令为准。 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..0b8c069 --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +# CYD INMP441 声贝检测 + +ESP32 Cheap Yellow Display + INMP441(I2S)+ LVGL 声级仪表盘(近似 dB SPL)。 + +默认 **2.8" ESP32-2432S028R**;可选 **3.5" ESP32-3248S035C**(`cyd_35r`)。 +引脚约定见同目录 [CYD_PROJECT_GUIDE.md](../CYD_PROJECT_GUIDE.md);UI 壳参考 [sgp30test](../sgp30test)。 + +## 硬件 + +| 项目 | 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** | +| 供电 | USB 5V;麦克风 **3.3V** | 同左 | + +接线: + +| 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 需要三根信号线,仅 IO22+IO27 不够。 + +## 功能 + +- 大圆弧显示近似 **dB SPL**(基于 INMP441 −26 dBFS @ 94 dB 的换算,非标定声级计) +- 分级:QUIET / SOFT / NORMAL / LOUD / VERY LOUD / DANGER +- PEAK 峰值保持(缓慢回落)、MIN/MAX、电平条、底部趋势图 +- EMA 平滑;串口打印 `dB / rms / peak` +- 短按切换背光(4 档);长按 ≥0.7s 重置 min/max +- 常亮运行(无自动熄屏) + +## 构建与烧录 + +依赖 [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 +src/main.cpp touch.cpp +scripts/exclude_lvgl_asm.py +firmware/ +README.md +``` + +## 变更记录 + +| 日期 | 说明 | +|------|------| +| 2026-10-27 | 初版:INMP441 I2S 声贝仪表盘(WS22/SCK27/SD35),LVGL 圆弧 + peak/min/max + 趋势图 | diff --git a/firmware/README.md b/firmware/README.md new file mode 100644 index 0000000..3f9bb81 --- /dev/null +++ b/firmware/README.md @@ -0,0 +1,24 @@ +# 预编译固件(可随时刷写) + +| 目录 | 板子 | 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)。 + +## 直接刷写 + +```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..4d1fccf --- /dev/null +++ b/firmware/cyd_28r/VERSION.txt @@ -0,0 +1,17 @@ +name: CYD inmp441test (cyd_28r) +git: unknown +date: 2026-10-27 +board: ESP32-2432S028R (ILI9341) +inmp441: WS=GPIO22 SCK=GPIO27 SD=GPIO35 +tft_bl: GPIO21 +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 0CA34A45377F5EDCAB501E510F97B28A9B7FCEB34D6C65F0B71691C784C41999 + 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..46ef4fa 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..0d87b94 --- /dev/null +++ b/firmware/cyd_28r/flash.ps1 @@ -0,0 +1,84 @@ +# Flash archived CYD INMP441 sound-meter 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..0b21d9a --- /dev/null +++ b/firmware/cyd_28r/meta.json @@ -0,0 +1,7 @@ +{ + "boardId": "esp32-2432s028", + "name": "CYD INMP441 sound level meter", + "summary": "Approximate dB SPL gauge from INMP441", + "description": "INMP441 on WS=GPIO22 / SCK=GPIO27 / SD=GPIO35. Live dB arc, peak, min/max, trend chart.", + "tags": ["sound", "inmp441", "i2s", "db", "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/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..a586008 --- /dev/null +++ b/firmware/cyd_35r/flash.ps1 @@ -0,0 +1,84 @@ +# Flash archived CYD SGP30 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_35r/meta.json b/firmware/cyd_35r/meta.json new file mode 100644 index 0000000..1a3046d --- /dev/null +++ b/firmware/cyd_35r/meta.json @@ -0,0 +1,7 @@ +{ + "boardId": "esp32-3248s035", + "name": "CYD INMP441 sound level meter", + "summary": "Approximate dB SPL gauge from INMP441", + "description": "INMP441 on WS=GPIO22 / SCK=GPIO21 / SD=GPIO35. Live dB arc, peak, min/max, trend chart.", + "tags": ["sound", "inmp441", "i2s", "db", "mic"] +} diff --git a/firmware/export_from_build.ps1 b/firmware/export_from_build.ps1 new file mode 100644 index 0000000..05832ee --- /dev/null +++ b/firmware/export_from_build.ps1 @@ -0,0 +1,73 @@ +# 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 inmp441test ($dstName)", + "git: $git", + "date: $date", + $boardLine, + $micLine, + $blLine, + "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..0047ced --- /dev/null +++ b/include/pins.h @@ -0,0 +1,21 @@ +#pragma once + +/* CYD + INMP441 I2S pin truth source — 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 +#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 +#endif 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..a227275 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,90 @@ +; CYD LVGL INMP441 sound-level (dB) meter +; 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..7ea3543 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,586 @@ +/** + * CYD LVGL INMP441 声贝(近似 dB SPL)仪表盘 + * 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 + * + * L/R -> GND(左声道);VDD -> 3.3V(勿接 5V) + */ + +#include +#include +#include +#include +#include +#include "pins.h" +#include "touch.h" + +#define I2S_PORT I2S_NUM_0 +#define SAMPLE_RATE 16000 +#define SAMPLE_BITS 32 +#define DMA_BUF_COUNT 4 +#define DMA_BUF_LEN 256 +#define READ_SAMPLES 512 +#define MIC_READ_MS 80 +#define EMA_ALPHA 0.40f +#define PEAK_DECAY_DB 1.2f +#define HISTORY_LEN 48 +#define DB_ARC_MIN 30 +#define DB_ARC_MAX 110 +/* INMP441 ≈ -26 dBFS @ 94 dB SPL → SPL ≈ dBFS + 120 */ +#define MIC_DB_OFFSET 120.0f + +#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 10 +#define UI_G 10 +#define UI_HDR_H 32 +#define UI_GAUGE_H 168 +#define UI_GAUGE_W 280 +#define UI_INFO_W 170 +#define UI_ARC 130 +#else +#define UI_M 6 +#define UI_G 6 +#define UI_HDR_H 22 +#define UI_GAUGE_H 124 +#define UI_GAUGE_W 188 +#define UI_INFO_W 114 +#define UI_ARC 96 +#endif +#define UI_BOT_Y (UI_HDR_H + UI_G + UI_GAUGE_H + UI_G) +#define UI_BOT_H (SCREEN_HEIGHT - UI_BOT_Y - UI_M) +#define UI_BOT_W (SCREEN_WIDTH - 2 * UI_M) + +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_LOUD = lv_color_hex(0xF0A04B); +static const lv_color_t COL_BAD = lv_color_hex(0xE05A5A); +static const lv_color_t COL_ARC_BG = lv_color_hex(0x243247); +static const lv_color_t COL_CHART_BG = lv_color_hex(0x0E1622); + +static uint32_t draw_buf[DRAW_BUF_SIZE / 4]; +static int32_t i2s_samples[READ_SAMPLES]; + +static lv_obj_t *arc_db; +static lv_obj_t *lbl_db_val; +static lv_obj_t *lbl_level; +static lv_obj_t *lbl_peak; +static lv_obj_t *lbl_range; +static lv_obj_t *lbl_rms; +static lv_obj_t *lbl_status; +static lv_obj_t *lbl_uptime; +static lv_obj_t *lbl_hint; +static lv_obj_t *led_status; +static lv_obj_t *bar_level; +static lv_obj_t *chart; +static lv_chart_series_t *ser_db; + +static float disp_db = NAN; +static float peak_db = NAN; +static float min_db = NAN; +static float max_db = NAN; +static float last_rms = 0.0f; +static uint32_t last_mic_ms = 0; +static uint32_t last_ok_ms = 0; +static uint32_t boot_ms = 0; +static bool mic_ok = false; +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 void set_backlight(uint8_t level) { + bright_level = level & 0x03; + ledcWrite(0, BRIGHT_PWM[bright_level]); +} + +static float ema(float prev, float sample) { + if (isnan(prev)) return sample; + return prev + EMA_ALPHA * (sample - prev); +} + +static lv_color_t db_color(float db) { + if (isnan(db)) return COL_MUTED; + if (db < 50.0f) return COL_OK; + if (db < 70.0f) return COL_ACCENT; + if (db < 85.0f) return COL_WARN; + if (db < 95.0f) return COL_LOUD; + return COL_BAD; +} + +static const char *db_level_text(float db) { + if (isnan(db)) return "NO DATA"; + if (db < 40.0f) return "QUIET"; + if (db < 55.0f) return "SOFT"; + if (db < 70.0f) return "NORMAL"; + if (db < 85.0f) return "LOUD"; + if (db < 95.0f) return "VERY LOUD"; + return "DANGER"; +} + +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 void reset_minmax(void) { + if (!isnan(disp_db)) { + min_db = max_db = disp_db; + } else { + min_db = max_db = NAN; + } + peak_db = disp_db; + show_hint("min/max reset", 1200); +} + +static void touchscreen_read(lv_indev_t *indev, lv_indev_data_t *data) { + static bool was_pressed = false; + static uint32_t press_ms = 0; + + touch_read_cb(indev, data); + + if (data->state == LV_INDEV_STATE_PRESSED) { + if (!was_pressed) { + was_pressed = true; + press_ms = millis(); + } + } else if (was_pressed) { + was_pressed = false; + uint32_t held = millis() - press_ms; + if (held >= 700) { + reset_minmax(); + } else if (held < 400) { + set_backlight((bright_level + 1) & 0x03); + char buf[20]; + lv_snprintf(buf, sizeof(buf), "brightness %u/3", (unsigned)bright_level); + show_hint(buf, 900); + } + } +} + +static void arc_anim_exec(void *obj, int32_t v) { + lv_arc_set_value((lv_obj_t *)obj, v); +} + +static void anim_arc(lv_obj_t *arc, int32_t value) { + int32_t cur = lv_arc_get_value(arc); + if (cur == value) return; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, arc); + lv_anim_set_values(&a, cur, value); + lv_anim_set_duration(&a, 280); + lv_anim_set_exec_cb(&a, arc_anim_exec); + lv_anim_set_path_cb(&a, lv_anim_path_ease_out); + lv_anim_start(&a); +} + +static void bar_anim_exec(void *obj, int32_t v) { + lv_bar_set_value((lv_obj_t *)obj, v, LV_ANIM_OFF); +} + +static void anim_bar(lv_obj_t *bar, int32_t value) { + int32_t cur = lv_bar_get_value(bar); + if (cur == value) return; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, bar); + lv_anim_set_values(&a, cur, value); + lv_anim_set_duration(&a, 220); + lv_anim_set_exec_cb(&a, bar_anim_exec); + lv_anim_set_path_cb(&a, lv_anim_path_ease_out); + lv_anim_start(&a); +} + +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, 6, 0); + lv_obj_clear_flag(p, LV_OBJ_FLAG_SCROLLABLE); + return p; +} + +static bool mic_init(void) { + i2s_config_t cfg = {}; + cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX); + cfg.sample_rate = SAMPLE_RATE; + cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT; + 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 = 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) { + Serial.println("I2S driver install failed"); + return false; + } + if (i2s_set_pin(I2S_PORT, &pins) != ESP_OK) { + Serial.println("I2S set_pin failed"); + return false; + } + i2s_zero_dma_buffer(I2S_PORT); + return true; +} + +static bool mic_read_db(float *out_db, float *out_rms) { + size_t bytes_read = 0; + esp_err_t err = i2s_read(I2S_PORT, (void *)i2s_samples, sizeof(i2s_samples), + &bytes_read, pdMS_TO_TICKS(40)); + if (err != ESP_OK || bytes_read < sizeof(int32_t) * 32) { + return false; + } + + int n = (int)(bytes_read / sizeof(int32_t)); + double sum_sq = 0.0; + int used = 0; + for (int i = 0; i < n; i++) { + /* INMP441: 24-bit left-justified in 32-bit word */ + int32_t s = i2s_samples[i] >> 8; + sum_sq += (double)s * (double)s; + used++; + } + if (used < 16) return false; + + double rms = sqrt(sum_sq / (double)used); + *out_rms = (float)rms; + if (rms < 1.0) rms = 1.0; + /* dBFS vs 24-bit full scale, then map to approximate SPL */ + float dbfs = 20.0f * log10f((float)rms / 8388607.0f); + *out_db = dbfs + MIC_DB_OFFSET; + if (*out_db < 0.0f) *out_db = 0.0f; + if (*out_db > 140.0f) *out_db = 140.0f; + return true; +} + +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, "SOUND"); + 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 gy = UI_HDR_H + UI_G; + + lv_obj_t *p_db = make_panel(scr, UI_M, gy, UI_GAUGE_W, UI_GAUGE_H); + lv_obj_t *cap = lv_label_create(p_db); + lv_label_set_text(cap, "dB SPL ~"); + lv_obj_set_style_text_font(cap, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(cap, COL_MUTED, 0); + lv_obj_align(cap, LV_ALIGN_TOP_LEFT, 0, -2); + + arc_db = lv_arc_create(p_db); + lv_obj_set_size(arc_db, UI_ARC, UI_ARC); + lv_obj_align(arc_db, LV_ALIGN_TOP_MID, 0, 2); + lv_arc_set_rotation(arc_db, 135); + lv_arc_set_bg_angles(arc_db, 0, 270); + lv_arc_set_range(arc_db, DB_ARC_MIN, DB_ARC_MAX); + lv_arc_set_value(arc_db, DB_ARC_MIN); + lv_obj_remove_style(arc_db, NULL, LV_PART_KNOB); + lv_obj_clear_flag(arc_db, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_style_arc_color(arc_db, COL_ARC_BG, LV_PART_MAIN); + lv_obj_set_style_arc_width(arc_db, 12, LV_PART_MAIN); + lv_obj_set_style_arc_color(arc_db, COL_ACCENT, LV_PART_INDICATOR); + lv_obj_set_style_arc_width(arc_db, 12, LV_PART_INDICATOR); + lv_obj_set_style_arc_rounded(arc_db, true, LV_PART_MAIN); + lv_obj_set_style_arc_rounded(arc_db, true, LV_PART_INDICATOR); + + lbl_db_val = lv_label_create(p_db); + lv_label_set_text(lbl_db_val, "--.-"); + lv_obj_set_style_text_font(lbl_db_val, &lv_font_montserrat_28, 0); + lv_obj_set_style_text_color(lbl_db_val, COL_ACCENT, 0); + lv_obj_align(lbl_db_val, LV_ALIGN_TOP_MID, 0, 30); + + lv_obj_t *unit = lv_label_create(p_db); + lv_label_set_text(unit, "dB"); + lv_obj_set_style_text_font(unit, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(unit, COL_MUTED, 0); + lv_obj_align(unit, LV_ALIGN_TOP_MID, 0, 62); + + lbl_level = lv_label_create(p_db); + lv_label_set_text(lbl_level, "----"); + 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_BOTTOM_MID, 0, 2); + + lv_obj_t *p_info = make_panel(scr, UI_M + UI_GAUGE_W + UI_G, gy, UI_INFO_W, UI_GAUGE_H); + + lv_obj_t *p_cap = lv_label_create(p_info); + lv_label_set_text(p_cap, "PEAK"); + lv_obj_set_style_text_font(p_cap, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(p_cap, COL_MUTED, 0); + lv_obj_align(p_cap, LV_ALIGN_TOP_LEFT, 0, -2); + + lbl_peak = lv_label_create(p_info); + lv_label_set_text(lbl_peak, "--.-"); + lv_obj_set_style_text_font(lbl_peak, &lv_font_montserrat_20, 0); + lv_obj_set_style_text_color(lbl_peak, COL_WARN, 0); + lv_obj_align(lbl_peak, LV_ALIGN_TOP_LEFT, 0, 14); + + lv_obj_t *r_cap = lv_label_create(p_info); + lv_label_set_text(r_cap, "MIN / MAX"); + lv_obj_set_style_text_font(r_cap, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(r_cap, COL_MUTED, 0); + lv_obj_align(r_cap, LV_ALIGN_TOP_LEFT, 0, 42); + + lbl_range = lv_label_create(p_info); + lv_label_set_text(lbl_range, "-- / --"); + lv_obj_set_style_text_font(lbl_range, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_color(lbl_range, COL_TEXT, 0); + lv_obj_align(lbl_range, LV_ALIGN_TOP_LEFT, 0, 56); + + bar_level = lv_bar_create(p_info); + lv_obj_set_size(bar_level, UI_INFO_W - 12, 12); + lv_obj_align(bar_level, LV_ALIGN_TOP_LEFT, 0, 82); + lv_bar_set_range(bar_level, DB_ARC_MIN, DB_ARC_MAX); + lv_bar_set_value(bar_level, DB_ARC_MIN, 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, 4, LV_PART_MAIN); + lv_obj_set_style_bg_color(bar_level, COL_ACCENT, LV_PART_INDICATOR); + lv_obj_set_style_radius(bar_level, 4, LV_PART_INDICATOR); + + lbl_rms = lv_label_create(p_info); + lv_label_set_text(lbl_rms, "rms --"); + lv_obj_set_style_text_font(lbl_rms, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_rms, COL_MUTED, 0); + lv_obj_align(lbl_rms, LV_ALIGN_BOTTOM_LEFT, 0, 2); + + lv_obj_t *p_bot = make_panel(scr, UI_M, UI_BOT_Y, UI_BOT_W, UI_BOT_H); + chart = lv_chart_create(p_bot); + lv_obj_set_size(chart, UI_BOT_W - 12, UI_BOT_H - 12); + lv_obj_align(chart, LV_ALIGN_CENTER, 0, 0); + lv_chart_set_type(chart, LV_CHART_TYPE_LINE); + lv_chart_set_point_count(chart, HISTORY_LEN); + lv_chart_set_range(chart, LV_CHART_AXIS_PRIMARY_Y, DB_ARC_MIN, DB_ARC_MAX); + lv_chart_set_update_mode(chart, LV_CHART_UPDATE_MODE_SHIFT); + lv_obj_set_style_bg_color(chart, COL_CHART_BG, 0); + lv_obj_set_style_bg_opa(chart, LV_OPA_COVER, 0); + lv_obj_set_style_border_color(chart, COL_EDGE, 0); + lv_obj_set_style_border_width(chart, 1, 0); + lv_obj_set_style_radius(chart, 8, 0); + lv_obj_set_style_pad_all(chart, 4, 0); + lv_obj_set_style_line_width(chart, 2, LV_PART_ITEMS); + lv_chart_set_div_line_count(chart, 2, 4); + lv_obj_set_style_line_color(chart, COL_EDGE, LV_PART_MAIN); + lv_obj_set_style_line_opa(chart, LV_OPA_40, LV_PART_MAIN); + ser_db = lv_chart_add_series(chart, COL_ACCENT, LV_CHART_AXIS_PRIMARY_Y); + + lv_obj_move_foreground(title); + lv_obj_move_foreground(lbl_uptime); + lv_obj_move_foreground(lbl_status); + lv_obj_move_foreground(led_status); + lv_obj_move_foreground(lbl_hint); +} + +static void refresh_meta(void) { + char buf[40]; + 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); + } + + if (mic_ok) { + uint32_t age = (millis() - last_ok_ms) / 1000; + lv_snprintf(buf, sizeof(buf), "LIVE %lus", (unsigned long)age); + lv_label_set_text(lbl_status, buf); + lv_led_set_color(led_status, COL_OK); + } else { + lv_label_set_text(lbl_status, "NO MIC"); + lv_led_set_color(led_status, COL_BAD); + } +} + +static void update_ui(bool ok) { + char buf[32]; + + if (!ok || isnan(disp_db)) { + lv_label_set_text(lbl_db_val, "--.-"); + lv_label_set_text(lbl_level, "NO DATA"); + lv_obj_set_style_text_color(lbl_level, COL_BAD, 0); + lv_label_set_text(lbl_status, "ERR"); + lv_led_set_color(led_status, COL_BAD); + return; + } + + lv_color_t c = db_color(disp_db); + lv_snprintf(buf, sizeof(buf), "%.1f", disp_db); + lv_label_set_text(lbl_db_val, buf); + lv_obj_set_style_text_color(lbl_db_val, c, 0); + lv_obj_set_style_arc_color(arc_db, c, LV_PART_INDICATOR); + anim_arc(arc_db, (int)lroundf(constrain(disp_db, (float)DB_ARC_MIN, (float)DB_ARC_MAX))); + + lv_label_set_text(lbl_level, db_level_text(disp_db)); + lv_obj_set_style_text_color(lbl_level, c, 0); + + lv_snprintf(buf, sizeof(buf), "%.1f", peak_db); + lv_label_set_text(lbl_peak, buf); + lv_obj_set_style_text_color(lbl_peak, db_color(peak_db), 0); + + lv_snprintf(buf, sizeof(buf), "%.0f / %.0f", min_db, max_db); + lv_label_set_text(lbl_range, buf); + + anim_bar(bar_level, (int)lroundf(constrain(disp_db, (float)DB_ARC_MIN, (float)DB_ARC_MAX))); + lv_obj_set_style_bg_color(bar_level, c, LV_PART_INDICATOR); + + lv_snprintf(buf, sizeof(buf), "rms %.0f", last_rms); + lv_label_set_text(lbl_rms, buf); + + lv_chart_set_next_value(chart, ser_db, + (int32_t)lroundf(constrain(disp_db, (float)DB_ARC_MIN, (float)DB_ARC_MAX))); + lv_obj_set_style_line_color(chart, c, LV_PART_ITEMS); + refresh_meta(); +} + +static void read_mic(void) { + float db = NAN; + float rms = 0.0f; + if (!mic_read_db(&db, &rms)) { + mic_ok = false; + update_ui(false); + return; + } + + mic_ok = true; + last_ok_ms = millis(); + last_rms = rms; + disp_db = ema(disp_db, db); + + if (isnan(peak_db) || db > peak_db) { + peak_db = db; + } else { + peak_db -= PEAK_DECAY_DB * (MIC_READ_MS / 1000.0f) * 10.0f; + if (peak_db < disp_db) peak_db = disp_db; + } + + if (isnan(min_db) || disp_db < min_db) min_db = disp_db; + if (isnan(max_db) || disp_db > max_db) max_db = disp_db; + + Serial.printf("dB=%.1f (raw %.1f) rms=%.0f peak=%.1f\n", disp_db, db, rms, peak_db); + update_ui(true); +} + +void setup() { + Serial.begin(115200); + delay(200); + boot_ms = millis(); + + ledcSetup(0, 5000, 8); + ledcAttachPin(TFT_BL_PIN, 0); + set_backlight(2); + + Serial.println("CYD LVGL INMP441 Sound Level Meter"); + Serial.printf("LVGL %d.%d.%d WS=%d SCK=%d SD=%d BL=%d\n", + lv_version_major(), lv_version_minor(), lv_version_patch(), + I2S_WS_PIN, I2S_SCK_PIN, I2S_SD_PIN, TFT_BL_PIN); + + touch_init(); + + bool ok = mic_init(); + Serial.println(ok ? "I2S mic OK" : "I2S mic FAIL — check wiring"); + + 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 (!ok) { + show_hint("mic init fail", 3000); + } + delay(100); + last_mic_ms = 0; +} + +void loop() { + uint32_t now = millis(); + if (now - last_mic_ms >= MIC_READ_MS) { + last_mic_ms = now; + read_mic(); + } + + static uint32_t last_meta_ms = 0; + if (now - last_meta_ms >= 1000) { + last_meta_ms = now; + refresh_meta(); + } + + lv_timer_handler(); + lv_tick_inc(5); + delay(5); +} diff --git a/src/touch.cpp b/src/touch.cpp new file mode 100644 index 0000000..fec313a --- /dev/null +++ b/src/touch.cpp @@ -0,0 +1,193 @@ +#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 leaves Wire free for SGP30 (3.5: SDA22/SCL21; TFT_BL=27). + */ + +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); + /* Backlight is GPIO27 — release INT(21) as input (may share SCL for SGP30). */ + 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