SHA256
Убрал лишние скетчи из проекта
This commit is contained in:
@@ -10,13 +10,13 @@ case "$MODE" in
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_adc_test"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-adc-test"
|
||||
;;
|
||||
potentiometer-breath-monitor)
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_breath_monitor"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-breath-monitor"
|
||||
buzzer-gpio6-test)
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/buzzer_gpio6_test"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-buzzer-gpio6-test"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown mode: $MODE" >&2
|
||||
echo "Known modes: potentiometer-adc-test, potentiometer-breath-monitor" >&2
|
||||
echo "Known modes: potentiometer-adc-test, buzzer-gpio6-test" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# AGENTS
|
||||
|
||||
This folder contains a temporary GPIO6 buzzer diagnostic for ESP32-S3-LCD-2. Keep screen/serial strings in English.
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
// Buzzer module wiring: GND -> GND, VCC -> 3V3, I/O -> P1 IO6 / GPIO6.
|
||||
static constexpr uint8_t PIN_BUZZER = 6;
|
||||
static constexpr uint32_t STEP_MS = 1800;
|
||||
static uint8_t gStep = 0;
|
||||
static uint32_t gChangedMs = 0;
|
||||
|
||||
static void applyStep(uint8_t step) {
|
||||
ledcDetach(PIN_BUZZER);
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
delay(80);
|
||||
switch (step) {
|
||||
case 0:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, HIGH);
|
||||
Serial.println("TEST 1: GPIO6 HIGH - active-high module should sound");
|
||||
break;
|
||||
case 1:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
Serial.println("TEST 2: GPIO6 LOW - active-low module should sound");
|
||||
break;
|
||||
case 2:
|
||||
ledcAttach(PIN_BUZZER, 1800, 8);
|
||||
ledcWriteTone(PIN_BUZZER, 1800);
|
||||
ledcWrite(PIN_BUZZER, 180);
|
||||
Serial.println("TEST 3: GPIO6 PWM 1800 Hz - passive module should sound");
|
||||
break;
|
||||
default:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
Serial.println("SILENCE");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println("GPIO6 BUZZER TEST: HIGH, LOW, PWM, SILENCE. Each step lasts 1.8 seconds.");
|
||||
applyStep(gStep);
|
||||
gChangedMs = millis();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (millis() - gChangedMs < STEP_MS) return;
|
||||
gStep = (gStep + 1) % 4;
|
||||
applyStep(gStep);
|
||||
gChangedMs = millis();
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
# AGENTS
|
||||
|
||||
## Назначение папки
|
||||
|
||||
Эта папка содержит отдельный Arduino-скетч `potentiometer_breath_monitor.ino` для Waveshare `ESP32-S3-LCD-2`.
|
||||
|
||||
Скетч измеряет дыхательные циклы по трёхконтактно подключённому переменному резистору. Звук пока намеренно не используется.
|
||||
|
||||
## Обязательная синхронизация
|
||||
|
||||
При любом изменении `potentiometer_breath_monitor.ino` обязательно обновлять рядом лежащий `README.md`.
|
||||
|
||||
Если меняются экранные тексты, пины, алгоритм определения фаз, настройки, touch-кнопки, serial-команды или логика паузы, описание в `README.md` должно быть обновлено в том же наборе изменений.
|
||||
|
||||
## Язык экрана
|
||||
|
||||
Экранные строки в скетче оставлять на английском языке.
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
# Potentiometer Breath Monitor for ESP32-S3-LCD-2
|
||||
|
||||
Отдельный скетч для Waveshare `ESP32-S3-LCD-2`, измеряющий дыхание по движению ползунка потенциометра. Звук в этой версии не подключается и не управляется.
|
||||
|
||||
## Подключение
|
||||
|
||||
Используется только устойчивый трёхконтактный вариант:
|
||||
|
||||
- крайний контакт потенциометра -> `3V3` на разъёме `P2`;
|
||||
- второй крайний контакт -> `GND`;
|
||||
- средний контакт (ползунок) -> `GPIO2 / IO2` на разъёме `P1`.
|
||||
|
||||
Нельзя подавать `5V` на `GPIO2`: входы ESP32-S3 не являются 5V tolerant.
|
||||
|
||||
## Принцип работы
|
||||
|
||||
- ADC считывается 40 раз в секунду и сглаживается.
|
||||
- Абсолютная калибровка не нужна: медленное смещение ремня/пояса отслеживается отдельным медленным фоном.
|
||||
- Направление определяется по сглаженному движению ползунка. В настройках выбирается, является ли движение вверх вдохом (`RISE INHALE`) или выдохом (`FALL INHALE`).
|
||||
- Во время каждой фазы скетч запоминает достигнутый максимум или минимум без ограничения по времени. Разворот принимается только после накопленного обратного хода от этой точки. Поэтому вдох или выдох может длиться значительно дольше пяти секунд, а мелкий дребезг не создаёт дополнительные фазы.
|
||||
- Порог обратного хода автоматически подстраивается к размаху недавнего движения и ограничен диапазоном `18..50 mV`. Он не зависит от скорости движения: даже очень плавный вдох в итоге будет распознан.
|
||||
- Полный цикл измеряется от начала вдоха до начала следующего вдоха. Циклы короче `2.0 s` не попадают в статистику.
|
||||
- Если движение не обнаруживается 60 секунд, отображается `PAUSE`. В этой версии звуковых сигналов нет.
|
||||
|
||||
## Экран и управление
|
||||
|
||||
Основной экран показывает:
|
||||
|
||||
- живую кольцевую линию положения ползунка без полной перерисовки дисплея;
|
||||
- текущую фазу `INHALE`, `EXHALE`, `FINDING MOTION` или `PAUSE`;
|
||||
- положение и текущую длительность цикла;
|
||||
- среднее последних пяти циклов и частоту в `bpm`;
|
||||
- пять последних длительностей;
|
||||
- время работы и выбранный предел `5 / 7 / 10 / 15 / 20 s`.
|
||||
|
||||
Если среднее пяти циклов меньше выбранного предела, метрики и отметка `FAST` становятся красными. Позже к этому же условию можно добавить звук.
|
||||
|
||||
`SET` на экране или короткое нажатие `BOOT / GPIO0` открывает настройки. Одно касание обрабатывается как одно действие. В настройках доступны предел и направление вдоха. `RESET` очищает текущую сессию и последние циклы.
|
||||
|
||||
Постоянные части экрана рисуются один раз. В цикле обновляются только числа, статус и узкая колонка графика, поэтому весь экран не мигает.
|
||||
|
||||
## Serial
|
||||
|
||||
Скорость: `115200`.
|
||||
|
||||
- `s` — открыть/закрыть настройки;
|
||||
- `r` — сбросить сессию;
|
||||
- `d` — сменить направление вдоха;
|
||||
- `+` / `-` — изменить предел.
|
||||
|
||||
## Сборка
|
||||
|
||||
Из папки `main-device`:
|
||||
|
||||
```bash
|
||||
./burn.sh potentiometer-breath-monitor
|
||||
```
|
||||
-481
@@ -1,481 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include <Wire.h>
|
||||
#include <bsp_cst816.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
|
||||
|
||||
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<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;
|
||||
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<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 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user