diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/burn.sh b/ESP32/esp32/ESP32-S3-LCD-2/main-device/burn.sh new file mode 100755 index 00000000..b63d4d75 --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/burn.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MODE="${1:-potentiometer-adc-test}" +PORT="${PORT:-}" + +case "$MODE" in + potentiometer-adc-test) + SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_adc_test" + BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-adc-test" + ;; + potentiometer-breath-monitor) + SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_breath_monitor" + BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-breath-monitor" + ;; + *) + echo "Unknown mode: $MODE" >&2 + echo "Known modes: potentiometer-adc-test, potentiometer-breath-monitor" >&2 + exit 2 + ;; +esac + +if [[ -z "$PORT" ]]; then + PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')" +fi + +if [[ -z "$PORT" ]]; then + echo "No serial port found. Set PORT=/dev/ttyACM0 explicitly." >&2 + exit 1 +fi + +FQBN="esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi" + +echo "== Mode: $MODE" +echo "== Sketch: $SKETCH_DIR" +echo "== Port: $PORT" +echo "== FQBN: $FQBN" + +arduino-cli compile \ + --fqbn "$FQBN" \ + --build-path "$BUILD_DIR" \ + "$SKETCH_DIR" + +arduino-cli upload \ + --fqbn "$FQBN" \ + -p "$PORT" \ + --input-dir "$BUILD_DIR" \ + "$SKETCH_DIR" + +echo +echo "== Done." diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/AGENTS.md b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/AGENTS.md new file mode 100644 index 00000000..9a2d4153 --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/AGENTS.md @@ -0,0 +1,17 @@ +# AGENTS + +## Назначение папки + +Эта папка содержит отдельный тестовый Arduino-скетч `potentiometer_adc_test.ino` для Waveshare `ESP32-S3-LCD-2`. + +Скетч проверяет переменный резистор на обычных GPIO/ADC, без использования USB `D+ / D-`. + +## Обязательная синхронизация + +При любом изменении `potentiometer_adc_test.ino` обязательно обновлять рядом лежащий `README.md`. + +Если меняются экранные тексты, режимы, пины подключения, правила расчёта, touch-кнопки или serial-команды, описание в `README.md` должно быть обновлено в том же наборе изменений. + +## Язык экрана + +Экранные строки в скетче оставлять на английском языке. diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/README.md b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/README.md new file mode 100644 index 00000000..3abf07cc --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/README.md @@ -0,0 +1,73 @@ +# Potentiometer ADC Test for ESP32-S3-LCD-2 + +Тестовый скетч для Waveshare `ESP32-S3-LCD-2`. + +Назначение: проверить переменный резистор `RP 6045-B50K` через обычные GPIO/ADC, без использования USB `D+ / D-`. + +## Пины + +Используются пины с разъёма `P1` платы: + +- `GPIO2 / IO2` — ADC-вход, сюда подключается ползунок потенциометра. +- `GPIO6 / IO6` — DRIVE-выход для грубого 2-проводного режима. +- `3V3` — питание потенциометра для 3-проводного режима, находится на разъёме `P2`. +- `GND` — земля. + +Не подавать `5V` на `GPIO2` или `GPIO6`: GPIO ESP32-S3 не являются 5V tolerant. + +## Режимы + +Переключение: + +- touch-кнопка `3-WIRE`; +- touch-кнопка `2-WIRE`; +- серийная команда `m`; +- короткое нажатие `BOOT / GPIO0`. + +Сброс min/max: + +- touch-кнопка `RESET`; +- серийная команда `r`. + +## 3-Wire Mode + +Правильное подключение: + +- один край потенциометра -> `3V3`; +- второй край потенциометра -> `GND`; +- средний ползунок -> `GPIO2 / IO2`. + +Скетч показывает напряжение на ползунке, raw ADC, абсолютное положение от `0..3.3V`, калиброванное положение между найденными min/max и примерное сопротивление участка `0..50 kΩ`. + +## 2-Wire Mode + +Грубое подключение: + +- один край потенциометра -> `GPIO6 / IO6`; +- средний ползунок -> `GPIO2 / IO2`; +- второй край не подключать. + +`GPIO6` выдаёт `HIGH`, `GPIO2` читается как ADC с внутренней подтяжкой вниз. Такой режим показывает движение ползунка, но не даёт точного сопротивления: внутренняя подтяжка ESP32 имеет большой разброс. + +## Экранные данные + +На экране выводятся: + +- режим и схема пинов; +- raw ADC и millivolts; +- абсолютный процент от `0..3300 mV`; +- калиброванный процент по найденному min/max; +- min/max/span; +- EMA-сглаживание; +- примерная оценка сопротивления; +- статус `OPEN/LOW/MID/HIGH/SATURATED/NO SPAN`; +- координаты последнего touch; +- serial-подсказка. + +## Сборка + +Из папки `main-device`: + +```bash +./burn.sh potentiometer-adc-test +``` diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/potentiometer_adc_test.ino b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/potentiometer_adc_test.ino new file mode 100644 index 00000000..9b5039d2 --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_adc_test/potentiometer_adc_test.ino @@ -0,0 +1,348 @@ +#include +#include +#include +#include + +#define PIN_LCD_SCLK 39 +#define PIN_LCD_MOSI 38 +#define PIN_LCD_MISO 40 +#define PIN_LCD_DC 42 +#define PIN_LCD_RST -1 +#define PIN_LCD_CS 45 +#define PIN_LCD_BL 1 + +#define PIN_TP_SDA 48 +#define PIN_TP_SCL 47 + +#define PIN_ADC_WIPER 2 +#define PIN_DRIVE_2WIRE 6 +#define PIN_BOOT_BUTTON 0 + +static const uint16_t DISP_W = 320; +static const uint16_t DISP_H = 240; +static const uint32_t ADC_FULL_MV = 3300; +static const float POT_OHMS = 50000.0f; +static const float ROUGH_PULLDOWN_OHMS = 45000.0f; + +static const uint16_t C_BG = 0x0841; +static const uint16_t C_PANEL = 0x18E3; +static const uint16_t C_CARD = 0x2126; +static const uint16_t C_TEXT = 0xF7BE; +static const uint16_t C_MUTE = 0x8C71; +static const uint16_t C_ACCENT = 0x05DF; +static const uint16_t C_OK = 0x47E8; +static const uint16_t C_WARN = 0xFD20; +static const uint16_t C_BAD = 0xF986; +static const uint16_t C_BORDER = 0x4208; + +struct Rect { + int16_t x; + int16_t y; + int16_t w; + int16_t h; +}; + +enum class Mode : uint8_t { + ThreeWire, + TwoWire, +}; + +struct Sample { + uint16_t raw; + uint32_t mv; + uint16_t rawMinBurst; + uint16_t rawMaxBurst; +}; + +Arduino_DataBus *bus = new Arduino_ESP32SPI( + PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO); +Arduino_GFX *gfx = new Arduino_ST7789( + bus, PIN_LCD_RST, 1, true, 240, 320); + +static const Rect BTN_3WIRE = {10, 38, 94, 30}; +static const Rect BTN_2WIRE = {113, 38, 94, 30}; +static const Rect BTN_RESET = {216, 38, 94, 30}; + +static Mode gMode = Mode::ThreeWire; +static uint32_t gLastUiMs = 0; +static uint32_t gLastSerialMs = 0; +static uint32_t gMinMv = 0xFFFFFFFF; +static uint32_t gMaxMv = 0; +static float gEmaMv = 0.0f; +static bool gHasEma = false; +static bool gTouchOk = false; +static uint16_t gLastTouchX = 0; +static uint16_t gLastTouchY = 0; +static bool gBootWasDown = false; +static uint32_t gBootLastChangeMs = 0; + +static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) { + gfx->setTextSize(size); + gfx->setTextColor(color); + gfx->setCursor(x, y); + gfx->print(text); +} + +static void drawButton(const Rect &r, const char *label, bool active) { + uint16_t fill = active ? C_ACCENT : C_CARD; + uint16_t text = active ? C_BG : C_TEXT; + gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill); + gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER); + int16_t tx = r.x + 10; + int16_t ty = r.y + 10; + drawText(tx, ty, label, text, 1); +} + +static bool contains(const Rect &r, uint16_t x, uint16_t y) { + return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h; +} + +static const char *modeName() { + return gMode == Mode::ThreeWire ? "3-WIRE" : "2-WIRE"; +} + +static void resetRange() { + gMinMv = 0xFFFFFFFF; + gMaxMv = 0; + gHasEma = false; +} + +static void configurePins() { + pinMode(PIN_ADC_WIPER, INPUT); + analogReadResolution(12); + analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db); + + if (gMode == Mode::TwoWire) { + pinMode(PIN_DRIVE_2WIRE, OUTPUT); + digitalWrite(PIN_DRIVE_2WIRE, HIGH); + pinMode(PIN_ADC_WIPER, INPUT_PULLDOWN); + } else { + pinMode(PIN_DRIVE_2WIRE, INPUT); + pinMode(PIN_ADC_WIPER, INPUT); + } +} + +static void setMode(Mode mode) { + if (gMode == mode) return; + gMode = mode; + configurePins(); + resetRange(); +} + +static Sample readSample() { + const uint8_t count = 32; + uint32_t rawSum = 0; + uint32_t mvSum = 0; + uint16_t rawMin = 4095; + uint16_t rawMax = 0; + + for (uint8_t i = 0; i < count; i++) { + uint16_t raw = analogRead(PIN_ADC_WIPER); + uint32_t mv = analogReadMilliVolts(PIN_ADC_WIPER); + rawSum += raw; + mvSum += mv; + if (raw < rawMin) rawMin = raw; + if (raw > rawMax) rawMax = raw; + delayMicroseconds(250); + } + + Sample s; + s.raw = rawSum / count; + s.mv = mvSum / count; + s.rawMinBurst = rawMin; + s.rawMaxBurst = rawMax; + return s; +} + +static uint8_t percentFromMv(uint32_t mv) { + if (mv >= ADC_FULL_MV) return 100; + return (uint8_t)((mv * 100UL + ADC_FULL_MV / 2) / ADC_FULL_MV); +} + +static uint8_t calibratedPercent(uint32_t mv, uint32_t span) { + if (span < 10 || gMinMv == 0xFFFFFFFF || mv <= gMinMv) return 0; + uint32_t pct = ((mv - gMinMv) * 100UL + span / 2) / span; + return (uint8_t)min(pct, 100); +} + +static const char *statusText(uint32_t mv, uint32_t span, uint8_t pctAbs) { + if (mv < 30) return "OPEN/GND"; + if (mv > 3250) return "SATURATED"; + if (span < 20) return "NO SPAN"; + if (pctAbs < 15) return "LOW"; + if (pctAbs > 85) return "HIGH"; + return "MID"; +} + +static float estimateOhms(uint32_t mv) { + if (gMode == Mode::ThreeWire) { + return POT_OHMS * ((float)percentFromMv(mv) / 100.0f); + } + if (mv < 5) return -1.0f; + if (mv >= ADC_FULL_MV) return 0.0f; + return ROUGH_PULLDOWN_OHMS * ((float)ADC_FULL_MV / (float)mv - 1.0f); +} + +static void drawStaticUi() { + gfx->fillScreen(C_BG); + drawText(10, 8, "POT ADC TEST", C_TEXT, 2); + drawText(210, 12, "ESP32-S3-LCD-2", C_MUTE, 1); + drawButton(BTN_3WIRE, "3-WIRE", gMode == Mode::ThreeWire); + drawButton(BTN_2WIRE, "2-WIRE", gMode == Mode::TwoWire); + drawButton(BTN_RESET, "RESET", false); + + gfx->drawRoundRect(8, 76, 304, 64, 8, C_BORDER); + gfx->drawRoundRect(8, 148, 304, 54, 8, C_BORDER); + gfx->drawRoundRect(8, 208, 304, 24, 6, C_BORDER); +} + +static void drawBar(uint8_t pct, uint16_t color) { + int x = 18; + int y = 123; + int w = 284; + int h = 10; + gfx->fillRect(x, y, w, h, C_BORDER); + gfx->fillRect(x, y, (w * pct) / 100, h, color); +} + +static void updateUi() { + Sample s = readSample(); + if (s.mv < gMinMv) gMinMv = s.mv; + if (s.mv > gMaxMv) gMaxMv = s.mv; + uint32_t span = (gMaxMv > gMinMv) ? (gMaxMv - gMinMv) : 0; + + if (!gHasEma) { + gEmaMv = (float)s.mv; + gHasEma = true; + } else { + gEmaMv = gEmaMv * 0.85f + (float)s.mv * 0.15f; + } + + uint8_t pctAbs = percentFromMv(s.mv); + uint8_t pctCal = calibratedPercent(s.mv, span); + float ohms = estimateOhms(s.mv); + const char *status = statusText(s.mv, span, pctAbs); + uint16_t statusColor = strcmp(status, "MID") == 0 ? C_OK : + strcmp(status, "NO SPAN") == 0 ? C_WARN : + strcmp(status, "SATURATED") == 0 ? C_BAD : C_ACCENT; + + char line[96]; + gfx->fillRect(9, 77, 302, 62, C_BG); + snprintf(line, sizeof(line), "%s ADC=IO2 DRIVE=IO6", modeName()); + drawText(16, 84, line, C_ACCENT, 1); + snprintf(line, sizeof(line), "raw:%4u mv:%4lu ema:%4lu", + s.raw, (unsigned long)s.mv, (unsigned long)(gEmaMv + 0.5f)); + drawText(16, 101, line, C_TEXT, 1); + snprintf(line, sizeof(line), "abs:%3u%% cal:%3u%% jitter:%u", + pctAbs, pctCal, (unsigned)(s.rawMaxBurst - s.rawMinBurst)); + drawText(16, 115, line, C_TEXT, 1); + drawBar(gMode == Mode::ThreeWire ? pctAbs : pctCal, statusColor); + + gfx->fillRect(9, 149, 302, 52, C_BG); + snprintf(line, sizeof(line), "min:%4lu max:%4lu span:%4lu mV", + (unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span); + drawText(16, 156, line, C_TEXT, 1); + if (ohms < 0) { + snprintf(line, sizeof(line), "ohm: open/too high status:%s", status); + } else { + snprintf(line, sizeof(line), "ohm:%6.1fk%s status:%s", + ohms / 1000.0f, gMode == Mode::TwoWire ? " rough" : "", status); + } + drawText(16, 172, line, statusColor, 1); + snprintf(line, sizeof(line), "touch:%s x:%u y:%u serial:m/r", + gTouchOk ? "ok" : "off", gLastTouchX, gLastTouchY); + drawText(16, 188, line, C_MUTE, 1); + + gfx->fillRect(9, 209, 302, 22, C_BG); + if (gMode == Mode::ThreeWire) { + drawText(16, 216, "Wire: 3V3-edge GND-edge IO2-wiper", C_MUTE, 1); + } else { + drawText(16, 216, "Wire: IO6-edge IO2-wiper third pin open", C_MUTE, 1); + } + + Serial.printf("mode=%s raw=%u mv=%lu ema=%.1f abs=%u cal=%u min=%lu max=%lu span=%lu jitter=%u status=%s\n", + modeName(), s.raw, (unsigned long)s.mv, gEmaMv, pctAbs, pctCal, + (unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span, + (unsigned)(s.rawMaxBurst - s.rawMinBurst), status); +} + +static void handleTouch() { + bsp_touch_read(); + uint16_t x = 0; + uint16_t y = 0; + if (!bsp_touch_get_coordinates(&x, &y)) return; + gLastTouchX = x; + gLastTouchY = y; + + if (contains(BTN_3WIRE, x, y)) { + setMode(Mode::ThreeWire); + drawStaticUi(); + } else if (contains(BTN_2WIRE, x, y)) { + setMode(Mode::TwoWire); + drawStaticUi(); + } else if (contains(BTN_RESET, x, y)) { + resetRange(); + } +} + +static void handleBootButton() { + bool down = digitalRead(PIN_BOOT_BUTTON) == LOW; + uint32_t now = millis(); + if (down != gBootWasDown && now - gBootLastChangeMs > 40) { + gBootWasDown = down; + gBootLastChangeMs = now; + if (!down) { + setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire); + drawStaticUi(); + } + } +} + +static void handleSerial() { + while (Serial.available() > 0) { + char c = (char)Serial.read(); + if (c == 'm' || c == 'M') { + setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire); + drawStaticUi(); + } else if (c == 'r' || c == 'R') { + resetRange(); + } + } +} + +void setup() { + Serial.begin(115200); + delay(100); + Serial.println("ESP32-S3-LCD-2 potentiometer ADC test"); + Serial.println("Commands: m=switch mode, r=reset min/max"); + + pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP); + configurePins(); + + if (!gfx->begin()) { + Serial.println("gfx->begin() failed"); + } + pinMode(PIN_LCD_BL, OUTPUT); + digitalWrite(PIN_LCD_BL, HIGH); + + Wire.begin(PIN_TP_SDA, PIN_TP_SCL); + gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H); + + drawStaticUi(); +} + +void loop() { + handleSerial(); + handleBootButton(); + if (gTouchOk) handleTouch(); + + uint32_t now = millis(); + if (now - gLastUiMs >= 250) { + updateUi(); + gLastUiMs = now; + } + if (now - gLastSerialMs >= 5000) { + Serial.println("Hint: m switches 3-WIRE/2-WIRE, r resets min/max. Never feed 5V into IO2/IO6."); + gLastSerialMs = now; + } +} diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/AGENTS.md b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/AGENTS.md new file mode 100644 index 00000000..c5a70794 --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/AGENTS.md @@ -0,0 +1,17 @@ +# AGENTS + +## Назначение папки + +Эта папка содержит отдельный Arduino-скетч `potentiometer_breath_monitor.ino` для Waveshare `ESP32-S3-LCD-2`. + +Скетч измеряет дыхательные циклы по трёхконтактно подключённому переменному резистору. Звук пока намеренно не используется. + +## Обязательная синхронизация + +При любом изменении `potentiometer_breath_monitor.ino` обязательно обновлять рядом лежащий `README.md`. + +Если меняются экранные тексты, пины, алгоритм определения фаз, настройки, touch-кнопки, serial-команды или логика паузы, описание в `README.md` должно быть обновлено в том же наборе изменений. + +## Язык экрана + +Экранные строки в скетче оставлять на английском языке. diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/README.md b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/README.md new file mode 100644 index 00000000..c4e99108 --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/README.md @@ -0,0 +1,57 @@ +# Potentiometer Breath Monitor for ESP32-S3-LCD-2 + +Отдельный скетч для Waveshare `ESP32-S3-LCD-2`, измеряющий дыхание по движению ползунка потенциометра. Звук в этой версии не подключается и не управляется. + +## Подключение + +Используется только устойчивый трёхконтактный вариант: + +- крайний контакт потенциометра -> `3V3` на разъёме `P2`; +- второй крайний контакт -> `GND`; +- средний контакт (ползунок) -> `GPIO2 / IO2` на разъёме `P1`. + +Нельзя подавать `5V` на `GPIO2`: входы ESP32-S3 не являются 5V tolerant. + +## Принцип работы + +- ADC считывается 40 раз в секунду и сглаживается. +- Абсолютная калибровка не нужна: медленное смещение ремня/пояса отслеживается отдельным медленным фоном. +- Направление определяется по сглаженному движению ползунка. В настройках выбирается, является ли движение вверх вдохом (`RISE INHALE`) или выдохом (`FALL INHALE`). +- Во время каждой фазы скетч запоминает достигнутый максимум или минимум без ограничения по времени. Разворот принимается только после накопленного обратного хода от этой точки. Поэтому вдох или выдох может длиться значительно дольше пяти секунд, а мелкий дребезг не создаёт дополнительные фазы. +- Порог обратного хода автоматически подстраивается к размаху недавнего движения и ограничен диапазоном `18..50 mV`. Он не зависит от скорости движения: даже очень плавный вдох в итоге будет распознан. +- Полный цикл измеряется от начала вдоха до начала следующего вдоха. Циклы короче `2.0 s` не попадают в статистику. +- Если движение не обнаруживается 60 секунд, отображается `PAUSE`. В этой версии звуковых сигналов нет. + +## Экран и управление + +Основной экран показывает: + +- живую кольцевую линию положения ползунка без полной перерисовки дисплея; +- текущую фазу `INHALE`, `EXHALE`, `FINDING MOTION` или `PAUSE`; +- положение и текущую длительность цикла; +- среднее последних пяти циклов и частоту в `bpm`; +- пять последних длительностей; +- время работы и выбранный предел `5 / 7 / 10 / 15 / 20 s`. + +Если среднее пяти циклов меньше выбранного предела, метрики и отметка `FAST` становятся красными. Позже к этому же условию можно добавить звук. + +`SET` на экране или короткое нажатие `BOOT / GPIO0` открывает настройки. Одно касание обрабатывается как одно действие. В настройках доступны предел и направление вдоха. `RESET` очищает текущую сессию и последние циклы. + +Постоянные части экрана рисуются один раз. В цикле обновляются только числа, статус и узкая колонка графика, поэтому весь экран не мигает. + +## Serial + +Скорость: `115200`. + +- `s` — открыть/закрыть настройки; +- `r` — сбросить сессию; +- `d` — сменить направление вдоха; +- `+` / `-` — изменить предел. + +## Сборка + +Из папки `main-device`: + +```bash +./burn.sh potentiometer-breath-monitor +``` diff --git a/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/potentiometer_breath_monitor.ino b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/potentiometer_breath_monitor.ino new file mode 100644 index 00000000..0a54a447 --- /dev/null +++ b/ESP32/esp32/ESP32-S3-LCD-2/main-device/test_sketches/potentiometer_breath_monitor/potentiometer_breath_monitor.ino @@ -0,0 +1,481 @@ +#include +#include +#include +#include + +#define PIN_LCD_SCLK 39 +#define PIN_LCD_MOSI 38 +#define PIN_LCD_MISO 40 +#define PIN_LCD_DC 42 +#define PIN_LCD_RST -1 +#define PIN_LCD_CS 45 +#define PIN_LCD_BL 1 + +#define PIN_TP_SDA 48 +#define PIN_TP_SCL 47 + +#define PIN_ADC_WIPER 2 +#define PIN_BOOT_BUTTON 0 + +static constexpr uint16_t DISP_W = 320; +static constexpr uint16_t DISP_H = 240; +static constexpr uint32_t SAMPLE_PERIOD_MS = 25; +static constexpr uint32_t UI_PERIOD_MS = 200; +static constexpr uint32_t PAUSE_AFTER_MS = 60000; +static constexpr uint32_t MIN_CYCLE_MS = 2000; +static constexpr uint16_t MIN_REVERSAL_MV = 18; +static constexpr uint16_t MAX_REVERSAL_MV = 50; +static constexpr uint8_t HISTORY_SIZE = 240; + +static constexpr uint16_t C_BG = 0x0841; +static constexpr uint16_t C_PANEL = 0x18E3; +static constexpr uint16_t C_CARD = 0x2126; +static constexpr uint16_t C_TEXT = 0xF7BE; +static constexpr uint16_t C_MUTE = 0x8C71; +static constexpr uint16_t C_ACCENT = 0x05DF; +static constexpr uint16_t C_OK = 0x47E8; +static constexpr uint16_t C_WARN = 0xFD20; +static constexpr uint16_t C_BAD = 0xF986; +static constexpr uint16_t C_BORDER = 0x4208; + +struct Rect { + int16_t x; + int16_t y; + int16_t w; + int16_t h; +}; + +enum class Phase : uint8_t { + Finding, + Inhale, + Exhale, + Pause, +}; + +Arduino_DataBus *bus = new Arduino_ESP32SPI( + PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO); +Arduino_GFX *gfx = new Arduino_ST7789( + bus, PIN_LCD_RST, 1, true, 240, 320); + +static const Rect BTN_SET = {252, 7, 58, 24}; +static const Rect BTN_RESET = {186, 7, 58, 24}; +static const Rect BTN_LIMIT_DOWN = {14, 82, 56, 34}; +static const Rect BTN_LIMIT_UP = {250, 82, 56, 34}; +static const Rect BTN_DIRECTION = {14, 138, 292, 34}; +static const Rect BTN_BACK = {92, 194, 136, 34}; + +static const uint8_t LIMITS_SEC[] = {5, 7, 10, 15, 20}; +static const uint8_t LIMIT_COUNT = sizeof(LIMITS_SEC) / sizeof(LIMITS_SEC[0]); + +static bool gTouchOk = false; +static bool gTouchWasDown = false; +static bool gSettingsOpen = false; +static bool gInhaleOnRising = true; +static bool gBootWasDown = false; +static uint32_t gBootChangedMs = 0; +static uint32_t gLastSampleMs = 0; +static uint32_t gLastUiMs = 0; +static uint32_t gLastSerialMs = 0; +static uint32_t gStartedMs = 0; +static uint32_t gLastMotionMs = 0; +static uint32_t gLastInhaleMs = 0; +static uint8_t gLimitIndex = 2; + +static bool gHasSignal = false; +static float gFilteredMv = 0.0f; +static float gBaselineMv = 0.0f; +static float gLastFilteredMv = 0.0f; +static float gExtremeMv = 0.0f; +static int8_t gDirection = 0; +static Phase gPhase = Phase::Finding; + +static uint16_t gHistory[HISTORY_SIZE] = {}; +static uint8_t gHistoryPos = 0; +static uint8_t gGraphX = 0; +static int16_t gGraphLastY = -1; +static uint32_t gCycleMs[5] = {}; +static uint8_t gCycleCount = 0; +static uint8_t gCycleNext = 0; + +static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) { + gfx->setTextSize(size); + gfx->setTextColor(color); + gfx->setCursor(x, y); + gfx->print(text); +} + +static void drawCentered(int16_t x, int16_t y, int16_t width, const char *text, uint16_t color, uint8_t size = 1) { + int16_t textWidth = strlen(text) * 6 * size; + drawText(x + max(0, (width - textWidth) / 2), y, text, color, size); +} + +static void drawButton(const Rect &r, const char *label, bool active = false) { + uint16_t fill = active ? C_ACCENT : C_CARD; + uint16_t text = active ? C_BG : C_TEXT; + gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill); + gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER); + drawCentered(r.x, r.y + 11, r.w, label, text, 1); +} + +static bool contains(const Rect &r, uint16_t x, uint16_t y) { + return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h; +} + +static uint16_t readMilliVolts() { + constexpr uint8_t COUNT = 8; + uint32_t sum = 0; + for (uint8_t i = 0; i < COUNT; ++i) { + sum += analogReadMilliVolts(PIN_ADC_WIPER); + } + return sum / COUNT; +} + +static uint16_t recentRangeMv() { + uint16_t low = 3300; + uint16_t high = 0; + uint8_t populated = gHasSignal ? HISTORY_SIZE : 0; + for (uint8_t i = 0; i < populated; ++i) { + low = min(low, gHistory[i]); + high = max(high, gHistory[i]); + } + return high > low ? high - low : 0; +} + +static uint16_t reversalThresholdMv() { + uint16_t range = recentRangeMv(); + return constrain(range / 10, MIN_REVERSAL_MV, MAX_REVERSAL_MV); +} + +static const char *phaseText() { + switch (gPhase) { + case Phase::Inhale: return "INHALE"; + case Phase::Exhale: return "EXHALE"; + case Phase::Pause: return "PAUSE"; + default: return "FINDING MOTION"; + } +} + +static uint16_t phaseColor() { + if (gPhase == Phase::Inhale) return C_ACCENT; + if (gPhase == Phase::Exhale) return C_OK; + if (gPhase == Phase::Pause) return C_BAD; + return C_WARN; +} + +static uint32_t averageCycleMs() { + if (gCycleCount == 0) return 0; + uint32_t sum = 0; + for (uint8_t i = 0; i < gCycleCount; ++i) sum += gCycleMs[i]; + return sum / gCycleCount; +} + +static void formatSeconds(char *out, size_t size, uint32_t ms) { + snprintf(out, size, "%lu.%lus", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100)); +} + +static void formatClock(char *out, size_t size, uint32_t ms) { + uint32_t sec = ms / 1000; + snprintf(out, size, "%02lu:%02lu", (unsigned long)(sec / 60), (unsigned long)(sec % 60)); +} + +static void resetSession() { + gStartedMs = millis(); + gLastMotionMs = gStartedMs; + gLastInhaleMs = 0; + gCycleCount = 0; + gCycleNext = 0; + memset(gCycleMs, 0, sizeof(gCycleMs)); + gDirection = 0; + gPhase = Phase::Finding; +} + +static void addCycle(uint32_t cycleMs) { + gCycleMs[gCycleNext] = cycleMs; + gCycleNext = (gCycleNext + 1) % 5; + if (gCycleCount < 5) ++gCycleCount; +} + +static void enterInhale(uint32_t now) { + if (gLastInhaleMs == 0) { + gLastInhaleMs = now; + } else { + uint32_t cycleMs = now - gLastInhaleMs; + if (cycleMs >= MIN_CYCLE_MS && cycleMs < PAUSE_AFTER_MS) { + addCycle(cycleMs); + gLastInhaleMs = now; + } else if (cycleMs >= PAUSE_AFTER_MS) { + gLastInhaleMs = now; + } + } + gPhase = Phase::Inhale; +} + +static void acceptDirection(int8_t direction, uint32_t now) { + gDirection = direction; + gExtremeMv = gFilteredMv; + bool isInhale = gInhaleOnRising ? direction > 0 : direction < 0; + if (isInhale) enterInhale(now); + else gPhase = Phase::Exhale; + gLastMotionMs = now; +} + +static void processSignal(uint16_t mv, uint32_t now) { + if (!gHasSignal) { + gHasSignal = true; + gFilteredMv = mv; + gBaselineMv = mv; + gLastFilteredMv = mv; + gExtremeMv = mv; + for (uint8_t i = 0; i < HISTORY_SIZE; ++i) gHistory[i] = mv; + return; + } + + gFilteredMv = gFilteredMv * 0.74f + mv * 0.26f; + // The background is for graph centering only. It must not erase a slow breath. + gBaselineMv = gBaselineMv * 0.9995f + gFilteredMv * 0.0005f; + gLastFilteredMv = gFilteredMv; + + gHistory[gHistoryPos] = (uint16_t)gFilteredMv; + gHistoryPos = (gHistoryPos + 1) % HISTORY_SIZE; + + uint16_t threshold = reversalThresholdMv(); + + if (gDirection == 0) { + float displacement = gFilteredMv - gExtremeMv; + if (fabsf(displacement) >= threshold) { + acceptDirection(displacement > 0 ? 1 : -1, now); + } + return; + } + + // Keep the extreme for as long as the phase lasts. A breath may be very slow: + // only accumulated travel away from that extreme can reverse the phase. + if ((gDirection > 0 && gFilteredMv >= gExtremeMv) || + (gDirection < 0 && gFilteredMv <= gExtremeMv)) { + gExtremeMv = gFilteredMv; + gLastMotionMs = now; + return; + } + + float awayFromExtreme = fabsf(gFilteredMv - gExtremeMv); + if (awayFromExtreme >= threshold) acceptDirection(-gDirection, now); +} + +static int16_t graphY(uint16_t mv) { + constexpr int16_t TOP = 43; + constexpr int16_t HEIGHT = 56; + uint16_t range = max(recentRangeMv(), 200); + float center = (float)(gBaselineMv); + float normalized = ((float)mv - center) / (float)range + 0.5f; + normalized = constrain(normalized, 0.0f, 1.0f); + return TOP + HEIGHT - 1 - (int16_t)(normalized * (HEIGHT - 1)); +} + +static void resetGraph() { + gfx->fillRect(10, 42, 300, 58, C_BG); + gfx->drawRect(9, 41, 302, 60, C_BORDER); + gGraphX = 0; + gGraphLastY = -1; +} + +static void drawGraphPoint() { + constexpr int16_t LEFT = 10; + constexpr int16_t TOP = 42; + constexpr int16_t HEIGHT = 58; + int16_t x = LEFT + gGraphX; + int16_t y = graphY((uint16_t)gFilteredMv); + gfx->fillRect(x, TOP, 2, HEIGHT, C_BG); + if (gGraphLastY >= TOP && gGraphX > 1) { + gfx->drawLine(x - 1, gGraphLastY, x, y, phaseColor()); + } + gfx->drawPixel(x, y, phaseColor()); + gGraphLastY = y; + gGraphX = (gGraphX + 2) % 300; +} + +static void drawMainStatic() { + gfx->fillScreen(C_BG); + drawText(10, 11, "BREATH MONITOR", C_TEXT, 2); + drawButton(BTN_RESET, "RESET"); + drawButton(BTN_SET, "SET"); + resetGraph(); + gfx->drawRoundRect(9, 108, 302, 48, 7, C_BORDER); + gfx->drawRoundRect(9, 162, 145, 39, 7, C_BORDER); + gfx->drawRoundRect(166, 162, 145, 39, 7, C_BORDER); + drawText(18, 170, "Average 5", C_MUTE, 1); + drawText(175, 170, "Rate", C_MUTE, 1); + gfx->drawRoundRect(9, 207, 302, 26, 6, C_BORDER); +} + +static void updateMainValues() { + char line[64]; + uint32_t now = millis(); + bool paused = gHasSignal && now - gLastMotionMs >= PAUSE_AFTER_MS; + if (paused) gPhase = Phase::Pause; + else if (gPhase == Phase::Pause) gPhase = Phase::Finding; + + gfx->fillRect(10, 109, 300, 46, C_BG); + drawCentered(10, 114, 300, phaseText(), phaseColor(), 2); + uint32_t currentMs = gLastInhaleMs == 0 ? 0 : now - gLastInhaleMs; + uint8_t position = constrain((int)((gFilteredMv / 3300.0f) * 100.0f), 0, 100); + snprintf(line, sizeof(line), "Position %u%% Current %lu.%lus threshold %umV", position, + (unsigned long)(currentMs / 1000), (unsigned long)((currentMs % 1000) / 100), reversalThresholdMv()); + drawCentered(10, 140, 300, line, C_MUTE, 1); + + uint32_t average = averageCycleMs(); + bool fastAverage = average > 0 && average < (uint32_t)LIMITS_SEC[gLimitIndex] * 1000UL; + uint16_t metricColor = fastAverage ? C_BAD : C_TEXT; + gfx->fillRect(10, 181, 143, 19, C_BG); + if (average == 0) drawText(18, 184, "--", C_TEXT, 2); + else { + formatSeconds(line, sizeof(line), average); + drawText(18, 184, line, metricColor, 2); + } + + gfx->fillRect(167, 181, 143, 19, C_BG); + if (average == 0) drawText(175, 184, "-- bpm", C_TEXT, 2); + else { + float bpm = 60000.0f / average; + snprintf(line, sizeof(line), "%.1f bpm", bpm); + drawText(175, 184, line, metricColor, 2); + } + + gfx->fillRect(10, 208, 300, 24, C_BG); + char cycles[80] = "Last: "; + for (uint8_t i = 0; i < gCycleCount; ++i) { + uint8_t index = (gCycleNext + 5 - gCycleCount + i) % 5; + char value[12]; + formatSeconds(value, sizeof(value), gCycleMs[index]); + strlcat(cycles, value, sizeof(cycles)); + if (i + 1 < gCycleCount) strlcat(cycles, " ", sizeof(cycles)); + } + if (gCycleCount == 0) strlcat(cycles, "--", sizeof(cycles)); + drawText(16, 215, cycles, C_TEXT, 1); + + gfx->fillRect(10, 234, 300, 6, C_BG); + char clock[12]; + formatClock(clock, sizeof(clock), now - gStartedMs); + snprintf(line, sizeof(line), "Run %s Limit %us %s%s", clock, LIMITS_SEC[gLimitIndex], + gInhaleOnRising ? "rise=in" : "fall=in", fastAverage ? " FAST" : ""); + drawText(11, 234, line, fastAverage ? C_BAD : C_MUTE, 1); +} + +static void drawSettings() { + gfx->fillScreen(C_BG); + drawText(10, 12, "SETTINGS", C_TEXT, 2); + drawText(10, 38, "Target average cycle", C_MUTE, 1); + drawButton(BTN_LIMIT_DOWN, "-"); + drawButton(BTN_LIMIT_UP, "+"); + char value[16]; + snprintf(value, sizeof(value), "%u s", LIMITS_SEC[gLimitIndex]); + drawCentered(70, 92, 180, value, C_ACCENT, 3); + drawText(10, 128, "Inhale direction", C_MUTE, 1); + drawButton(BTN_DIRECTION, gInhaleOnRising ? "RISE = INHALE" : "FALL = INHALE", true); + drawText(18, 178, "No calibration. Audio disabled.", C_MUTE, 1); + drawButton(BTN_BACK, "BACK"); +} + +static void toggleSettings() { + gSettingsOpen = !gSettingsOpen; + if (gSettingsOpen) drawSettings(); + else drawMainStatic(); +} + +static void changeLimit(int8_t delta) { + int16_t next = (int16_t)gLimitIndex + delta; + gLimitIndex = constrain(next, 0, (int16_t)LIMIT_COUNT - 1); + if (gSettingsOpen) drawSettings(); +} + +static void handleTouch() { + bsp_touch_read(); + uint16_t x = 0; + uint16_t y = 0; + if (!bsp_touch_get_coordinates(&x, &y)) { + gTouchWasDown = false; + return; + } + if (gTouchWasDown) return; + gTouchWasDown = true; + + if (!gSettingsOpen) { + if (contains(BTN_SET, x, y)) toggleSettings(); + else if (contains(BTN_RESET, x, y)) { + resetSession(); + resetGraph(); + } + return; + } + if (contains(BTN_LIMIT_DOWN, x, y)) changeLimit(-1); + else if (contains(BTN_LIMIT_UP, x, y)) changeLimit(1); + else if (contains(BTN_DIRECTION, x, y)) { + gInhaleOnRising = !gInhaleOnRising; + drawSettings(); + } else if (contains(BTN_BACK, x, y)) toggleSettings(); +} + +static void handleBootButton() { + bool down = digitalRead(PIN_BOOT_BUTTON) == LOW; + uint32_t now = millis(); + if (down != gBootWasDown && now - gBootChangedMs >= 45) { + gBootWasDown = down; + gBootChangedMs = now; + if (!down) toggleSettings(); + } +} + +static void handleSerial() { + while (Serial.available()) { + char c = (char)Serial.read(); + if (c == 's' || c == 'S') toggleSettings(); + else if (c == 'r' || c == 'R') resetSession(); + else if (c == 'd' || c == 'D') { + gInhaleOnRising = !gInhaleOnRising; + if (gSettingsOpen) drawSettings(); + } else if (c == '+') changeLimit(1); + else if (c == '-') changeLimit(-1); + } +} + +void setup() { + Serial.begin(115200); + delay(100); + Serial.println("ESP32-S3-LCD-2 potentiometer breath monitor"); + Serial.println("Commands: s=settings r=reset d=direction +/-=limit"); + + pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP); + pinMode(PIN_ADC_WIPER, INPUT); + analogReadResolution(12); + analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db); + + gfx->begin(); + pinMode(PIN_LCD_BL, OUTPUT); + digitalWrite(PIN_LCD_BL, HIGH); + Wire.begin(PIN_TP_SDA, PIN_TP_SCL); + gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H); + resetSession(); + drawMainStatic(); +} + +void loop() { + handleSerial(); + handleBootButton(); + if (gTouchOk) handleTouch(); + + uint32_t now = millis(); + if (now - gLastSampleMs >= SAMPLE_PERIOD_MS) { + processSignal(readMilliVolts(), now); + if (!gSettingsOpen && gHasSignal) drawGraphPoint(); + gLastSampleMs = now; + } + if (!gSettingsOpen && now - gLastUiMs >= UI_PERIOD_MS) { + updateMainValues(); + gLastUiMs = now; + } + if (now - gLastSerialMs >= 2000 && gHasSignal) { + Serial.printf("mv=%.0f base=%.0f range=%u threshold=%u phase=%s cycles=%u avg=%lu\n", + gFilteredMv, gBaselineMv, recentRangeMv(), reversalThresholdMv(), phaseText(), + gCycleCount, (unsigned long)averageCycleMs()); + gLastSerialMs = now; + } +} diff --git a/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/AGENTS.md b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/AGENTS.md new file mode 100644 index 00000000..e0d42acf --- /dev/null +++ b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/AGENTS.md @@ -0,0 +1,28 @@ +# AGENTS + +## Назначение папки + +Эта папка содержит отдельный ESP32-скетч `breath_dual_mode_monitor.ino` для Waveshare `ESP32-S3-Touch-AMOLED-2.16`. + +Скетч совмещает два режима измерения дыхания: + +- `START USB SENSOR` — датчик-сухой контакт на USB `D- / D+`; +- `START MANUAL MONITOR` — ручной монитор с двумя внешними кнопками пользователя `KEY3 / GPIO18` и `BOOT / GPIO0`. +- `START POT 3-WIRE` — тест переменного резистора по 3-проводной схеме через `USB D- / D+ / GND`. +- `START POT 2-WIRE` — грубый тест переменного резистора по двум контактам `USB D- / D+`. +- `START POT CAL` — калиброванный грубый тест переменного резистора по двум контактам `USB D- / D+`. +- `START PIN DIAG` — диагностика возможности использовать `USB D- / D+` как GPIO/ADC. + +## Обязательная синхронизация + +При любом изменении `breath_dual_mode_monitor.ino` обязательно обновлять рядом лежащий `README.md`. + +Если меняются экранные тексты, кнопки, режимы старта, пины, настройки, звуковые сигналы, правила подсчёта циклов или поведение тревоги после 60 секунд, описание в `README.md` должно быть обновлено в том же наборе изменений. + +Также при изменении поведения скетча обновлять общий reference-документ: + +- `../../../../reference/usb_contact_sensor_test_spec.md` + +## Язык экрана + +Экранные строки в скетче оставлять на английском языке. diff --git a/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/README.md b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/README.md new file mode 100644 index 00000000..d631a5ec --- /dev/null +++ b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/README.md @@ -0,0 +1,147 @@ +# Breath Dual Mode Monitor + +Dual-mode breath monitor для Waveshare `ESP32-S3-Touch-AMOLED-2.16`. + +## Режимы + +На стартовом экране есть кнопки выбора режима: + +- `START USB SENSOR` — использует USB `D- / D+` как сухой контакт. +- `START MANUAL MONITOR` — ручной монитор, использующий две внешние кнопки пользователя. +- `START POT 3-WIRE` — использует USB `D- / D+` и `USB GND` для проверки переменного резистора. +- `START POT 2-WIRE` — грубо оценивает положение переменного резистора только по `D- / D+`. +- `START POT CAL` — калиброванный грубый режим по двум контактам `D- / D+`, показывает положение внутри реально увиденного диапазона. +- `START PIN DIAG` — диагностирует, могут ли USB `D- / D+` реально работать как GPIO/ADC. + +## USB Sensor Mode + +- `GPIO19 / USB D-` переводится в `OUTPUT LOW`. +- `GPIO20 / USB D+` переводится в `INPUT_PULLUP`. +- Замкнутый контакт считается `EXHALE`. +- Разомкнутый контакт считается `INHALE`. +- Короткие USB-циклы меньше 3 секунд не считаются завершённым циклом: время текущего цикла продолжает идти от предыдущего принятого `EXHALE`. +- Короткое нажатие `KEY3 / GPIO18` открывает или закрывает settings в USB-режиме. +- Внизу рабочего экрана USB-режима показываются длительности последних пяти засчитанных циклов. +- После старта USB data-линии заняты GPIO-режимом до перезагрузки. + +## Buttons Mode + +- `KEY3 / GPIO18` — `INHALE`, active LOW. +- `BOOT / GPIO0` — `EXHALE`, active LOW. +- `BOOT` нельзя удерживать во время включения или reset платы. +- На рабочем экране нет touch-кнопок `INHALE` / `EXHALE`: дыхание переключается только внешними кнопками. +- Долгое удержание `KEY3 / INHALE` около 850 мс открывает settings и одновременно считается нажатием `INHALE`. +- Когда settings открыты, следующее нажатие `KEY3 / INHALE` закрывает settings и тоже считается нажатием `INHALE`. + +## Pot Test Mode + +Режим для проверки переменного резистора `RP 6045-B50K` на 50 kΩ по 3-проводной схеме: + +- `USB D- / GPIO19` — источник `3.3V`, подключается к одному крайнему выводу резистора. +- `USB D+ / GPIO20` — ADC-вход, подключается к средней ножке/ползунку. +- `USB GND` — земля, подключается ко второму крайнему выводу резистора. + +На экране показываются: + +- положение ползунка `0..100%`; +- горизонтальная шкала; +- напряжение на `D+`; +- raw ADC; +- примерное сопротивление участка `0..50 kΩ`. + +Программная защита best-effort: + +- если ADC насыщается или показывает опасно высокое напряжение, скетч переводит `D-` и `D+` в `INPUT`, пищит и показывает `USB/PIN FAULT`; +- это не делает 5V на GPIO безопасными: ESP32-S3 GPIO не являются 5V tolerant; +- после fault нужно отключить неправильное подключение и перезагрузить плату. + +## Pot 2-Wire Test Mode + +Грубый режим для проверки переменного резистора по двум контактам: + +- `USB D- / GPIO19` — источник `3.3V`; +- `USB D+ / GPIO20` — ADC-вход с внутренней подтяжкой вниз; +- подключить два вывода потенциометра между `D-` и `D+`: средний ползунок и один крайний вывод. + +Ограничения: + +- измерение грубое, потому что внутренняя подтяжка ESP32 имеет большой разброс; +- положение и сопротивление могут быть нелинейными и отличаться между платами; +- для проверки движения ползунка и примерного края диапазона режим подходит; +- для будущей точной логики дыхания лучше использовать `START POT 3-WIRE`. + +## Pot Cal Test Mode + +Калиброванный грубый режим для случаев, когда USB-линии дают маленький или смещённый диапазон, но движение всё равно видно: + +- `USB D- / GPIO19` — источник `3.3V`; +- `USB D+ / GPIO20` — ADC-вход с внутренней подтяжкой вниз; +- подключить два вывода потенциометра между `D-` и `D+`: средний ползунок и один крайний вывод. + +На экране показываются: + +- процент `0..100%` внутри автоматически найденного диапазона; +- текущие `mV` и raw ADC; +- найденный диапазон `min-max`; +- состояние `CALIBRATING`, `SMALL RANGE`, `LOW EDGE`, `MID` или `HIGH EDGE`. + +Как пользоваться: + +- открыть `START POT CAL`; +- медленно провести ползунок от одного края до другого, чтобы скетч запомнил минимум и максимум; +- если нужно начать калибровку заново, нажать `KEY3 / GPIO18`. + +Этот режим не измеряет настоящее сопротивление. Он нужен, чтобы понять, можно ли получить хотя бы относительное положение ползунка на проблемной USB-паре. + +## USB Pin Diag Mode + +Режим для проверки, не удерживает ли USB PHY/кабель линии `D- / D+` около нуля. + +Тесты: + +- `Test A`: `D- / GPIO19` переводится в `OUTPUT HIGH`, `D+ / GPIO20` читается как ADC. +- `Test B`: `D+ / GPIO20` переводится в `OUTPUT HIGH`, `D- / GPIO19` читается как ADC. + +Как пользоваться: + +- открыть `START PIN DIAG`; +- замкнуть `D-` и `D+` напрямую; +- смотреть, появляется ли около `3.3V` / высокий ADC хотя бы в одном направлении. + +Если оба теста остаются около нуля, значит USB-линии, вероятно, удерживаются USB-подключением, USB PHY или платной обвязкой, и использовать этот разъём как аналоговый датчик при таком подключении нельзя. + +## Логика дыхания + +- Цикл считается от одного `EXHALE` до следующего `EXHALE`. +- `INHALE` до первого `EXHALE` не создаёт цикл. +- В Buttons Mode циклы короче 1.5 секунды игнорируются. +- Ручной монитор принимает фазы только в порядке `INHALE -> EXHALE -> INHALE`. Повторное нажатие текущей кнопки и `EXHALE` до первого `INHALE` полностью игнорируются: не меняют фазу, не сбрасывают таймер и не подают звук. +- Каждое принятое нажатие даёт один тихий подтверждающий сигнал. В ручном режиме поле `Phase time` показывает длительность именно текущего вдоха или выдоха. +- В USB Sensor Mode циклы короче 3 секунд игнорируются без сброса текущего таймера цикла. +- Среднее считается по последним 5 завершённым циклам. +- Экран показывает текущий цикл, среднее за 5 циклов, время сессии, выбранный лимит и счётчики тревог. +- Нижние два числовых поля (`From start` и `Limit`) выводятся увеличенным размером. + +## Settings + +Settings сохраняются в NVS: + +- limit: `5 / 7 / 10 / 15 / 20` секунд; +- quiet cycle tick volume: `0..10`; +- alert volume: `0..10`. + +## Тревоги + +- Если среднее последних циклов меньше выбранного лимита, звучат предупреждения как в USB breath monitor: серия растёт до 5 сигналов. +- Если текущий цикл длится 60 секунд, звучит 5 громких сигналов. +- После этого каждые 5 секунд снова звучит серия из 5 громких сигналов. +- Повтор продолжается до смены фазы / выхода из длинного цикла. +- В ручном мониторе для одной затянувшейся фазы звучит один громкий сигнал на `35`, `40`, `45`, `50` и `55` секундах. С `60` секунд начинается обычная серия из 5 громких сигналов с повтором каждые 5 секунд. + +## Прошивка + +Из папки `main-device`: + +```bash +./burn.sh breath-dual-mode-monitor +``` diff --git a/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/breath_dual_mode_monitor.ino b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/breath_dual_mode_monitor.ino new file mode 100644 index 00000000..d4e29b5a --- /dev/null +++ b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/breath_dual_mode_monitor.ino @@ -0,0 +1,1169 @@ +#include +#include +#include +#include +#include +#include +#include "ESP_I2S.h" +#include "es8311.h" + +#define PIN_LCD_CS 12 +#define PIN_LCD_SCLK 38 +#define PIN_LCD_D0 4 +#define PIN_LCD_D1 5 +#define PIN_LCD_D2 6 +#define PIN_LCD_D3 7 +#define PIN_LCD_RST 2 +#define PIN_I2C_SDA 15 +#define PIN_I2C_SCL 14 +#define PIN_TP_INT 11 +#define PIN_INHALE 18 +#define PIN_EXHALE 0 +#define PIN_PA 46 +#define PIN_I2S_BCLK 9 +#define PIN_I2S_LRCK 45 +#define PIN_I2S_DOUT 8 +#define PIN_I2S_DIN 10 +#define PIN_I2S_MCLK 42 + +#define DISP_W 480 +#define DISP_H 480 + +static constexpr uint32_t kUiPeriodMs = 200; +static constexpr uint32_t kSampleRate = 16000; +static constexpr uint32_t kMinCycleMs = 1500; +static constexpr uint32_t kUsbMinCycleMs = 3000; +static constexpr uint32_t kPauseAfterMs = 60000; +static constexpr uint32_t kLongPressMs = 850; +static constexpr uint32_t kButtonDebounceMs = 45; +static constexpr uint32_t kContactDebounceMs = 80; +static constexpr uint32_t kRepeatAlertMs = 5000; +static constexpr uint32_t kPotUiPeriodMs = 120; +static constexpr uint32_t kPotSamples = 24; +static constexpr uint32_t kPinDiagPeriodMs = 350; +static constexpr uint32_t kPotOvervoltageMv = 3400; +static constexpr float kPotOhms = 50000.0f; +static constexpr float kApproxInternalPulldownOhms = 45000.0f; +static constexpr int kUsbDmPin = 19; +static constexpr int kUsbDpPin = 20; + +#define C_BG 0x0841u +#define C_PANEL 0x1082u +#define C_CARD 0x18C3u +#define C_BORDER 0x39C7u +#define C_TEXT 0xFFFFu +#define C_MUTE 0xBDF7u +#define C_ACCENT 0x5D5Fu +#define C_OK 0x3666u +#define C_BAD 0xD145u +#define C_BUTTON 0x2145u + +Arduino_DataBus *gBus = new Arduino_ESP32QSPI( + PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3); +Arduino_CO5300 *gfx = new Arduino_CO5300( + gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0); + +TouchDrvCST92xx gTouch; +I2SClass gI2s; +Preferences gPrefs; + +struct Rect { + int16_t x; + int16_t y; + int16_t w; + int16_t h; +}; + +struct DebouncedButton { + int pin; + bool rawPressed = false; + bool stablePressed = false; + uint32_t rawChangedMs = 0; + uint32_t pressedAtMs = 0; +}; + +enum class InputMode : uint8_t { + None, + UsbContact, + ExternalButtons, + PotTest, + PotTwoWireTest, + UsbPinDiag, + PotCalTest, +}; + +static const Rect kStartUsbButton = {44, 198, 392, 34}; +static const Rect kStartButtonsButton = {44, 238, 392, 34}; +static const Rect kStartPotButton = {44, 278, 392, 34}; +static const Rect kStartPot2Button = {44, 318, 392, 34}; +static const Rect kStartPotCalButton = {44, 358, 392, 34}; +static const Rect kStartPinDiagButton = {44, 398, 392, 34}; +static const Rect kLimitSlider = {42, 158, 396, 44}; +static const Rect kTickSlider = {42, 270, 396, 44}; +static const Rect kAlertSlider = {42, 382, 396, 44}; +static const uint16_t kLimitsSec[] = {5, 7, 10, 15, 20}; +static const int16_t kTickAmpByVolume[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600}; +static const int16_t kAlertAmpByVolume[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000}; + +static bool gStarted = false; +static InputMode gInputMode = InputMode::None; +static bool gSettingsOpen = false; +static bool gAudioReady = false; +static bool gInExhale = false; +static bool gButtonPhaseKnown = false; +static bool gInhalePressClosedSettings = false; +static bool gNeedRedraw = true; +static bool gNeedStaticRedraw = true; +static bool gStaticDrawn = false; +static bool gLastDrawnExhale = true; +static bool gLongPauseActive = false; +static bool gLastDrawnPaused = true; +static bool gTouchDown = false; +static bool gPotFault = false; +static bool gLastRawClosed = false; +static uint32_t gLastRawChangeMs = 0; +static DebouncedButton gInhaleButton{PIN_INHALE}; +static DebouncedButton gExhaleButton{PIN_EXHALE}; +static int16_t gTouchStartX = 0; +static int16_t gTouchStartY = 0; +static int16_t gTouchLastX = 0; +static int16_t gTouchLastY = 0; +static uint32_t gTouchDownMs = 0; +static uint32_t gStartedMs = 0; +static uint32_t gLastCycleStartMs = 0; +static uint32_t gPhaseStartMs = 0; +static uint32_t gLastUiMs = 0; +static uint32_t gLastPotUiMs = 0; +static uint32_t gLastPinDiagUiMs = 0; +static uint32_t gPotCalMinMv = 0xFFFFFFFF; +static uint32_t gPotCalMaxMv = 0; +static uint32_t gCycleMs[5] = {}; +static uint8_t gCycleCount = 0; +static uint8_t gCycleNext = 0; +static uint8_t gLimitIndex = 2; +static uint8_t gTickVolume = 3; +static uint8_t gAlertVolume = 10; +static uint8_t gShortStreak = 0; +static uint16_t gShortAvgEvents = 0; +static uint16_t gLongPauseEvents = 0; +static uint32_t gLastRepeatAlertMs = 0; +static uint8_t gLastSinglePhaseAlertSlot = 0; +static char gLastTopLine[56] = ""; +static char gLastBottomLine[64] = ""; + +static void releaseUsbPins() { + pinMode(kUsbDmPin, INPUT); + pinMode(kUsbDpPin, INPUT); +} + +static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) { + gfx->fillRoundRect(x, y, w, h, radius, fill); + gfx->drawRoundRect(x, y, w, h, radius, border); +} + +static void drawText(int x, int y, const char *text, uint16_t color, uint8_t size = 2) { + gfx->setFont(); + gfx->setTextSize(size); + gfx->setTextColor(color); + gfx->setCursor(x, y); + gfx->print(text); +} + +static void drawCenteredText(int x, int y, int w, const char *text, uint16_t color, uint8_t size = 2) { + int textW = strlen(text) * 6 * size; + int textX = x + (w - textW) / 2; + if (textX < x + 8) { + textX = x + 8; + } + drawText(textX, y, text, color, size); +} + +static void drawButton(const Rect &rect, const char *label, uint16_t fill, uint8_t size = 2) { + drawPanel(rect.x, rect.y, rect.w, rect.h, fill, C_BORDER, 12); + drawCenteredText(rect.x, rect.y + 15, rect.w, label, C_TEXT, size); +} + +static bool pollPressedEdge(DebouncedButton &button, uint32_t now) { + bool raw = (digitalRead(button.pin) == LOW); + if (raw != button.rawPressed) { + button.rawPressed = raw; + button.rawChangedMs = now; + } + + if (button.stablePressed != button.rawPressed && + (uint32_t)(now - button.rawChangedMs) >= kButtonDebounceMs) { + button.stablePressed = button.rawPressed; + if (button.stablePressed) { + button.pressedAtMs = now; + } + return button.stablePressed; + } + + return false; +} + +static bool pollReleasedEdge(DebouncedButton &button, uint32_t now, uint32_t &heldMs) { + bool raw = (digitalRead(button.pin) == LOW); + if (raw != button.rawPressed) { + button.rawPressed = raw; + button.rawChangedMs = now; + } + + if (button.stablePressed != button.rawPressed && + (uint32_t)(now - button.rawChangedMs) >= kButtonDebounceMs) { + button.stablePressed = button.rawPressed; + if (!button.stablePressed) { + heldMs = now - button.pressedAtMs; + return true; + } + } + + return false; +} + +static void pollButtonEvent(DebouncedButton &button, uint32_t now, + bool &pressed, bool &released, uint32_t &heldMs) { + pressed = false; + released = false; + heldMs = 0; + + bool raw = (digitalRead(button.pin) == LOW); + if (raw != button.rawPressed) { + button.rawPressed = raw; + button.rawChangedMs = now; + } + + if (button.stablePressed == button.rawPressed || + (uint32_t)(now - button.rawChangedMs) < kButtonDebounceMs) { + return; + } + + button.stablePressed = button.rawPressed; + if (button.stablePressed) { + button.pressedAtMs = now; + pressed = true; + } else { + heldMs = now - button.pressedAtMs; + released = true; + } +} + +static bool contains(const Rect &rect, int16_t x, int16_t y) { + return x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h; +} + +static void clearArea(int x, int y, int w, int h, uint16_t fill) { + gfx->fillRect(x, y, w, h, fill); +} + +static void formatSec(char *out, size_t outSize, uint32_t ms) { + snprintf(out, outSize, "%lu.%01lus", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100)); +} + +static void formatClock(char *out, size_t outSize, uint32_t ms) { + uint32_t sec = ms / 1000; + snprintf(out, outSize, "%02lu:%02lu", (unsigned long)(sec / 60), (unsigned long)(sec % 60)); +} + +static uint32_t averageCycleMs() { + if (gCycleCount == 0) { + return 0; + } + uint32_t sum = 0; + for (uint8_t i = 0; i < gCycleCount; i++) { + sum += gCycleMs[i]; + } + return sum / gCycleCount; +} + +static uint32_t minCycleMsForCurrentMode() { + return gInputMode == InputMode::UsbContact ? kUsbMinCycleMs : kMinCycleMs; +} + +static const char *modeTitle() { + if (gInputMode == InputMode::UsbContact) return "USB BREATH"; + if (gInputMode == InputMode::ExternalButtons) return "MANUAL MONITOR"; + if (gInputMode == InputMode::PotTest) return "POT TEST"; + if (gInputMode == InputMode::PotTwoWireTest) return "POT 2W TEST"; + if (gInputMode == InputMode::UsbPinDiag) return "USB PIN DIAG"; + if (gInputMode == InputMode::PotCalTest) return "POT CAL TEST"; + return "BREATH MONITOR"; +} + +static uint32_t readPotMilliVolts(uint32_t *rawOut) { + uint32_t rawSum = 0; + uint32_t mvSum = 0; + for (uint32_t i = 0; i < kPotSamples; i++) { + rawSum += analogRead(kUsbDpPin); + mvSum += analogReadMilliVolts(kUsbDpPin); + delayMicroseconds(250); + } + if (rawOut) { + *rawOut = rawSum / kPotSamples; + } + return mvSum / kPotSamples; +} + +static uint32_t readAdcMilliVolts(int pin, uint32_t *rawOut) { + uint32_t rawSum = 0; + uint32_t mvSum = 0; + for (uint32_t i = 0; i < kPotSamples; i++) { + rawSum += analogRead(pin); + mvSum += analogReadMilliVolts(pin); + delayMicroseconds(250); + } + if (rawOut) { + *rawOut = rawSum / kPotSamples; + } + return mvSum / kPotSamples; +} + +static void formatLastFiveCycles(char *out, size_t outSize) { + if (gCycleCount == 0) { + snprintf(out, outSize, "Last 5: --"); + return; + } + + size_t used = snprintf(out, outSize, "Last 5:"); + for (uint8_t i = 0; i < gCycleCount && used < outSize; i++) { + uint8_t idx = (gCycleNext + 5 - gCycleCount + i) % 5; + uint32_t ms = gCycleMs[idx]; + used += snprintf(out + used, outSize - used, " %u:%lu.%lu", + (unsigned)(i + 1), + (unsigned long)(ms / 1000), + (unsigned long)((ms % 1000) / 100)); + } +} + +static void resetCachedUiText() { + gLastTopLine[0] = '\0'; + gLastBottomLine[0] = '\0'; +} + +static void loadSettings() { + gPrefs.begin("manual-br", false); + gLimitIndex = gPrefs.getUChar("limit", gLimitIndex); + gTickVolume = gPrefs.getUChar("tick", gTickVolume); + gAlertVolume = gPrefs.getUChar("alert", gAlertVolume); + if (gLimitIndex > 4) gLimitIndex = 2; + if (gTickVolume > 10) gTickVolume = 3; + if (gAlertVolume > 10) gAlertVolume = 10; +} + +static void saveSettings() { + gPrefs.putUChar("limit", gLimitIndex); + gPrefs.putUChar("tick", gTickVolume); + gPrefs.putUChar("alert", gAlertVolume); +} + +static esp_err_t codecInit() { + es8311_handle_t esHandle = es8311_create(0, ES8311_ADDRRES_0); + if (!esHandle) return ESP_FAIL; + const es8311_clock_config_t clk = { + .mclk_inverted = false, + .sclk_inverted = false, + .mclk_from_mclk_pin = true, + .mclk_frequency = (int)kSampleRate * 256, + .sample_frequency = (int)kSampleRate, + }; + if (es8311_init(esHandle, &clk, ES8311_RESOLUTION_16, ES8311_RESOLUTION_16) != ESP_OK) { + return ESP_FAIL; + } + es8311_voice_volume_set(esHandle, 100, nullptr); + es8311_voice_mute(esHandle, false); + return ESP_OK; +} + +static void initAudio() { + pinMode(PIN_PA, OUTPUT); + digitalWrite(PIN_PA, HIGH); + gI2s.setPins(PIN_I2S_BCLK, PIN_I2S_LRCK, PIN_I2S_DOUT, PIN_I2S_DIN, PIN_I2S_MCLK); + if (!gI2s.begin(I2S_MODE_STD, kSampleRate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO, I2S_STD_SLOT_BOTH)) { + Serial.println("I2S init failed"); + return; + } + gAudioReady = (codecInit() == ESP_OK); + Serial.println(gAudioReady ? "Audio init OK" : "Audio codec init failed"); +} + +static void playBeep(uint16_t freq, uint16_t samples, int16_t amp) { + if (!gAudioReady || amp <= 0) return; + static int16_t toneBuf[1600 * 2]; + if (samples > 1600) samples = 1600; + for (int i = 0; i < samples; i++) { + float s = sinf(2.0f * 3.1415926f * (float)freq * ((float)i / (float)kSampleRate)); + int16_t v = (int16_t)(s * amp); + toneBuf[i * 2] = v; + toneBuf[i * 2 + 1] = v; + } + gI2s.write((uint8_t *)toneBuf, samples * 2 * sizeof(int16_t)); +} + +static void playCycleTick() { + playBeep(880, 480, kTickAmpByVolume[gTickVolume]); +} + +static void playAlertBeep() { + playBeep(1200, 1600, kAlertAmpByVolume[gAlertVolume]); +} + +static void playFiveAlertBeeps() { + for (uint8_t i = 0; i < 5; i++) { + playAlertBeep(); + delay(80); + } +} + +static void alertIfNeeded() { + if (gShortStreak == 0) return; + uint8_t count = min(gShortStreak, 5); + for (uint8_t i = 0; i < count; i++) { + playAlertBeep(); + delay(80); + } +} + +static void addCycle(uint32_t cycleMs) { + gCycleMs[gCycleNext] = cycleMs; + gCycleNext = (gCycleNext + 1) % 5; + if (gCycleCount < 5) { + gCycleCount++; + } + + uint32_t avgMs = averageCycleMs(); + if (avgMs > 0 && avgMs < (uint32_t)kLimitsSec[gLimitIndex] * 1000UL) { + if (gShortStreak < 5) gShortStreak++; + gShortAvgEvents++; + } else { + gShortStreak = 0; + } +} + +static void drawReadyScreen() { + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 42, "BREATH MONITOR", C_TEXT, 3); + drawText(28, 78, "Choose input mode", C_MUTE, 2); + drawPanel(34, 112, 412, 84, C_CARD, C_BORDER, 14); + drawCenteredText(34, 132, 412, "USB / buttons / pots", C_ACCENT, 2); + drawCenteredText(34, 166, 412, "plus USB pin diagnostics", C_TEXT, 1); + drawButton(kStartUsbButton, "START USB SENSOR", C_BUTTON, 2); + drawButton(kStartButtonsButton, "START MANUAL MONITOR", C_OK, 2); + drawButton(kStartPotButton, "START POT 3-WIRE", C_ACCENT, 2); + drawButton(kStartPot2Button, "START POT 2-WIRE", C_BUTTON, 2); + drawButton(kStartPotCalButton, "START POT CAL", C_OK, 2); + drawButton(kStartPinDiagButton, "START PIN DIAG", C_BAD, 2); +} + +static void drawSlider(const Rect &rect, const char *title, const char *value, uint8_t pos, uint8_t maxPos) { + drawText(rect.x, rect.y - 28, title, C_TEXT, 2); + drawText(rect.x + 278, rect.y - 28, value, C_ACCENT, 2); + drawPanel(rect.x, rect.y, rect.w, rect.h, C_BUTTON, C_BORDER, 12); + int trackX = rect.x + 22; + int trackW = rect.w - 44; + int trackY = rect.y + rect.h / 2 - 3; + gfx->fillRect(trackX, trackY, trackW, 6, C_BORDER); + int knobX = trackX + (trackW * pos) / max(1, maxPos); + gfx->fillRoundRect(knobX - 10, rect.y + 8, 20, rect.h - 16, 8, C_ACCENT); +} + +static void drawSettingsScreen() { + char value[24]; + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 32, "SETTINGS", C_TEXT, 3); + drawText(28, 82, "Press INHALE to close", C_MUTE, 2); + + snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]); + drawSlider(kLimitSlider, "Limit", value, gLimitIndex, 4); + snprintf(value, sizeof(value), "%u/10", gTickVolume); + drawSlider(kTickSlider, "Cycle tick volume", value, gTickVolume, 10); + snprintf(value, sizeof(value), "%u/10", gAlertVolume); + drawSlider(kAlertSlider, "Alert volume", value, gAlertVolume, 10); + + gStaticDrawn = false; + gNeedStaticRedraw = true; +} + +static void drawMonitorStatic() { + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 32, modeTitle(), C_TEXT, 2); + drawPanel(28, 102, 424, 96, C_CARD, C_BORDER, 14); + drawPanel(28, 216, 200, 72, C_CARD, C_BORDER, 10); + drawText(42, 236, gInputMode == InputMode::ExternalButtons ? "Phase time" : "Current", C_MUTE, 1); + drawPanel(252, 216, 200, 72, C_CARD, C_BORDER, 10); + drawText(266, 236, "Average 5", C_MUTE, 1); + drawPanel(28, 304, 200, 64, C_CARD, C_BORDER, 10); + drawText(42, 322, "From start", C_MUTE, 1); + drawPanel(252, 304, 200, 64, C_CARD, C_BORDER, 10); + drawText(266, 322, "Limit", C_MUTE, 1); + gStaticDrawn = true; + gLastDrawnExhale = !gInExhale; + gLastDrawnPaused = !gLongPauseActive; + resetCachedUiText(); +} + +static void drawPotStatic() { + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 32, modeTitle(), C_TEXT, 3); + drawText(28, 72, + gInputMode == InputMode::PotTwoWireTest ? "D-=3.3V D+=wiper/edge rough" : "D-=3.3V D+=wiper GND=edge", + C_MUTE, 1); + drawPanel(28, 112, 424, 88, C_CARD, C_BORDER, 14); + drawPanel(28, 220, 424, 44, C_CARD, C_BORDER, 10); + drawPanel(28, 288, 200, 72, C_CARD, C_BORDER, 10); + drawText(42, 308, "Voltage", C_MUTE, 1); + drawPanel(252, 288, 200, 72, C_CARD, C_BORDER, 10); + drawText(266, 308, "ADC raw", C_MUTE, 1); + drawPanel(28, 378, 424, 54, C_CARD, C_BORDER, 10); + drawText(42, 394, "Estimated resistance", C_MUTE, 1); + gStaticDrawn = true; + resetCachedUiText(); +} + +static void updatePotValues(bool force) { + if (gInputMode != InputMode::PotTest && gInputMode != InputMode::PotTwoWireTest) return; + + uint32_t raw = 0; + uint32_t mv = readPotMilliVolts(&raw); + if (!gPotFault && (mv >= kPotOvervoltageMv || raw >= 4090)) { + gPotFault = true; + releaseUsbPins(); + playFiveAlertBeeps(); + force = true; + } + + char line[64]; + if (gPotFault) { + clearArea(42, 128, 396, 58, C_CARD); + drawCenteredText(28, 126, 424, "USB/PIN FAULT", C_BAD, 3); + drawCenteredText(28, 166, 424, "pins released; reboot to retry", C_MUTE, 1); + clearArea(38, 232, 404, 20, C_CARD); + drawText(42, 234, "Possible overvoltage or USB host connection", C_BAD, 1); + return; + } + + float percent = 0.0f; + float ohms = 0.0f; + if (gInputMode == InputMode::PotTwoWireTest) { + if (mv < 20) { + ohms = kPotOhms; + } else { + ohms = kApproxInternalPulldownOhms * ((3300.0f / (float)mv) - 1.0f); + ohms = constrain(ohms, 0.0f, kPotOhms); + } + percent = 100.0f - constrain(ohms * 100.0f / kPotOhms, 0.0f, 100.0f); + } else { + percent = constrain((float)mv * 100.0f / 3300.0f, 0.0f, 100.0f); + ohms = kPotOhms * percent / 100.0f; + } + + clearArea(42, 128, 396, 58, C_CARD); + snprintf(line, sizeof(line), "%u%%", (unsigned)(percent + 0.5f)); + drawCenteredText(28, 126, 424, line, C_ACCENT, 4); + + int barX = 48; + int barY = 234; + int barW = 384; + int fillW = (int)((barW * percent) / 100.0f); + gfx->fillRect(barX, barY, barW, 16, C_BORDER); + gfx->fillRect(barX, barY, fillW, 16, C_ACCENT); + + clearArea(42, 326, 160, 28, C_CARD); + snprintf(line, sizeof(line), "%lumV", (unsigned long)mv); + drawText(42, 328, line, C_TEXT, 2); + + clearArea(266, 326, 160, 28, C_CARD); + snprintf(line, sizeof(line), "%lu", (unsigned long)raw); + drawText(266, 328, line, C_TEXT, 2); + + clearArea(42, 414, 360, 16, C_CARD); + snprintf(line, sizeof(line), "%.1fk / 50.0k%s", ohms / 1000.0f, + gInputMode == InputMode::PotTwoWireTest ? " rough" : ""); + drawText(42, 414, line, C_TEXT, 2); + + (void)force; +} + +static void resetPotCal() { + gPotCalMinMv = 0xFFFFFFFF; + gPotCalMaxMv = 0; + resetCachedUiText(); +} + +static void drawPotCalStatic() { + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 32, "POT CAL TEST", C_TEXT, 3); + drawText(28, 72, "D-=HIGH D+=ADC KEY3 resets min/max", C_MUTE, 1); + drawPanel(28, 112, 424, 88, C_CARD, C_BORDER, 14); + drawPanel(28, 220, 424, 44, C_CARD, C_BORDER, 10); + drawPanel(28, 288, 200, 72, C_CARD, C_BORDER, 10); + drawText(42, 308, "Now", C_MUTE, 1); + drawPanel(252, 288, 200, 72, C_CARD, C_BORDER, 10); + drawText(266, 308, "Range", C_MUTE, 1); + drawPanel(28, 378, 424, 54, C_CARD, C_BORDER, 10); + drawText(42, 394, "State", C_MUTE, 1); + gStaticDrawn = true; + resetCachedUiText(); +} + +static void updatePotCalValues() { + if (gInputMode != InputMode::PotCalTest) return; + + uint32_t raw = 0; + uint32_t mv = readPotMilliVolts(&raw); + if (mv < gPotCalMinMv) gPotCalMinMv = mv; + if (mv > gPotCalMaxMv) gPotCalMaxMv = mv; + + uint32_t span = (gPotCalMaxMv > gPotCalMinMv) ? (gPotCalMaxMv - gPotCalMinMv) : 0; + uint8_t percent = 0; + if (span >= 5 && mv >= gPotCalMinMv) { + percent = (uint8_t)constrain(((mv - gPotCalMinMv) * 100UL + span / 2) / span, 0UL, 100UL); + } + + const char *state = "CALIBRATING"; + uint16_t stateColor = C_MUTE; + if (span >= 50) { + if (percent < 20) { + state = "LOW EDGE"; + stateColor = C_ACCENT; + } else if (percent > 80) { + state = "HIGH EDGE"; + stateColor = C_OK; + } else { + state = "MID"; + stateColor = C_TEXT; + } + } else if (span > 0) { + state = "SMALL RANGE"; + stateColor = C_BAD; + } + + char line[80]; + clearArea(42, 128, 396, 58, C_CARD); + snprintf(line, sizeof(line), "%u%%", percent); + drawCenteredText(28, 126, 424, line, span >= 50 ? C_ACCENT : C_MUTE, 4); + + int barX = 48; + int barY = 234; + int barW = 384; + int fillW = (barW * percent) / 100; + gfx->fillRect(barX, barY, barW, 16, C_BORDER); + gfx->fillRect(barX, barY, fillW, 16, span >= 50 ? C_ACCENT : C_BAD); + + clearArea(42, 326, 160, 28, C_CARD); + snprintf(line, sizeof(line), "%lumV r%lu", (unsigned long)mv, (unsigned long)raw); + drawText(42, 328, line, C_TEXT, 1); + + clearArea(266, 326, 170, 28, C_CARD); + snprintf(line, sizeof(line), "%lu-%lu", (unsigned long)gPotCalMinMv, (unsigned long)gPotCalMaxMv); + drawText(266, 328, line, C_TEXT, 1); + + clearArea(42, 414, 360, 16, C_CARD); + snprintf(line, sizeof(line), "%s span %lumV", state, (unsigned long)span); + drawText(42, 414, line, stateColor, 2); +} + +static void drawPinDiagStatic() { + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 32, "USB PIN DIAG", C_TEXT, 3); + drawText(28, 72, "Short D- and D+ to test GPIO drive", C_MUTE, 1); + drawPanel(28, 110, 424, 128, C_CARD, C_BORDER, 14); + drawText(42, 128, "Test A: D- HIGH, D+ ADC", C_ACCENT, 2); + drawPanel(28, 260, 424, 128, C_CARD, C_BORDER, 14); + drawText(42, 278, "Test B: D+ HIGH, D- ADC", C_ACCENT, 2); + drawPanel(28, 410, 424, 36, C_CARD, C_BORDER, 10); + gStaticDrawn = true; + resetCachedUiText(); +} + +static void updatePinDiagValues() { + if (gInputMode != InputMode::UsbPinDiag) return; + + char line[80]; + uint32_t rawA = 0; + uint32_t rawB = 0; + + pinMode(kUsbDpPin, INPUT); + pinMode(kUsbDmPin, OUTPUT); + digitalWrite(kUsbDmPin, HIGH); + delay(8); + uint32_t mvA = readAdcMilliVolts(kUsbDpPin, &rawA); + int dmReadA = digitalRead(kUsbDmPin); + int dpReadA = digitalRead(kUsbDpPin); + + pinMode(kUsbDmPin, INPUT); + pinMode(kUsbDpPin, OUTPUT); + digitalWrite(kUsbDpPin, HIGH); + delay(8); + uint32_t mvB = readAdcMilliVolts(kUsbDmPin, &rawB); + int dpReadB = digitalRead(kUsbDpPin); + int dmReadB = digitalRead(kUsbDmPin); + + releaseUsbPins(); + + clearArea(42, 158, 380, 66, C_CARD); + snprintf(line, sizeof(line), "D+ %lumV raw %lu", (unsigned long)mvA, (unsigned long)rawA); + drawText(42, 160, line, mvA > 2500 ? C_OK : C_BAD, 2); + snprintf(line, sizeof(line), "D- read %d D+ read %d", dmReadA, dpReadA); + drawText(42, 194, line, C_TEXT, 2); + + clearArea(42, 308, 380, 66, C_CARD); + snprintf(line, sizeof(line), "D- %lumV raw %lu", (unsigned long)mvB, (unsigned long)rawB); + drawText(42, 310, line, mvB > 2500 ? C_OK : C_BAD, 2); + snprintf(line, sizeof(line), "D+ read %d D- read %d", dpReadB, dmReadB); + drawText(42, 344, line, C_TEXT, 2); + + clearArea(42, 424, 380, 16, C_CARD); + if (mvA < 500 && mvB < 500) { + drawText(42, 424, "Both low: USB PHY/cable may hold pins", C_BAD, 1); + } else if (mvA > 2500 || mvB > 2500) { + drawText(42, 424, "High seen: short should change ADC", C_OK, 1); + } else { + drawText(42, 424, "Weak/partial drive detected", C_MUTE, 1); + } +} + +static void updateMonitorValues(bool force) { + char line[64]; + char value[16]; + uint32_t now = millis(); + uint32_t runMs = now - gStartedMs; + uint32_t activeStartMs = gInputMode == InputMode::ExternalButtons ? gPhaseStartMs : gLastCycleStartMs; + uint32_t currentMs = (activeStartMs == 0) ? 0 : now - activeStartMs; + uint32_t avgMs = averageCycleMs(); + + if (gInputMode == InputMode::ExternalButtons && activeStartMs != 0 && + currentMs >= 35000 && currentMs < kPauseAfterMs) { + uint8_t alertSlot = currentMs / 5000; + if (alertSlot >= 7 && alertSlot <= 11 && alertSlot > gLastSinglePhaseAlertSlot) { + gLastSinglePhaseAlertSlot = alertSlot; + playAlertBeep(); + } + } + + if (activeStartMs != 0 && currentMs >= kPauseAfterMs) { + if (!gLongPauseActive) { + gLongPauseActive = true; + gLongPauseEvents++; + gLastRepeatAlertMs = now; + playFiveAlertBeeps(); + } else if ((uint32_t)(now - gLastRepeatAlertMs) >= kRepeatAlertMs) { + gLastRepeatAlertMs = now; + playFiveAlertBeeps(); + } + } + + if (force || gLastDrawnExhale != gInExhale || gLastDrawnPaused != gLongPauseActive) { + clearArea(42, 120, 396, 66, C_CARD); + if (gLongPauseActive) { + drawCenteredText(28, 120, 424, "OVER 60S", C_BAD, 4); + drawCenteredText(28, 170, 424, "waiting for next phase", C_MUTE, 1); + } else { + drawCenteredText(28, 120, 424, gInExhale ? "EXHALE" : "INHALE", + gInExhale ? C_OK : C_ACCENT, 4); + drawCenteredText(28, 170, 424, + gInputMode == InputMode::UsbContact ? "USB contact sensor" : "external buttons", + C_MUTE, 1); + } + gLastDrawnExhale = gInExhale; + gLastDrawnPaused = gLongPauseActive; + } + + snprintf(line, sizeof(line), "%s Limit: %us", + gInputMode == InputMode::UsbContact ? "USB D-/D+" : "hold INHALE: settings", + kLimitsSec[gLimitIndex]); + if (strcmp(line, gLastTopLine) != 0) { + clearArea(28, 58, 424, 20, C_PANEL); + drawText(28, 60, line, C_MUTE, 1); + strncpy(gLastTopLine, line, sizeof(gLastTopLine) - 1); + gLastTopLine[sizeof(gLastTopLine) - 1] = '\0'; + } + + clearArea(42, 254, 160, 28, C_CARD); + formatSec(value, sizeof(value), currentMs); + drawText(42, 256, value, gLongPauseActive ? C_BAD : C_TEXT, 3); + + clearArea(266, 254, 160, 28, C_CARD); + if (avgMs > 0) { + formatSec(value, sizeof(value), avgMs); + } else { + snprintf(value, sizeof(value), "--"); + } + drawText(266, 256, value, C_TEXT, 3); + + clearArea(42, 336, 170, 30, C_CARD); + formatClock(value, sizeof(value), runMs); + drawText(42, 338, value, C_TEXT, 3); + + clearArea(266, 336, 160, 30, C_CARD); + snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]); + drawText(266, 338, value, C_TEXT, 3); + + if (gInputMode == InputMode::UsbContact) { + formatLastFiveCycles(line, sizeof(line)); + } else { + snprintf(line, sizeof(line), "Long >60s: %u Short avg: %u Streak: %u", + gLongPauseEvents, gShortAvgEvents, gShortStreak); + } + if (strcmp(line, gLastBottomLine) != 0) { + clearArea(24, 398, 432, 40, C_PANEL); + drawText(30, 402, line, (gLongPauseEvents || gShortAvgEvents) ? C_BAD : C_MUTE, 1); + strncpy(gLastBottomLine, line, sizeof(gLastBottomLine) - 1); + gLastBottomLine[sizeof(gLastBottomLine) - 1] = '\0'; + } +} + +static void redrawScreen() { + if (gSettingsOpen) { + drawSettingsScreen(); + } else if (gInputMode == InputMode::PotTest || gInputMode == InputMode::PotTwoWireTest) { + if (gNeedStaticRedraw || !gStaticDrawn) { + drawPotStatic(); + gNeedStaticRedraw = false; + } + updatePotValues(true); + } else if (gInputMode == InputMode::PotCalTest) { + if (gNeedStaticRedraw || !gStaticDrawn) { + drawPotCalStatic(); + gNeedStaticRedraw = false; + } + updatePotCalValues(); + } else if (gInputMode == InputMode::UsbPinDiag) { + if (gNeedStaticRedraw || !gStaticDrawn) { + drawPinDiagStatic(); + gNeedStaticRedraw = false; + } + updatePinDiagValues(); + } else if (gStarted) { + if (gNeedStaticRedraw || !gStaticDrawn) { + drawMonitorStatic(); + gNeedStaticRedraw = false; + } + updateMonitorValues(true); + } else { + drawReadyScreen(); + } + gNeedRedraw = false; + gLastUiMs = millis(); +} + +static void startMonitor(InputMode mode) { + uint32_t now = millis(); + gStarted = true; + gInputMode = mode; + gPotFault = false; + gStartedMs = now; + gLastCycleStartMs = 0; + gPhaseStartMs = 0; + gInExhale = false; + gButtonPhaseKnown = false; + gInhalePressClosedSettings = false; + gLongPauseActive = false; + gCycleCount = 0; + gCycleNext = 0; + gShortStreak = 0; + gShortAvgEvents = 0; + gLongPauseEvents = 0; + gLastRepeatAlertMs = 0; + gLastSinglePhaseAlertSlot = 0; + resetPotCal(); + memset(gCycleMs, 0, sizeof(gCycleMs)); + if (mode == InputMode::UsbContact) { + Serial.flush(); + delay(30); + pinMode(kUsbDmPin, OUTPUT); + digitalWrite(kUsbDmPin, LOW); + pinMode(kUsbDpPin, INPUT_PULLUP); + gLastRawClosed = (digitalRead(kUsbDpPin) == LOW); + gLastRawChangeMs = now; + gInExhale = gLastRawClosed; + if (gInExhale) { + gLastCycleStartMs = now; + playCycleTick(); + } + } else if (mode == InputMode::PotTest || mode == InputMode::PotTwoWireTest || mode == InputMode::PotCalTest) { + Serial.flush(); + delay(30); + pinMode(kUsbDmPin, OUTPUT); + digitalWrite(kUsbDmPin, HIGH); + pinMode(kUsbDpPin, (mode == InputMode::PotTwoWireTest || mode == InputMode::PotCalTest) ? INPUT_PULLDOWN : INPUT); + analogReadResolution(12); + analogSetPinAttenuation(kUsbDpPin, ADC_11db); + } else if (mode == InputMode::UsbPinDiag) { + Serial.flush(); + delay(30); + analogReadResolution(12); + analogSetPinAttenuation(kUsbDmPin, ADC_11db); + analogSetPinAttenuation(kUsbDpPin, ADC_11db); + releaseUsbPins(); + } + gNeedStaticRedraw = true; + gNeedRedraw = true; +} + +static void toggleSettings() { + if (!gStarted) startMonitor(InputMode::ExternalButtons); + gSettingsOpen = !gSettingsOpen; + gNeedStaticRedraw = true; + gNeedRedraw = true; + resetCachedUiText(); +} + +static bool handleBreathPress(bool exhale) { + if (!gStarted) startMonitor(InputMode::ExternalButtons); + + if (gInputMode == InputMode::ExternalButtons) { + // Manual phases must alternate. A repeated button press has no side effects. + if ((!gButtonPhaseKnown && exhale) || (gButtonPhaseKnown && exhale == gInExhale)) { + return false; + } + } + + uint32_t now = millis(); + bool shouldPlayTick = gInputMode == InputMode::ExternalButtons; + if (gLongPauseActive) { + gLongPauseActive = false; + gLastRepeatAlertMs = 0; + } + if (exhale) { + if (gLastCycleStartMs != 0) { + uint32_t cycleMs = now - gLastCycleStartMs; + if (cycleMs >= kPauseAfterMs) { + gLongPauseActive = false; + gLastCycleStartMs = now; + shouldPlayTick = true; + } else if (cycleMs >= minCycleMsForCurrentMode()) { + addCycle(cycleMs); + gLastCycleStartMs = now; + gLongPauseActive = false; + shouldPlayTick = true; + alertIfNeeded(); + } + } else { + gLastCycleStartMs = now; + gLongPauseActive = false; + shouldPlayTick = true; + } + gInExhale = true; + } else { + gInExhale = false; + } + + if (gInputMode == InputMode::ExternalButtons) { + gButtonPhaseKnown = true; + gPhaseStartMs = now; + gLastSinglePhaseAlertSlot = 0; + } + if (shouldPlayTick) playCycleTick(); + + if (!gSettingsOpen) gNeedRedraw = true; + return true; +} + +static uint8_t sliderValueFromX(const Rect &rect, int16_t x, uint8_t maxValue) { + int16_t left = rect.x + 22; + int16_t right = rect.x + rect.w - 22; + if (x < left) x = left; + if (x > right) x = right; + return (uint8_t)(((uint32_t)(x - left) * maxValue + (right - left) / 2) / (right - left)); +} + +static void handleSettingsTouch(int16_t x, int16_t y) { + if (contains(kLimitSlider, x, y)) { + uint8_t next = sliderValueFromX(kLimitSlider, x, 4); + if (next == gLimitIndex) return; + gLimitIndex = next; + } else if (contains(kTickSlider, x, y)) { + uint8_t next = sliderValueFromX(kTickSlider, x, 10); + if (next == gTickVolume) return; + gTickVolume = next; + playCycleTick(); + } else if (contains(kAlertSlider, x, y)) { + uint8_t next = sliderValueFromX(kAlertSlider, x, 10); + if (next == gAlertVolume) return; + gAlertVolume = next; + playAlertBeep(); + } else { + return; + } + saveSettings(); + gNeedRedraw = true; +} + +static void handleTap(int16_t x, int16_t y, uint32_t heldMs) { + if (gSettingsOpen) { + handleSettingsTouch(x, y); + return; + } + + if (!gStarted && contains(kStartUsbButton, x, y)) { + startMonitor(InputMode::UsbContact); + return; + } + if (!gStarted && contains(kStartButtonsButton, x, y)) { + startMonitor(InputMode::ExternalButtons); + return; + } + if (!gStarted && contains(kStartPotButton, x, y)) { + startMonitor(InputMode::PotTest); + return; + } + if (!gStarted && contains(kStartPot2Button, x, y)) { + startMonitor(InputMode::PotTwoWireTest); + return; + } + if (!gStarted && contains(kStartPotCalButton, x, y)) { + startMonitor(InputMode::PotCalTest); + return; + } + if (!gStarted && contains(kStartPinDiagButton, x, y)) { + startMonitor(InputMode::UsbPinDiag); + return; + } + + (void)heldMs; +} + +static void pollExternalButtons() { + if (!gStarted) return; + + uint32_t now = millis(); + bool pressed = false; + bool released = false; + uint32_t heldMs = 0; + pollButtonEvent(gInhaleButton, now, pressed, released, heldMs); + if (gInputMode == InputMode::UsbContact) { + if (pressed) { + toggleSettings(); + } + return; + } + if (gInputMode == InputMode::PotCalTest) { + if (pressed) { + resetPotCal(); + gNeedRedraw = true; + } + return; + } + if (gInputMode != InputMode::ExternalButtons) return; + + if (pressed) { + gInhalePressClosedSettings = gSettingsOpen; + handleBreathPress(false); + if (gInhalePressClosedSettings) toggleSettings(); + } + if (released) { + if (!gInhalePressClosedSettings && heldMs >= kLongPressMs) { + toggleSettings(); + } + gInhalePressClosedSettings = false; + } + pollButtonEvent(gExhaleButton, now, pressed, released, heldMs); + if (pressed) { + handleBreathPress(true); + } +} + +static void pollUsbContact() { + if (!gStarted || gInputMode != InputMode::UsbContact) return; + + bool rawClosed = (digitalRead(kUsbDpPin) == LOW); + uint32_t now = millis(); + if (rawClosed != gLastRawClosed) { + gLastRawClosed = rawClosed; + gLastRawChangeMs = now; + } + if ((now - gLastRawChangeMs) >= kContactDebounceMs && rawClosed != gInExhale) { + handleBreathPress(rawClosed); + } +} + +static void pollTouch() { + int16_t x = 0; + int16_t y = 0; + bool touching = gTouch.getPoint(&x, &y, 1) > 0; + if (touching && !gTouchDown) { + gTouchDown = true; + gTouchStartX = x; + gTouchStartY = y; + gTouchLastX = x; + gTouchLastY = y; + gTouchDownMs = millis(); + return; + } + if (touching && gTouchDown) { + gTouchLastX = x; + gTouchLastY = y; + return; + } + if (!touching && gTouchDown) { + gTouchDown = false; + int dx = abs(gTouchLastX - gTouchStartX); + int dy = abs(gTouchLastY - gTouchStartY); + if (dx >= 18 || dy >= 18) return; + handleTap(gTouchLastX, gTouchLastY, millis() - gTouchDownMs); + } +} + +void setup() { + Serial.begin(115200); + Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL); + pinMode(PIN_INHALE, INPUT_PULLUP); + pinMode(PIN_EXHALE, INPUT_PULLUP); + loadSettings(); + initAudio(); + + gfx->begin(); + gBus->writeC8D8(0x36, 0xA0); + gfx->setBrightness(220); + gfx->fillScreen(C_BG); + + gTouch.setPins(PIN_TP_INT, -1); + bool touchOk = gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL); + gTouch.setMaxCoordinates(DISP_W, DISP_H); + gTouch.setSwapXY(true); + gTouch.setMirrorXY(true, false); + + Serial.println("Dual mode breath monitor ready."); + Serial.println(touchOk ? "Touch init OK" : "Touch init failed"); + gNeedRedraw = true; +} + +void loop() { + pollTouch(); + pollExternalButtons(); + pollUsbContact(); + if (gStarted && !gSettingsOpen && + (gInputMode == InputMode::PotTest || gInputMode == InputMode::PotTwoWireTest) && + millis() - gLastPotUiMs >= kPotUiPeriodMs) { + updatePotValues(false); + gLastPotUiMs = millis(); + } + if (gStarted && !gSettingsOpen && gInputMode == InputMode::PotCalTest && + millis() - gLastPotUiMs >= kPotUiPeriodMs) { + updatePotCalValues(); + gLastPotUiMs = millis(); + } + if (gStarted && !gSettingsOpen && gInputMode == InputMode::UsbPinDiag && + millis() - gLastPinDiagUiMs >= kPinDiagPeriodMs) { + updatePinDiagValues(); + gLastPinDiagUiMs = millis(); + } + if (gStarted && !gSettingsOpen && + gInputMode != InputMode::PotTest && gInputMode != InputMode::PotTwoWireTest && + gInputMode != InputMode::PotCalTest && + gInputMode != InputMode::UsbPinDiag && + millis() - gLastUiMs >= kUiPeriodMs) { + updateMonitorValues(false); + gLastUiMs = millis(); + } + if (gNeedRedraw) { + redrawScreen(); + } + delay(10); +} diff --git a/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/reference/usb_contact_sensor_test_spec.md b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/reference/usb_contact_sensor_test_spec.md index d880ddf8..1f81ff9c 100644 --- a/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/reference/usb_contact_sensor_test_spec.md +++ b/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/reference/usb_contact_sensor_test_spec.md @@ -125,7 +125,11 @@ Initial screen: - title: `BREATH MONITOR` - state: `READY` - action button: `START USB SENSOR` -- action button: `START BUTTONS` +- action button: `START MANUAL MONITOR` +- action button: `START POT 3-WIRE` +- action button: `START POT 2-WIRE` +- action button: `START POT CAL` +- action button: `START PIN DIAG` After `START USB SENSOR`: @@ -137,15 +141,54 @@ After `START USB SENSOR`: - a short `KEY3 / GPIO18` press opens or closes settings in USB sensor mode - the bottom line shows the durations of the last 5 accepted USB sensor cycles -After `START BUTTONS`: +After `START MANUAL MONITOR`: - `KEY3 / GPIO18` is the external `INHALE` button, active LOW - `BOOT / GPIO0` is the external `EXHALE` button, active LOW - do not hold `BOOT` while booting or resetting the board +- the mode title is `MANUAL MONITOR` +- accepted manual phases strictly alternate: `INHALE`, then `EXHALE`; a repeated current button or `EXHALE` before the first `INHALE` is ignored without a beep or timer reset +- each accepted button press plays one quiet confirmation beep and starts a fresh `Phase time` timer for that inhale or exhale - the working screen does not show touch `INHALE`/`EXHALE` buttons - long-holding `KEY3 / INHALE` for about 850 ms opens settings; the long press still counts as an inhale press - while settings are open, the next `KEY3 / INHALE` press closes settings and also counts as an inhale press +After `START POT 3-WIRE`: + +- `GPIO19 / USB D-` is configured as `OUTPUT HIGH` and works as the 3.3 V side of the potentiometer test +- `GPIO20 / USB D+` is configured as ADC input and must be connected to the potentiometer wiper +- `USB GND` must be connected to the other edge pin of the potentiometer +- the screen shows position `0..100%`, a bar, ADC raw value, measured millivolts, and estimated `0..50 kΩ` resistance +- if ADC saturates or reaches an unsafe high-voltage threshold, the firmware releases `D-` and `D+` to `INPUT`, beeps, and shows `USB/PIN FAULT` +- this is only best-effort software protection; ESP32-S3 GPIO pins are not 5 V tolerant, so external wiring must still prevent 5 V from reaching `D+` or `D-` + +After `START POT 2-WIRE`: + +- `GPIO19 / USB D-` is configured as `OUTPUT HIGH` +- `GPIO20 / USB D+` is configured as ADC input with internal pulldown +- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin +- the screen shows rough position, raw ADC, millivolts, and rough estimated resistance +- this mode is intentionally approximate because the ESP32 internal pulldown value is not precise and can vary between boards +- use `START POT 3-WIRE` for stable and more linear future breath sensing + +After `START POT CAL`: + +- `GPIO19 / USB D-` is configured as `OUTPUT HIGH` +- `GPIO20 / USB D+` is configured as ADC input with internal pulldown +- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin +- the firmware tracks the observed minimum and maximum ADC millivolts +- the screen shows a calibrated `0..100%` position within the observed range, current millivolts, raw ADC, min-max range, and state +- `KEY3 / GPIO18` resets the learned min-max calibration +- this mode is for relative position testing on weak or shifted USB-pin ranges; it does not report real resistance + +After `START PIN DIAG`: + +- the firmware runs two alternating USB pin drive/read checks +- Test A drives `GPIO19 / USB D-` HIGH and reads `GPIO20 / USB D+` as ADC +- Test B drives `GPIO20 / USB D+` HIGH and reads `GPIO19 / USB D-` as ADC +- shorting `D-` and `D+` should make the ADC side rise if the pins are actually controllable as GPIO +- if both tests stay near 0 mV, the USB cable/host, USB PHY, or board wiring is likely holding the lines and the USB data pins are not usable as an analog sensor in that setup + In both modes: - one breathing cycle is measured from one `EXHALE` tap to the next `EXHALE` tap @@ -156,4 +199,5 @@ In both modes: - the lower numeric fields use a larger font than before - if the average of the last up to 5 completed cycles is shorter than the selected limit, warning beeps are played like in the USB contact breath monitor - if the current cycle reaches 60 seconds, 5 loud warning beeps are played, then after 5 seconds another 5 loud warning beeps are played, repeating until the user changes phase / exits the long cycle +- in manual monitor mode, a single loud warning beep is also played at 35, 40, 45, 50, and 55 seconds of an unchanged inhale or exhale; the repeated five-beep alarm starts at 60 seconds - settings keep the same sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10` diff --git a/VERSION.properties b/VERSION.properties index 458a65c1..19dabb9e 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.18.1 +client.version=1.18.2 server.version=1.14.1