Скетчи не по делу: ручной монитор и тесты потенциометра

This commit is contained in:
AidarKC
2026-10-13 19:04:15 +03:00
parent bb725ee451
commit d25894149b
12 changed files with 2436 additions and 3 deletions
@@ -0,0 +1,17 @@
# AGENTS
## Назначение папки
Эта папка содержит отдельный тестовый Arduino-скетч `potentiometer_adc_test.ino` для Waveshare `ESP32-S3-LCD-2`.
Скетч проверяет переменный резистор на обычных GPIO/ADC, без использования USB `D+ / D-`.
## Обязательная синхронизация
При любом изменении `potentiometer_adc_test.ino` обязательно обновлять рядом лежащий `README.md`.
Если меняются экранные тексты, режимы, пины подключения, правила расчёта, touch-кнопки или serial-команды, описание в `README.md` должно быть обновлено в том же наборе изменений.
## Язык экрана
Экранные строки в скетче оставлять на английском языке.
@@ -0,0 +1,73 @@
# Potentiometer ADC Test for ESP32-S3-LCD-2
Тестовый скетч для Waveshare `ESP32-S3-LCD-2`.
Назначение: проверить переменный резистор `RP 6045-B50K` через обычные GPIO/ADC, без использования USB `D+ / D-`.
## Пины
Используются пины с разъёма `P1` платы:
- `GPIO2 / IO2` — ADC-вход, сюда подключается ползунок потенциометра.
- `GPIO6 / IO6` — DRIVE-выход для грубого 2-проводного режима.
- `3V3` — питание потенциометра для 3-проводного режима, находится на разъёме `P2`.
- `GND` — земля.
Не подавать `5V` на `GPIO2` или `GPIO6`: GPIO ESP32-S3 не являются 5V tolerant.
## Режимы
Переключение:
- touch-кнопка `3-WIRE`;
- touch-кнопка `2-WIRE`;
- серийная команда `m`;
- короткое нажатие `BOOT / GPIO0`.
Сброс min/max:
- touch-кнопка `RESET`;
- серийная команда `r`.
## 3-Wire Mode
Правильное подключение:
- один край потенциометра -> `3V3`;
- второй край потенциометра -> `GND`;
- средний ползунок -> `GPIO2 / IO2`.
Скетч показывает напряжение на ползунке, raw ADC, абсолютное положение от `0..3.3V`, калиброванное положение между найденными min/max и примерное сопротивление участка `0..50 kΩ`.
## 2-Wire Mode
Грубое подключение:
- один край потенциометра -> `GPIO6 / IO6`;
- средний ползунок -> `GPIO2 / IO2`;
- второй край не подключать.
`GPIO6` выдаёт `HIGH`, `GPIO2` читается как ADC с внутренней подтяжкой вниз. Такой режим показывает движение ползунка, но не даёт точного сопротивления: внутренняя подтяжка ESP32 имеет большой разброс.
## Экранные данные
На экране выводятся:
- режим и схема пинов;
- raw ADC и millivolts;
- абсолютный процент от `0..3300 mV`;
- калиброванный процент по найденному min/max;
- min/max/span;
- EMA-сглаживание;
- примерная оценка сопротивления;
- статус `OPEN/LOW/MID/HIGH/SATURATED/NO SPAN`;
- координаты последнего touch;
- serial-подсказка.
## Сборка
Из папки `main-device`:
```bash
./burn.sh potentiometer-adc-test
```
@@ -0,0 +1,348 @@
#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_DRIVE_2WIRE 6
#define PIN_BOOT_BUTTON 0
static const uint16_t DISP_W = 320;
static const uint16_t DISP_H = 240;
static const uint32_t ADC_FULL_MV = 3300;
static const float POT_OHMS = 50000.0f;
static const float ROUGH_PULLDOWN_OHMS = 45000.0f;
static const uint16_t C_BG = 0x0841;
static const uint16_t C_PANEL = 0x18E3;
static const uint16_t C_CARD = 0x2126;
static const uint16_t C_TEXT = 0xF7BE;
static const uint16_t C_MUTE = 0x8C71;
static const uint16_t C_ACCENT = 0x05DF;
static const uint16_t C_OK = 0x47E8;
static const uint16_t C_WARN = 0xFD20;
static const uint16_t C_BAD = 0xF986;
static const uint16_t C_BORDER = 0x4208;
struct Rect {
int16_t x;
int16_t y;
int16_t w;
int16_t h;
};
enum class Mode : uint8_t {
ThreeWire,
TwoWire,
};
struct Sample {
uint16_t raw;
uint32_t mv;
uint16_t rawMinBurst;
uint16_t rawMaxBurst;
};
Arduino_DataBus *bus = new Arduino_ESP32SPI(
PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO);
Arduino_GFX *gfx = new Arduino_ST7789(
bus, PIN_LCD_RST, 1, true, 240, 320);
static const Rect BTN_3WIRE = {10, 38, 94, 30};
static const Rect BTN_2WIRE = {113, 38, 94, 30};
static const Rect BTN_RESET = {216, 38, 94, 30};
static Mode gMode = Mode::ThreeWire;
static uint32_t gLastUiMs = 0;
static uint32_t gLastSerialMs = 0;
static uint32_t gMinMv = 0xFFFFFFFF;
static uint32_t gMaxMv = 0;
static float gEmaMv = 0.0f;
static bool gHasEma = false;
static bool gTouchOk = false;
static uint16_t gLastTouchX = 0;
static uint16_t gLastTouchY = 0;
static bool gBootWasDown = false;
static uint32_t gBootLastChangeMs = 0;
static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) {
gfx->setTextSize(size);
gfx->setTextColor(color);
gfx->setCursor(x, y);
gfx->print(text);
}
static void drawButton(const Rect &r, const char *label, bool active) {
uint16_t fill = active ? C_ACCENT : C_CARD;
uint16_t text = active ? C_BG : C_TEXT;
gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill);
gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER);
int16_t tx = r.x + 10;
int16_t ty = r.y + 10;
drawText(tx, ty, label, text, 1);
}
static bool contains(const Rect &r, uint16_t x, uint16_t y) {
return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
}
static const char *modeName() {
return gMode == Mode::ThreeWire ? "3-WIRE" : "2-WIRE";
}
static void resetRange() {
gMinMv = 0xFFFFFFFF;
gMaxMv = 0;
gHasEma = false;
}
static void configurePins() {
pinMode(PIN_ADC_WIPER, INPUT);
analogReadResolution(12);
analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db);
if (gMode == Mode::TwoWire) {
pinMode(PIN_DRIVE_2WIRE, OUTPUT);
digitalWrite(PIN_DRIVE_2WIRE, HIGH);
pinMode(PIN_ADC_WIPER, INPUT_PULLDOWN);
} else {
pinMode(PIN_DRIVE_2WIRE, INPUT);
pinMode(PIN_ADC_WIPER, INPUT);
}
}
static void setMode(Mode mode) {
if (gMode == mode) return;
gMode = mode;
configurePins();
resetRange();
}
static Sample readSample() {
const uint8_t count = 32;
uint32_t rawSum = 0;
uint32_t mvSum = 0;
uint16_t rawMin = 4095;
uint16_t rawMax = 0;
for (uint8_t i = 0; i < count; i++) {
uint16_t raw = analogRead(PIN_ADC_WIPER);
uint32_t mv = analogReadMilliVolts(PIN_ADC_WIPER);
rawSum += raw;
mvSum += mv;
if (raw < rawMin) rawMin = raw;
if (raw > rawMax) rawMax = raw;
delayMicroseconds(250);
}
Sample s;
s.raw = rawSum / count;
s.mv = mvSum / count;
s.rawMinBurst = rawMin;
s.rawMaxBurst = rawMax;
return s;
}
static uint8_t percentFromMv(uint32_t mv) {
if (mv >= ADC_FULL_MV) return 100;
return (uint8_t)((mv * 100UL + ADC_FULL_MV / 2) / ADC_FULL_MV);
}
static uint8_t calibratedPercent(uint32_t mv, uint32_t span) {
if (span < 10 || gMinMv == 0xFFFFFFFF || mv <= gMinMv) return 0;
uint32_t pct = ((mv - gMinMv) * 100UL + span / 2) / span;
return (uint8_t)min<uint32_t>(pct, 100);
}
static const char *statusText(uint32_t mv, uint32_t span, uint8_t pctAbs) {
if (mv < 30) return "OPEN/GND";
if (mv > 3250) return "SATURATED";
if (span < 20) return "NO SPAN";
if (pctAbs < 15) return "LOW";
if (pctAbs > 85) return "HIGH";
return "MID";
}
static float estimateOhms(uint32_t mv) {
if (gMode == Mode::ThreeWire) {
return POT_OHMS * ((float)percentFromMv(mv) / 100.0f);
}
if (mv < 5) return -1.0f;
if (mv >= ADC_FULL_MV) return 0.0f;
return ROUGH_PULLDOWN_OHMS * ((float)ADC_FULL_MV / (float)mv - 1.0f);
}
static void drawStaticUi() {
gfx->fillScreen(C_BG);
drawText(10, 8, "POT ADC TEST", C_TEXT, 2);
drawText(210, 12, "ESP32-S3-LCD-2", C_MUTE, 1);
drawButton(BTN_3WIRE, "3-WIRE", gMode == Mode::ThreeWire);
drawButton(BTN_2WIRE, "2-WIRE", gMode == Mode::TwoWire);
drawButton(BTN_RESET, "RESET", false);
gfx->drawRoundRect(8, 76, 304, 64, 8, C_BORDER);
gfx->drawRoundRect(8, 148, 304, 54, 8, C_BORDER);
gfx->drawRoundRect(8, 208, 304, 24, 6, C_BORDER);
}
static void drawBar(uint8_t pct, uint16_t color) {
int x = 18;
int y = 123;
int w = 284;
int h = 10;
gfx->fillRect(x, y, w, h, C_BORDER);
gfx->fillRect(x, y, (w * pct) / 100, h, color);
}
static void updateUi() {
Sample s = readSample();
if (s.mv < gMinMv) gMinMv = s.mv;
if (s.mv > gMaxMv) gMaxMv = s.mv;
uint32_t span = (gMaxMv > gMinMv) ? (gMaxMv - gMinMv) : 0;
if (!gHasEma) {
gEmaMv = (float)s.mv;
gHasEma = true;
} else {
gEmaMv = gEmaMv * 0.85f + (float)s.mv * 0.15f;
}
uint8_t pctAbs = percentFromMv(s.mv);
uint8_t pctCal = calibratedPercent(s.mv, span);
float ohms = estimateOhms(s.mv);
const char *status = statusText(s.mv, span, pctAbs);
uint16_t statusColor = strcmp(status, "MID") == 0 ? C_OK :
strcmp(status, "NO SPAN") == 0 ? C_WARN :
strcmp(status, "SATURATED") == 0 ? C_BAD : C_ACCENT;
char line[96];
gfx->fillRect(9, 77, 302, 62, C_BG);
snprintf(line, sizeof(line), "%s ADC=IO2 DRIVE=IO6", modeName());
drawText(16, 84, line, C_ACCENT, 1);
snprintf(line, sizeof(line), "raw:%4u mv:%4lu ema:%4lu",
s.raw, (unsigned long)s.mv, (unsigned long)(gEmaMv + 0.5f));
drawText(16, 101, line, C_TEXT, 1);
snprintf(line, sizeof(line), "abs:%3u%% cal:%3u%% jitter:%u",
pctAbs, pctCal, (unsigned)(s.rawMaxBurst - s.rawMinBurst));
drawText(16, 115, line, C_TEXT, 1);
drawBar(gMode == Mode::ThreeWire ? pctAbs : pctCal, statusColor);
gfx->fillRect(9, 149, 302, 52, C_BG);
snprintf(line, sizeof(line), "min:%4lu max:%4lu span:%4lu mV",
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span);
drawText(16, 156, line, C_TEXT, 1);
if (ohms < 0) {
snprintf(line, sizeof(line), "ohm: open/too high status:%s", status);
} else {
snprintf(line, sizeof(line), "ohm:%6.1fk%s status:%s",
ohms / 1000.0f, gMode == Mode::TwoWire ? " rough" : "", status);
}
drawText(16, 172, line, statusColor, 1);
snprintf(line, sizeof(line), "touch:%s x:%u y:%u serial:m/r",
gTouchOk ? "ok" : "off", gLastTouchX, gLastTouchY);
drawText(16, 188, line, C_MUTE, 1);
gfx->fillRect(9, 209, 302, 22, C_BG);
if (gMode == Mode::ThreeWire) {
drawText(16, 216, "Wire: 3V3-edge GND-edge IO2-wiper", C_MUTE, 1);
} else {
drawText(16, 216, "Wire: IO6-edge IO2-wiper third pin open", C_MUTE, 1);
}
Serial.printf("mode=%s raw=%u mv=%lu ema=%.1f abs=%u cal=%u min=%lu max=%lu span=%lu jitter=%u status=%s\n",
modeName(), s.raw, (unsigned long)s.mv, gEmaMv, pctAbs, pctCal,
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span,
(unsigned)(s.rawMaxBurst - s.rawMinBurst), status);
}
static void handleTouch() {
bsp_touch_read();
uint16_t x = 0;
uint16_t y = 0;
if (!bsp_touch_get_coordinates(&x, &y)) return;
gLastTouchX = x;
gLastTouchY = y;
if (contains(BTN_3WIRE, x, y)) {
setMode(Mode::ThreeWire);
drawStaticUi();
} else if (contains(BTN_2WIRE, x, y)) {
setMode(Mode::TwoWire);
drawStaticUi();
} else if (contains(BTN_RESET, x, y)) {
resetRange();
}
}
static void handleBootButton() {
bool down = digitalRead(PIN_BOOT_BUTTON) == LOW;
uint32_t now = millis();
if (down != gBootWasDown && now - gBootLastChangeMs > 40) {
gBootWasDown = down;
gBootLastChangeMs = now;
if (!down) {
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
drawStaticUi();
}
}
}
static void handleSerial() {
while (Serial.available() > 0) {
char c = (char)Serial.read();
if (c == 'm' || c == 'M') {
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
drawStaticUi();
} else if (c == 'r' || c == 'R') {
resetRange();
}
}
}
void setup() {
Serial.begin(115200);
delay(100);
Serial.println("ESP32-S3-LCD-2 potentiometer ADC test");
Serial.println("Commands: m=switch mode, r=reset min/max");
pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP);
configurePins();
if (!gfx->begin()) {
Serial.println("gfx->begin() failed");
}
pinMode(PIN_LCD_BL, OUTPUT);
digitalWrite(PIN_LCD_BL, HIGH);
Wire.begin(PIN_TP_SDA, PIN_TP_SCL);
gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H);
drawStaticUi();
}
void loop() {
handleSerial();
handleBootButton();
if (gTouchOk) handleTouch();
uint32_t now = millis();
if (now - gLastUiMs >= 250) {
updateUi();
gLastUiMs = now;
}
if (now - gLastSerialMs >= 5000) {
Serial.println("Hint: m switches 3-WIRE/2-WIRE, r resets min/max. Never feed 5V into IO2/IO6.");
gLastSerialMs = now;
}
}