This smart sleep watch combines heart rate monitoring, motion tracking, and haptic feedback to analyze sleep patterns and provide real-time biometric data. Built around an ESP32 microcontroller, it integrates a MAX30102 pulse oximetry sensor for accurate heart rate detection, an MPU-6050 accelerometer for movement tracking, and a vibrant 1.28-inch round TFT display to show sleep metrics and notifications.
The guide provides a complete wiring diagram connecting all sensors and peripherals, a full parts list with sourcing information, and step-by-step assembly instructions from power preparation through final enclosure mounting. Firmware with Bluetooth connectivity and cloud integration is included, allowing the watch to stream telemetry data to companion applications and respond to remote commands.
Wiring diagram

Gather all the parts
Assemble it in 5 steps
1. Prepare a alimentação sem a bateria
Use PowerBoost 1000C e bateria protegida de 3,7 V, 1000 mAh, aprovada pelo fabricante para carga de 1 A. Ligue saída 5V do PowerBoost a VIN e GND a GND. Não ligue bateria diretamente ao ESP32.
- Não use bateria sem proteção, inchada ou com polaridade invertida. Não carregue no pulso ou durante o sono.
- Antes de conectar USB ao ESP32 para Deploy, desconecte a saída 5V do PowerBoost de VIN para evitar retorno de corrente. Refaça a ligação somente após retirar o USB do ESP32.
2. Ligue os sensores
MAX30102 VCC e MPU6050 VIN vão ao 3V3. Ambos GND vão a GND, SDA a GPIO21 (dados) e SCL a GPIO22 (relógio de comunicação). Use módulos com regulador e resistores de comunicação para 3,3 V.
3. Ligue a tela redonda
VCC a 3V3; GND a GND; SCK/CLK a GPIO18 (relógio); MOSI/DIN a GPIO23 (dados); CS a GPIO13 (seleção); DC a GPIO14 (comando); RST a GPIO27 (reinício); BL a GPIO26 (iluminação). Tela Waveshare GC9A01 1,28 polegada, 240x240, sem toque.
4. Ligue botão e vibração
Botão entre GPIO32 e GND. DRV2605L VIN a 3V3, GND a GND, SDA a GPIO21 e SCL a GPIO22. Motor de dois fios entre OUT+ e OUT-. Nunca ligue motor diretamente ao ESP32.
5. Teste na bancada e monte a caixa
Confira todas as ligações antes de conectar a bateria ao PowerBoost. Carregue pelo USB do PowerBoost. Mantenha eletrônica e bateria isoladas da pele; deixe somente a janela óptica do sensor voltada ao pulso sem apertar. Não é resistente à água.
- A autonomia estimada é cerca de 2 horas, não uma noite inteira. Esta montagem precisa de otimização e testes antes de uso noturno.
- Pulso e intervalos são estimativas experimentais; movimento prejudica leituras no pulso. Não diagnostica apneia ou fases do sono.
Review all connections
1. Connections between "pulse" and "ESP32"
2. Connections between "motion" and "ESP32"
3. Connections between "haptic" and "ESP32"
4. Connections between "screen" and "ESP32"
5. Connections between "button1" and "ESP32"
6. Connections between "battery" and "ESP32"
7. Connections between "supply" and "ESP32"
Deploy the firmware
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_GC9A01A.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_DRV2605.h>
#include <MAX30105.h>
#include <heartRate.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <BLESecurity.h>
#include <SPIFFS.h>
#include <Preferences.h>
#include <esp_system.h>
#include <esp_bt.h>
#include <time.h>
#include "config.h"
// 1 = placa sozinha (sem tela e sem sensores): pula I2C/SPI e desenho.
// Troque para 0 quando ligar o hardware.
#define BARE_BOARD 1
Adafruit_GC9A01A lcd(13, 14, 27);
Adafruit_MPU6050 imu;
Adafruit_DRV2605 vib;
MAX30105 ppg;
bool pulseOK = false, imuOK = false, vibOK = false, fsOK = false;
volatile bool connected = false;
BLECharacteristic *telemetry = nullptr;
BLECharacteristic *media = nullptr;
QueueHandle_t commands, records;
struct Command { uint16_t n; uint8_t b[256]; };
struct Record { char text[240]; };
static const char *SERVICE_UUID = "3a4c0001-1bca-4c30-9050-2093389d419a";
static const char *TELEMETRY_UUID = "3a4c0002-1bca-4c30-9050-2093389d419a";
static const char *CONTROL_UUID = "3a4c0003-1bca-4c30-9050-2093389d419a";
static const char *MEDIA_UUID = "3a4c0004-1bca-4c30-9050-2093389d419a";
volatile bool internetOK = false;
String title = "App nao conectado";
bool dirty = true, recording = false, wallpaper = false;
uint32_t sampleClock = 0, lastBeat = 0, lastContact = 0;
float bpm = 0, movement = 0, rotation = 0;
uint32_t ibi = 0;
uint32_t imageOffset = 0;
File image;
// ---------------------------------------------------------------
// Configuracao de Wi-Fi via BLE (NVS)
// 0 = roteador, 1 = hotspot | Modo: 0 = router, 1 = hotspot, 2 = auto
// ---------------------------------------------------------------
Preferences prefs;
String wSsid[2], wPass[2];
int wSlot = 0, wPref = 2;
uint32_t wTryAt = 0;
bool wFirst = true;
const char* slotName(int i) { return i ? "hotspot" : "router"; }
class ServerEvents : public BLEServerCallbacks {
void onConnect(BLEServer *) override {
connected = true;
dirty = true;
Serial.println("[BLE] CONECTADO (1 param)");
}
void onConnect(BLEServer *, esp_ble_gatts_cb_param_t *p) override {
connected = true;
dirty = true;
Serial.printf("[BLE] CONECTADO de %02x:%02x:%02x:%02x:%02x:%02x\n",
p->connect.remote_bda[0], p->connect.remote_bda[1],
p->connect.remote_bda[2], p->connect.remote_bda[3],
p->connect.remote_bda[4], p->connect.remote_bda[5]);
}
void onDisconnect(BLEServer *) override {
connected = false;
dirty = true;
Serial.println("[BLE] DESCONECTADO, voltando a anunciar...");
delay(250);
BLEDevice::startAdvertising();
}
};
class Commands : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *c) override {
auto v = c->getValue();
if (v.length() == 0 || v.length() > 256) return;
Serial.printf("[BLE] escrita de %u bytes\n", (unsigned)v.length());
Command cmd{};
cmd.n = v.length();
memcpy(cmd.b, v.c_str(), cmd.n);
xQueueSend(commands, &cmd, 0);
}
};
void notifyText(BLECharacteristic *c, const String &s) {
if (!connected || c == nullptr) return;
String line = s + "\n";
for (size_t i = 0; i < line.length(); i += 20) {
String part = line.substring(i, i + 20);
c->setValue(part.c_str());
c->notify();
delay(6);
}
}
// ---- Funcoes de Wi-Fi ----
String jesc(const String &s) {
String o;
for (size_t i = 0; i < s.length(); i++) {
char ch = s[i];
if (ch == '"' || ch == '\\') { o += '\\'; o += ch; }
else if ((uint8_t)ch < 0x20) o += ' ';
else o += ch;
}
return o;
}
void wifiLoad() {
prefs.begin("sono", true);
wSsid[0] = prefs.getString("s0", ""); wPass[0] = prefs.getString("p0", "");
wSsid[1] = prefs.getString("s1", ""); wPass[1] = prefs.getString("p1", "");
wPref = prefs.getInt("pref", 2);
prefs.end();
if (wSsid[0].length() == 0 && strlen(WIFI_SSID) > 0) {
wSsid[0] = WIFI_SSID;
wPass[0] = WIFI_PASSWORD;
}
}
void wifiSave() {
prefs.begin("sono", false);
prefs.putString("s0", wSsid[0]); prefs.putString("p0", wPass[0]);
prefs.putString("s1", wSsid[1]); prefs.putString("p1", wPass[1]);
prefs.putInt("pref", wPref);
prefs.end();
}
void wifiConnect(int slot) {
wSlot = slot;
wTryAt = millis();
if (wSsid[slot].length() == 0) return;
WiFi.mode(WIFI_STA);
WiFi.disconnect(false);
WiFi.begin(wSsid[slot].c_str(), wPass[slot].c_str());
}
void wifiNotifyStatus() {
bool ok = WiFi.status() == WL_CONNECTED;
String j = String("{\"kind\":\"wifi\",\"state\":\"") + (ok ? "connected" : "disconnected") +
"\",\"slot\":\"" + slotName(wSlot) +
"\",\"mode\":\"" + (wPref == 2 ? "auto" : slotName(wPref)) +
"\",\"ssid\":\"" + jesc(wSsid[wSlot]) +
"\",\"ip\":\"" + (ok ? WiFi.localIP().toString() : String("")) + "\"}";
notifyText(telemetry, j);
}
void wifiTick() {
static bool last = false;
bool ok = WiFi.status() == WL_CONNECTED;
if (ok != last) {
last = ok;
wifiNotifyStatus();
if (ok) configTime(-3 * 3600, 0, "pool.ntp.org", "a.ntp.br");
}
// So tenta Wi-Fi se houver rede salva, 15s apos ligar e com BLE livre
bool hasSaved = wSsid[0].length() > 0 || wSsid[1].length() > 0;
if (hasSaved && !ok && !connected && millis() > 15000 && millis() - wTryAt > 30000) {
int next = wSlot;
if (wFirst) { wFirst = false; }
else if (wPref == 2) { int o = wSlot ^ 1; if (wSsid[o].length()) next = o; }
else next = wPref;
wifiConnect(next);
}
}
void wifiScan() {
if (WiFi.getMode() == WIFI_OFF) WiFi.mode(WIFI_STA);
int n = WiFi.scanNetworks();
if (n < 0) n = 0;
if (n > 10) n = 10;
for (int i = 0; i < n; i++) {
String j = String("{\"kind\":\"wifi_scan\",\"ssid\":\"") + jesc(WiFi.SSID(i)) +
"\",\"rssi\":" + String(WiFi.RSSI(i)) +
",\"open\":" + (WiFi.encryptionType(i) == WIFI_AUTH_OPEN ? "true" : "false") + "}";
notifyText(telemetry, j);
}
notifyText(telemetry, String("{\"kind\":\"wifi_scan_end\",\"n\":") + String(n) + "}");
WiFi.scanDelete();
}
bool handleNet(const String &s) {
if (s.startsWith("NET_SAVE:")) {
String r = s.substring(9);
int i1 = r.indexOf('\t');
int i2 = i1 < 0 ? -1 : r.indexOf('\t', i1 + 1);
if (i1 <= 0 || i2 < 0) return true;
String which = r.substring(0, i1), ssid = r.substring(i1 + 1, i2), pass = r.substring(i2 + 1);
if (ssid.length() == 0 || ssid.length() > 32 || pass.length() > 63) return true;
int slot = which == "hotspot" ? 1 : 0;
wSsid[slot] = ssid; wPass[slot] = pass;
if (wPref != 2) wPref = slot;
wifiSave();
wifiConnect(slot);
wifiNotifyStatus();
return true;
}
if (s.startsWith("NET_USE:")) {
String m = s.substring(8); m.trim();
wPref = m == "hotspot" ? 1 : m == "router" ? 0 : 2;
wifiSave();
int start = wPref == 2 ? (wSsid[0].length() ? 0 : 1) : wPref;
wifiConnect(start);
wifiNotifyStatus();
return true;
}
if (s.startsWith("NET_FORGET:")) {
String m = s.substring(11); m.trim();
int slot = m == "hotspot" ? 1 : 0;
wSsid[slot] = ""; wPass[slot] = "";
wifiSave();
if (wSlot == slot) WiFi.disconnect(false);
wifiNotifyStatus();
return true;
}
if (s == "NET_SCAN") { wifiScan(); return true; }
if (s == "NET_STATUS") { wifiNotifyStatus(); return true; }
return false;
}
void networkTask(void *) {
Record r{};
bool pending = false;
uint32_t retry = 0;
for (;;) {
if (!pending) pending = xQueueReceive(records, &r, pdMS_TO_TICKS(20)) == pdTRUE;
if (pending && millis() - retry > 5000) {
retry = millis();
bool sent = false;
if (WiFi.status() == WL_CONNECTED && strlen(HTTPS_ENDPOINT) > 8 && strlen(SERVER_ROOT_CA) > 0) {
WiFiClientSecure client;
client.setCACert(SERVER_ROOT_CA);
HTTPClient http;
http.setConnectTimeout(2000);
http.setTimeout(2000);
if (http.begin(client, HTTPS_ENDPOINT)) {
http.addHeader("Content-Type", "application/json");
if (strlen(API_TOKEN)) http.addHeader("Authorization", String("Bearer ") + API_TOKEN);
int status = http.POST((uint8_t *)r.text, strlen(r.text));
sent = status >= 200 && status < 300;
http.end();
}
}
internetOK = sent;
if (sent) pending = false;
else if (connected) { notifyText(telemetry, r.text); pending = false; }
}
vTaskDelay(pdMS_TO_TICKS(20));
}
}
void addRecord(const char *kind) {
Record r{};
snprintf(r.text, sizeof(r.text),
"{\"kind\":\"%s\",\"ms\":%lu,\"epoch\":%lld,\"bpm\":%.1f,\"ibi_ms\":%lu,\"motion\":%.2f,\"gyro\":%.2f,\"contact\":%s}",
kind, (unsigned long)millis(), (long long)time(nullptr), bpm, (unsigned long)ibi,
movement, rotation, (lastContact && millis() - lastContact < 2000) ? "true" : "false");
if (xQueueSend(records, &r, 0) != pdTRUE) Serial.println("Fila cheia: registro descartado");
}
void handleCommands() {
Command c{};
if (xQueueReceive(commands, &c, 0) != pdTRUE) return;
// Binary wallpaper: W + uint32 little-endian byte offset + RGB565 bytes
if (c.n >= 5 && c.b[0] == 'W' && fsOK) {
uint32_t off = (uint32_t)c.b[1] | ((uint32_t)c.b[2] << 8) |
((uint32_t)c.b[3] << 16) | ((uint32_t)c.b[4] << 24);
if (off == 0) {
if (image) image.close();
image = SPIFFS.open("/wp.bin", FILE_WRITE);
imageOffset = 0;
}
if (image && off == imageOffset) {
size_t payload = c.n - 5;
image.write(&c.b[5], payload);
imageOffset += payload;
if (imageOffset >= 240UL * 240UL * 2UL) {
image.close();
wallpaper = true;
dirty = true;
}
}
return;
}
String s;
s.reserve(c.n);
for (uint16_t i = 0; i < c.n; i++) s += (char)c.b[i];
s.trim();
if (s.length() == 0) return;
if (handleNet(s)) return;
if (s == "START") {
recording = true;
dirty = true;
addRecord("start");
notifyText(telemetry, "{\"kind\":\"start\"}");
} else if (s == "STOP") {
recording = false;
dirty = true;
addRecord("stop");
notifyText(telemetry, "{\"kind\":\"stop\"}");
} else if (s == "CLEAR") {
if (fsOK && SPIFFS.exists("/wp.bin")) SPIFFS.remove("/wp.bin");
wallpaper = false;
dirty = true;
} else if (s.startsWith("TITLE:")) {
title = s.substring(6);
dirty = true;
} else if (s.startsWith("MEDIA:")) {
notifyText(media, s.substring(6));
}
}
void readSensors() {
#if !BARE_BOARD
if (imuOK) {
sensors_event_t a, g, temp;
imu.getEvent(&a, &g, &temp);
movement = sqrtf(a.acceleration.x * a.acceleration.x +
a.acceleration.y * a.acceleration.y +
a.acceleration.z * a.acceleration.z);
rotation = sqrtf(g.gyro.x * g.gyro.x + g.gyro.y * g.gyro.y + g.gyro.z * g.gyro.z);
}
if (pulseOK) {
long ir = ppg.getIR();
if (ir > 50000) {
lastContact = millis();
if (checkForBeat(ir)) {
uint32_t now = millis();
if (lastBeat > 0) {
uint32_t delta = now - lastBeat;
if (delta > 300 && delta < 2000) {
ibi = delta;
bpm = 60000.0f / (float)delta;
}
}
lastBeat = now;
}
} else {
bpm = 0;
}
}
#else
if (recording) {
bpm = 72.0f;
lastContact = millis();
}
#endif
}
void drawScreen() {
#if !BARE_BOARD
if (!dirty) return;
dirty = false;
lcd.fillScreen(0x0000);
lcd.setTextColor(0xFFFF);
lcd.setTextSize(2);
lcd.setCursor(36, 70);
lcd.println(connected ? "Conectado" : "Desconectado");
lcd.setCursor(36, 105);
lcd.printf("BPM: %.0f", bpm);
lcd.setCursor(36, 140);
lcd.println(recording ? "Gravando..." : "Parado");
#endif
}
void setup() {
Serial.begin(115200);
delay(300);
Serial.printf("\n[SONOWATCH] Boot | Heap livre: %u\n", (unsigned)ESP.getFreeHeap());
commands = xQueueCreate(16, sizeof(Command));
records = xQueueCreate(24, sizeof(Record));
fsOK = SPIFFS.begin(true);
if (fsOK && SPIFFS.exists("/wp.bin")) wallpaper = true;
wifiLoad();
WiFi.mode(WIFI_OFF); // Comeca desligado para nao atrapalhar o Bluetooth
#if !BARE_BOARD
Wire.begin();
lcd.begin();
lcd.setRotation(0);
imuOK = imu.begin();
vibOK = vib.begin();
if (vibOK) { vib.selectLibrary(1); vib.setMode(DRV2605_MODE_INTTRIG); }
pulseOK = ppg.begin(Wire, I2C_SPEED_FAST);
if (pulseOK) { ppg.setup(); ppg.setPulseAmplitudeRed(0x0A); }
#endif
// Libera RAM do Bluetooth Classico antes de iniciar o BLE
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
BLEDevice::init("SonoWatch");
BLEDevice::setPower(ESP_PWR_LVL_P9);
// Ativa pareamento nativo do Android (Bonding BLE)
BLESecurity *pSecurity = new BLESecurity();
pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND);
pSecurity->setCapability(ESP_IO_CAP_NONE);
pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
BLEServer *server = BLEDevice::createServer();
server->setCallbacks(new ServerEvents());
BLEService *service = server->createService(SERVICE_UUID);
telemetry = service->createCharacteristic(TELEMETRY_UUID, BLECharacteristic::PROPERTY_NOTIFY);
telemetry->addDescriptor(new BLE2902());
auto control = service->createCharacteristic(
CONTROL_UUID,
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR
);
control->setCallbacks(new Commands());
media = service->createCharacteristic(MEDIA_UUID, BLECharacteristic::PROPERTY_NOTIFY);
media->addDescriptor(new BLE2902());
service->start();
BLEAdvertising *adv = BLEDevice::getAdvertising();
adv->addServiceUUID(SERVICE_UUID);
adv->setScanResponse(true);
adv->setMinPreferred(0x06);
BLEDevice::startAdvertising();
xTaskCreatePinnedToCore(networkTask, "net", 6144, nullptr, 1, nullptr, 0);
Serial.printf("[BLE] Pronto e anunciando | Heap livre: %u\n", (unsigned)ESP.getFreeHeap());
}
void loop() {
static uint32_t lastHb = 0, lastTel = 0;
uint32_t now = millis();
handleCommands();
wifiTick();
if (now - sampleClock >= 50) {
sampleClock = now;
readSensors();
}
if (now - lastTel >= 1000) {
lastTel = now;
if (recording) {
addRecord("telemetry");
} else if (connected) {
char buf[96];
snprintf(buf, sizeof(buf), "{\"kind\":\"telemetry\",\"bpm\":%.0f,\"recording\":false}", bpm);
notifyText(telemetry, buf);
}
drawScreen();
}
if (now - lastHb >= 5000) {
lastHb = now;
Serial.printf("[HB] t=%lus ble=%d wifi=%d heap=%u\n",
(unsigned long)(now / 1000), (int)connected,
(int)WiFi.status(), (unsigned)ESP.getFreeHeap());
}
delay(5);
}Download project files
Remix this project
Make it yours in one click
Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.




