Зафиксировать рабочий BreathMonitor v1 и сервер

This commit is contained in:
AidarKC
2026-10-25 14:14:27 +03:00
parent 370f4ae94e
commit d5a37d3009
43 changed files with 2490 additions and 1522 deletions
@@ -0,0 +1,45 @@
# 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`.
- Мелко: бегущее время текущего полного цикла.
- Мелко: длительность текущей сессии.
Полный экран не перерисовывается в рабочем цикле. Обновляются только небольшие области с изменившимися значениями. Полная перерисовка происходит только при переходе между рабочим экраном и настройками.
## Прошивка
Из этой папки:
```bash
./burn.sh
```
Только проверить сборку, не прошивая плату:
```bash
NO_UPLOAD=1 ./burn.sh
```
@@ -0,0 +1,695 @@
#include <Arduino.h>
#include <Wire.h>
#include <Preferences.h>
#include <math.h>
#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);
}
@@ -0,0 +1,43 @@
#!/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"
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}"
BUILD_DIR="$ROOT_DIR/../../.arduino-build/breath-button-monitor"
OUT_DIR="$ROOT_DIR/../../.arduino-build/out-breath-button-monitor"
if [[ ! -d "$DEMO_BASE/libraries" ]]; then
echo "Missing Waveshare libraries: $DEMO_BASE/libraries" >&2
exit 1
fi
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"
"$ROOT_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" "$ROOT_DIR"
@@ -0,0 +1,443 @@
/*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#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[] = {
/*!<mclk rate pre_div mult adc_div dac_div fs_mode lrch lrcl bckdiv osr */
/* 8k */
{12288000, 8000, 0x06, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 8000, 0x03, 0x01, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x10},
{16384000, 8000, 0x08, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 8000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 8000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{4096000, 8000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 8000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2048000, 8000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 8000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1024000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 11.025k */
{11289600, 11025, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 11025, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 11025, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 12k */
{12288000, 12000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 12000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 12000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 16k */
{12288000, 16000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 16000, 0x03, 0x01, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
{16384000, 16000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 16000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{4096000, 16000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2048000, 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 16000, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1024000, 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 22.05k */
{11289600, 22050, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 22050, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{705600, 22050, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 24k */
{12288000, 24000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 24000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 24000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 32k */
{12288000, 32000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 32000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
{16384000, 32000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 32000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{4096000, 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 32000, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2048000, 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 32000, 0x03, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
{1024000, 32000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 44.1k */
{11289600, 44100, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 44100, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 48k */
{12288000, 48000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 48000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 48000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 64k */
{12288000, 64000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 64000, 0x03, 0x02, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{16384000, 64000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 64000, 0x01, 0x02, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{4096000, 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 64000, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{2048000, 64000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 64000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18},
{1024000, 64000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
/* 88.2k */
{11289600, 88200, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 88200, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 88200, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
/* 96k */
{12288000, 96000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 96000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 96000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 96000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
};
static const char *TAG = "ES8311";
static inline esp_err_t es8311_write_reg(es8311_handle_t dev, uint8_t reg_addr, uint8_t data)
{
es8311_dev_t *es = (es8311_dev_t *) dev;
const uint8_t write_buf[2] = {reg_addr, data};
return i2cWrite(es->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, &reg_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, &regv), 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, &regv), 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, &regv), 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, &reg06), 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, &reg00), 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, &reg09);
es8311_resolution_config(res_out, &reg0a);
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, &reg32), 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, &reg31), 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, &reg37), 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, &reg15), 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;
}
@@ -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
@@ -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