commit c0bb7d6b9ab245c417fc41d6291124799adf57b4 Author: AidarKC Date: Fri Oct 16 18:36:00 2026 +0300 Добавить скетчи SHiNE diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5841aa9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.arduino-build/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c4f9897 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# AGENTS + +`SKETCH` is a local collection outside the main product git repository. + +- Keep each sketch folder self-contained with its custom source files and its README. +- When changing sketch behavior, wiring, controls, or build instructions, update its adjacent README in the same change. +- Keep ESP32 screen strings in English because the supported font path is ASCII/Latin only. +- Use the group `burn.sh` scripts for compilation and flashing. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b52de2a --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# SKETCH + +Отдельная рабочая коллекция ESP32-скетчей. Папка лежит рядом с `SHiNE-product`, поэтому не входит в git основного продукта. + +## Группы + +- `potentiometer_breath_monitor/` — Waveshare ESP32-S3-LCD-2: дыхание по трёхпроводному потенциометру, с пищалкой и без неё. +- `breath_button_monitor/` — Waveshare ESP32-S3-Touch-AMOLED-2.16: ручные и двухрежимные дыхательные мониторы. + +У каждой группы есть свой `burn.sh`. Скрипты используют Arduino CLI и внешние библиотеки Waveshare из соседнего `SHiNE-product/ESP32/.../official-demo`. diff --git a/breath_button_monitor/AGENTS.md b/breath_button_monitor/AGENTS.md new file mode 100644 index 0000000..aed4269 --- /dev/null +++ b/breath_button_monitor/AGENTS.md @@ -0,0 +1,9 @@ +# AGENTS + +This group contains Waveshare ESP32-S3-Touch-AMOLED-2.16 breath-monitor sketches. + +- `breath_button_monitor` is the original external-button monitor. +- `breath_dual_mode_monitor` supports USB sensor and manual-button modes. +- `manual_monitor_lvgl_v2` is the current LVGL manual monitor. +- Each AMOLED sketch needs Waveshare's common libraries from the adjacent `SHiNE-product` checkout; its local `es8311` files are included beside the sketch when required. +- Run `./burn.sh ` from this folder to compile or flash. diff --git a/breath_button_monitor/breath_button_monitor/README.md b/breath_button_monitor/breath_button_monitor/README.md new file mode 100644 index 0000000..b4e2145 --- /dev/null +++ b/breath_button_monitor/breath_button_monitor/README.md @@ -0,0 +1,39 @@ +# Breath Button Monitor + +Отдельный ручной монитор дыхания для Waveshare ESP32-S3-Touch-AMOLED-2.16. + +## Управление + +- `KEY3 / GPIO18` — начало вдоха. +- `BOOT / GPIO0` — начало выдоха. Не держать BOOT во время включения/reset платы. +- `PWR` — штатное аппаратное включение/выключение платы. +- Свайп по экрану слева направо — открыть настройки. +- В настройках `- / +` меняют минимальное допустимое среднее полного цикла от 5 до 15 секунд. Значение сохраняется в NVS. +- Через 15 секунд без действий настройки автоматически блокируются. + +## Логика измерения + +1. Первое нажатие `INHALE` начинает сессию и новый полный цикл. +2. `EXHALE` переключает фазу, но таймер текущего полного цикла продолжает идти. +3. Следующее `INHALE` завершает предыдущий полный цикл и сразу начинает новый. +4. Повторное нажатие той же кнопки в неверной фазе игнорируется. +5. Среднее считается по завершённым полным циклам за последние 60 секунд. +6. Первые 60 секунд — прогрев статистики: тревога не включается. +7. После прогрева, если среднее ниже порога, последовательные циклы дают 1, затем 2, затем 3 предупреждающих сигнала. При возвращении среднего к норме серия сбрасывается. + +## Экран + +- Крупно: среднее время полного цикла за последние 60 секунд. +- Отдельно: текущая фаза `INHALE / EXHALE`. +- Мелко: бегущее время текущего полного цикла. +- Мелко: длительность текущей сессии. + +Полный экран не перерисовывается в рабочем цикле. Обновляются только небольшие области с изменившимися значениями. Полная перерисовка происходит только при переходе между рабочим экраном и настройками. + +## Прошивка + +Из `SKETCH/breath_button_monitor`: + +```bash +./burn.sh breath-button-monitor +``` diff --git a/breath_button_monitor/breath_button_monitor/breath_button_monitor.ino b/breath_button_monitor/breath_button_monitor/breath_button_monitor.ino new file mode 100644 index 0000000..0a65e51 --- /dev/null +++ b/breath_button_monitor/breath_button_monitor/breath_button_monitor.ino @@ -0,0 +1,695 @@ +#include +#include +#include +#include +#include "ESP_I2S.h" +#include "Arduino_GFX_Library.h" +#include "TouchDrvCSTXXX.hpp" +#include "es8311.h" + +// ----------------------------------------------------------------------------- +// SHiNE Breath Button Monitor +// Board: Waveshare ESP32-S3-Touch-AMOLED-2.16 +// +// Controls: +// GPIO18 / KEY3 : start INHALE +// GPIO0 / BOOT : start EXHALE +// PWR : hardware power button (handled by the board PMU) +// Touch : swipe left -> right to unlock settings +// +// A full breathing cycle starts on INHALE and finishes on the next INHALE. +// EXHALE changes only the phase; the current-cycle timer keeps running. +// ----------------------------------------------------------------------------- + +// Display/touch pins follow the working SHiNE main-device sketch. +static constexpr int PIN_LCD_CS = 12; +static constexpr int PIN_LCD_SCLK = 38; +static constexpr int PIN_LCD_D0 = 4; +static constexpr int PIN_LCD_D1 = 5; +static constexpr int PIN_LCD_D2 = 6; +static constexpr int PIN_LCD_D3 = 7; +static constexpr int PIN_LCD_RST = 2; +static constexpr int PIN_I2C_SDA = 15; +static constexpr int PIN_I2C_SCL = 14; +static constexpr int PIN_TP_INT = 11; + +static constexpr int PIN_INHALE = 18; // KEY3, active LOW +static constexpr int PIN_EXHALE = 0; // BOOT, active LOW; do not hold during boot/reset +static constexpr int PIN_SPK_AMP = 46; + +static constexpr int DISP_W = 480; +static constexpr int DISP_H = 480; + +// I2S / ES8311 pins are copied from the proven simple_av_test. +static constexpr int PIN_I2S_BCLK = 9; +static constexpr int PIN_I2S_LRCK = 45; +static constexpr int PIN_I2S_DOUT = 8; +static constexpr int PIN_I2S_DIN = 10; +static constexpr int PIN_I2S_MCLK = 42; +static constexpr uint32_t AUDIO_SAMPLE_RATE = 16000; +static constexpr int I2C_PORT_NUM = 0; + +static constexpr uint32_t AVG_WINDOW_MS = 60UL * 1000UL; +static constexpr uint32_t SETTINGS_AUTOLOCK_MS = 15UL * 1000UL; +static constexpr uint32_t BUTTON_DEBOUNCE_MS = 45; +static constexpr uint32_t CURRENT_TIMER_REFRESH_MS = 100; +static constexpr uint32_t SESSION_TIMER_REFRESH_MS = 1000; +static constexpr int SWIPE_UNLOCK_MIN_DX = 85; +static constexpr int SWIPE_UNLOCK_MAX_DY = 100; + +static constexpr uint8_t THRESHOLD_MIN_SEC = 5; +static constexpr uint8_t THRESHOLD_MAX_SEC = 15; +static constexpr uint8_t THRESHOLD_DEFAULT_SEC = 10; + +static constexpr uint16_t C_BG = RGB565_BLACK; +static constexpr uint16_t C_TEXT = RGB565_WHITE; +static constexpr uint16_t C_MUTED = RGB565_LIGHTGREY; +static constexpr uint16_t C_ACCENT = RGB565_CYAN; +static constexpr uint16_t C_INHALE = RGB565_GREEN; +static constexpr uint16_t C_EXHALE = RGB565_ORANGE; +static constexpr uint16_t C_WARN = RGB565_RED; +static constexpr uint16_t C_PANEL = RGB565_DARKGREY; + +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; + +bool gAudioReady = false; + +struct DebouncedButton { + int pin; + bool rawPressed = false; + bool stablePressed = false; + uint32_t rawChangedMs = 0; +}; + +DebouncedButton gInhaleButton{PIN_INHALE}; +DebouncedButton gExhaleButton{PIN_EXHALE}; + +enum class BreathPhase : uint8_t { + Waiting, + Inhale, + Exhale, +}; + +BreathPhase gPhase = BreathPhase::Waiting; +bool gSessionStarted = false; +uint32_t gSessionStartMs = 0; +uint32_t gCycleStartMs = 0; + +struct CycleSample { + uint32_t endMs; + uint32_t durationMs; +}; + +// 64 is ample for a 60 s window even with very fast manual tapping. +CycleSample gCycles[64]; +size_t gCycleHead = 0; +size_t gCycleCount = 0; +uint8_t gWarningStreak = 0; +uint8_t gThresholdSec = THRESHOLD_DEFAULT_SEC; + +bool gSettingsOpen = false; +uint32_t gSettingsLastActionMs = 0; + +bool gTouchDown = false; +int16_t gTouchStartX = 0; +int16_t gTouchStartY = 0; +int16_t gTouchLastX = 0; +int16_t gTouchLastY = 0; + +uint32_t gLastCurrentTimerDrawMs = 0; +uint32_t gLastSessionTimerDrawMs = 0; +int32_t gLastCurrentDecisecond = -1; +int32_t gLastSessionSecond = -1; +int32_t gLastWarmupSecond = -1; +String gLastAverageText; +String gLastPhaseText; + +// ------------------------------- audio --------------------------------------- + +static bool initAudio() { + pinMode(PIN_SPK_AMP, OUTPUT); + digitalWrite(PIN_SPK_AMP, HIGH); + + gI2s.setPins(PIN_I2S_BCLK, PIN_I2S_LRCK, PIN_I2S_DOUT, PIN_I2S_DIN, PIN_I2S_MCLK); + if (!gI2s.begin(I2S_MODE_STD, + AUDIO_SAMPLE_RATE, + I2S_DATA_BIT_WIDTH_16BIT, + I2S_SLOT_MODE_STEREO, + I2S_STD_SLOT_BOTH)) { + Serial.println("I2S init failed"); + return false; + } + + es8311_handle_t es = es8311_create(I2C_PORT_NUM, ES8311_ADDRRES_0); + if (!es) { + Serial.println("ES8311 create failed"); + return false; + } + + const es8311_clock_config_t clk = { + .mclk_inverted = false, + .sclk_inverted = false, + .mclk_from_mclk_pin = true, + .mclk_frequency = AUDIO_SAMPLE_RATE * 256, + .sample_frequency = AUDIO_SAMPLE_RATE, + }; + + if (es8311_init(es, &clk, ES8311_RESOLUTION_16, ES8311_RESOLUTION_16) != ESP_OK || + es8311_sample_frequency_config(es, clk.mclk_frequency, clk.sample_frequency) != ESP_OK || + es8311_voice_volume_set(es, 72, nullptr) != ESP_OK) { + Serial.println("ES8311 init failed"); + return false; + } + + return true; +} + +static void playTone(uint16_t frequencyHz, uint16_t durationMs, int16_t amplitude) { + if (!gAudioReady || durationMs == 0) return; + + constexpr size_t FRAMES = 192; + static int16_t stereo[FRAMES * 2]; + const uint32_t totalFrames = (AUDIO_SAMPLE_RATE * (uint32_t)durationMs) / 1000UL; + uint32_t produced = 0; + + while (produced < totalFrames) { + const size_t frames = min((uint32_t)FRAMES, totalFrames - produced); + for (size_t i = 0; i < frames; ++i) { + const float t = (float)(produced + i) / (float)AUDIO_SAMPLE_RATE; + const float s = sinf(2.0f * PI * (float)frequencyHz * t); + const int16_t v = (int16_t)(s * amplitude); + stereo[i * 2] = v; + stereo[i * 2 + 1] = v; + } + gI2s.write((uint8_t *)stereo, frames * 2 * sizeof(int16_t)); + produced += frames; + } +} + +static void playAcceptedClick() { + playTone(1550, 26, 900); +} + +static void playWarning(uint8_t level) { + if (level < 1) return; + if (level > 3) level = 3; + + const int16_t amp = (level == 1) ? 4800 : (level == 2 ? 7000 : 9200); + for (uint8_t i = 0; i < level; ++i) { + playTone(880, 135, amp); + if (i + 1 < level) delay(85); + } +} + +// ------------------------------- storage ------------------------------------- + +static void loadSettings() { + gPrefs.begin("breath-monitor", false); + uint8_t saved = gPrefs.getUChar("threshold", THRESHOLD_DEFAULT_SEC); + if (saved < THRESHOLD_MIN_SEC || saved > THRESHOLD_MAX_SEC) { + saved = THRESHOLD_DEFAULT_SEC; + } + gThresholdSec = saved; +} + +static void saveThreshold() { + gPrefs.putUChar("threshold", gThresholdSec); +} + +// ------------------------------- statistics ---------------------------------- + +static void pushCycle(uint32_t endMs, uint32_t durationMs) { + if (gCycleCount < (sizeof(gCycles) / sizeof(gCycles[0]))) { + const size_t idx = (gCycleHead + gCycleCount) % (sizeof(gCycles) / sizeof(gCycles[0])); + gCycles[idx] = {endMs, durationMs}; + ++gCycleCount; + } else { + gCycles[gCycleHead] = {endMs, durationMs}; + gCycleHead = (gCycleHead + 1) % (sizeof(gCycles) / sizeof(gCycles[0])); + } +} + +static void pruneCycles(uint32_t nowMs) { + while (gCycleCount > 0) { + const CycleSample &s = gCycles[gCycleHead]; + if ((uint32_t)(nowMs - s.endMs) <= AVG_WINDOW_MS) break; + gCycleHead = (gCycleHead + 1) % (sizeof(gCycles) / sizeof(gCycles[0])); + --gCycleCount; + } +} + +static bool averageCycleMs(uint32_t nowMs, float &avgMsOut) { + pruneCycles(nowMs); + if (gCycleCount == 0) return false; + + uint64_t sum = 0; + for (size_t i = 0; i < gCycleCount; ++i) { + const size_t idx = (gCycleHead + i) % (sizeof(gCycles) / sizeof(gCycles[0])); + sum += gCycles[idx].durationMs; + } + avgMsOut = (float)sum / (float)gCycleCount; + return true; +} + +static bool warmupFinished(uint32_t nowMs) { + return gSessionStarted && (uint32_t)(nowMs - gSessionStartMs) >= AVG_WINDOW_MS; +} + +// ------------------------------- drawing ------------------------------------- + +static void clearRect(int x, int y, int w, int h) { + gfx->fillRect(x, y, w, h, C_BG); +} + +static void drawCenteredText(const String &text, int y, uint8_t size, uint16_t color) { + // Default Arduino_GFX font is approximately 6x8 pixels per character before scaling. + const int w = text.length() * 6 * size; + const int x = max(0, (DISP_W - w) / 2); + gfx->setTextSize(size); + gfx->setTextColor(color); + gfx->setCursor(x, y); + gfx->print(text); +} + +static String formatSecondsTenths(uint32_t ms) { + char out[16]; + snprintf(out, sizeof(out), "%lu.%lus", + (unsigned long)(ms / 1000UL), + (unsigned long)((ms / 100UL) % 10UL)); + return String(out); +} + +static String formatClock(uint32_t totalSeconds) { + const uint32_t minutes = totalSeconds / 60UL; + const uint32_t seconds = totalSeconds % 60UL; + char out[20]; + snprintf(out, sizeof(out), "%02lu:%02lu", + (unsigned long)minutes, + (unsigned long)seconds); + return String(out); +} + +static void drawPhase(bool force = false) { + String text; + uint16_t color = C_MUTED; + if (gPhase == BreathPhase::Waiting) { + text = "PRESS INHALE"; + } else if (gPhase == BreathPhase::Inhale) { + text = "INHALE"; + color = C_INHALE; + } else { + text = "EXHALE"; + color = C_EXHALE; + } + + if (!force && text == gLastPhaseText) return; + gLastPhaseText = text; + clearRect(35, 284, 410, 48); + drawCenteredText(text, 292, 3, color); +} + +static void drawAverage(uint32_t nowMs, bool force = false) { + String text = "--.- s"; + if (warmupFinished(nowMs)) { + float avg = 0.0f; + if (averageCycleMs(nowMs, avg)) { + char out[16]; + snprintf(out, sizeof(out), "%.1f s", avg / 1000.0f); + text = out; + } + } + + if (!force && text == gLastAverageText) return; + gLastAverageText = text; + clearRect(20, 120, 440, 100); + drawCenteredText(text, 132, 7, C_TEXT); +} + +static void drawWarmupOrWindow(uint32_t nowMs, bool force = false) { + int32_t marker = 60; + String text; + if (!gSessionStarted) { + marker = -1; + text = "average: last 60 s"; + } else if (!warmupFinished(nowMs)) { + const uint32_t elapsed = (nowMs - gSessionStartMs) / 1000UL; + marker = (int32_t)elapsed; + text = "collecting " + String(elapsed) + "/60 s"; + } else { + marker = 60; + text = "average: last 60 s"; + } + + if (!force && marker == gLastWarmupSecond) return; + gLastWarmupSecond = marker; + clearRect(40, 222, 400, 34); + drawCenteredText(text, 226, 2, C_MUTED); +} + +static void drawCurrentCycle(uint32_t nowMs, bool force = false) { + uint32_t elapsedMs = 0; + if (gPhase != BreathPhase::Waiting) { + elapsedMs = nowMs - gCycleStartMs; + } + const int32_t ds = (int32_t)(elapsedMs / 100UL); + if (!force && ds == gLastCurrentDecisecond) return; + gLastCurrentDecisecond = ds; + + clearRect(230, 350, 210, 42); + gfx->setTextSize(3); + gfx->setTextColor(C_ACCENT); + gfx->setCursor(246, 354); + gfx->print(formatSecondsTenths(elapsedMs)); +} + +static void drawSessionTime(uint32_t nowMs, bool force = false) { + uint32_t sec = 0; + if (gSessionStarted) sec = (nowMs - gSessionStartMs) / 1000UL; + if (!force && (int32_t)sec == gLastSessionSecond) return; + gLastSessionSecond = (int32_t)sec; + + clearRect(230, 410, 210, 42); + gfx->setTextSize(3); + gfx->setTextColor(C_TEXT); + gfx->setCursor(246, 414); + gfx->print(formatClock(sec)); +} + +static void drawPracticeStatic() { + gfx->fillScreen(C_BG); + gfx->setTextColor(C_MUTED); + gfx->setTextSize(2); + gfx->setCursor(28, 26); + gfx->print("BREATH MONITOR"); + + gfx->setTextSize(2); + gfx->setTextColor(C_MUTED); + gfx->setCursor(28, 88); + gfx->print("AVERAGE CYCLE"); + + gfx->drawFastHLine(28, 267, 424, C_PANEL); + + gfx->setTextSize(2); + gfx->setTextColor(C_MUTED); + gfx->setCursor(42, 360); + gfx->print("CURRENT"); + gfx->setCursor(42, 420); + gfx->print("SESSION"); + + gfx->setTextSize(1); + gfx->setTextColor(C_MUTED); + gfx->setCursor(28, 464); + gfx->print("Swipe -> for settings"); + + gLastAverageText = "#force#"; + gLastPhaseText = "#force#"; + gLastCurrentDecisecond = -1; + gLastSessionSecond = -1; + gLastWarmupSecond = -2; + + const uint32_t nowMs = millis(); + drawAverage(nowMs, true); + drawWarmupOrWindow(nowMs, true); + drawPhase(true); + drawCurrentCycle(nowMs, true); + drawSessionTime(nowMs, true); +} + +static void drawThresholdValue() { + clearRect(166, 164, 150, 70); + gfx->setTextSize(5); + gfx->setTextColor(C_TEXT); + gfx->setCursor(181, 178); + gfx->print(String(gThresholdSec) + " s"); +} + +static void drawSettingsScreen() { + gfx->fillScreen(C_BG); + gfx->setTextSize(3); + gfx->setTextColor(C_TEXT); + gfx->setCursor(34, 36); + gfx->print("SETTINGS"); + + gfx->setTextSize(2); + gfx->setTextColor(C_MUTED); + gfx->setCursor(34, 108); + gfx->print("Minimum average cycle"); + + gfx->drawRoundRect(34, 164, 108, 70, 14, C_ACCENT); + gfx->drawRoundRect(338, 164, 108, 70, 14, C_ACCENT); + gfx->setTextSize(5); + gfx->setTextColor(C_ACCENT); + gfx->setCursor(74, 177); + gfx->print("-"); + gfx->setCursor(373, 177); + gfx->print("+"); + drawThresholdValue(); + + gfx->setTextSize(2); + gfx->setTextColor(C_MUTED); + gfx->setCursor(34, 264); + gfx->print("Range: 5-15 s"); + + gfx->drawRoundRect(86, 344, 308, 72, 16, C_TEXT); + gfx->setTextSize(3); + gfx->setTextColor(C_TEXT); + gfx->setCursor(190, 368); + gfx->print("LOCK"); + + gfx->setTextSize(1); + gfx->setTextColor(C_MUTED); + gfx->setCursor(84, 442); + gfx->print("Auto-lock after 15 seconds"); +} + +static void openSettings() { + gSettingsOpen = true; + gSettingsLastActionMs = millis(); + drawSettingsScreen(); +} + +static void closeSettings() { + gSettingsOpen = false; + drawPracticeStatic(); +} + +// ------------------------------- breathing ----------------------------------- + +static void evaluateWarning(uint32_t nowMs) { + if (!warmupFinished(nowMs)) { + gWarningStreak = 0; + return; + } + + float avgMs = 0.0f; + if (!averageCycleMs(nowMs, avgMs)) { + gWarningStreak = 0; + return; + } + + if (avgMs < (float)gThresholdSec * 1000.0f) { + if (gWarningStreak < 3) ++gWarningStreak; + delay(55); + playWarning(gWarningStreak); + } else { + gWarningStreak = 0; + } +} + +static void onInhalePressed(uint32_t nowMs) { + if (gPhase == BreathPhase::Inhale) return; // duplicate / accidental press + + playAcceptedClick(); + + if (!gSessionStarted) { + gSessionStarted = true; + gSessionStartMs = nowMs; + gCycleStartMs = nowMs; + gPhase = BreathPhase::Inhale; + } else if (gPhase == BreathPhase::Exhale) { + const uint32_t duration = nowMs - gCycleStartMs; + // Discard obviously accidental cycles below 0.5 s from statistics. + if (duration >= 500) { + pushCycle(nowMs, duration); + evaluateWarning(nowMs); + } + gCycleStartMs = nowMs; + gPhase = BreathPhase::Inhale; + } else { // Waiting after boot, defensive path + gCycleStartMs = nowMs; + gPhase = BreathPhase::Inhale; + } + + if (!gSettingsOpen) { + drawPhase(); + drawAverage(nowMs); + drawWarmupOrWindow(nowMs); + drawCurrentCycle(nowMs, true); + drawSessionTime(nowMs); + } +} + +static void onExhalePressed(uint32_t nowMs) { + if (gPhase != BreathPhase::Inhale) return; + playAcceptedClick(); + gPhase = BreathPhase::Exhale; + if (!gSettingsOpen) { + drawPhase(); + drawCurrentCycle(nowMs, true); + } +} + +// ------------------------------- input --------------------------------------- + +static bool pollPressedEdge(DebouncedButton &button, uint32_t nowMs) { + const bool raw = digitalRead(button.pin) == LOW; + if (raw != button.rawPressed) { + button.rawPressed = raw; + button.rawChangedMs = nowMs; + } + + if (button.stablePressed != button.rawPressed && + (uint32_t)(nowMs - button.rawChangedMs) >= BUTTON_DEBOUNCE_MS) { + button.stablePressed = button.rawPressed; + return button.stablePressed; + } + return false; +} + +static bool inside(int x, int y, int x1, int y1, int x2, int y2) { + return x >= x1 && x <= x2 && y >= y1 && y <= y2; +} + +static void handleSettingsTap(int x, int y) { + bool changed = false; + if (inside(x, y, 34, 164, 142, 234)) { + if (gThresholdSec > THRESHOLD_MIN_SEC) { + --gThresholdSec; + changed = true; + } + } else if (inside(x, y, 338, 164, 446, 234)) { + if (gThresholdSec < THRESHOLD_MAX_SEC) { + ++gThresholdSec; + changed = true; + } + } else if (inside(x, y, 86, 344, 394, 416)) { + closeSettings(); + return; + } + + gSettingsLastActionMs = millis(); + if (changed) { + saveThreshold(); + drawThresholdValue(); // partial redraw only + } +} + +static void handleTouch(uint32_t nowMs) { + int16_t x = 0; + int16_t y = 0; + const bool touching = gTouch.getPoint(&x, &y, 1) > 0; + + if (touching) { + if (!gTouchDown) { + gTouchDown = true; + gTouchStartX = x; + gTouchStartY = y; + } + gTouchLastX = x; + gTouchLastY = y; + if (gSettingsOpen) gSettingsLastActionMs = nowMs; + return; + } + + if (!gTouchDown) return; + gTouchDown = false; + + const int dx = gTouchLastX - gTouchStartX; + const int dy = gTouchLastY - gTouchStartY; + + if (!gSettingsOpen) { + if (dx >= SWIPE_UNLOCK_MIN_DX && abs(dy) <= SWIPE_UNLOCK_MAX_DY) { + openSettings(); + } + return; + } + + // In settings, large movement is a gesture, not a tap. + if (abs(dx) <= 24 && abs(dy) <= 24) { + handleSettingsTap(gTouchLastX, gTouchLastY); + } +} + +// ------------------------------- Arduino ------------------------------------- + +void setup() { + Serial.begin(115200); + delay(100); + + pinMode(PIN_INHALE, INPUT_PULLUP); + pinMode(PIN_EXHALE, INPUT_PULLUP); + + Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL); + loadSettings(); + + if (!gfx->begin()) { + Serial.println("Display init failed"); + } + gBus->writeC8D8(0x36, 0xA0); + gfx->setBrightness(210); + + // Same touch setup as the current working SHiNE main firmware. + gTouch.setPins(PIN_TP_INT, -1); + if (!gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL)) { + Serial.println("Touch init failed"); + } + gTouch.setMaxCoordinates(DISP_W, DISP_H); + gTouch.setSwapXY(true); + gTouch.setMirrorXY(true, false); + + gAudioReady = initAudio(); + if (!gAudioReady) Serial.println("Audio unavailable; breathing monitor continues silently"); + + drawPracticeStatic(); + Serial.println("Breath Button Monitor ready"); +} + +void loop() { + const uint32_t nowMs = millis(); + + if (pollPressedEdge(gInhaleButton, nowMs)) { + onInhalePressed(nowMs); + } + if (pollPressedEdge(gExhaleButton, nowMs)) { + onExhalePressed(nowMs); + } + + handleTouch(nowMs); + + if (gSettingsOpen) { + if ((uint32_t)(nowMs - gSettingsLastActionMs) >= SETTINGS_AUTOLOCK_MS) { + closeSettings(); + } + } else { + // No full-screen redraws here. Each function repaints only its own small field, + // and only when the visible value actually changes. + if ((uint32_t)(nowMs - gLastCurrentTimerDrawMs) >= CURRENT_TIMER_REFRESH_MS) { + gLastCurrentTimerDrawMs = nowMs; + drawCurrentCycle(nowMs); + } + if ((uint32_t)(nowMs - gLastSessionTimerDrawMs) >= SESSION_TIMER_REFRESH_MS) { + gLastSessionTimerDrawMs = nowMs; + drawSessionTime(nowMs); + drawWarmupOrWindow(nowMs); + drawAverage(nowMs); + } + } + + delay(4); +} diff --git a/breath_button_monitor/breath_button_monitor/es8311.c b/breath_button_monitor/breath_button_monitor/es8311.c new file mode 100644 index 0000000..c78bc2b --- /dev/null +++ b/breath_button_monitor/breath_button_monitor/es8311.c @@ -0,0 +1,443 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "es8311.h" +#include "driver/gpio.h" +#include "esp_log.h" +#include "esp_err.h" +#include "esp_check.h" +#include "es8311_reg.h" +#include "esp32-hal-i2c.h" + + +typedef struct { + unsigned int port; + uint16_t dev_addr; +} es8311_dev_t; + +/* + * Clock coefficient structure + */ +struct _coeff_div { + uint32_t mclk; /* mclk frequency */ + uint32_t rate; /* sample rate */ + uint8_t pre_div; /* the pre divider with range from 1 to 8 */ + uint8_t pre_multi; /* the pre multiplier with 0: 1x, 1: 2x, 2: 4x, 3: 8x selection */ + uint8_t adc_div; /* adcclk divider */ + uint8_t dac_div; /* dacclk divider */ + uint8_t fs_mode; /* double speed or single speed, =0, ss, =1, ds */ + uint8_t lrck_h; /* adclrck divider and daclrck divider */ + uint8_t lrck_l; + uint8_t bclk_div; /* sclk divider */ + uint8_t adc_osr; /* adc osr */ + uint8_t dac_osr; /* dac osr */ +}; + +/* codec hifi mclk clock divider coefficients */ +static const struct _coeff_div coeff_div[] = { + /*!port, es->dev_addr, write_buf, sizeof(write_buf), 1000); +} + +static inline esp_err_t es8311_read_reg(es8311_handle_t dev, uint8_t reg_addr, uint8_t *reg_value) +{ + es8311_dev_t *es = (es8311_dev_t *) dev; + size_t readCount = 0; + return i2cWriteReadNonStop(es->port, es->dev_addr, ®_addr, 1, reg_value, 1, 1000, &readCount); +} + +/* +* look for the coefficient in coeff_div[] table +*/ +static int get_coeff(uint32_t mclk, uint32_t rate) +{ + for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) { + if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) { + return i; + } + } + + return -1; +} + +esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency) +{ + uint8_t regv; + + /* Get clock coefficients from coefficient table */ + int coeff = get_coeff(mclk_frequency, sample_frequency); + + if (coeff < 0) { + ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_frequency, mclk_frequency); + return ESP_ERR_INVALID_ARG; + } + + const struct _coeff_div *const selected_coeff = &coeff_div[coeff]; + + /* register 0x02 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG02, ®v), TAG, "I2C read/write error"); + regv &= 0x07; + regv |= (selected_coeff->pre_div - 1) << 5; + regv |= selected_coeff->pre_multi << 3; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG02, regv), TAG, "I2C read/write error"); + + /* register 0x03 */ + const uint8_t reg03 = (selected_coeff->fs_mode << 6) | selected_coeff->adc_osr; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG03, reg03), TAG, "I2C read/write error"); + + /* register 0x04 */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG04, selected_coeff->dac_osr), TAG, "I2C read/write error"); + + /* register 0x05 */ + const uint8_t reg05 = ((selected_coeff->adc_div - 1) << 4) | (selected_coeff->dac_div - 1); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG05, reg05), TAG, "I2C read/write error"); + + /* register 0x06 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®v), TAG, "I2C read/write error"); + regv &= 0xE0; + + if (selected_coeff->bclk_div < 19) { + regv |= (selected_coeff->bclk_div - 1) << 0; + } else { + regv |= (selected_coeff->bclk_div) << 0; + } + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, regv), TAG, "I2C read/write error"); + + /* register 0x07 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG07, ®v), TAG, "I2C read/write error"); + regv &= 0xC0; + regv |= selected_coeff->lrck_h << 0; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG07, regv), TAG, "I2C read/write error"); + + /* register 0x08 */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG08, selected_coeff->lrck_l), TAG, "I2C read/write error"); + + return ESP_OK; +} + +static esp_err_t es8311_clock_config(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, es8311_resolution_t res) +{ + uint8_t reg06; + uint8_t reg01 = 0x3F; // Enable all clocks + int mclk_hz; + + /* Select clock source for internal MCLK and determine its frequency */ + if (clk_cfg->mclk_from_mclk_pin) { + mclk_hz = clk_cfg->mclk_frequency; + } else { + mclk_hz = clk_cfg->sample_frequency * (int)res * 2; + reg01 |= BIT(7); // Select BCLK (a.k.a. SCK) pin + } + + if (clk_cfg->mclk_inverted) { + reg01 |= BIT(6); // Invert MCLK pin + } + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG01, reg01), TAG, "I2C read/write error"); + + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®06), TAG, "I2C read/write error"); + if (clk_cfg->sclk_inverted) { + reg06 |= BIT(5); + } else { + reg06 &= ~BIT(5); + } + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, reg06), TAG, "I2C read/write error"); + + /* Configure clock dividers */ + return es8311_sample_frequency_config(dev, mclk_hz, clk_cfg->sample_frequency); +} + +static esp_err_t es8311_resolution_config(const es8311_resolution_t res, uint8_t *reg) +{ + switch (res) { + case ES8311_RESOLUTION_16: + *reg |= (3 << 2); + break; + case ES8311_RESOLUTION_18: + *reg |= (2 << 2); + break; + case ES8311_RESOLUTION_20: + *reg |= (1 << 2); + break; + case ES8311_RESOLUTION_24: + *reg |= (0 << 2); + break; + case ES8311_RESOLUTION_32: + *reg |= (4 << 2); + break; + default: + return ESP_ERR_INVALID_ARG; + } + return ESP_OK; +} + +static esp_err_t es8311_fmt_config(es8311_handle_t dev, const es8311_resolution_t res_in, const es8311_resolution_t res_out) +{ + uint8_t reg09 = 0; // SDP In + uint8_t reg0a = 0; // SDP Out + + ESP_LOGI(TAG, "ES8311 in Slave mode and I2S format"); + uint8_t reg00; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_RESET_REG00, ®00), TAG, "I2C read/write error"); + reg00 &= 0xBF; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, reg00), TAG, "I2C read/write error"); // Slave serial port - default + + /* Setup SDP In and Out resolution */ + es8311_resolution_config(res_in, ®09); + es8311_resolution_config(res_out, ®0a); + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPIN_REG09, reg09), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPOUT_REG0A, reg0a), TAG, "I2C read/write error"); + + return ESP_OK; +} + +esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic) +{ + uint8_t reg14 = 0x1A; // enable analog MIC and max PGA gain + + /* PDM digital microphone enable or disable */ + if (digital_mic) { + reg14 |= BIT(6); + } + es8311_write_reg(dev, ES8311_ADC_REG17, 0xC8); // Set ADC gain @todo move this to ADC config section + + return es8311_write_reg(dev, ES8311_SYSTEM_REG14, reg14); +} + +esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, const es8311_resolution_t res_out) +{ + ESP_RETURN_ON_FALSE( + (clk_cfg->sample_frequency >= 8000) && (clk_cfg->sample_frequency <= 96000), + ESP_ERR_INVALID_ARG, TAG, "ES8311 init needs frequency in interval [8000; 96000] Hz" + ); + if (!clk_cfg->mclk_from_mclk_pin) { + ESP_RETURN_ON_FALSE(res_out == res_in, ESP_ERR_INVALID_ARG, TAG, "Resolution IN/OUT must be equal if MCLK is taken from SCK pin"); + } + + + /* Reset ES8311 to its default */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x1F), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x00), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x80), TAG, "I2C read/write error"); // Power-on command + + /* Setup clock: source, polarity and clock dividers */ + ESP_RETURN_ON_ERROR(es8311_clock_config(dev, clk_cfg, res_out), TAG, ""); + + /* Setup audio format (fmt): master/slave, resolution, I2S */ + ESP_RETURN_ON_ERROR(es8311_fmt_config(dev, res_in, res_out), TAG, ""); + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0D, 0x01), TAG, "I2C read/write error"); // Power up analog circuitry - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0E, 0x02), TAG, "I2C read/write error"); // Enable analog PGA, enable ADC modulator - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG12, 0x00), TAG, "I2C read/write error"); // power-up DAC - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG13, 0x10), TAG, "I2C read/write error"); // Enable output to HP drive - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_ADC_REG1C, 0x6A), TAG, "I2C read/write error"); // ADC Equalizer bypass, cancel DC offset in digital domain + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_DAC_REG37, 0x08), TAG, "I2C read/write error"); // Bypass DAC equalizer - NOT default + + return ESP_OK; +} + +void es8311_delete(es8311_handle_t dev) +{ + free(dev); +} + +esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set) +{ + if (volume < 0) { + volume = 0; + } else if (volume > 100) { + volume = 100; + } + + int reg32; + if (volume == 0) { + reg32 = 0; + } else { + reg32 = ((volume) * 256 / 100) - 1; + } + + // provide user with real volume set + if (volume_set != NULL) { + *volume_set = volume; + } + return es8311_write_reg(dev, ES8311_DAC_REG32, reg32); +} + +esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume) +{ + uint8_t reg32; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG32, ®32), TAG, "I2C read/write error"); + + if (reg32 == 0) { + *volume = 0; + } else { + *volume = ((reg32 * 100) / 256) + 1; + } + return ESP_OK; +} + +esp_err_t es8311_voice_mute(es8311_handle_t dev, bool mute) +{ + uint8_t reg31; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG31, ®31), TAG, "I2C read/write error"); + + if (mute) { + reg31 |= BIT(6) | BIT(5); + } else { + reg31 &= ~(BIT(6) | BIT(5)); + } + + return es8311_write_reg(dev, ES8311_DAC_REG31, reg31); +} + +esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db) +{ + return es8311_write_reg(dev, ES8311_ADC_REG16, gain_db); // ADC gain scale up +} + +esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade) +{ + uint8_t reg37; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG37, ®37), TAG, "I2C read/write error"); + reg37 &= 0x0F; + reg37 |= (fade << 4); + return es8311_write_reg(dev, ES8311_DAC_REG37, reg37); +} + +esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade) +{ + uint8_t reg15; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_ADC_REG15, ®15), TAG, "I2C read/write error"); + reg15 &= 0x0F; + reg15 |= (fade << 4); + return es8311_write_reg(dev, ES8311_ADC_REG15, reg15); +} + +void es8311_register_dump(es8311_handle_t dev) +{ + for (int reg = 0; reg < 0x4A; reg++) { + uint8_t value; + ESP_ERROR_CHECK(es8311_read_reg(dev, reg, &value)); + printf("REG:%02x: %02x", reg, value); + } +} + +es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr) +{ + es8311_dev_t *sensor = (es8311_dev_t *) calloc(1, sizeof(es8311_dev_t)); + sensor->port = port; + sensor->dev_addr = dev_addr; + return (es8311_handle_t) sensor; +} diff --git a/breath_button_monitor/breath_button_monitor/es8311.h b/breath_button_monitor/breath_button_monitor/es8311.h new file mode 100644 index 0000000..9930fc7 --- /dev/null +++ b/breath_button_monitor/breath_button_monitor/es8311.h @@ -0,0 +1,227 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief ES8311 driver + */ + +#pragma once + +#include "esp_types.h" +#include "esp_err.h" + +/* ES8311 address: CE pin low - 0x18, CE pin high - 0x19 */ +#define ES8311_ADDRRES_0 0x18u // Leaving this here for backward compatibility +#define ES8311_ADDRESS_0 0x18u +#define ES8311_ADDRESS_1 0x19u + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *es8311_handle_t; + +typedef enum { + ES8311_MIC_GAIN_MIN = -1, + ES8311_MIC_GAIN_0DB, + ES8311_MIC_GAIN_6DB, + ES8311_MIC_GAIN_12DB, + ES8311_MIC_GAIN_18DB, + ES8311_MIC_GAIN_24DB, + ES8311_MIC_GAIN_30DB, + ES8311_MIC_GAIN_36DB, + ES8311_MIC_GAIN_42DB, + ES8311_MIC_GAIN_MAX +} es8311_mic_gain_t; + +typedef enum { + ES8311_FADE_OFF = 0, + ES8311_FADE_4LRCK, // 4LRCK means ramp 0.25dB/4LRCK + ES8311_FADE_8LRCK, + ES8311_FADE_16LRCK, + ES8311_FADE_32LRCK, + ES8311_FADE_64LRCK, + ES8311_FADE_128LRCK, + ES8311_FADE_256LRCK, + ES8311_FADE_512LRCK, + ES8311_FADE_1024LRCK, + ES8311_FADE_2048LRCK, + ES8311_FADE_4096LRCK, + ES8311_FADE_8192LRCK, + ES8311_FADE_16384LRCK, + ES8311_FADE_32768LRCK, + ES8311_FADE_65536LRCK +} es8311_fade_t; + +typedef enum es8311_resolution_t { + ES8311_RESOLUTION_16 = 16, + ES8311_RESOLUTION_18 = 18, + ES8311_RESOLUTION_20 = 20, + ES8311_RESOLUTION_24 = 24, + ES8311_RESOLUTION_32 = 32 +} es8311_resolution_t; + +typedef struct es8311_clock_config_t { + bool mclk_inverted; + bool sclk_inverted; + bool mclk_from_mclk_pin; // true: from MCLK pin (pin no. 2), false: from SCLK pin (pin no. 6) + int mclk_frequency; // This parameter is ignored if MCLK is taken from SCLK pin + int sample_frequency; // in Hz +} es8311_clock_config_t; + +/** + * @brief Initialize ES8311 + * + * There are two ways of providing Master Clock (MCLK) signal to ES8311 in Slave Mode: + * 1. From MCLK pin: + * For flexible scenarios. A clock signal from I2S master is routed to MCLK pin. + * Its frequency must be defined in clk_cfg->mclk_frequency parameter. + * 2. From SCLK pin: + * For simpler scenarios. ES8311 takes its clock from SCK pin. MCLK pin does not have to be connected. + * In this case, res_in must equal res_out; clk_cfg->mclk_frequency parameter is ignored + * and MCLK is calculated as MCLK = clk_cfg->sample_frequency * res_out * 2. + * Not all sampling frequencies are supported in this mode. + * + * @param dev ES8311 handle + * @param[in] clk_cfg Clock configuration + * @param[in] res_in Input serial port resolution + * @param[in] res_out Output serial port resolution + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Sample frequency or resolution invalid + * - Else fail + */ +esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, + const es8311_resolution_t res_out); + +/** + * @brief Set output volume + * + * Volume paramter out of <0, 100> interval will be truncated. + * + * @param dev ES8311 handle + * @param[in] volume Set volume (0 ~ 100) + * @param[out] volume_set Volume that was set. Same as volume, unless volume is outside of <0, 100> interval. + * This parameter can be set to NULL, if user does not need this information. + * + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set); + +/** + * @brief Get output volume + * + * @param dev ES8311 handle + * @param[out] volume get volume (0 ~ 100) + * + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume); + +/** + * @brief Print out ES8311 register content + * + * @param dev ES8311 handle + */ +void es8311_register_dump(es8311_handle_t dev); + +/** + * @brief Mute ES8311 output + * + * @param dev ES8311 handle + * @param[in] enable true: mute, false: don't mute + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_mute(es8311_handle_t dev, bool enable); + +/** + * @brief Set Microphone gain + * + * @param dev ES8311 handle + * @param[in] gain_db Microphone gain + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db); + +/** + * @brief Configure microphone + * + * @param dev ES8311 handle + * @param[in] digital_mic Set to true for digital microphone + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic); + +/** + * @brief Configure sampling frequency + * + * @note This function is called by es8311_init(). + * Call this function explicitly only if you want to change sample frequency during runtime. + * @param dev ES8311 handle + * @param[in] mclk_frequency MCLK frequency in [Hz] (MCLK or SCLK pin, depending on bit register01[7]) + * @param[in] sample_frequency Required sample frequency in [Hz], e.g. 44100, 22050... + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG cannot set clock dividers for given MCLK and sampling frequency + * - Else I2C read/write error + */ +esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency); + +/** + * @brief Configure fade in/out for ADC: voice + * + * @param dev ES8311 handle + * @param[in] fade Fade ramp rate + * @return + * - ESP_OK success + * - Else I2C read/write error + */ +esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade); + +/** + * @brief Configure fade in/out for DAC: microphone + * + * @param dev ES8311 handle + * @param[in] fade Fade ramp rate + * @return + * - ESP_OK success + * - Else I2C read/write error + */ +esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade); + +/** + * @brief Create ES8311 object and return its handle + * + * @param[in] port I2C port number + * @param[in] dev_addr I2C device address of ES8311 + * + * @return + * - NULL Fail + * - Others Success + */ +es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr); + +/** + * @brief Delete ES8311 object + * + * @param dev ES8311 handle + */ +void es8311_delete(es8311_handle_t dev); + +#ifdef __cplusplus +} +#endif diff --git a/breath_button_monitor/breath_button_monitor/es8311_reg.h b/breath_button_monitor/breath_button_monitor/es8311_reg.h new file mode 100644 index 0000000..aeae4c0 --- /dev/null +++ b/breath_button_monitor/breath_button_monitor/es8311_reg.h @@ -0,0 +1,76 @@ +/* + * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +/* + * ES8311_REGISTER NAME_REG_REGISTER ADDRESS + */ +#define ES8311_RESET_REG00 0x00 /*reset digital,csm,clock manager etc.*/ + +/* + * Clock Scheme Register definition + */ +#define ES8311_CLK_MANAGER_REG01 0x01 /* select clk src for mclk, enable clock for codec */ +#define ES8311_CLK_MANAGER_REG02 0x02 /* clk divider and clk multiplier */ +#define ES8311_CLK_MANAGER_REG03 0x03 /* adc fsmode and osr */ +#define ES8311_CLK_MANAGER_REG04 0x04 /* dac osr */ +#define ES8311_CLK_MANAGER_REG05 0x05 /* clk divier for adc and dac */ +#define ES8311_CLK_MANAGER_REG06 0x06 /* bclk inverter and divider */ +#define ES8311_CLK_MANAGER_REG07 0x07 /* tri-state, lrck divider */ +#define ES8311_CLK_MANAGER_REG08 0x08 /* lrck divider */ +/* + * SDP + */ +#define ES8311_SDPIN_REG09 0x09 /* dac serial digital port */ +#define ES8311_SDPOUT_REG0A 0x0A /* adc serial digital port */ +/* + * SYSTEM + */ +#define ES8311_SYSTEM_REG0B 0x0B /* system */ +#define ES8311_SYSTEM_REG0C 0x0C /* system */ +#define ES8311_SYSTEM_REG0D 0x0D /* system, power up/down */ +#define ES8311_SYSTEM_REG0E 0x0E /* system, power up/down */ +#define ES8311_SYSTEM_REG0F 0x0F /* system, low power */ +#define ES8311_SYSTEM_REG10 0x10 /* system */ +#define ES8311_SYSTEM_REG11 0x11 /* system */ +#define ES8311_SYSTEM_REG12 0x12 /* system, Enable DAC */ +#define ES8311_SYSTEM_REG13 0x13 /* system */ +#define ES8311_SYSTEM_REG14 0x14 /* system, select DMIC, select analog pga gain */ +/* + * ADC + */ +#define ES8311_ADC_REG15 0x15 /* ADC, adc ramp rate, dmic sense */ +#define ES8311_ADC_REG16 0x16 /* ADC */ +#define ES8311_ADC_REG17 0x17 /* ADC, volume */ +#define ES8311_ADC_REG18 0x18 /* ADC, alc enable and winsize */ +#define ES8311_ADC_REG19 0x19 /* ADC, alc maxlevel */ +#define ES8311_ADC_REG1A 0x1A /* ADC, alc automute */ +#define ES8311_ADC_REG1B 0x1B /* ADC, alc automute, adc hpf s1 */ +#define ES8311_ADC_REG1C 0x1C /* ADC, equalizer, hpf s2 */ +/* + * DAC + */ +#define ES8311_DAC_REG31 0x31 /* DAC, mute */ +#define ES8311_DAC_REG32 0x32 /* DAC, volume */ +#define ES8311_DAC_REG33 0x33 /* DAC, offset */ +#define ES8311_DAC_REG34 0x34 /* DAC, drc enable, drc winsize */ +#define ES8311_DAC_REG35 0x35 /* DAC, drc maxlevel, minilevel */ +#define ES8311_DAC_REG37 0x37 /* DAC, ramprate */ +/* + *GPIO + */ +#define ES8311_GPIO_REG44 0x44 /* GPIO, dac2adc for test */ +#define ES8311_GP_REG45 0x45 /* GP CONTROL */ +/* + * CHIP + */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ +#define ES8311_CHD2_REGFE 0xFE /* CHIP ID2 */ +#define ES8311_CHVER_REGFF 0xFF /* VERSION */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ + +#define ES8311_MAX_REGISTER 0xFF diff --git a/breath_button_monitor/breath_dual_mode_monitor/AGENTS.md b/breath_button_monitor/breath_dual_mode_monitor/AGENTS.md new file mode 100644 index 0000000..36fa0cf --- /dev/null +++ b/breath_button_monitor/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/breath_button_monitor/breath_dual_mode_monitor/README.md b/breath_button_monitor/breath_dual_mode_monitor/README.md new file mode 100644 index 0000000..4120ed0 --- /dev/null +++ b/breath_button_monitor/breath_dual_mode_monitor/README.md @@ -0,0 +1,160 @@ +# 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. + +`START MANUAL MONITOR` является большой основной кнопкой. Все остальные режимы находятся ниже как компактные служебные кнопки. + +## 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`. +- В правом верхнем углу показываются заряд батареи и значок молнии во время зарядки. Данные читает AXP2101. +- Дисплей гаснет после выбранного времени без касания экрана или внешней кнопки. Измерение, кнопки и предупреждения продолжают работать; касание или кнопка сразу включает подсветку обратно. +- Если после принятой фазы нет следующей корректной противоположной кнопки: первые 30 секунд скетч молчит, затем 30 секунд тихо сигналит каждые 5 секунд, следующие 30 секунд громко сигналит каждые 5 секунд, затем ещё 5 минут громко сигналит раз в 15 секунд. После этого AXP2101 выключает прибор. + +## 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` не создаёт цикл. +- В ручном режиме учитывается каждый полный цикл, включая длительности меньше 3 секунд. +- Ручной монитор принимает фазы только в порядке `INHALE -> EXHALE -> INHALE`. Повторное нажатие текущей кнопки и `EXHALE` до первого `INHALE` полностью игнорируются: не меняют фазу, не сбрасывают таймер и не подают звук. +- Каждое принятое нажатие даёт один тихий подтверждающий сигнал. В ручном режиме поле `Phase time` показывает длительность именно текущего вдоха или выдоха. +- В USB Sensor Mode циклы короче 3 секунд игнорируются без сброса текущего таймера цикла. +- Среднее считается с округлением по миллисекундам по последним 5 завершённым циклам и выводится до десятых секунды. +- После принятого `EXHALE` добавляется полный цикл, пересчитывается среднее и при среднем ниже лимита срабатывает предупреждение. +- Внизу экрана всегда показаны те же последние 5 измерений, из которых считается среднее. +- Нижние два числовых поля (`From start` и `Limit`) выводятся увеличенным размером. + +## Settings + +Settings сохраняются в NVS: + +- limit: `5 / 7 / 10 / 15 / 20` секунд; +- quiet cycle tick volume: `0..10`; +- alert volume: `0..10`. +- screen timeout: `10s / 30s / 60s / Always`. + +Настройки прокручиваются вертикальным свайпом, чтобы поместить все четыре пункта. + +## Тревоги + +- Если среднее последних циклов меньше выбранного лимита, звучат предупреждения как в USB breath monitor: серия растёт до 5 сигналов. +- В USB-режиме длинный цикл с 60 секунд использует 5 громких сигналов с повтором каждые 5 секунд. +- В ручном мониторе используется отдельная экономная лестница напоминаний, описанная выше, с выключением питания через 6 минут 30 секунд без корректной следующей фазы. + +## Прошивка + +Из папки `SKETCH/breath_button_monitor`: + +```bash +./burn.sh breath-dual-mode-monitor +``` + +Только проверить сборку, не прошивая плату: + +```bash +NO_UPLOAD=1 ./burn.sh breath-dual-mode-monitor +``` diff --git a/breath_button_monitor/breath_dual_mode_monitor/breath_dual_mode_monitor.ino b/breath_button_monitor/breath_dual_mode_monitor/breath_dual_mode_monitor.ino new file mode 100644 index 0000000..01ef423 --- /dev/null +++ b/breath_button_monitor/breath_dual_mode_monitor/breath_dual_mode_monitor.ino @@ -0,0 +1,1327 @@ +#include +#include +#include +#include +#include +#include +#define XPOWERS_CHIP_AXP2101 +#include "XPowersLib.h" +#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 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 kBatteryUiPeriodMs = 5000; +static constexpr uint32_t kManualQuietStartMs = 30000; +static constexpr uint32_t kManualLoudStartMs = 60000; +static constexpr uint32_t kManualSlowLoudStartMs = 90000; +static constexpr uint32_t kManualPowerOffMs = 390000; +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; +XPowersPMU gPower; +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 kStartButtonsButton = {44, 196, 392, 66}; +static const Rect kStartUsbButton = {44, 282, 188, 30}; +static const Rect kStartPotButton = {248, 282, 188, 30}; +static const Rect kStartPot2Button = {44, 322, 188, 30}; +static const Rect kStartPotCalButton = {248, 322, 188, 30}; +static const Rect kStartPinDiagButton = {44, 362, 392, 30}; +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 Rect kScreenSlider = {42, 494, 396, 44}; +static const uint16_t kLimitsSec[] = {5, 7, 10, 15, 20}; +static const uint32_t kScreenTimeoutMs[] = {10000, 30000, 60000, 0}; +static const char *kScreenTimeoutNames[] = {"10s", "30s", "60s", "Always"}; +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 gPowerReady = false; +static bool gScreenOn = true; +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 gLastBatteryUiMs = 0; +static uint32_t gLastScreenActivityMs = 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 gScreenTimeoutIndex = 1; +static uint8_t gSettingsScroll = 0; +static uint8_t gShortStreak = 0; +static uint16_t gShortAvgEvents = 0; +static uint16_t gLongPauseEvents = 0; +static uint32_t gLastRepeatAlertMs = 0; +static uint8_t gLastManualReminderSlot = 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 initPowerManagement() { + gPowerReady = gPower.begin(Wire, AXP2101_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL); + if (!gPowerReady) return; + gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); + gPower.setChargeTargetVoltage(3); + gPower.clearIrqStatus(); + gPower.enableTemperatureMeasure(); + gPower.enableBattDetection(); + gPower.enableBattVoltageMeasure(); + gPower.enableVbusVoltageMeasure(); + gPower.enableSystemVoltageMeasure(); +} + +static int batteryPercentValue() { + if (!gPowerReady || !gPower.isBatteryConnect()) return -1; + return constrain(gPower.getBatteryPercent(), 0, 100); +} + +static bool batteryIsChargingNow() { + return gPowerReady && gPower.isBatteryConnect() && gPower.isCharging(); +} + +static void drawBatteryStatus() { + gfx->fillRect(344, 14, 104, 24, C_PANEL); + int battery = batteryPercentValue(); + bool charging = batteryIsChargingNow(); + char text[12]; + snprintf(text, sizeof(text), battery >= 0 ? "%d%%" : "--", battery); + drawText(344, 18, text, C_MUTE, 1); + int x = 390; + int y = 18; + gfx->drawRoundRect(x, y, 30, 15, 3, C_MUTE); + gfx->fillRect(x + 30, y + 4, 3, 7, C_MUTE); + if (battery > 0) { + int width = max(2, min(26, battery * 26 / 100)); + uint16_t color = battery <= 10 ? C_BAD : C_OK; + gfx->fillRoundRect(x + 2, y + 2, width, 11, 2, color); + } + if (charging) { + gfx->drawLine(428, 16, 423, 25, C_ACCENT); + gfx->drawLine(423, 25, 427, 25, C_ACCENT); + gfx->drawLine(427, 25, 424, 35, C_ACCENT); + } +} + +static void noteScreenActivity() { + gLastScreenActivityMs = millis(); + if (!gScreenOn) { + gScreenOn = true; + gfx->setBrightness(220); + gNeedStaticRedraw = true; + gNeedRedraw = true; + } +} + +static void pollScreenTimeout() { + uint32_t timeout = kScreenTimeoutMs[gScreenTimeoutIndex]; + if (!gScreenOn || timeout == 0 || millis() - gLastScreenActivityMs < timeout) return; + gScreenOn = false; + gfx->setBrightness(0); +} + +static void turnOffDevice() { + gfx->setBrightness(0); + digitalWrite(PIN_PA, LOW); + if (gPowerReady) { + gPower.shutdown(); + delay(100); + } + esp_deep_sleep_start(); +} + +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; + } + uint64_t sum = 0; + for (uint8_t i = 0; i < gCycleCount; i++) { + sum += gCycleMs[i]; + } + return (uint32_t)((sum + gCycleCount / 2) / gCycleCount); +} + +static uint32_t minCycleMsForCurrentMode() { + return gInputMode == InputMode::UsbContact ? kUsbMinCycleMs : 0; +} + +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, " %lu.%lus", + (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); + gScreenTimeoutIndex = gPrefs.getUChar("screen", gScreenTimeoutIndex); + if (gLimitIndex > 4) gLimitIndex = 2; + if (gTickVolume > 10) gTickVolume = 3; + if (gAlertVolume > 10) gAlertVolume = 10; + if (gScreenTimeoutIndex > 3) gScreenTimeoutIndex = 1; +} + +static void saveSettings() { + gPrefs.putUChar("limit", gLimitIndex); + gPrefs.putUChar("tick", gTickVolume); + gPrefs.putUChar("alert", gAlertVolume); + gPrefs.putUChar("screen", gScreenTimeoutIndex); +} + +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, 106, 412, 72, C_CARD, C_BORDER, 14); + drawCenteredText(34, 126, 412, "Main mode", C_MUTE, 1); + drawCenteredText(34, 150, 412, "manual breath buttons", C_TEXT, 2); + drawButton(kStartButtonsButton, "START MANUAL MONITOR", C_OK, 3); + drawText(44, 268, "Service modes", C_MUTE, 1); + drawButton(kStartUsbButton, "USB SENSOR", C_BUTTON, 1); + drawButton(kStartPotButton, "POT 3-WIRE", C_ACCENT, 1); + drawButton(kStartPot2Button, "POT 2-WIRE", C_BUTTON, 1); + drawButton(kStartPotCalButton, "POT CAL", C_OK, 1); + drawButton(kStartPinDiagButton, "USB PIN DIAG", C_BAD, 1); +} + +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]; + int yOffset = gSettingsScroll * 112; + gfx->fillScreen(C_BG); + drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); + drawText(28, 32, "SETTINGS", C_TEXT, 3); + drawText(28, 68, "Swipe up/down INHALE closes", C_MUTE, 1); + + snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]); + Rect limit = kLimitSlider; + limit.y -= yOffset; + drawSlider(limit, "Limit", value, gLimitIndex, 4); + snprintf(value, sizeof(value), "%u/10", gTickVolume); + Rect tick = kTickSlider; + tick.y -= yOffset; + drawSlider(tick, "Cycle tick volume", value, gTickVolume, 10); + snprintf(value, sizeof(value), "%u/10", gAlertVolume); + Rect alert = kAlertSlider; + alert.y -= yOffset; + drawSlider(alert, "Alert volume", value, gAlertVolume, 10); + Rect screen = kScreenSlider; + screen.y -= yOffset; + drawSlider(screen, "Screen timeout", kScreenTimeoutNames[gScreenTimeoutIndex], gScreenTimeoutIndex, 3); + + 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 pollBreathAlerts() { + if (!gStarted || gSettingsOpen || gInputMode == InputMode::PotTest || + gInputMode == InputMode::PotTwoWireTest || gInputMode == InputMode::PotCalTest || + gInputMode == InputMode::UsbPinDiag) { + return; + } + + uint32_t now = millis(); + uint32_t activeStartMs = gInputMode == InputMode::ExternalButtons ? gPhaseStartMs : gLastCycleStartMs; + if (activeStartMs == 0) return; + uint32_t elapsedMs = now - activeStartMs; + + if (gInputMode == InputMode::ExternalButtons) { + if (elapsedMs >= kManualPowerOffMs) { + turnOffDevice(); + return; + } + + uint8_t slot = 0; + bool loud = false; + if (elapsedMs >= kManualSlowLoudStartMs) { + slot = 100 + (elapsedMs - kManualSlowLoudStartMs) / 15000; + loud = true; + } else if (elapsedMs >= kManualLoudStartMs) { + slot = 50 + (elapsedMs - kManualLoudStartMs) / 5000; + loud = true; + } else if (elapsedMs >= kManualQuietStartMs) { + slot = 10 + (elapsedMs - kManualQuietStartMs) / 5000; + } + if (slot != 0 && slot != gLastManualReminderSlot) { + gLastManualReminderSlot = slot; + if (loud) playAlertBeep(); + else playCycleTick(); + } + gLongPauseActive = elapsedMs >= kManualLoudStartMs; + return; + } + + if (elapsedMs < kPauseAfterMs) return; + if (!gLongPauseActive) { + gLongPauseActive = true; + gLongPauseEvents++; + gLastRepeatAlertMs = now; + playFiveAlertBeeps(); + } else if ((uint32_t)(now - gLastRepeatAlertMs) >= kRepeatAlertMs) { + gLastRepeatAlertMs = now; + playFiveAlertBeeps(); + } +} + +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 (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); + + formatLastFiveCycles(line, sizeof(line)); + 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 (!gScreenOn) { + gNeedRedraw = false; + return; + } + 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(); + } + drawBatteryStatus(); + 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; + gLastManualReminderSlot = 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; + if (gSettingsOpen) gSettingsScroll = 0; + 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; + gLastManualReminderSlot = 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) { + int16_t contentY = y + gSettingsScroll * 112; + if (contains(kLimitSlider, x, contentY)) { + uint8_t next = sliderValueFromX(kLimitSlider, x, 4); + if (next == gLimitIndex) return; + gLimitIndex = next; + } else if (contains(kTickSlider, x, contentY)) { + uint8_t next = sliderValueFromX(kTickSlider, x, 10); + if (next == gTickVolume) return; + gTickVolume = next; + playCycleTick(); + } else if (contains(kAlertSlider, x, contentY)) { + uint8_t next = sliderValueFromX(kAlertSlider, x, 10); + if (next == gAlertVolume) return; + gAlertVolume = next; + playAlertBeep(); + } else if (contains(kScreenSlider, x, contentY)) { + uint8_t next = sliderValueFromX(kScreenSlider, x, 3); + if (next == gScreenTimeoutIndex) return; + gScreenTimeoutIndex = next; + } 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 (pressed) noteScreenActivity(); + 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) { + noteScreenActivity(); + 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) { + noteScreenActivity(); + 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) { + if (gSettingsOpen && dy >= 18) { + if (gTouchLastY < gTouchStartY && gSettingsScroll == 0) { + gSettingsScroll = 1; + gNeedRedraw = true; + } else if (gTouchLastY > gTouchStartY && gSettingsScroll == 1) { + gSettingsScroll = 0; + gNeedRedraw = true; + } + } + 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); + initPowerManagement(); + loadSettings(); + initAudio(); + + gfx->begin(); + gBus->writeC8D8(0x36, 0xA0); + gfx->setBrightness(220); + gfx->fillScreen(C_BG); + gLastScreenActivityMs = millis(); + + 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(); + pollBreathAlerts(); + pollScreenTimeout(); + if (gScreenOn && gStarted && !gSettingsOpen && + (gInputMode == InputMode::PotTest || gInputMode == InputMode::PotTwoWireTest) && + millis() - gLastPotUiMs >= kPotUiPeriodMs) { + updatePotValues(false); + gLastPotUiMs = millis(); + } + if (gScreenOn && gStarted && !gSettingsOpen && gInputMode == InputMode::PotCalTest && + millis() - gLastPotUiMs >= kPotUiPeriodMs) { + updatePotCalValues(); + gLastPotUiMs = millis(); + } + if (gScreenOn && gStarted && !gSettingsOpen && gInputMode == InputMode::UsbPinDiag && + millis() - gLastPinDiagUiMs >= kPinDiagPeriodMs) { + updatePinDiagValues(); + gLastPinDiagUiMs = millis(); + } + if (gScreenOn && gStarted && !gSettingsOpen && + gInputMode != InputMode::PotTest && gInputMode != InputMode::PotTwoWireTest && + gInputMode != InputMode::PotCalTest && + gInputMode != InputMode::UsbPinDiag && + millis() - gLastUiMs >= kUiPeriodMs) { + updateMonitorValues(false); + gLastUiMs = millis(); + } + if (gScreenOn && millis() - gLastBatteryUiMs >= kBatteryUiPeriodMs) { + drawBatteryStatus(); + gLastBatteryUiMs = millis(); + } + if (gNeedRedraw) { + redrawScreen(); + } + delay(10); +} diff --git a/breath_button_monitor/breath_dual_mode_monitor/es8311.c b/breath_button_monitor/breath_dual_mode_monitor/es8311.c new file mode 100644 index 0000000..c78bc2b --- /dev/null +++ b/breath_button_monitor/breath_dual_mode_monitor/es8311.c @@ -0,0 +1,443 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "es8311.h" +#include "driver/gpio.h" +#include "esp_log.h" +#include "esp_err.h" +#include "esp_check.h" +#include "es8311_reg.h" +#include "esp32-hal-i2c.h" + + +typedef struct { + unsigned int port; + uint16_t dev_addr; +} es8311_dev_t; + +/* + * Clock coefficient structure + */ +struct _coeff_div { + uint32_t mclk; /* mclk frequency */ + uint32_t rate; /* sample rate */ + uint8_t pre_div; /* the pre divider with range from 1 to 8 */ + uint8_t pre_multi; /* the pre multiplier with 0: 1x, 1: 2x, 2: 4x, 3: 8x selection */ + uint8_t adc_div; /* adcclk divider */ + uint8_t dac_div; /* dacclk divider */ + uint8_t fs_mode; /* double speed or single speed, =0, ss, =1, ds */ + uint8_t lrck_h; /* adclrck divider and daclrck divider */ + uint8_t lrck_l; + uint8_t bclk_div; /* sclk divider */ + uint8_t adc_osr; /* adc osr */ + uint8_t dac_osr; /* dac osr */ +}; + +/* codec hifi mclk clock divider coefficients */ +static const struct _coeff_div coeff_div[] = { + /*!port, es->dev_addr, write_buf, sizeof(write_buf), 1000); +} + +static inline esp_err_t es8311_read_reg(es8311_handle_t dev, uint8_t reg_addr, uint8_t *reg_value) +{ + es8311_dev_t *es = (es8311_dev_t *) dev; + size_t readCount = 0; + return i2cWriteReadNonStop(es->port, es->dev_addr, ®_addr, 1, reg_value, 1, 1000, &readCount); +} + +/* +* look for the coefficient in coeff_div[] table +*/ +static int get_coeff(uint32_t mclk, uint32_t rate) +{ + for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) { + if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) { + return i; + } + } + + return -1; +} + +esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency) +{ + uint8_t regv; + + /* Get clock coefficients from coefficient table */ + int coeff = get_coeff(mclk_frequency, sample_frequency); + + if (coeff < 0) { + ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_frequency, mclk_frequency); + return ESP_ERR_INVALID_ARG; + } + + const struct _coeff_div *const selected_coeff = &coeff_div[coeff]; + + /* register 0x02 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG02, ®v), TAG, "I2C read/write error"); + regv &= 0x07; + regv |= (selected_coeff->pre_div - 1) << 5; + regv |= selected_coeff->pre_multi << 3; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG02, regv), TAG, "I2C read/write error"); + + /* register 0x03 */ + const uint8_t reg03 = (selected_coeff->fs_mode << 6) | selected_coeff->adc_osr; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG03, reg03), TAG, "I2C read/write error"); + + /* register 0x04 */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG04, selected_coeff->dac_osr), TAG, "I2C read/write error"); + + /* register 0x05 */ + const uint8_t reg05 = ((selected_coeff->adc_div - 1) << 4) | (selected_coeff->dac_div - 1); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG05, reg05), TAG, "I2C read/write error"); + + /* register 0x06 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®v), TAG, "I2C read/write error"); + regv &= 0xE0; + + if (selected_coeff->bclk_div < 19) { + regv |= (selected_coeff->bclk_div - 1) << 0; + } else { + regv |= (selected_coeff->bclk_div) << 0; + } + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, regv), TAG, "I2C read/write error"); + + /* register 0x07 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG07, ®v), TAG, "I2C read/write error"); + regv &= 0xC0; + regv |= selected_coeff->lrck_h << 0; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG07, regv), TAG, "I2C read/write error"); + + /* register 0x08 */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG08, selected_coeff->lrck_l), TAG, "I2C read/write error"); + + return ESP_OK; +} + +static esp_err_t es8311_clock_config(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, es8311_resolution_t res) +{ + uint8_t reg06; + uint8_t reg01 = 0x3F; // Enable all clocks + int mclk_hz; + + /* Select clock source for internal MCLK and determine its frequency */ + if (clk_cfg->mclk_from_mclk_pin) { + mclk_hz = clk_cfg->mclk_frequency; + } else { + mclk_hz = clk_cfg->sample_frequency * (int)res * 2; + reg01 |= BIT(7); // Select BCLK (a.k.a. SCK) pin + } + + if (clk_cfg->mclk_inverted) { + reg01 |= BIT(6); // Invert MCLK pin + } + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG01, reg01), TAG, "I2C read/write error"); + + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®06), TAG, "I2C read/write error"); + if (clk_cfg->sclk_inverted) { + reg06 |= BIT(5); + } else { + reg06 &= ~BIT(5); + } + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, reg06), TAG, "I2C read/write error"); + + /* Configure clock dividers */ + return es8311_sample_frequency_config(dev, mclk_hz, clk_cfg->sample_frequency); +} + +static esp_err_t es8311_resolution_config(const es8311_resolution_t res, uint8_t *reg) +{ + switch (res) { + case ES8311_RESOLUTION_16: + *reg |= (3 << 2); + break; + case ES8311_RESOLUTION_18: + *reg |= (2 << 2); + break; + case ES8311_RESOLUTION_20: + *reg |= (1 << 2); + break; + case ES8311_RESOLUTION_24: + *reg |= (0 << 2); + break; + case ES8311_RESOLUTION_32: + *reg |= (4 << 2); + break; + default: + return ESP_ERR_INVALID_ARG; + } + return ESP_OK; +} + +static esp_err_t es8311_fmt_config(es8311_handle_t dev, const es8311_resolution_t res_in, const es8311_resolution_t res_out) +{ + uint8_t reg09 = 0; // SDP In + uint8_t reg0a = 0; // SDP Out + + ESP_LOGI(TAG, "ES8311 in Slave mode and I2S format"); + uint8_t reg00; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_RESET_REG00, ®00), TAG, "I2C read/write error"); + reg00 &= 0xBF; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, reg00), TAG, "I2C read/write error"); // Slave serial port - default + + /* Setup SDP In and Out resolution */ + es8311_resolution_config(res_in, ®09); + es8311_resolution_config(res_out, ®0a); + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPIN_REG09, reg09), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPOUT_REG0A, reg0a), TAG, "I2C read/write error"); + + return ESP_OK; +} + +esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic) +{ + uint8_t reg14 = 0x1A; // enable analog MIC and max PGA gain + + /* PDM digital microphone enable or disable */ + if (digital_mic) { + reg14 |= BIT(6); + } + es8311_write_reg(dev, ES8311_ADC_REG17, 0xC8); // Set ADC gain @todo move this to ADC config section + + return es8311_write_reg(dev, ES8311_SYSTEM_REG14, reg14); +} + +esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, const es8311_resolution_t res_out) +{ + ESP_RETURN_ON_FALSE( + (clk_cfg->sample_frequency >= 8000) && (clk_cfg->sample_frequency <= 96000), + ESP_ERR_INVALID_ARG, TAG, "ES8311 init needs frequency in interval [8000; 96000] Hz" + ); + if (!clk_cfg->mclk_from_mclk_pin) { + ESP_RETURN_ON_FALSE(res_out == res_in, ESP_ERR_INVALID_ARG, TAG, "Resolution IN/OUT must be equal if MCLK is taken from SCK pin"); + } + + + /* Reset ES8311 to its default */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x1F), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x00), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x80), TAG, "I2C read/write error"); // Power-on command + + /* Setup clock: source, polarity and clock dividers */ + ESP_RETURN_ON_ERROR(es8311_clock_config(dev, clk_cfg, res_out), TAG, ""); + + /* Setup audio format (fmt): master/slave, resolution, I2S */ + ESP_RETURN_ON_ERROR(es8311_fmt_config(dev, res_in, res_out), TAG, ""); + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0D, 0x01), TAG, "I2C read/write error"); // Power up analog circuitry - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0E, 0x02), TAG, "I2C read/write error"); // Enable analog PGA, enable ADC modulator - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG12, 0x00), TAG, "I2C read/write error"); // power-up DAC - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG13, 0x10), TAG, "I2C read/write error"); // Enable output to HP drive - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_ADC_REG1C, 0x6A), TAG, "I2C read/write error"); // ADC Equalizer bypass, cancel DC offset in digital domain + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_DAC_REG37, 0x08), TAG, "I2C read/write error"); // Bypass DAC equalizer - NOT default + + return ESP_OK; +} + +void es8311_delete(es8311_handle_t dev) +{ + free(dev); +} + +esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set) +{ + if (volume < 0) { + volume = 0; + } else if (volume > 100) { + volume = 100; + } + + int reg32; + if (volume == 0) { + reg32 = 0; + } else { + reg32 = ((volume) * 256 / 100) - 1; + } + + // provide user with real volume set + if (volume_set != NULL) { + *volume_set = volume; + } + return es8311_write_reg(dev, ES8311_DAC_REG32, reg32); +} + +esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume) +{ + uint8_t reg32; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG32, ®32), TAG, "I2C read/write error"); + + if (reg32 == 0) { + *volume = 0; + } else { + *volume = ((reg32 * 100) / 256) + 1; + } + return ESP_OK; +} + +esp_err_t es8311_voice_mute(es8311_handle_t dev, bool mute) +{ + uint8_t reg31; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG31, ®31), TAG, "I2C read/write error"); + + if (mute) { + reg31 |= BIT(6) | BIT(5); + } else { + reg31 &= ~(BIT(6) | BIT(5)); + } + + return es8311_write_reg(dev, ES8311_DAC_REG31, reg31); +} + +esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db) +{ + return es8311_write_reg(dev, ES8311_ADC_REG16, gain_db); // ADC gain scale up +} + +esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade) +{ + uint8_t reg37; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG37, ®37), TAG, "I2C read/write error"); + reg37 &= 0x0F; + reg37 |= (fade << 4); + return es8311_write_reg(dev, ES8311_DAC_REG37, reg37); +} + +esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade) +{ + uint8_t reg15; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_ADC_REG15, ®15), TAG, "I2C read/write error"); + reg15 &= 0x0F; + reg15 |= (fade << 4); + return es8311_write_reg(dev, ES8311_ADC_REG15, reg15); +} + +void es8311_register_dump(es8311_handle_t dev) +{ + for (int reg = 0; reg < 0x4A; reg++) { + uint8_t value; + ESP_ERROR_CHECK(es8311_read_reg(dev, reg, &value)); + printf("REG:%02x: %02x", reg, value); + } +} + +es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr) +{ + es8311_dev_t *sensor = (es8311_dev_t *) calloc(1, sizeof(es8311_dev_t)); + sensor->port = port; + sensor->dev_addr = dev_addr; + return (es8311_handle_t) sensor; +} diff --git a/breath_button_monitor/breath_dual_mode_monitor/es8311.h b/breath_button_monitor/breath_dual_mode_monitor/es8311.h new file mode 100644 index 0000000..9930fc7 --- /dev/null +++ b/breath_button_monitor/breath_dual_mode_monitor/es8311.h @@ -0,0 +1,227 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief ES8311 driver + */ + +#pragma once + +#include "esp_types.h" +#include "esp_err.h" + +/* ES8311 address: CE pin low - 0x18, CE pin high - 0x19 */ +#define ES8311_ADDRRES_0 0x18u // Leaving this here for backward compatibility +#define ES8311_ADDRESS_0 0x18u +#define ES8311_ADDRESS_1 0x19u + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *es8311_handle_t; + +typedef enum { + ES8311_MIC_GAIN_MIN = -1, + ES8311_MIC_GAIN_0DB, + ES8311_MIC_GAIN_6DB, + ES8311_MIC_GAIN_12DB, + ES8311_MIC_GAIN_18DB, + ES8311_MIC_GAIN_24DB, + ES8311_MIC_GAIN_30DB, + ES8311_MIC_GAIN_36DB, + ES8311_MIC_GAIN_42DB, + ES8311_MIC_GAIN_MAX +} es8311_mic_gain_t; + +typedef enum { + ES8311_FADE_OFF = 0, + ES8311_FADE_4LRCK, // 4LRCK means ramp 0.25dB/4LRCK + ES8311_FADE_8LRCK, + ES8311_FADE_16LRCK, + ES8311_FADE_32LRCK, + ES8311_FADE_64LRCK, + ES8311_FADE_128LRCK, + ES8311_FADE_256LRCK, + ES8311_FADE_512LRCK, + ES8311_FADE_1024LRCK, + ES8311_FADE_2048LRCK, + ES8311_FADE_4096LRCK, + ES8311_FADE_8192LRCK, + ES8311_FADE_16384LRCK, + ES8311_FADE_32768LRCK, + ES8311_FADE_65536LRCK +} es8311_fade_t; + +typedef enum es8311_resolution_t { + ES8311_RESOLUTION_16 = 16, + ES8311_RESOLUTION_18 = 18, + ES8311_RESOLUTION_20 = 20, + ES8311_RESOLUTION_24 = 24, + ES8311_RESOLUTION_32 = 32 +} es8311_resolution_t; + +typedef struct es8311_clock_config_t { + bool mclk_inverted; + bool sclk_inverted; + bool mclk_from_mclk_pin; // true: from MCLK pin (pin no. 2), false: from SCLK pin (pin no. 6) + int mclk_frequency; // This parameter is ignored if MCLK is taken from SCLK pin + int sample_frequency; // in Hz +} es8311_clock_config_t; + +/** + * @brief Initialize ES8311 + * + * There are two ways of providing Master Clock (MCLK) signal to ES8311 in Slave Mode: + * 1. From MCLK pin: + * For flexible scenarios. A clock signal from I2S master is routed to MCLK pin. + * Its frequency must be defined in clk_cfg->mclk_frequency parameter. + * 2. From SCLK pin: + * For simpler scenarios. ES8311 takes its clock from SCK pin. MCLK pin does not have to be connected. + * In this case, res_in must equal res_out; clk_cfg->mclk_frequency parameter is ignored + * and MCLK is calculated as MCLK = clk_cfg->sample_frequency * res_out * 2. + * Not all sampling frequencies are supported in this mode. + * + * @param dev ES8311 handle + * @param[in] clk_cfg Clock configuration + * @param[in] res_in Input serial port resolution + * @param[in] res_out Output serial port resolution + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Sample frequency or resolution invalid + * - Else fail + */ +esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, + const es8311_resolution_t res_out); + +/** + * @brief Set output volume + * + * Volume paramter out of <0, 100> interval will be truncated. + * + * @param dev ES8311 handle + * @param[in] volume Set volume (0 ~ 100) + * @param[out] volume_set Volume that was set. Same as volume, unless volume is outside of <0, 100> interval. + * This parameter can be set to NULL, if user does not need this information. + * + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set); + +/** + * @brief Get output volume + * + * @param dev ES8311 handle + * @param[out] volume get volume (0 ~ 100) + * + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume); + +/** + * @brief Print out ES8311 register content + * + * @param dev ES8311 handle + */ +void es8311_register_dump(es8311_handle_t dev); + +/** + * @brief Mute ES8311 output + * + * @param dev ES8311 handle + * @param[in] enable true: mute, false: don't mute + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_mute(es8311_handle_t dev, bool enable); + +/** + * @brief Set Microphone gain + * + * @param dev ES8311 handle + * @param[in] gain_db Microphone gain + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db); + +/** + * @brief Configure microphone + * + * @param dev ES8311 handle + * @param[in] digital_mic Set to true for digital microphone + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic); + +/** + * @brief Configure sampling frequency + * + * @note This function is called by es8311_init(). + * Call this function explicitly only if you want to change sample frequency during runtime. + * @param dev ES8311 handle + * @param[in] mclk_frequency MCLK frequency in [Hz] (MCLK or SCLK pin, depending on bit register01[7]) + * @param[in] sample_frequency Required sample frequency in [Hz], e.g. 44100, 22050... + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG cannot set clock dividers for given MCLK and sampling frequency + * - Else I2C read/write error + */ +esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency); + +/** + * @brief Configure fade in/out for ADC: voice + * + * @param dev ES8311 handle + * @param[in] fade Fade ramp rate + * @return + * - ESP_OK success + * - Else I2C read/write error + */ +esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade); + +/** + * @brief Configure fade in/out for DAC: microphone + * + * @param dev ES8311 handle + * @param[in] fade Fade ramp rate + * @return + * - ESP_OK success + * - Else I2C read/write error + */ +esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade); + +/** + * @brief Create ES8311 object and return its handle + * + * @param[in] port I2C port number + * @param[in] dev_addr I2C device address of ES8311 + * + * @return + * - NULL Fail + * - Others Success + */ +es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr); + +/** + * @brief Delete ES8311 object + * + * @param dev ES8311 handle + */ +void es8311_delete(es8311_handle_t dev); + +#ifdef __cplusplus +} +#endif diff --git a/breath_button_monitor/breath_dual_mode_monitor/es8311_reg.h b/breath_button_monitor/breath_dual_mode_monitor/es8311_reg.h new file mode 100644 index 0000000..aeae4c0 --- /dev/null +++ b/breath_button_monitor/breath_dual_mode_monitor/es8311_reg.h @@ -0,0 +1,76 @@ +/* + * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +/* + * ES8311_REGISTER NAME_REG_REGISTER ADDRESS + */ +#define ES8311_RESET_REG00 0x00 /*reset digital,csm,clock manager etc.*/ + +/* + * Clock Scheme Register definition + */ +#define ES8311_CLK_MANAGER_REG01 0x01 /* select clk src for mclk, enable clock for codec */ +#define ES8311_CLK_MANAGER_REG02 0x02 /* clk divider and clk multiplier */ +#define ES8311_CLK_MANAGER_REG03 0x03 /* adc fsmode and osr */ +#define ES8311_CLK_MANAGER_REG04 0x04 /* dac osr */ +#define ES8311_CLK_MANAGER_REG05 0x05 /* clk divier for adc and dac */ +#define ES8311_CLK_MANAGER_REG06 0x06 /* bclk inverter and divider */ +#define ES8311_CLK_MANAGER_REG07 0x07 /* tri-state, lrck divider */ +#define ES8311_CLK_MANAGER_REG08 0x08 /* lrck divider */ +/* + * SDP + */ +#define ES8311_SDPIN_REG09 0x09 /* dac serial digital port */ +#define ES8311_SDPOUT_REG0A 0x0A /* adc serial digital port */ +/* + * SYSTEM + */ +#define ES8311_SYSTEM_REG0B 0x0B /* system */ +#define ES8311_SYSTEM_REG0C 0x0C /* system */ +#define ES8311_SYSTEM_REG0D 0x0D /* system, power up/down */ +#define ES8311_SYSTEM_REG0E 0x0E /* system, power up/down */ +#define ES8311_SYSTEM_REG0F 0x0F /* system, low power */ +#define ES8311_SYSTEM_REG10 0x10 /* system */ +#define ES8311_SYSTEM_REG11 0x11 /* system */ +#define ES8311_SYSTEM_REG12 0x12 /* system, Enable DAC */ +#define ES8311_SYSTEM_REG13 0x13 /* system */ +#define ES8311_SYSTEM_REG14 0x14 /* system, select DMIC, select analog pga gain */ +/* + * ADC + */ +#define ES8311_ADC_REG15 0x15 /* ADC, adc ramp rate, dmic sense */ +#define ES8311_ADC_REG16 0x16 /* ADC */ +#define ES8311_ADC_REG17 0x17 /* ADC, volume */ +#define ES8311_ADC_REG18 0x18 /* ADC, alc enable and winsize */ +#define ES8311_ADC_REG19 0x19 /* ADC, alc maxlevel */ +#define ES8311_ADC_REG1A 0x1A /* ADC, alc automute */ +#define ES8311_ADC_REG1B 0x1B /* ADC, alc automute, adc hpf s1 */ +#define ES8311_ADC_REG1C 0x1C /* ADC, equalizer, hpf s2 */ +/* + * DAC + */ +#define ES8311_DAC_REG31 0x31 /* DAC, mute */ +#define ES8311_DAC_REG32 0x32 /* DAC, volume */ +#define ES8311_DAC_REG33 0x33 /* DAC, offset */ +#define ES8311_DAC_REG34 0x34 /* DAC, drc enable, drc winsize */ +#define ES8311_DAC_REG35 0x35 /* DAC, drc maxlevel, minilevel */ +#define ES8311_DAC_REG37 0x37 /* DAC, ramprate */ +/* + *GPIO + */ +#define ES8311_GPIO_REG44 0x44 /* GPIO, dac2adc for test */ +#define ES8311_GP_REG45 0x45 /* GP CONTROL */ +/* + * CHIP + */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ +#define ES8311_CHD2_REGFE 0xFE /* CHIP ID2 */ +#define ES8311_CHVER_REGFF 0xFF /* VERSION */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ + +#define ES8311_MAX_REGISTER 0xFF diff --git a/breath_button_monitor/burn.sh b/breath_button_monitor/burn.sh new file mode 100755 index 0000000..cf8dd6f --- /dev/null +++ b/breath_button_monitor/burn.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +WORKSPACE_DIR="$(cd "$ROOT_DIR/../.." && pwd)" +DEMO_BASE="$WORKSPACE_DIR/SHiNE-product/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5" +MODE="${1:-manual-monitor-lvgl-v2}" +PORT="${PORT:-}" +FQBN="${FQBN:-esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi}" + +case "$MODE" in + breath-button-monitor) SKETCH_DIR="$ROOT_DIR/breath_button_monitor" ;; + breath-dual-mode-monitor) SKETCH_DIR="$ROOT_DIR/breath_dual_mode_monitor" ;; + manual-monitor-lvgl-v2) SKETCH_DIR="$ROOT_DIR/manual_monitor_lvgl_v2" ;; + *) echo "Use: breath-button-monitor, breath-dual-mode-monitor, or manual-monitor-lvgl-v2" >&2; exit 2 ;; +esac + +if [[ ! -d "$DEMO_BASE/libraries" ]]; then + echo "Missing Waveshare libraries: $DEMO_BASE/libraries" >&2 + exit 1 +fi + +BUILD_DIR="$ROOT_DIR/.arduino-build/$MODE" +OUT_DIR="$ROOT_DIR/.arduino-build/out-$MODE" +compile_args=( + --fqbn "$FQBN" + --build-path "$BUILD_DIR" + --output-dir "$OUT_DIR" + --library "$DEMO_BASE/libraries/GFX_Library_for_Arduino" + --library "$DEMO_BASE/libraries/SensorLib" + --library "$DEMO_BASE/libraries/XPowersLib" + --library "$DEMO_BASE/libraries/lvgl" + --library "$DEMO_BASE/libraries/Mylibrary" + "$SKETCH_DIR" +) +if ! arduino-cli compile "${compile_args[@]}"; then + arduino-cli compile --clean "${compile_args[@]}" +fi + +if [[ "${NO_UPLOAD:-0}" == "1" ]]; then + exit 0 +fi +if [[ -z "$PORT" ]]; then + PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')" +fi +if [[ -z "$PORT" ]]; then + echo "Set PORT=/dev/ttyACM0 or use NO_UPLOAD=1." >&2 + exit 1 +fi +arduino-cli upload --fqbn "$FQBN" -p "$PORT" --input-dir "$OUT_DIR" "$SKETCH_DIR" diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/AGENTS.md b/breath_button_monitor/manual_monitor_lvgl_v2/AGENTS.md new file mode 100644 index 0000000..147fa1a --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/AGENTS.md @@ -0,0 +1,5 @@ +# AGENTS + +`manual_monitor_lvgl_v2.ino` is the dedicated LVGL version of the manual two-button breath monitor for Waveshare ESP32-S3-Touch-AMOLED-2.16. + +Keep every on-screen string in English. When behavior, pins, settings, alert cadence, pause, or UI changes, update this folder's `README.md` and `../../../../reference/usb_contact_sensor_test_spec.md` in the same change. diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/README.md b/breath_button_monitor/manual_monitor_lvgl_v2/README.md new file mode 100644 index 0000000..e2c4bf7 --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/README.md @@ -0,0 +1,30 @@ +# Manual Monitor LVGL v2 + +Dedicated LVGL firmware for the Waveshare ESP32-S3-Touch-AMOLED-2.16 manual breath monitor. It is separate from the legacy multi-mode GFX sketch and does not use USB D+/D- as sensor inputs. + +## Controls + +- `KEY2 / GPIO18`: `INHALE`, active LOW. Hold for about 1.2 seconds to open or close settings; this still accepts the INHALE phase. +- `KEY3 / GPIO0`: `EXHALE`, active LOW. Do not hold it during reset/boot. +- Short EXHALE completes a valid inhale/exhale cycle. Repeated INHALE or EXHALE presses are ignored. +- Hold `KEY3 / EXHALE` for about 1.2 seconds to enter or leave conscious pause. Hold does not create an EXHALE event. Paused time is removed from the phase and cycle timers; reminders and automatic power-off are suspended. + +## Functionality + +- Full-screen LVGL UI with a non-flickering partial draw buffer and the board's proven built-in LVGL font path. +- AXP2101 battery percentage, drawn battery icon, and charging marker at top right. +- Four numeric monitor cards are label-free; the spaced `HISTORY` row shows the last five completed cycles and their exact average is rendered to tenths of a second. +- Numeric cards use the display's straight built-in GFX digits; when AXP2101 reports an invalid `0%` while battery voltage is at least 3.3 V, the displayed percentage falls back to a voltage-derived estimate. +- Settings for limit, confirmation tick volume, alert volume, and screen timeout (`10 / 30 / 60 sec / Always on`), stored in NVS. +- The screen turns off after its selected idle timeout while monitoring continues. A touch or physical button wakes it. +- After a valid phase, reminders are silent for 30 seconds, quiet every 5 seconds through 60 seconds, loud every 5 seconds through 90 seconds, and loud every 15 seconds until 6:30. Then AXP2101 shuts down the device. +- A short average is evaluated at EXHALE, after the cycle is accepted. Consecutive short averages increase the warning sequence from one beep to five. + +## Build or flash + +From `SKETCH/breath_button_monitor`: + +```bash +NO_UPLOAD=1 ./burn.sh manual-monitor-lvgl-v2 +./burn.sh manual-monitor-lvgl-v2 +``` diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/SHiNE-bundle-2026.10.16-18.29.14.zip b/breath_button_monitor/manual_monitor_lvgl_v2/SHiNE-bundle-2026.10.16-18.29.14.zip new file mode 100644 index 0000000..699e10e Binary files /dev/null and b/breath_button_monitor/manual_monitor_lvgl_v2/SHiNE-bundle-2026.10.16-18.29.14.zip differ diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/bundle.sh b/breath_button_monitor/manual_monitor_lvgl_v2/bundle.sh new file mode 100644 index 0000000..0672d75 --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/bundle.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +# Build a source bundle ZIP while excluding credentials, private keys, +# local state, generated artifacts and other likely secrets. +# +# Usage: +# ./bundle.sh +# ./bundle.sh path/to/output.zip +# +# Run from anywhere inside the project; the script resolves its own directory. + +ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +cd "$ROOT" + +DEFAULT_OUT=0 +if [[ $# -gt 0 ]]; then + OUT="$1" +else + DEFAULT_OUT=1 + OUT="SHiNE-bundle-$(date +%Y.%m.%d-%H.%M.%S).zip" +fi +case "$OUT" in + /*) ;; + *) OUT="$ROOT/$OUT" ;; +esac + +if ! command -v zip >/dev/null 2>&1; then + echo "ERROR: 'zip' is required." >&2 + exit 1 +fi + +TMP="$(mktemp -d)" +LIST="$TMP/files.txt" +SAFE_LIST="$TMP/safe-files.txt" +trap 'rm -rf "$TMP"' EXIT + +# Paths / filenames that must never be bundled. +is_denied_path() { + local p="/$1" + + case "$p" in + */.git/*|*/.git|\ + */.gradle/*|*/.gradle|\ + */.gradle-home/*|*/.gradle-home|\ + */.idea/*|*/.idea|\ + */.vscode/*|*/.vscode|\ + */node_modules/*|*/node_modules|\ + */target/*|*/target|\ + */build/*|*/build|\ + */out/*|*/out|\ + */bin/*|*/bin|\ + */logs/*|*/logs|\ + */data/*|*/data|\ + */test-ledger/*|*/test-ledger|\ + */.anchor/*|*/.anchor|\ + */.yarn/*|*/.yarn|\ + */.vendor/*|*/.vendor|\ + */.agents/*|*/.agents|\ + */.codex/*|*/.codex|\ + */.claude/*|*/.claude|\ + */deploy/backup/archive/*|\ + */scripts/*/runs/*|\ + */scripts/*/keypairs/*|\ + */keys/*|\ + */.git-local-backup/*) + return 0 + ;; + esac + + local base="${p##*/}" + local lower + lower="$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]')" + + case "$lower" in + .env|.env.*|\ + .debug-token|\ + .npmrc|.pypirc|.netrc|\ + credentials|credentials.*|\ + secrets|secrets.*|\ + secret|secret.*|\ + id_rsa|id_dsa|id_ecdsa|id_ed25519|\ + *.pem|*.key|*.p12|*.pfx|*.jks|*.keystore|\ + *keypair*.json|\ + service-account*.json|\ + firebase-adminsdk*.json|\ + google-services.json|\ + validator.log) + return 0 + ;; + esac + + case "$lower" in + *.class|*.jar|*.war|*.ear|*.o|*.a|*.so|*.dll|*.dylib|\ + *.elf|*.map|*.uf2|*.bin|*.merged.bin|\ + *.log|*.bak|*.bak.png|*.tmp|*.swp|*.swo|\ + .ds_store) + return 0 + ;; + esac + + return 1 +} + +# Collect files. Prefer Git because it naturally avoids most ignored local files. +if command -v git >/dev/null 2>&1 && git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + git -C "$ROOT" ls-files -co --exclude-standard -z > "$TMP/files.z" +else + find "$ROOT" -type f -print0 > "$TMP/files.z" +fi + +# Convert to project-relative paths and enforce hard deny rules. +: > "$LIST" +while IFS= read -r -d '' f; do + if [[ "$f" = /* ]]; then + rel="${f#"$ROOT"/}" + else + rel="$f" + fi + + [[ "$rel" == "$OUT" ]] && continue + [[ -z "$rel" ]] && continue + + if is_denied_path "$rel"; then + continue + fi + + printf '%s\n' "$rel" >> "$LIST" +done < "$TMP/files.z" + +sort -u "$LIST" -o "$LIST" + +# Always include Gradle wrapper bootstrap, even though generic JARs are denied. +if [[ -f "$ROOT/SHiNE-server/gradle/wrapper/gradle-wrapper.jar" ]]; then + if ! grep -Fxq 'SHiNE-server/gradle/wrapper/gradle-wrapper.jar' "$LIST"; then + printf '%s\n' 'SHiNE-server/gradle/wrapper/gradle-wrapper.jar' >> "$LIST" + sort -u "$LIST" -o "$LIST" + fi +fi + +# Content scan: fail closed on common credential/private-key patterns. +# We scan only text-ish files; grep -I skips binary data. +SECRET_RE='-----BEGIN ([A-Z0-9 ]+ )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,}|(^|[^A-Za-z0-9])(password|passwd|pwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key)[[:space:]]*[:=][[:space:]]*["'\'']?[^${[:space:]]{][^[:space:]]{7,}' + +: > "$SAFE_LIST" +found_secret=0 + +while IFS= read -r rel; do + [[ -f "$ROOT/$rel" ]] || continue + + # Files that contain examples/templates can legitimately mention secret keys + # with placeholders. They are scanned too, but placeholder-looking values + # are less likely to match the regex above. + if LC_ALL=C grep -IEnq "$SECRET_RE" "$ROOT/$rel" 2>/dev/null; then + echo "BLOCKED: possible secret in $rel" >&2 + LC_ALL=C grep -IEn "$SECRET_RE" "$ROOT/$rel" 2>/dev/null \ + | sed -E 's/(:[[:space:]]*).*/\1[REDACTED]/' \ + | head -n 3 >&2 || true + found_secret=1 + continue + fi + + printf '%s\n' "$rel" >> "$SAFE_LIST" +done < "$LIST" + +if (( found_secret != 0 )); then + echo >&2 + echo "Bundle NOT created because possible secrets were detected." >&2 + echo "Move secrets to ignored/local files or adjust the scanner only after review." >&2 + exit 2 +fi + +if [[ ! -s "$SAFE_LIST" ]]; then + echo "ERROR: no files left to bundle." >&2 + exit 3 +fi + +if (( DEFAULT_OUT == 1 )); then + rm -f -- "$ROOT"/SHiNE-bundle-*.zip +else + rm -f -- "$OUT" +fi + +( + cd "$ROOT" + zip -q -9 "$OUT" -@ < "$SAFE_LIST" +) + +echo "Created: $OUT" +echo "Files: $(wc -l < "$SAFE_LIST" | tr -d ' ')" +echo "Size: $(du -h "$OUT" | awk '{print $1}')" diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/es8311.c b/breath_button_monitor/manual_monitor_lvgl_v2/es8311.c new file mode 100644 index 0000000..c78bc2b --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/es8311.c @@ -0,0 +1,443 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "es8311.h" +#include "driver/gpio.h" +#include "esp_log.h" +#include "esp_err.h" +#include "esp_check.h" +#include "es8311_reg.h" +#include "esp32-hal-i2c.h" + + +typedef struct { + unsigned int port; + uint16_t dev_addr; +} es8311_dev_t; + +/* + * Clock coefficient structure + */ +struct _coeff_div { + uint32_t mclk; /* mclk frequency */ + uint32_t rate; /* sample rate */ + uint8_t pre_div; /* the pre divider with range from 1 to 8 */ + uint8_t pre_multi; /* the pre multiplier with 0: 1x, 1: 2x, 2: 4x, 3: 8x selection */ + uint8_t adc_div; /* adcclk divider */ + uint8_t dac_div; /* dacclk divider */ + uint8_t fs_mode; /* double speed or single speed, =0, ss, =1, ds */ + uint8_t lrck_h; /* adclrck divider and daclrck divider */ + uint8_t lrck_l; + uint8_t bclk_div; /* sclk divider */ + uint8_t adc_osr; /* adc osr */ + uint8_t dac_osr; /* dac osr */ +}; + +/* codec hifi mclk clock divider coefficients */ +static const struct _coeff_div coeff_div[] = { + /*!port, es->dev_addr, write_buf, sizeof(write_buf), 1000); +} + +static inline esp_err_t es8311_read_reg(es8311_handle_t dev, uint8_t reg_addr, uint8_t *reg_value) +{ + es8311_dev_t *es = (es8311_dev_t *) dev; + size_t readCount = 0; + return i2cWriteReadNonStop(es->port, es->dev_addr, ®_addr, 1, reg_value, 1, 1000, &readCount); +} + +/* +* look for the coefficient in coeff_div[] table +*/ +static int get_coeff(uint32_t mclk, uint32_t rate) +{ + for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) { + if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) { + return i; + } + } + + return -1; +} + +esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency) +{ + uint8_t regv; + + /* Get clock coefficients from coefficient table */ + int coeff = get_coeff(mclk_frequency, sample_frequency); + + if (coeff < 0) { + ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_frequency, mclk_frequency); + return ESP_ERR_INVALID_ARG; + } + + const struct _coeff_div *const selected_coeff = &coeff_div[coeff]; + + /* register 0x02 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG02, ®v), TAG, "I2C read/write error"); + regv &= 0x07; + regv |= (selected_coeff->pre_div - 1) << 5; + regv |= selected_coeff->pre_multi << 3; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG02, regv), TAG, "I2C read/write error"); + + /* register 0x03 */ + const uint8_t reg03 = (selected_coeff->fs_mode << 6) | selected_coeff->adc_osr; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG03, reg03), TAG, "I2C read/write error"); + + /* register 0x04 */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG04, selected_coeff->dac_osr), TAG, "I2C read/write error"); + + /* register 0x05 */ + const uint8_t reg05 = ((selected_coeff->adc_div - 1) << 4) | (selected_coeff->dac_div - 1); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG05, reg05), TAG, "I2C read/write error"); + + /* register 0x06 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®v), TAG, "I2C read/write error"); + regv &= 0xE0; + + if (selected_coeff->bclk_div < 19) { + regv |= (selected_coeff->bclk_div - 1) << 0; + } else { + regv |= (selected_coeff->bclk_div) << 0; + } + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, regv), TAG, "I2C read/write error"); + + /* register 0x07 */ + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG07, ®v), TAG, "I2C read/write error"); + regv &= 0xC0; + regv |= selected_coeff->lrck_h << 0; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG07, regv), TAG, "I2C read/write error"); + + /* register 0x08 */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG08, selected_coeff->lrck_l), TAG, "I2C read/write error"); + + return ESP_OK; +} + +static esp_err_t es8311_clock_config(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, es8311_resolution_t res) +{ + uint8_t reg06; + uint8_t reg01 = 0x3F; // Enable all clocks + int mclk_hz; + + /* Select clock source for internal MCLK and determine its frequency */ + if (clk_cfg->mclk_from_mclk_pin) { + mclk_hz = clk_cfg->mclk_frequency; + } else { + mclk_hz = clk_cfg->sample_frequency * (int)res * 2; + reg01 |= BIT(7); // Select BCLK (a.k.a. SCK) pin + } + + if (clk_cfg->mclk_inverted) { + reg01 |= BIT(6); // Invert MCLK pin + } + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG01, reg01), TAG, "I2C read/write error"); + + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®06), TAG, "I2C read/write error"); + if (clk_cfg->sclk_inverted) { + reg06 |= BIT(5); + } else { + reg06 &= ~BIT(5); + } + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, reg06), TAG, "I2C read/write error"); + + /* Configure clock dividers */ + return es8311_sample_frequency_config(dev, mclk_hz, clk_cfg->sample_frequency); +} + +static esp_err_t es8311_resolution_config(const es8311_resolution_t res, uint8_t *reg) +{ + switch (res) { + case ES8311_RESOLUTION_16: + *reg |= (3 << 2); + break; + case ES8311_RESOLUTION_18: + *reg |= (2 << 2); + break; + case ES8311_RESOLUTION_20: + *reg |= (1 << 2); + break; + case ES8311_RESOLUTION_24: + *reg |= (0 << 2); + break; + case ES8311_RESOLUTION_32: + *reg |= (4 << 2); + break; + default: + return ESP_ERR_INVALID_ARG; + } + return ESP_OK; +} + +static esp_err_t es8311_fmt_config(es8311_handle_t dev, const es8311_resolution_t res_in, const es8311_resolution_t res_out) +{ + uint8_t reg09 = 0; // SDP In + uint8_t reg0a = 0; // SDP Out + + ESP_LOGI(TAG, "ES8311 in Slave mode and I2S format"); + uint8_t reg00; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_RESET_REG00, ®00), TAG, "I2C read/write error"); + reg00 &= 0xBF; + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, reg00), TAG, "I2C read/write error"); // Slave serial port - default + + /* Setup SDP In and Out resolution */ + es8311_resolution_config(res_in, ®09); + es8311_resolution_config(res_out, ®0a); + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPIN_REG09, reg09), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPOUT_REG0A, reg0a), TAG, "I2C read/write error"); + + return ESP_OK; +} + +esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic) +{ + uint8_t reg14 = 0x1A; // enable analog MIC and max PGA gain + + /* PDM digital microphone enable or disable */ + if (digital_mic) { + reg14 |= BIT(6); + } + es8311_write_reg(dev, ES8311_ADC_REG17, 0xC8); // Set ADC gain @todo move this to ADC config section + + return es8311_write_reg(dev, ES8311_SYSTEM_REG14, reg14); +} + +esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, const es8311_resolution_t res_out) +{ + ESP_RETURN_ON_FALSE( + (clk_cfg->sample_frequency >= 8000) && (clk_cfg->sample_frequency <= 96000), + ESP_ERR_INVALID_ARG, TAG, "ES8311 init needs frequency in interval [8000; 96000] Hz" + ); + if (!clk_cfg->mclk_from_mclk_pin) { + ESP_RETURN_ON_FALSE(res_out == res_in, ESP_ERR_INVALID_ARG, TAG, "Resolution IN/OUT must be equal if MCLK is taken from SCK pin"); + } + + + /* Reset ES8311 to its default */ + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x1F), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x00), TAG, "I2C read/write error"); + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x80), TAG, "I2C read/write error"); // Power-on command + + /* Setup clock: source, polarity and clock dividers */ + ESP_RETURN_ON_ERROR(es8311_clock_config(dev, clk_cfg, res_out), TAG, ""); + + /* Setup audio format (fmt): master/slave, resolution, I2S */ + ESP_RETURN_ON_ERROR(es8311_fmt_config(dev, res_in, res_out), TAG, ""); + + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0D, 0x01), TAG, "I2C read/write error"); // Power up analog circuitry - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0E, 0x02), TAG, "I2C read/write error"); // Enable analog PGA, enable ADC modulator - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG12, 0x00), TAG, "I2C read/write error"); // power-up DAC - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG13, 0x10), TAG, "I2C read/write error"); // Enable output to HP drive - NOT default + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_ADC_REG1C, 0x6A), TAG, "I2C read/write error"); // ADC Equalizer bypass, cancel DC offset in digital domain + ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_DAC_REG37, 0x08), TAG, "I2C read/write error"); // Bypass DAC equalizer - NOT default + + return ESP_OK; +} + +void es8311_delete(es8311_handle_t dev) +{ + free(dev); +} + +esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set) +{ + if (volume < 0) { + volume = 0; + } else if (volume > 100) { + volume = 100; + } + + int reg32; + if (volume == 0) { + reg32 = 0; + } else { + reg32 = ((volume) * 256 / 100) - 1; + } + + // provide user with real volume set + if (volume_set != NULL) { + *volume_set = volume; + } + return es8311_write_reg(dev, ES8311_DAC_REG32, reg32); +} + +esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume) +{ + uint8_t reg32; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG32, ®32), TAG, "I2C read/write error"); + + if (reg32 == 0) { + *volume = 0; + } else { + *volume = ((reg32 * 100) / 256) + 1; + } + return ESP_OK; +} + +esp_err_t es8311_voice_mute(es8311_handle_t dev, bool mute) +{ + uint8_t reg31; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG31, ®31), TAG, "I2C read/write error"); + + if (mute) { + reg31 |= BIT(6) | BIT(5); + } else { + reg31 &= ~(BIT(6) | BIT(5)); + } + + return es8311_write_reg(dev, ES8311_DAC_REG31, reg31); +} + +esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db) +{ + return es8311_write_reg(dev, ES8311_ADC_REG16, gain_db); // ADC gain scale up +} + +esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade) +{ + uint8_t reg37; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG37, ®37), TAG, "I2C read/write error"); + reg37 &= 0x0F; + reg37 |= (fade << 4); + return es8311_write_reg(dev, ES8311_DAC_REG37, reg37); +} + +esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade) +{ + uint8_t reg15; + ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_ADC_REG15, ®15), TAG, "I2C read/write error"); + reg15 &= 0x0F; + reg15 |= (fade << 4); + return es8311_write_reg(dev, ES8311_ADC_REG15, reg15); +} + +void es8311_register_dump(es8311_handle_t dev) +{ + for (int reg = 0; reg < 0x4A; reg++) { + uint8_t value; + ESP_ERROR_CHECK(es8311_read_reg(dev, reg, &value)); + printf("REG:%02x: %02x", reg, value); + } +} + +es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr) +{ + es8311_dev_t *sensor = (es8311_dev_t *) calloc(1, sizeof(es8311_dev_t)); + sensor->port = port; + sensor->dev_addr = dev_addr; + return (es8311_handle_t) sensor; +} diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/es8311.h b/breath_button_monitor/manual_monitor_lvgl_v2/es8311.h new file mode 100644 index 0000000..9930fc7 --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/es8311.h @@ -0,0 +1,227 @@ +/* + * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief ES8311 driver + */ + +#pragma once + +#include "esp_types.h" +#include "esp_err.h" + +/* ES8311 address: CE pin low - 0x18, CE pin high - 0x19 */ +#define ES8311_ADDRRES_0 0x18u // Leaving this here for backward compatibility +#define ES8311_ADDRESS_0 0x18u +#define ES8311_ADDRESS_1 0x19u + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *es8311_handle_t; + +typedef enum { + ES8311_MIC_GAIN_MIN = -1, + ES8311_MIC_GAIN_0DB, + ES8311_MIC_GAIN_6DB, + ES8311_MIC_GAIN_12DB, + ES8311_MIC_GAIN_18DB, + ES8311_MIC_GAIN_24DB, + ES8311_MIC_GAIN_30DB, + ES8311_MIC_GAIN_36DB, + ES8311_MIC_GAIN_42DB, + ES8311_MIC_GAIN_MAX +} es8311_mic_gain_t; + +typedef enum { + ES8311_FADE_OFF = 0, + ES8311_FADE_4LRCK, // 4LRCK means ramp 0.25dB/4LRCK + ES8311_FADE_8LRCK, + ES8311_FADE_16LRCK, + ES8311_FADE_32LRCK, + ES8311_FADE_64LRCK, + ES8311_FADE_128LRCK, + ES8311_FADE_256LRCK, + ES8311_FADE_512LRCK, + ES8311_FADE_1024LRCK, + ES8311_FADE_2048LRCK, + ES8311_FADE_4096LRCK, + ES8311_FADE_8192LRCK, + ES8311_FADE_16384LRCK, + ES8311_FADE_32768LRCK, + ES8311_FADE_65536LRCK +} es8311_fade_t; + +typedef enum es8311_resolution_t { + ES8311_RESOLUTION_16 = 16, + ES8311_RESOLUTION_18 = 18, + ES8311_RESOLUTION_20 = 20, + ES8311_RESOLUTION_24 = 24, + ES8311_RESOLUTION_32 = 32 +} es8311_resolution_t; + +typedef struct es8311_clock_config_t { + bool mclk_inverted; + bool sclk_inverted; + bool mclk_from_mclk_pin; // true: from MCLK pin (pin no. 2), false: from SCLK pin (pin no. 6) + int mclk_frequency; // This parameter is ignored if MCLK is taken from SCLK pin + int sample_frequency; // in Hz +} es8311_clock_config_t; + +/** + * @brief Initialize ES8311 + * + * There are two ways of providing Master Clock (MCLK) signal to ES8311 in Slave Mode: + * 1. From MCLK pin: + * For flexible scenarios. A clock signal from I2S master is routed to MCLK pin. + * Its frequency must be defined in clk_cfg->mclk_frequency parameter. + * 2. From SCLK pin: + * For simpler scenarios. ES8311 takes its clock from SCK pin. MCLK pin does not have to be connected. + * In this case, res_in must equal res_out; clk_cfg->mclk_frequency parameter is ignored + * and MCLK is calculated as MCLK = clk_cfg->sample_frequency * res_out * 2. + * Not all sampling frequencies are supported in this mode. + * + * @param dev ES8311 handle + * @param[in] clk_cfg Clock configuration + * @param[in] res_in Input serial port resolution + * @param[in] res_out Output serial port resolution + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Sample frequency or resolution invalid + * - Else fail + */ +esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, + const es8311_resolution_t res_out); + +/** + * @brief Set output volume + * + * Volume paramter out of <0, 100> interval will be truncated. + * + * @param dev ES8311 handle + * @param[in] volume Set volume (0 ~ 100) + * @param[out] volume_set Volume that was set. Same as volume, unless volume is outside of <0, 100> interval. + * This parameter can be set to NULL, if user does not need this information. + * + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set); + +/** + * @brief Get output volume + * + * @param dev ES8311 handle + * @param[out] volume get volume (0 ~ 100) + * + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume); + +/** + * @brief Print out ES8311 register content + * + * @param dev ES8311 handle + */ +void es8311_register_dump(es8311_handle_t dev); + +/** + * @brief Mute ES8311 output + * + * @param dev ES8311 handle + * @param[in] enable true: mute, false: don't mute + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_voice_mute(es8311_handle_t dev, bool enable); + +/** + * @brief Set Microphone gain + * + * @param dev ES8311 handle + * @param[in] gain_db Microphone gain + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db); + +/** + * @brief Configure microphone + * + * @param dev ES8311 handle + * @param[in] digital_mic Set to true for digital microphone + * @return + * - ESP_OK success + * - Else fail + */ +esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic); + +/** + * @brief Configure sampling frequency + * + * @note This function is called by es8311_init(). + * Call this function explicitly only if you want to change sample frequency during runtime. + * @param dev ES8311 handle + * @param[in] mclk_frequency MCLK frequency in [Hz] (MCLK or SCLK pin, depending on bit register01[7]) + * @param[in] sample_frequency Required sample frequency in [Hz], e.g. 44100, 22050... + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG cannot set clock dividers for given MCLK and sampling frequency + * - Else I2C read/write error + */ +esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency); + +/** + * @brief Configure fade in/out for ADC: voice + * + * @param dev ES8311 handle + * @param[in] fade Fade ramp rate + * @return + * - ESP_OK success + * - Else I2C read/write error + */ +esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade); + +/** + * @brief Configure fade in/out for DAC: microphone + * + * @param dev ES8311 handle + * @param[in] fade Fade ramp rate + * @return + * - ESP_OK success + * - Else I2C read/write error + */ +esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade); + +/** + * @brief Create ES8311 object and return its handle + * + * @param[in] port I2C port number + * @param[in] dev_addr I2C device address of ES8311 + * + * @return + * - NULL Fail + * - Others Success + */ +es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr); + +/** + * @brief Delete ES8311 object + * + * @param dev ES8311 handle + */ +void es8311_delete(es8311_handle_t dev); + +#ifdef __cplusplus +} +#endif diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/es8311_reg.h b/breath_button_monitor/manual_monitor_lvgl_v2/es8311_reg.h new file mode 100644 index 0000000..aeae4c0 --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/es8311_reg.h @@ -0,0 +1,76 @@ +/* + * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +/* + * ES8311_REGISTER NAME_REG_REGISTER ADDRESS + */ +#define ES8311_RESET_REG00 0x00 /*reset digital,csm,clock manager etc.*/ + +/* + * Clock Scheme Register definition + */ +#define ES8311_CLK_MANAGER_REG01 0x01 /* select clk src for mclk, enable clock for codec */ +#define ES8311_CLK_MANAGER_REG02 0x02 /* clk divider and clk multiplier */ +#define ES8311_CLK_MANAGER_REG03 0x03 /* adc fsmode and osr */ +#define ES8311_CLK_MANAGER_REG04 0x04 /* dac osr */ +#define ES8311_CLK_MANAGER_REG05 0x05 /* clk divier for adc and dac */ +#define ES8311_CLK_MANAGER_REG06 0x06 /* bclk inverter and divider */ +#define ES8311_CLK_MANAGER_REG07 0x07 /* tri-state, lrck divider */ +#define ES8311_CLK_MANAGER_REG08 0x08 /* lrck divider */ +/* + * SDP + */ +#define ES8311_SDPIN_REG09 0x09 /* dac serial digital port */ +#define ES8311_SDPOUT_REG0A 0x0A /* adc serial digital port */ +/* + * SYSTEM + */ +#define ES8311_SYSTEM_REG0B 0x0B /* system */ +#define ES8311_SYSTEM_REG0C 0x0C /* system */ +#define ES8311_SYSTEM_REG0D 0x0D /* system, power up/down */ +#define ES8311_SYSTEM_REG0E 0x0E /* system, power up/down */ +#define ES8311_SYSTEM_REG0F 0x0F /* system, low power */ +#define ES8311_SYSTEM_REG10 0x10 /* system */ +#define ES8311_SYSTEM_REG11 0x11 /* system */ +#define ES8311_SYSTEM_REG12 0x12 /* system, Enable DAC */ +#define ES8311_SYSTEM_REG13 0x13 /* system */ +#define ES8311_SYSTEM_REG14 0x14 /* system, select DMIC, select analog pga gain */ +/* + * ADC + */ +#define ES8311_ADC_REG15 0x15 /* ADC, adc ramp rate, dmic sense */ +#define ES8311_ADC_REG16 0x16 /* ADC */ +#define ES8311_ADC_REG17 0x17 /* ADC, volume */ +#define ES8311_ADC_REG18 0x18 /* ADC, alc enable and winsize */ +#define ES8311_ADC_REG19 0x19 /* ADC, alc maxlevel */ +#define ES8311_ADC_REG1A 0x1A /* ADC, alc automute */ +#define ES8311_ADC_REG1B 0x1B /* ADC, alc automute, adc hpf s1 */ +#define ES8311_ADC_REG1C 0x1C /* ADC, equalizer, hpf s2 */ +/* + * DAC + */ +#define ES8311_DAC_REG31 0x31 /* DAC, mute */ +#define ES8311_DAC_REG32 0x32 /* DAC, volume */ +#define ES8311_DAC_REG33 0x33 /* DAC, offset */ +#define ES8311_DAC_REG34 0x34 /* DAC, drc enable, drc winsize */ +#define ES8311_DAC_REG35 0x35 /* DAC, drc maxlevel, minilevel */ +#define ES8311_DAC_REG37 0x37 /* DAC, ramprate */ +/* + *GPIO + */ +#define ES8311_GPIO_REG44 0x44 /* GPIO, dac2adc for test */ +#define ES8311_GP_REG45 0x45 /* GP CONTROL */ +/* + * CHIP + */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ +#define ES8311_CHD2_REGFE 0xFE /* CHIP ID2 */ +#define ES8311_CHVER_REGFF 0xFF /* VERSION */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ + +#define ES8311_MAX_REGISTER 0xFF diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/manual_monitor_lvgl_v2.ino b/breath_button_monitor/manual_monitor_lvgl_v2/manual_monitor_lvgl_v2.ino new file mode 100644 index 0000000..b17b718 --- /dev/null +++ b/breath_button_monitor/manual_monitor_lvgl_v2/manual_monitor_lvgl_v2.ino @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include +#define XPOWERS_CHIP_AXP2101 +#include +#include "ESP_I2S.h" +#include "es8311.h" + +void setup(); +void loop(); + +// Dedicated LVGL v2 of the manual two-button breath monitor. +#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 + +static constexpr uint16_t DISP_W = 480, DISP_H = 480; +static constexpr uint32_t LVGL_TICK_MS = 2, UI_MS = 120, HOLD_PAUSE_MS = 1200; +static constexpr uint32_t DEBOUNCE_MS = 45, BATT_MS = 5000; +static constexpr uint32_t QUIET_START_MS = 30000, LOUD_START_MS = 60000; +static constexpr uint32_t SLOW_LOUD_MS = 90000, POWER_OFF_MS = 390000; +static constexpr uint16_t LIMITS[] = {5, 7, 10, 15, 20}; +static constexpr uint32_t SCREEN_TIMEOUTS[] = {10000, 30000, 60000, 0}; +static const char *SCREEN_TIMEOUT_NAMES[] = {"10 sec", "30 sec", "60 sec", "Always on"}; +static const int16_t TICK_VOLUME[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600}; +static const int16_t ALERT_VOLUME[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000}; + +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; +XPowersPMU gPower; +I2SClass gI2s; +Preferences gPrefs; + +struct Button { int pin; bool raw = false; bool stable = false; uint32_t changed = 0; uint32_t pressed = 0; }; +static Button gInhale{PIN_INHALE}, gExhale{PIN_EXHALE}; +enum class Screen : uint8_t { Home, Monitor, Settings }; +static Screen gScreen = Screen::Home; +static bool gPowerReady = false, gAudioReady = false, gTouchDown = false; +static bool gScreenOn = true, gPaused = false, gHaveInhale = false; +static uint32_t gPauseStarted = 0, gPhaseStarted = 0, gCycleStarted = 0, gLastActivity = 0, gLastUi = 0, gLastBatt = 0, gLastReminder = 0; +static uint8_t gLimit = 2, gTick = 3, gAlert = 10, gScreenTimeout = 1; +static uint32_t gCycles[5] = {}; static uint8_t gCycleCount = 0, gCycleNext = 0, gShortStreak = 0; +static lv_disp_draw_buf_t gDrawBuf; static lv_color_t *gBuf1 = nullptr, *gBuf2 = nullptr; +static lv_obj_t *gRoot = nullptr, *gPhase = nullptr, *gPhaseValue = nullptr, *gAverage = nullptr, *gAverageValue = nullptr; +static lv_obj_t *gElapsedValue = nullptr, *gLimitValue = nullptr, *gLastFive = nullptr, *gState = nullptr; +static lv_obj_t *gBatteryText = nullptr, *gBatteryFill = nullptr, *gBolt = nullptr; +static bool gDirectNumbersPending = false; +static char gDirectPhase[16] = "0.0 s", gDirectAverage[16] = "--", gDirectElapsed[12] = "00:00", gDirectLimit[16] = "10.0 s"; + +static lv_color_t color(uint32_t c) { return lv_color_hex(c); } +static void flush(lv_disp_drv_t *d, const lv_area_t *a, lv_color_t *p) { + uint32_t w = a->x2-a->x1+1, h = a->y2-a->y1+1; +#if LV_COLOR_16_SWAP != 0 + gfx->draw16bitBeRGBBitmap(a->x1,a->y1,(uint16_t *)&p->full,w,h); +#else + gfx->draw16bitRGBBitmap(a->x1,a->y1,(uint16_t *)&p->full,w,h); +#endif + lv_disp_flush_ready(d); +} +static void tick(void *) { lv_tick_inc(LVGL_TICK_MS); } +static void touchRead(lv_indev_drv_t *, lv_indev_data_t *d) { + int16_t x=0,y=0; bool down = gTouch.getPoint(&x,&y,1)>0; + if (down && !gTouchDown) { gTouchDown=true; gLastActivity=millis(); if (!gScreenOn) { gfx->setBrightness(220); gScreenOn=true; } } + if (!down) gTouchDown=false; + d->state=down ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; d->point.x=x; d->point.y=y; +} +static void card(lv_obj_t *o, uint32_t bg=0x142331) { lv_obj_set_style_bg_color(o,color(bg),0); lv_obj_set_style_border_color(o,color(0x365264),0); lv_obj_set_style_border_width(o,1,0); lv_obj_set_style_radius(o,14,0); lv_obj_clear_flag(o,LV_OBJ_FLAG_SCROLLABLE); } +static lv_obj_t *label(lv_obj_t *p,const char *s,const lv_font_t *f,uint32_t c) { + lv_obj_t *o=lv_label_create(p); + lv_label_set_text(o,s); + lv_obj_set_style_text_font(o,f,0); + lv_obj_set_style_text_color(o,color(c),0); + return o; +} +static lv_obj_t *panel(int x,int y,int w,int h,uint32_t bg=0x142331) { lv_obj_t *o=lv_obj_create(gRoot); lv_obj_set_pos(o,x,y); lv_obj_set_size(o,w,h); card(o,bg); return o; } +static void fmt(char *out,size_t n,uint32_t ms) { snprintf(out,n,"%lu.%01lu s",(unsigned long)(ms/1000),(unsigned long)((ms%1000)/100)); } +static uint32_t average() { uint64_t total=0; for(uint8_t i=0;i(4,gPrefs.getUChar("limit",2)); gTick=min(10,gPrefs.getUChar("tick",3)); gAlert=min(10,gPrefs.getUChar("alert",10)); gScreenTimeout=min(3,gPrefs.getUChar("screen",1)); } +static void saveSettings() { gPrefs.putUChar("limit",gLimit); gPrefs.putUChar("tick",gTick); gPrefs.putUChar("alert",gAlert); gPrefs.putUChar("screen",gScreenTimeout); } +static void initPower() { gPowerReady=gPower.begin(Wire,AXP2101_SLAVE_ADDRESS,PIN_I2C_SDA,PIN_I2C_SCL); if(!gPowerReady)return; gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); gPower.setChargeTargetVoltage(3); gPower.clearIrqStatus(); gPower.enableBattDetection(); gPower.enableBattVoltageMeasure(); gPower.enableVbusVoltageMeasure(); } +static int battery() { if(!gPowerReady || !gPower.isBatteryConnect())return -1; int percent=constrain(gPower.getBatteryPercent(),0,100); uint16_t mv=gPower.getBattVoltage(); if(percent==0 && mv>=3300) return constrain((int)((mv-3300UL)*100UL/900UL),1,100); return percent; } +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,16000,I2S_DATA_BIT_WIDTH_16BIT,I2S_SLOT_MODE_STEREO,I2S_STD_SLOT_BOTH))return; es8311_handle_t h=es8311_create(0,ES8311_ADDRRES_0); if(!h)return; es8311_clock_config_t c={false,false,true,4096000,16000}; gAudioReady=es8311_init(h,&c,ES8311_RESOLUTION_16,ES8311_RESOLUTION_16)==ESP_OK; if(gAudioReady){es8311_voice_volume_set(h,100,nullptr);es8311_voice_mute(h,false);} } +static void beep(uint16_t hz,uint16_t count,int16_t amp) { if(!gAudioReady||amp<=0)return; static int16_t buf[1600*2]; count=min(count,1600); for(uint16_t i=0;i0?max(2,min(26,p*26/100)):0); if(gBolt)lv_obj_set_style_opa(gBolt,(gPowerReady&&gPower.isCharging())?LV_OPA_COVER:LV_OPA_TRANSP,0); } +static void topBar(const char *title) { label(gRoot,title,&lv_font_montserrat_24,0xFFFFFF); lv_obj_align(lv_obj_get_child(gRoot,0),LV_ALIGN_TOP_LEFT,26,20); gBatteryText=label(gRoot,"--",&lv_font_montserrat_16,0xC9D3DE); lv_obj_set_pos(gBatteryText,297,22); if(gPowerReady){static const lv_point_t bolt[]={{6,0},{1,9},{5,9},{2,18},{10,7},{6,7}};gBolt=lv_line_create(gRoot);lv_line_set_points(gBolt,bolt,6);lv_obj_set_pos(gBolt,337,17);lv_obj_set_style_line_width(gBolt,2,0);lv_obj_set_style_line_color(gBolt,color(0xFFD34D),0);lv_obj_set_style_line_rounded(gBolt,true,0);} lv_obj_t *b=lv_obj_create(gRoot);lv_obj_set_pos(b,349,24);lv_obj_set_size(b,32,16);lv_obj_set_style_bg_opa(b,LV_OPA_TRANSP,0);lv_obj_set_style_border_color(b,color(0xC9D3DE),0);lv_obj_set_style_border_width(b,2,0);lv_obj_set_style_radius(b,4,0);lv_obj_clear_flag(b,LV_OBJ_FLAG_SCROLLABLE); lv_obj_t *cap=lv_obj_create(gRoot);lv_obj_set_pos(cap,381,28);lv_obj_set_size(cap,4,8);lv_obj_set_style_bg_color(cap,color(0xC9D3DE),0);lv_obj_set_style_border_width(cap,0,0);lv_obj_set_style_radius(cap,2,0); gBatteryFill=lv_obj_create(gRoot);lv_obj_set_pos(gBatteryFill,352,27);lv_obj_set_size(gBatteryFill,2,10);lv_obj_set_style_bg_color(gBatteryFill,color(0x38B26D),0);lv_obj_set_style_border_width(gBatteryFill,0,0);lv_obj_set_style_radius(gBatteryFill,2,0); batteryUi(); } +static void clearUi() { lv_obj_clean(lv_scr_act()); gRoot=lv_scr_act(); lv_obj_set_style_bg_color(gRoot,color(0x08111B),0);lv_obj_set_style_bg_opa(gRoot,LV_OPA_COVER,0);lv_obj_set_style_pad_all(gRoot,0,0); gBatteryText=gBatteryFill=gBolt=nullptr; } +static void drawDirectNumber(int x,int y,int w,int h,const char *text,uint16_t textColor,uint8_t size) { gfx->fillRect(x+2,y+2,w-4,h-4,0x142331); gfx->setFont(); gfx->setTextSize(size); gfx->setTextColor(textColor); int tx=x+(w-(int)strlen(text)*6*size)/2; gfx->setCursor(max(x+6,tx),y+(h-8*size)/2+7*size); gfx->print(text); } +static void drawDirectNumbers() { if(!gDirectNumbersPending || gScreen!=Screen::Monitor || !gScreenOn)return; drawDirectNumber(24,202,204,88,gDirectPhase,0xFFFF,4); drawDirectNumber(252,202,204,88,gDirectAverage,0xFFFF,4); drawDirectNumber(24,306,204,72,gDirectElapsed,0xFFFF,4); drawDirectNumber(252,306,204,72,gDirectLimit,0xFFE0,4); gDirectNumbersPending=false; } +static void enterMonitor(lv_event_t *) { gScreen=Screen::Monitor; gLastActivity=millis(); clearUi(); topBar("MANUAL MONITOR"); lv_obj_t *hero=panel(24,72,432,112,0x102A36); gState=label(hero,"READY",&lv_font_montserrat_28,0x4FB3FF);lv_obj_align(gState,LV_ALIGN_TOP_MID,0,18); lv_obj_t *hint=label(hero,"KEY2: INHALE KEY3: EXHALE",&lv_font_montserrat_14,0xB8C7D2);lv_obj_align(hint,LV_ALIGN_BOTTOM_MID,0,-17); lv_obj_t *a=panel(24,202,204,88);gPhaseValue=label(a,"",&lv_font_montserrat_32,0xFFFFFF); lv_obj_t *b=panel(252,202,204,88);gAverageValue=label(b,"",&lv_font_montserrat_32,0xFFFFFF); lv_obj_t *c=panel(24,306,204,72);gElapsedValue=label(c,"",&lv_font_montserrat_28,0xFFFFFF); lv_obj_t *d=panel(252,306,204,72);gLimitValue=label(d,"",&lv_font_montserrat_28,0xFFD34D); lv_obj_t *last=panel(24,394,432,60);gLastFive=label(last,"HISTORY: --",&lv_font_montserrat_16,0xD7E3EA);lv_obj_align(gLastFive,LV_ALIGN_CENTER,0,0); gDirectNumbersPending=true; } +static void home(lv_event_t *); static void settings(lv_event_t *); +static lv_obj_t *button(lv_obj_t *p,const char *text,int x,int y,int w,int h,uint32_t bg,lv_event_cb_t cb) { lv_obj_t *b=lv_btn_create(p);lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h);card(b,bg);lv_obj_add_event_cb(b,cb,LV_EVENT_CLICKED,nullptr);lv_obj_t *l=label(b,text,&lv_font_montserrat_20,0xFFFFFF);lv_obj_center(l);return b; } +static void home(lv_event_t *) { gScreen=Screen::Home;clearUi();topBar("BREATH MONITOR");lv_obj_t *intro=panel(24,78,432,84,0x102A36);lv_obj_t *i=label(intro,"Two external buttons",&lv_font_montserrat_22,0xFFFFFF);lv_obj_align(i,LV_ALIGN_TOP_MID,0,14);i=label(intro,"Manual breathing cadence monitor",&lv_font_montserrat_14,0xB8C7D2);lv_obj_align(i,LV_ALIGN_BOTTOM_MID,0,-14);button(gRoot,"START MANUAL MONITOR",24,188,432,82,0x28775E,enterMonitor);button(gRoot,"SETTINGS",24,290,208,58,0x214D69,settings);button(gRoot,"ABOUT",248,290,208,58,0x403C68,[](lv_event_t *){});lv_obj_t *h=panel(24,374,432,70);i=label(h,"Hold EXHALE to pause / resume",&lv_font_montserrat_16,0xFFD34D);lv_obj_align(i,LV_ALIGN_TOP_MID,0,12);i=label(h,"Screen can turn off; measurement continues",&lv_font_montserrat_14,0xB8C7D2);lv_obj_align(i,LV_ALIGN_BOTTOM_MID,0,-12); } +static void settingChanged(lv_event_t *e){uint8_t *v=(uint8_t *)lv_event_get_user_data(e);*v=lv_slider_get_value(lv_event_get_target(e));saveSettings();} +static void settings(lv_event_t *) {gScreen=Screen::Settings;clearUi();topBar("SETTINGS");lv_obj_t *list=lv_obj_create(gRoot);lv_obj_set_pos(list,20,68);lv_obj_set_size(list,440,352);card(list,0x10202D);lv_obj_set_style_pad_all(list,16,0);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN);lv_obj_set_style_pad_row(list,18,0);struct Item{const char *name;uint8_t *v;uint8_t max;};Item items[]={{"Breath limit",&gLimit,4},{"Cycle tick",&gTick,10},{"Alert volume",&gAlert,10},{"Screen timeout",&gScreenTimeout,3}};for(auto &it:items){lv_obj_t *row=lv_obj_create(list);lv_obj_set_size(row,400,66);card(row,0x172C3C);lv_obj_t *n=label(row,it.name,&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(n,12,8);lv_obj_t *s=lv_slider_create(row);lv_obj_set_pos(s,12,34);lv_obj_set_size(s,376,18);lv_slider_set_range(s,0,it.max);lv_slider_set_value(s,*it.v,LV_ANIM_OFF);lv_obj_add_event_cb(s,settingChanged,LV_EVENT_VALUE_CHANGED,it.v);}button(gRoot,"BACK",150,430,180,38,0x214D69,home);} +static void toggleSettingsFromKey(){ if(gScreen==Screen::Monitor) settings(nullptr); else if(gScreen==Screen::Settings) enterMonitor(nullptr); } +static void addCycle(uint32_t ms){gCycles[gCycleNext]=ms;gCycleNext=(gCycleNext+1)%5;if(gCycleCount<5)gCycleCount++;uint32_t a=average();if(a && a(5,gShortStreak+1);for(uint8_t i=0;isetBrightness(220);}if(gScreen==Screen::Monitor&&inhale)phase(true);return;}uint32_t held=now-b.pressed;if(inhale&&held>=HOLD_PAUSE_MS){toggleSettingsFromKey();return;}if(gScreen!=Screen::Monitor)return;if(!inhale&&held>=HOLD_PAUSE_MS)togglePause();else if(!inhale)phase(false);} +static void refresh(){if(gScreen!=Screen::Monitor)return;uint32_t now=millis(),phaseMs=gPhaseStarted&&!gPaused?now-gPhaseStarted:0;char s[100]; if(gPaused)lv_label_set_text(gState,"PAUSED");else if(!gHaveInhale)lv_label_set_text(gState,"WAITING FOR INHALE");else lv_label_set_text(gState,"INHALE - PRESS EXHALE");fmt(gDirectPhase,sizeof(gDirectPhase),phaseMs);uint32_t a=average();if(a)fmt(gDirectAverage,sizeof(gDirectAverage),a);else snprintf(gDirectAverage,sizeof(gDirectAverage),"--");snprintf(gDirectLimit,sizeof(gDirectLimit),"%u.%01u s",LIMITS[gLimit],0);uint32_t elapsed=gCycleStarted&&!gPaused?now-gCycleStarted:0;snprintf(gDirectElapsed,sizeof(gDirectElapsed),"%02lu:%02lu",(unsigned long)(elapsed/60000),(unsigned long)((elapsed/1000)%60));size_t used=snprintf(s,sizeof(s),"HISTORY:");for(uint8_t i=0;isetBrightness(0);if(gPowerReady)gPower.shutdown();esp_deep_sleep_start();}} +void setup(){Serial.begin(115200);Wire.begin(PIN_I2C_SDA,PIN_I2C_SCL);initPower();pinMode(PIN_INHALE,INPUT_PULLUP);pinMode(PIN_EXHALE,INPUT_PULLUP);initAudio();gfx->begin();gBus->writeC8D8(0x36,0xA0);gfx->setBrightness(220);gTouch.setPins(PIN_TP_INT,-1);gTouch.begin(Wire,0x5A,PIN_I2C_SDA,PIN_I2C_SCL);gTouch.setMaxCoordinates(DISP_W,DISP_H);gTouch.setSwapXY(true);gTouch.setMirrorXY(true,false);loadSettings();lv_init();gBuf1=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);gBuf2=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);lv_disp_draw_buf_init(&gDrawBuf,gBuf1,gBuf2,DISP_W*40);static lv_disp_drv_t dd;lv_disp_drv_init(&dd);dd.hor_res=DISP_W;dd.ver_res=DISP_H;dd.flush_cb=flush;dd.draw_buf=&gDrawBuf;lv_disp_drv_register(&dd);static lv_indev_drv_t id;lv_indev_drv_init(&id);id.type=LV_INDEV_TYPE_POINTER;id.read_cb=touchRead;lv_indev_drv_register(&id);const esp_timer_create_args_t ta={.callback=&tick,.name="lvgl_tick"};esp_timer_handle_t timer;esp_timer_create(&ta,&timer);esp_timer_start_periodic(timer,LVGL_TICK_MS*1000);gLastActivity=millis();home(nullptr);} +void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();}if(now-gLastBatt>=BATT_MS){gLastBatt=now;batteryUi();}uint32_t timeout=SCREEN_TIMEOUTS[gScreenTimeout];if(gScreenOn&&timeout&&now-gLastActivity>=timeout){gScreenOn=false;gfx->setBrightness(0);}lv_timer_handler();drawDirectNumbers();delay(5);} diff --git a/potentiometer_breath_monitor/AGENTS.md b/potentiometer_breath_monitor/AGENTS.md new file mode 100644 index 0000000..5d1c8cd --- /dev/null +++ b/potentiometer_breath_monitor/AGENTS.md @@ -0,0 +1,8 @@ +# AGENTS + +This group contains Waveshare ESP32-S3-LCD-2 potentiometer breath-monitor sketches. + +- `potentiometer_breath_monitor` has no audio output. +- `potentiometer_breath_monitor_buzzer` uses the active-high buzzer on GPIO6. +- Keep the three-wire potentiometer sensor on GPIO2 unless the adjacent README is updated. +- Run `./burn.sh ` from this folder to compile or flash. diff --git a/potentiometer_breath_monitor/burn.sh b/potentiometer_breath_monitor/burn.sh new file mode 100755 index 0000000..16b1339 --- /dev/null +++ b/potentiometer_breath_monitor/burn.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MODE="${1:-potentiometer-breath-monitor}" +PORT="${PORT:-}" + +case "$MODE" in + potentiometer-breath-monitor) SKETCH_DIR="$ROOT_DIR/potentiometer_breath_monitor" ;; + potentiometer-breath-monitor-buzzer) SKETCH_DIR="$ROOT_DIR/potentiometer_breath_monitor_buzzer" ;; + *) echo "Use: potentiometer-breath-monitor or potentiometer-breath-monitor-buzzer" >&2; exit 2 ;; +esac + +if [[ -z "$PORT" ]]; then + PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')" +fi +if [[ -z "$PORT" && "${NO_UPLOAD:-0}" != "1" ]]; then + echo "Set PORT=/dev/ttyACM0 or use NO_UPLOAD=1." >&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" +BUILD_DIR="$ROOT_DIR/.arduino-build/$MODE" + +arduino-cli compile --fqbn "$FQBN" --build-path "$BUILD_DIR" "$SKETCH_DIR" +if [[ "${NO_UPLOAD:-0}" == "1" ]]; then + exit 0 +fi +arduino-cli upload --fqbn "$FQBN" -p "$PORT" --input-dir "$BUILD_DIR" "$SKETCH_DIR" diff --git a/potentiometer_breath_monitor/potentiometer_breath_monitor/AGENTS.md b/potentiometer_breath_monitor/potentiometer_breath_monitor/AGENTS.md new file mode 100644 index 0000000..07b70a5 --- /dev/null +++ b/potentiometer_breath_monitor/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/potentiometer_breath_monitor/potentiometer_breath_monitor/README.md b/potentiometer_breath_monitor/potentiometer_breath_monitor/README.md new file mode 100644 index 0000000..7b45429 --- /dev/null +++ b/potentiometer_breath_monitor/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` — сменить направление вдоха; +- `+` / `-` — изменить предел. + +## Сборка + +Из папки `SKETCH/potentiometer_breath_monitor`: + +```bash +./burn.sh potentiometer-breath-monitor +``` diff --git a/potentiometer_breath_monitor/potentiometer_breath_monitor/potentiometer_breath_monitor.ino b/potentiometer_breath_monitor/potentiometer_breath_monitor/potentiometer_breath_monitor.ino new file mode 100644 index 0000000..ddc479e --- /dev/null +++ b/potentiometer_breath_monitor/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/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/AGENTS.md b/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/AGENTS.md new file mode 100644 index 0000000..6f697e8 --- /dev/null +++ b/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/AGENTS.md @@ -0,0 +1,5 @@ +# AGENTS + +This folder contains the separate `potentiometer_breath_monitor_buzzer.ino` sketch for Waveshare ESP32-S3-LCD-2. + +It uses the 3-wire potentiometer sensor on GPIO2 and a three-pin buzzer module on GPIO6. Keep screen text in English. When changing behavior, pins, sound settings, or screens, update the adjacent README in the same change. diff --git a/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/README.md b/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/README.md new file mode 100644 index 0000000..d98fd3c --- /dev/null +++ b/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/README.md @@ -0,0 +1,31 @@ +# Potentiometer Breath Monitor With Buzzer + +Separate firmware for Waveshare ESP32-S3-LCD-2. It retains the stable three-wire potentiometer breath sensor from `potentiometer_breath_monitor` and adds an Arduino three-pin buzzer module. + +## Wiring + +- potentiometer wiper: `GPIO2 / IO2`; +- buzzer `GND`: board `GND`; +- buzzer `VCC`: board `3V3` only; +- buzzer `I/O`: `GPIO6 / IO6`. + +Do not feed 5 V into GPIO2 or GPIO6. + +## Sound behavior + +- A complete cycle is stored when EXHALE ends and the following INHALE starts. The average is recalculated from the newest five complete cycles at that point, while alerts use only the newest complete cycle. +- A direction reversal that lasts under two seconds is ignored as sensor jitter unless its movement is at least three times the adaptive reversal threshold. +- `Minimum cycle` compares the newest complete inhale-plus-exhale cycle with the limit. A shorter cycle produces two 500 ms beeps with a 500 ms pause; a cycle at or above the limit produces one 50 ms beep. +- `Maximum phase idle` defaults to 30 seconds. If either INHALE or EXHALE has no detected movement for that time, the module makes a 400 ms beep and repeats it every 10 seconds until movement resumes. +- The main screen has a `PAUSE` / `RESUME` button. While paused, signal processing and alerts stop; resuming starts a fresh current cycle without erasing history. +- `SET` opens settings. `Minimum cycle`, `Maximum phase idle`, and the upside-down display mode are saved in NVS. +- A short `BOOT` press puts the board into deep sleep. Pressing `BOOT` again wakes it. The ESP32 wake source is the button press itself, so firmware cannot require a long press before wake-up. +- The tested three-pin module is an active-high buzzer: `GPIO6 HIGH` turns it on. Its physical pitch and loudness are fixed by the module, so the firmware intentionally does not offer fake frequency or volume controls. + +## Build and flash + +From `SKETCH/potentiometer_breath_monitor`: + +```bash +./burn.sh potentiometer-breath-monitor-buzzer +``` diff --git a/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/potentiometer_breath_monitor_buzzer.ino b/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/potentiometer_breath_monitor_buzzer.ino new file mode 100644 index 0000000..74cc42d --- /dev/null +++ b/potentiometer_breath_monitor/potentiometer_breath_monitor_buzzer/potentiometer_breath_monitor_buzzer.ino @@ -0,0 +1,584 @@ +#include +#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 +#define PIN_BUZZER 6 + +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 MIN_CYCLE_MS = 2000; +static constexpr uint32_t MIN_PHASE_MS = 2000; +static constexpr uint16_t SHORT_CYCLE_BEEP_MS = 50; +static constexpr uint16_t LONG_CYCLE_BEEP_MS = 500; +static constexpr uint16_t SENSOR_IDLE_BEEP_MS = 400; +static constexpr uint16_t BEEP_GAP_MS = 500; +static constexpr uint32_t SENSOR_IDLE_REPEAT_MS = 10000; +static constexpr uint8_t DEFAULT_IDLE_LIMIT_SEC = 30; +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_PAUSE = {186, 7, 66, 24}; +static const Rect BTN_SET = {260, 7, 50, 24}; +static const Rect BTN_LIMIT_DOWN = {14, 42, 56, 28}; +static const Rect BTN_LIMIT_UP = {250, 42, 56, 28}; +static const Rect BTN_IDLE_DOWN = {14, 86, 56, 28}; +static const Rect BTN_IDLE_UP = {250, 86, 56, 28}; +static const Rect BTN_DIRECTION = {14, 126, 292, 28}; +static const Rect BTN_MIRROR = {14, 164, 292, 28}; +static const Rect BTN_BACK = {92, 202, 136, 30}; + +static bool gTouchOk = false; +static bool gTouchWasDown = false; +static bool gSettingsOpen = false; +static bool gManualPaused = false; +static bool gInhaleOnRising = true; +static bool gMirrorDisplay = false; +static bool gBootWasDown = false; +static uint32_t gBootChangedMs = 0; +static uint32_t gBootDownMs = 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 uint32_t gPhaseStartedMs = 0; +static uint8_t gAverageLimitSec = 10; +static uint8_t gIdleLimitSec = DEFAULT_IDLE_LIMIT_SEC; +static bool gPauseAlerted = false; +static bool gBuzzerOn = false; +static uint8_t gQueuedBeeps = 0; +static uint16_t gQueuedBeepDurationMs = LONG_CYCLE_BEEP_MS; +static uint32_t gBuzzerStopMs = 0; +static uint32_t gNextBeepMs = 0; +static Preferences gPrefs; + +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 uint32_t gLastCycleMs = 0; +static bool gIdleAlerted = false; +static uint32_t gLastIdleBeepMs = 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; + gPhaseStartedMs = gStartedMs; + gCycleCount = 0; + gCycleNext = 0; + gLastCycleMs = 0; + gIdleAlerted = false; + gLastIdleBeepMs = 0; + memset(gCycleMs, 0, sizeof(gCycleMs)); + gDirection = 0; + gPhase = Phase::Finding; + gManualPaused = false; + gPauseAlerted = false; +} + +static void resetCurrentPhase(uint32_t now) { + gDirection = 0; + gPhase = Phase::Finding; + gLastInhaleMs = 0; + gPhaseStartedMs = now; + gLastMotionMs = now; + gIdleAlerted = false; + gLastIdleBeepMs = 0; +} + +static void saveBreathSettings() { gPrefs.putUChar("cycleLimit", gAverageLimitSec); gPrefs.putUChar("idleLimit", gIdleLimitSec); gPrefs.putBool("mirror", gMirrorDisplay); } +static void startBeep() { digitalWrite(PIN_BUZZER, HIGH); gBuzzerOn = true; gBuzzerStopMs = millis() + gQueuedBeepDurationMs; } +static void queueBeeps(uint8_t count, uint16_t durationMs) { if (count == 0) return; if (!gBuzzerOn && gQueuedBeeps == 0) gQueuedBeepDurationMs = durationMs; else gQueuedBeepDurationMs = max(gQueuedBeepDurationMs, durationMs); gQueuedBeeps = max(gQueuedBeeps, count); gNextBeepMs = millis(); } +static void serviceBuzzer() { uint32_t now = millis(); if (gBuzzerOn && now >= gBuzzerStopMs) { digitalWrite(PIN_BUZZER, LOW); gBuzzerOn = false; gNextBeepMs = now + BEEP_GAP_MS; } if (!gBuzzerOn && gQueuedBeeps && now >= gNextBeepMs) { --gQueuedBeeps; startBeep(); } } + +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) { + addCycle(cycleMs); + gLastCycleMs = cycleMs; + bool shortCycle = cycleMs < (uint32_t)gAverageLimitSec * 1000UL; + queueBeeps(shortCycle ? 2 : 1, shortCycle ? LONG_CYCLE_BEEP_MS : SHORT_CYCLE_BEEP_MS); + gLastInhaleMs = now; + } + } + gPhase = Phase::Inhale; +} + +static void acceptDirection(int8_t direction, uint32_t now) { + bool wasInhale = gPhase == Phase::Inhale; + bool isInhale = gInhaleOnRising ? direction > 0 : direction < 0; + gDirection = direction; + gExtremeMv = gFilteredMv; + if (isInhale) enterInhale(now); + else gPhase = Phase::Exhale; + gPhaseStartedMs = now; + gLastMotionMs = now; + gPauseAlerted = false; + gIdleAlerted = false; + gLastIdleBeepMs = 0; +} + +static void serviceSensorIdle(uint32_t now) { + if (gManualPaused || gPhase == Phase::Finding) return; + uint32_t idleMs = (uint32_t)gIdleLimitSec * 1000UL; + if (now - gLastMotionMs < idleMs) { + gIdleAlerted = false; + gLastIdleBeepMs = 0; + return; + } + if (!gIdleAlerted || now - gLastIdleBeepMs >= SENSOR_IDLE_REPEAT_MS) { + queueBeeps(1, SENSOR_IDLE_BEEP_MS); + gIdleAlerted = true; + gLastIdleBeepMs = 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) { + bool shortPhase = gPhaseStartedMs != 0 && now - gPhaseStartedMs < MIN_PHASE_MS; + bool sharpReversal = awayFromExtreme >= threshold * 3; + if (!shortPhase || sharpReversal) 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", C_TEXT, 2); + drawButton(BTN_PAUSE, gManualPaused ? "RESUME" : "PAUSE", gManualPaused); + 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, "Last cycle", C_MUTE, 1); + gfx->drawRoundRect(9, 207, 302, 26, 6, C_BORDER); +} + +static void updateMainValues() { + char line[64]; + uint32_t now = millis(); + + gfx->fillRect(10, 109, 300, 46, C_BG); + uint32_t phaseMs = gPhaseStartedMs == 0 ? 0 : now - gPhaseStartedMs; + uint32_t cycleMs = gLastInhaleMs == 0 ? 0 : now - gLastInhaleMs; + drawCentered(10, 111, 300, gManualPaused ? "PAUSED" : phaseText(), gManualPaused ? C_WARN : phaseColor(), 2); + uint8_t position = constrain((int)((gFilteredMv / 3300.0f) * 100.0f), 0, 100); + formatSeconds(line, sizeof(line), phaseMs); + drawCentered(10, 132, 300, line, C_TEXT, 2); + snprintf(line, sizeof(line), "Pos %u%%", position); + drawCentered(10, 151, 300, line, C_MUTE, 1); + + uint32_t average = averageCycleMs(); + uint16_t metricColor = 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 (gLastCycleMs == 0) drawText(175, 184, "--", C_TEXT, 2); + else { + formatSeconds(line, sizeof(line), gLastCycleMs); + 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 Cycle min %us Idle %us", clock, gAverageLimitSec, gIdleLimitSec); + drawText(11, 234, line, C_MUTE, 1); +} + +static void drawSettings() { + gfx->fillScreen(C_BG); + drawText(10, 12, "SETTINGS", C_TEXT, 2); + drawText(10, 32, "Minimum cycle", C_MUTE, 1); + drawButton(BTN_LIMIT_DOWN, "-"); + drawButton(BTN_LIMIT_UP, "+"); + char value[16]; + snprintf(value, sizeof(value), "%u s", gAverageLimitSec); + drawCentered(70, 48, 180, value, C_ACCENT, 2); + drawText(10, 76, "Maximum phase idle", C_MUTE, 1); + drawButton(BTN_IDLE_DOWN, "-"); + drawButton(BTN_IDLE_UP, "+"); + snprintf(value, sizeof(value), "%u s", gIdleLimitSec); + drawCentered(70, 92, 180, value, C_ACCENT, 2); + drawText(10, 114, "Inhale direction", C_MUTE, 1); + drawButton(BTN_DIRECTION, gInhaleOnRising ? "RISE = INHALE" : "FALL = INHALE", true); + drawButton(BTN_MIRROR, gMirrorDisplay ? "DISPLAY UPSIDE DOWN: ON" : "DISPLAY UPSIDE DOWN: OFF"); + drawButton(BTN_BACK, "BACK"); +} + +static void toggleSettings() { + gSettingsOpen = !gSettingsOpen; + if (gSettingsOpen) drawSettings(); + else drawMainStatic(); +} + +static void changeLimit(int8_t delta) { + gAverageLimitSec = constrain((int16_t)gAverageLimitSec + delta * 5, 5, 60); + saveBreathSettings(); + if (gSettingsOpen) drawSettings(); +} + +static void changeIdleLimit(int8_t delta) { + gIdleLimitSec = constrain((int16_t)gIdleLimitSec + delta * 5, 5, 120); + saveBreathSettings(); + if (gSettingsOpen) drawSettings(); +} + +static void togglePause() { + gManualPaused = !gManualPaused; + if (!gManualPaused) resetCurrentPhase(millis()); + if (!gSettingsOpen) drawMainStatic(); +} + +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 (gMirrorDisplay) { x = DISP_W - 1 - x; y = DISP_H - 1 - y; } + + if (!gSettingsOpen) { + if (contains(BTN_SET, x, y)) toggleSettings(); + else if (contains(BTN_PAUSE, x, y)) togglePause(); + return; + } + if (contains(BTN_LIMIT_DOWN, x, y)) changeLimit(-1); + else if (contains(BTN_LIMIT_UP, x, y)) changeLimit(1); + else if (contains(BTN_IDLE_DOWN, x, y)) changeIdleLimit(-1); + else if (contains(BTN_IDLE_UP, x, y)) changeIdleLimit(1); + else if (contains(BTN_DIRECTION, x, y)) { + gInhaleOnRising = !gInhaleOnRising; + drawSettings(); + } else if (contains(BTN_MIRROR, x, y)) { + gMirrorDisplay = !gMirrorDisplay; + gPrefs.putBool("mirror", gMirrorDisplay); + gfx->setRotation(gMirrorDisplay ? 3 : 1); + 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) gBootDownMs = now; + else { + digitalWrite(PIN_BUZZER, LOW); + digitalWrite(PIN_LCD_BL, LOW); + esp_sleep_enable_ext0_wakeup((gpio_num_t)PIN_BOOT_BUTTON, LOW); + esp_deep_sleep_start(); + } + } +} + +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); + gPrefs.begin("pot-buzzer", false); + gAverageLimitSec = constrain(gPrefs.getUChar("cycleLimit", gPrefs.getUChar("inhaleLimit", gPrefs.getUChar("avgLimit", 10))), 5, 60); + gIdleLimitSec = constrain(gPrefs.getUChar("idleLimit", DEFAULT_IDLE_LIMIT_SEC), 5, 120); + gMirrorDisplay = gPrefs.getBool("mirror", false); + pinMode(PIN_BUZZER, OUTPUT); + digitalWrite(PIN_BUZZER, LOW); + pinMode(PIN_ADC_WIPER, INPUT); + analogReadResolution(12); + analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db); + + gfx->begin(); + gfx->setRotation(gMirrorDisplay ? 3 : 1); + 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() { + serviceBuzzer(); + handleSerial(); + handleBootButton(); + if (gTouchOk) handleTouch(); + + uint32_t now = millis(); + if (!gManualPaused && now - gLastSampleMs >= SAMPLE_PERIOD_MS) { + processSignal(readMilliVolts(), now); + serviceSensorIdle(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; + } +}