Добавить скетчи SHiNE

This commit is contained in:
AidarKC
2026-10-16 18:36:00 +03:00
commit c0bb7d6b9a
32 changed files with 6126 additions and 0 deletions
@@ -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.
@@ -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
```
@@ -0,0 +1,584 @@
#include <Arduino.h>
#include <Arduino_GFX_Library.h>
#include <Wire.h>
#include <bsp_cst816.h>
#include <Preferences.h>
#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<int16_t>(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<uint16_t>(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;
}
}