Siddhant Kumar
Project 023 · Health & Wearables

Baby Breathing Monitor.

A crib monitor that watches an infant's breathing movement without any contact, alarms locally within seconds if it stops, and — above all — is honest that no monitor prevents SIDS.

Intermediate 12–18 hours 36 min read SensorsSafetyAlerts
Jump to source Bill of materials
Baby Breathing Monitor — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
₹2,400 – ₹3,200
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Health & Wearables
Last updated
28 July 2026
Contents — 26 sections

Project Overview

A crib monitor that watches an infant's breathing movement without any contact, alarms locally within seconds if it stops, and — above all — is honest that no monitor prevents SIDS.

This is the most emotionally charged project in the catalogue, and it demands the most caution in how it is presented. Baby breathing monitors are bought by frightened parents, and the industry around them has a genuine problem: there is no evidence that consumer breathing monitors reduce sudden infant death syndrome (SIDS), and there is real concern that they provide false reassurance that leads parents to relax the safe-sleep practices that actually do reduce risk. This documentation leads with that, because a build guide that does not would be irresponsible.

With that understood, what the device actually does is detect the movement associated with breathing and alarm if that movement stops for longer than a set period. It uses contactless radar sensing — a 24 GHz or 60 GHz module that detects the sub-millimetre chest movement of breathing through the air, with no sensor on the baby. Contactless is the right choice here specifically because a sensor pad under a mattress can be defeated by the baby rolling off it, and anything attached to the baby is a hazard in itself.

The signal processing extracts a respiration rate from the radar's phase output and detects the two failure modes that matter: a cessation of movement (apnoea), and a movement pattern that is present but abnormal. A local alarm — loud, immediate, and independent of any network — is the core function. Everything else, including phone notifications, is secondary and must never be the primary alert.

The design deliberately keeps the alarm local and fast, distinguishes a baby who has simply moved out of the sensor field from one who has genuinely stopped breathing, and states its limitations in the device itself. It is presented as an awareness and reassurance aid layered on top of safe-sleep practices, never as a medical device or a substitute for them.

What this project does

  • Detects infant breathing movement contactlessly using a 24/60 GHz radar module.
  • Extracts respiration rate from the radar phase signal.
  • Alarms locally within a configurable period (default 15 s) if breathing movement stops.
  • Distinguishes "no breathing detected" from "baby out of sensor field" to reduce false alarms.
  • Provides a loud local alarm independent of any network or phone.
  • Optionally notifies a phone as a secondary alert, never the primary one.
  • Logs respiration rate overnight for review with a paediatrician if wanted.

Real-World Applications

SettingHow it is used
Parental reassuranceThe honest primary use — reducing anxiety, layered on top of (never replacing) safe-sleep practice.
Monitoring after a clinical concernFor infants a paediatrician is monitoring, as an adjunct to and under medical guidance, not instead of it.
Respiration-rate awarenessA rising respiration rate can accompany illness; a trend is informative context for a parent.
Learning radar signal processingContactless vital-sign sensing is a genuinely advanced and current technique.
Elder or patient monitoringThe same contactless respiration sensing applies to any bed-bound person, with fewer of the emotional stakes.
Research prototypingA platform for contactless vital-sign algorithms against a reference.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Contactless radar sensing — nothing on or under the baby, no pad to be displaced.
  • Respiration-rate extraction from the radar phase, typically 30–60 breaths/min in infants.
  • Presence discrimination — an empty field is reported as "no baby", not as apnoea.
  • Fast local alarm that works with the network, the phone and the internet all down.
  • Configurable apnoea window with a default that reflects clinical apnoea definitions.
  • Secondary phone alert clearly subordinate to the local alarm.
  • Overnight respiration log for optional clinical review.
  • Prominent honesty: the device states it does not prevent SIDS, in its own documentation and setup.

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build cost₹2,400 – ₹3,200
Primary disciplineHealth & Wearables
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Arduino C++ with signal processing
  • Radar module configuration over UART
  • Phase-signal extraction and band-pass filtering
  • Peak detection and rate estimation
  • A clear-eyed understanding of what the device can and cannot claim

Bill of Materials

Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.

ComponentKey specificationQtyApprox. cost
ESP32 DevKit V1 (ESP-WROOM-32)
Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC1₹450
Active piezo buzzer 5 V
Active buzzers make tone on DC; passive ones need a PWM carrier.
85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter1₹25
0.96″ SSD1306 OLED display
Static images burn in — invert or scroll the screen periodically.
128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C1₹250
5 V 3 A regulated SMPS adapter
Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A.
100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection1₹350
Double-sided perfboard 7 × 9 cm + headers
Solder female headers so the MCU can be swapped without desoldering.
FR-4, 0.1″ pitch, plated through-holes, 24 × 18 grid1₹60
IP65 ABS junction enclosure 158 × 90 × 60 mm
Fit cable glands, not drilled holes, or the IP rating means nothing.
IP65, ABS, −20 to +80 °C, transparent lid, wall-mount lugs1₹260
MR60BHA1 or LD2410 mmWave radar module
A respiration-capable 60 GHz module (e.g. Seeed MR60BHA1) reports breathing rate directly. A 24 GHz LD2410 detects presence and gross movement only.
60 GHz (respiration-capable) or 24 GHz presence, UART1₹900
100 dB piezo alarm5 V, loud enough to wake a sleeping adult in another room1₹320
Crib-mount arm / bracket
The radar must be aimed at the baby's torso from above.
Adjustable, positions the radar 30–60 cm above the mattress1₹280
RGB status LEDCommon cathode1₹20

Estimated total: ₹2,915, excluding tools, shipping and consumables.

Tools and consumables

  • Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
  • Digital multimeter — continuity, DC volts and current ranges
  • Wire strippers, flush cutters and a small set of precision screwdrivers
  • Heat-shrink tubing and a heat gun (or a lighter, carefully)
  • A laptop with a USB port and the toolchain listed above

Hardware Specifications

PartSpecificationSupplyInterfaceReference
ESP32 DevKit V1 (ESP-WROOM-32)Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
Active piezo buzzer 5 V85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter3–5 VDigital / PWMDatasheet
0.96″ SSD1306 OLED display128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C3.3–5 VI²C (0x3C)Datasheet
5 V 3 A regulated SMPS adapter100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection5 VDC barrel / USBDatasheet
Double-sided perfboard 7 × 9 cm + headersFR-4, 0.1″ pitch, plated through-holes, 24 × 18 gridDatasheet
IP65 ABS junction enclosure 158 × 90 × 60 mmIP65, ABS, −20 to +80 °C, transparent lid, wall-mount lugsDatasheet

Consolidated electrical and interface specifications for every active part in the build.

Power Budget & Supply Sizing

Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
Active piezo buzzer 5 V3–5 V30Active buzzers make tone on DC; passive ones need a PWM carrier.
0.96″ SSD1306 OLED display3.3–5 V20Static images burn in — invert or scroll the screen periodically.
5 V 3 A regulated SMPS adapter5 V3000Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A.

Summed typical draw is 3210 mA. With a 1.5× design margin the supply should deliver at least 4900 mA continuously at the stated rail voltage.

Software Requirements & Development Environment

Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.

  • Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
  • Add https://espressif.github.io/arduino-esp32/package_esp32_index.json under File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager.
  • Set the correct port under Tools → Port. On Linux add yourself to the dialout group: sudo usermod -aG dialout $USER and log out and back in.
  • Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
  • Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.

Required libraries

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager → "Adafruit SSD1306"
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core

Block Diagram

The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.

Baby Breathing Monitor — system block diagramFunctional block diagram of the Baby Breathing Monitor system. SensemmWave radarchest movementPresencebaby in field?ExtractRespiration rateband-passMovement present?apnoea detectDecideNo movement > 15 s?and baby presentPresence gatereject empty cribAlertLocal 100 dB alarmno network neededPhone (secondary)never primaryphase / raterate + presenceapnoea
Baby Breathing Monitor — system block diagram

Circuit Diagram & Wiring

Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.

Baby Breathing Monitor — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBmmWave radar moduleGPIO 16 / 17UART,module-specific baudRadar presence GPIO (iffitted)GPIO 32Digital presenceSilence buttonGPIO 33Temporarily silencea nuisance alarm100 dB alarmGPIO 25Local alarm, alwaysworksRGB status LEDGPIO 12 / 13 / 14Green breathing,amber no-baby, redalarmSSD1306 OLEDGPIO 21 / 22Rate + status,dimmed
Baby Breathing Monitor — wiring schematic
PeripheralPeripheral pinController pinSignal
mmWave radar moduleTX / RXGPIO 16 / 17UART, module-specific baud
Radar presence GPIO (if fitted)OUTGPIO 32Digital presence
Silence buttonNOGPIO 33Temporarily silence a nuisance alarm
100 dB alarmTransistor baseGPIO 25Local alarm, always works
RGB status LEDR / G / BGPIO 12 / 13 / 14Green breathing, amber no-baby, red alarm
SSD1306 OLEDSDA / SCLGPIO 21 / 22Rate + status, dimmed

Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.

Wiring explanation

  • Mount the radar 30–60 cm above the mattress, aimed at the baby's torso, on a rigid arm that cannot fall into the crib. The mounting must be mechanically secure and free of any cord that could reach the baby.
  • A 60 GHz respiration-capable module (like the Seeed MR60BHA1) reports breathing rate over UART directly and is strongly preferred. A 24 GHz LD2410 detects presence and gross movement but not fine breathing — with a 24 GHz module you can detect gross apnoea (no movement at all) but not a true respiration rate.
  • Keep the radar's field clear of fans, curtains and other periodic movement, which the radar will happily interpret as breathing. Aim it so the baby's torso fills the beam and little else moves.
  • The alarm must be loud and driven directly by the ESP32 through a transistor — it is the primary safety output and must never depend on Wi-Fi. Site it where a sleeping parent will hear it.
  • Power from a reliable mains adapter with the electronics well away from the crib. Consider a small battery backup so a power cut does not silently disable the monitor.
  • Dim the OLED and LEDs heavily — this is a nursery at night, and a glowing device disrupts the infant's sleep you are trying to protect.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
An ESP32 development board running the detection and, crucially, the network-independent local alarm. Photograph sourced from Wikimedia Commons — ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

System Architecture

Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.

Baby Breathing Monitor — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · sensors and actuatorsDriver layerwifi · pubsub · arduinojson · ssd1306Application logicsampling loop · filtering · thresholds · state machineTransport layerWi-Fi + MQTT (secondary only) · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Baby Breathing Monitor — architecture stack

Working Principle

A millimetre-wave radar transmits a continuous signal and measures the reflection. When it reflects off a surface that moves — such as a chest wall rising and falling with breathing — the reflected signal's phase shifts in proportion to the movement. Breathing moves the chest by a few millimetres, and at 60 GHz the wavelength is 5 mm, so even sub-millimetre movement produces a measurable, periodic phase change. Extracting that periodicity gives the respiration rate, with no contact at all.

This is genuinely powerful: the same technique measures heartbeat (a much smaller movement at a higher frequency) and is used in contactless vital-sign research and in some commercial products. For an infant monitor, contactless is not just convenient but safer — there is no pad the baby can roll off, no cord, no sensor against delicate skin.

The key distinction the device must make is between no breathing detected and no baby present. If a parent picks the baby up, the radar sees an empty crib — no movement — which is exactly what apnoea looks like on a movement sensor. Alarming then would be a false alarm, and false alarms are the specific failure that makes parents distrust and eventually ignore a monitor. So the device uses a presence signal (the radar's own presence detection, or a distinction between an empty field and a still-but-present body) to gate the alarm: it only alarms on absence of breathing when a baby is present.

The alarm timing reflects clinical definitions loosely. A pathological apnoea in an infant is generally defined as a pause of 20 seconds or more, or a shorter pause with other signs. A default alarm window of around 15 seconds gives a margin before that threshold. Shorter windows produce false alarms from the normal brief irregularity of infant breathing (periodic breathing is common and normal in newborns); longer windows delay a genuine alert. This is a real trade-off and the parent should set it in consultation with their paediatrician.

Everything about the alert prioritises local, immediate, network-independent operation. The 100 dB alarm is driven directly by the microcontroller. A phone notification is added as a secondary channel, but it is explicitly subordinate — Wi-Fi can drop, a phone can be silenced, and the one alert that must always work is the loud noise in the house. A monitor whose primary alert depends on the internet is a monitor that fails exactly when it matters.

Finally, and most importantly, the device is honest in its own interface. It shows a safe-sleep reminder at startup, it never claims to prevent SIDS, and its documentation states plainly that the evidence does not support consumer breathing monitors reducing infant death. This is not legal boilerplate; it is the single most important design requirement, because a device that fosters false reassurance can do net harm.

The maths behind it

Radar phase and chest movement

plainRadar phase and chest movement
Transmitted: 60 GHz → wavelength λ = c/f = 5.0 mm

Phase shift from a target moving Δd:
  Δφ = 4π·Δd / λ

Chest movement of 3 mm (typical infant breathing):
  Δφ = 4π × 3 / 5 = 7.54 rad = 432°

That is comfortably measurable — even 0.1 mm gives 14°.
The respiration signal is the periodic component of φ(t)
in the 0.3–1.5 Hz band (18–90 breaths/min).

Respiration rate extraction

plainRespiration rate extraction
Phase signal φ(t) sampled at fs (module-dependent).
Band-pass 0.3–1.5 Hz to isolate breathing.

Rate by peak counting over a 30 s window:
  rate_bpm = 60 · (peaks in window) / window_seconds

Infant reference ranges (breaths/min, at rest):
  newborn      : 30–60
  1–12 months  : 25–50

Alarm on: no peak detected for > apnoea_window
          AND presence = true.

Alarm-window trade-off

plainAlarm-window trade-off
Pathological apnoea (clinical): pause ≥ 20 s
Periodic breathing (normal newborn): pauses up to ~10 s

Alarm window choices:
  10 s : frequent false alarms from normal periodic breathing
  15 s : reasonable default — margin before 20 s
  20 s : matches the clinical threshold, later warning

Set in consultation with a paediatrician. There is no
choice that is both maximally sensitive and free of
false alarms — that is inherent, not a bug.

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Baby Breathing Monitor — firmware flowchartControl flow through the main program loop. Boot: init radar, showsafe-sleep reminderRead radar: presence andbreathing rateBaby present in the field?monitorshow "no baby", no alarmBreathing movementdetected?reset timer, greenstart apnoea timerNo movement for longerthan 15 s?ALARMkeep watchingSound local alarm, flash redSend secondary phone alertLog rate, continue
Baby Breathing Monitor — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

Step-by-Step Implementation Guide

Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.

Complete Source Code

The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.

cppbaby-breathing-monitor.ino
/* ═══════════════════════════════════════════════════════════════
   Baby Breathing Monitor — ESP32 + mmWave radar (contactless)

   Detects breathing movement with a 60 GHz radar, alarms locally if
   movement stops while a baby is present, and distinguishes an empty
   crib from apnoea.

   IMPORTANT: This device does NOT prevent SIDS. No consumer breathing
   monitor has been shown to. It is a reassurance aid layered on top
   of safe-sleep practices, which it does not replace.
   ══════════════════════════════════════════════════════════════════ */

#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Preferences.h>

#define WIFI_SSID "YOUR_WIFI"
#define WIFI_PASS "YOUR_PASSWORD"
#define MQTT_HOST "192.168.1.50"
#define DEVICE_ID "crib-monitor"

#define PIN_ALARM   25
#define PIN_SILENCE 33
#define PIN_LED_R   12
#define PIN_LED_G   13
#define PIN_LED_B   14

#define APNEA_WINDOW_MS   15000    // set WITH a paediatrician
#define RATE_LOW_BPM        15     // implausibly low — likely artefact
#define RATE_HIGH_BPM       80     // implausibly high for sleep

HardwareSerial radar(2);           // GPIO 16/17
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WiFiClient   net;
PubSubClient mqtt(net);
Preferences  prefs;

float    breathingRate = 0;
bool     babyPresent = false, breathingDetected = false, alarming = false;
uint32_t lastBreathMs = 0, silencedUntil = 0, lastLog = 0;

/* ── radar parsing (Seeed MR60BHA1-style frame) ─────────────────
   The exact frame format is module-specific; adapt to your module's
   protocol. This parser expects a breathing-rate report frame. */
bool parseRadar() {
  static uint8_t buf[32]; static int idx = 0;
  bool updated = false;

  while (radar.available()) {
    uint8_t b = radar.read();
    // Frame header 0x53 0x59 (example); presence and rate follow.
    if (idx == 0 && b != 0x53) continue;
    if (idx == 1 && b != 0x59) { idx = 0; continue; }
    buf[idx++] = b;

    if (idx >= 12) {                       // complete frame
      babyPresent   = buf[4] != 0;         // presence byte
      float rate    = buf[6];              // breathing rate byte
      bool  moving  = buf[5] != 0;         // movement present

      if (rate >= RATE_LOW_BPM && rate <= RATE_HIGH_BPM) breathingRate = rate;
      if (moving && babyPresent) {
        breathingDetected = true;
        lastBreathMs = millis();
      }
      idx = 0;
      updated = true;
    }
  }
  return updated;
}

/* ── feedback ───────────────────────────────────────────────── */
void setLed(uint8_t r, uint8_t g, uint8_t b) {
  digitalWrite(PIN_LED_R, r); digitalWrite(PIN_LED_G, g); digitalWrite(PIN_LED_B, b);
}

void alarmOn() {
  alarming = true;
  digitalWrite(PIN_ALARM, HIGH);
  setLed(1, 0, 0);
  mqtt.publish("care/" DEVICE_ID "/alarm", "apnea", true);   // secondary alert
}

void alarmOff() {
  alarming = false;
  digitalWrite(PIN_ALARM, LOW);
  mqtt.publish("care/" DEVICE_ID "/alarm", "clear", true);
}

/* ── display ────────────────────────────────────────────────── */
void draw() {
  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.dim(true);                          // nursery — keep it dark

  if (!babyPresent) {
    oled.setTextSize(1); oled.setCursor(0, 24);
    oled.println("No baby detected"); oled.println("(monitor idle)");
    oled.display();
    return;
  }

  oled.setTextSize(2); oled.setCursor(0, 0);
  oled.printf("%2.0f", breathingRate);
  oled.setTextSize(1); oled.setCursor(38, 6); oled.print("breaths/min");
  oled.setCursor(0, 28);
  oled.print(alarming ? "!! NO BREATHING !!"
           : breathingDetected ? "breathing detected" : "watching...");
  oled.setCursor(0, 54); oled.print("Not a medical device");
  oled.display();
}

/* ── setup / loop ───────────────────────────────────────────── */
void setup() {
  Serial.begin(115200);
  pinMode(PIN_ALARM, OUTPUT); digitalWrite(PIN_ALARM, LOW);
  pinMode(PIN_SILENCE, INPUT_PULLUP);
  pinMode(PIN_LED_R, OUTPUT); pinMode(PIN_LED_G, OUTPUT); pinMode(PIN_LED_B, OUTPUT);

  radar.begin(115200, SERIAL_8N1, 16, 17);
  Wire.begin(21, 22);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  // Safe-sleep reminder at every startup — the most important screen.
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE); oled.setTextSize(1);
  oled.setCursor(0, 0);
  oled.println("SAFE SLEEP:");
  oled.println("back, firm flat");
  oled.println("surface, no loose");
  oled.println("bedding. This does");
  oled.println("NOT prevent SIDS.");
  oled.display();
  delay(5000);

  WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS);
  for (int i = 0; i < 40 && WiFi.status() != WL_CONNECTED; i++) delay(250);
  mqtt.setServer(MQTT_HOST, 1883);

  lastBreathMs = millis();
  Serial.println("Monitor running — LOCAL ALARM is the primary alert");
}

void loop() {
  if (!mqtt.connected() && WiFi.status() == WL_CONNECTED) mqtt.connect(DEVICE_ID);
  mqtt.loop();

  parseRadar();

  /* Silence button: temporarily mute a nuisance alarm. */
  if (digitalRead(PIN_SILENCE) == LOW) {
    silencedUntil = millis() + 30000;      // 30 s only — never permanent
    if (alarming) alarmOff();
  }

  uint32_t now = millis();

  if (!babyPresent) {
    // Empty crib is NOT apnoea. Reset the timer and stand down.
    setLed(1, 1, 0);                       // amber: idle
    lastBreathMs = now;
    if (alarming) alarmOff();
  } else {
    breathingDetected = (now - lastBreathMs) < APNEA_WINDOW_MS;

    if (breathingDetected) {
      setLed(0, 1, 0);                     // green: breathing
      if (alarming) alarmOff();
    } else if (now > silencedUntil) {
      if (!alarming) {
        Serial.println("APNEA: no breathing movement detected");
        alarmOn();
      }
    }
  }

  static uint32_t lastDraw = 0;
  if (now - lastDraw > 500) { lastDraw = now; draw(); }

  if (now - lastLog > 10000 && babyPresent) {
    lastLog = now;
    JsonDocument d;
    d["rate"] = breathingRate;
    d["breathing"] = breathingDetected;
    d["present"] = babyPresent;
    char b[96]; size_t n = serializeJson(d, b, sizeof(b));
    mqtt.publish("care/" DEVICE_ID "/state", (uint8_t *)b, n, true);
  }
}
if (!babyPresent) → reset timer, no alarmThis is the single most important logic in the device. An empty crib produces no movement, which is indistinguishable from apnoea on a movement sensor. Gating the alarm on presence is what prevents the false alarm that fires every time a parent picks the baby up — and false alarms are what make parents disable a monitor.
Safe-sleep reminder at every startupA deliberate five-second screen at every boot, stating the evidence-based measures and that the device does not prevent SIDS. This is not decoration; it is the most important thing the device displays, because false reassurance is the real risk of this class of product.
Local alarm driven directly by GPIOThe 100 dB alarm is the primary alert and is driven by a hardware pin, entirely independent of Wi-Fi, MQTT and the internet. The phone notification is explicitly labelled secondary. A monitor whose main alert can be lost to a dropped connection fails exactly when it matters.
silencedUntil = now + 30000 (never permanent)The silence button mutes for only 30 seconds and can never disable the alarm permanently. A monitor that can be muted for the night is a monitor that will be, and then it is useless.
RATE_LOW / RATE_HIGH plausibility gatesRates outside the physiological range are treated as artefact — a fan, a curtain, or radar noise — rather than as a real reading, which reduces spurious rates from periodic movement in the field.
"Not a medical device" always on screenThe disclaimer is persistent, not a one-time popup. It sits on the monitoring screen the parent glances at, keeping the honest framing present rather than buried in documentation.

Configuration & Calibration

Configuration steps

  • Choose a respiration-capable 60 GHz module if you want a true breathing rate. A 24 GHz LD2410 can only detect gross movement and presence — usable for a crude apnoea detector but not for rate.
  • Set APNEA_WINDOW_MS in consultation with your paediatrician. 15 seconds is a starting default; the trade-off between false alarms and warning time is genuine and personal.
  • Aim the radar at the baby's torso from 30–60 cm above, and keep fans, curtains and other periodic movement out of its field.
  • Site the alarm where a sleeping parent will reliably hear it, and test that they do.
  • Adapt the radar frame parser to your specific module's protocol — the byte layout shown is illustrative and modules differ.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. Verify breathing detection

    Place a soft toy that you move gently by hand to simulate breathing, or (with appropriate care and supervision) observe with a real infant under a parent's watch. Confirm the device reports a plausible rate and shows green.

  2. Test the presence gate

    Remove the target from the field. The device must show "no baby / idle" and must NOT alarm. If it alarms on an empty crib, the presence detection is not working and the device is not safe to rely on.

  3. Test the apnoea alarm

    With a target present, stop the movement. The alarm must sound within the configured window. Time it and confirm it matches your setting.

  4. Confirm false-trigger immunity

    Introduce a fan or a moving curtain into the field. If the device reports this as breathing, re-aim the radar so only the baby's torso is in the beam.

Network Architecture & Connectivity

Baby Breathing Monitor — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsCrib monitorESP32 + radarWi-Fi 2.4 GHzRouteralarm works without itMQTT 1883Local brokernever the primary alertParent phonesecondary alertRate logoptional review
Baby Breathing Monitor — network topology

Communication protocol

The MQTT layer is deliberately secondary. The device functions completely — detection, presence gating, and the loud local alarm — with no network at all. MQTT adds a phone notification and an optional overnight rate log, and nothing that matters for safety depends on it.

The alarm state is published retained so a phone connecting after the event still sees it, but the phone notification must never be presented to the parent as the primary alert.

Topic / endpointDirectionPayload
care/crib-monitor/alarmdevice → broker (retained)"apnea" / "clear" — secondary alert only
care/crib-monitor/statedevice → broker (retained)JSON: rate, breathing, present

Message contract between the device and the broker.

Security considerations

  • This is intimate data about an infant. Keep it strictly on a local broker with authentication; never route it through a third-party cloud service.
  • A radar in a nursery raises the same privacy considerations as a camera would — treat the data accordingly.
  • The phone alert must be subordinate to the local alarm in the parent's mind and in the setup instructions. Never configure it as the only alert.

Testing Procedure & Expected Output

Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.

TestWhat you should see
Power onA five-second safe-sleep reminder stating the device does not prevent SIDS, then the monitoring screen.
Empty fieldAmber "no baby / idle", no alarm, timer held reset.
Simulated breathing movement in the fieldGreen, a plausible breathing rate, "breathing detected".
Stop the movement with a target presentThe local alarm sounds within the configured window and the LED goes red.
Remove the target during an alarmThe device recognises the empty field and stands down — no more alarm on an empty crib.
Introduce a fan into the fieldIf it is read as breathing, re-aim the radar; the device should ideally not be fooled by non-torso movement in a well-aimed setup.
Disconnect Wi-Fi and trigger an apnoeaThe local alarm still sounds. Only the phone notification is lost — which is why it is secondary.
Press silence during an alarmAlarm mutes for 30 seconds only, then resumes if the condition persists. It can never be muted permanently.

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

With everything wired and the firmware uploaded, the Serial Monitor at 115200 baud should look similar to the trace below. Values will differ; the shape of the output should not.

A wrist-worn fitness tracker
A monitoring device. Whatever it shows, the honest framing must remain: it is a reassurance aid, not protection against SIDS. Photograph sourced from Wikimedia Commons — Fitness tracker.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Frequent false apnoea alarms

Likely cause. Breathing movement below the radar's sensitivity, or the baby out of the beam.

Fix. Re-aim the radar directly at the torso from the correct distance. Confirm the module is respiration-capable — a 24 GHz presence module cannot detect fine breathing. Consider lengthening the alarm window slightly (with paediatric advice), since normal newborn periodic breathing includes pauses.

The device alarms every time the baby is picked up

Likely cause. The presence gate is not working, so an empty crib reads as apnoea.

Fix. This must be fixed before the device is used. Verify the presence byte from the radar and confirm the code only alarms when presence is true. An empty crib must always report idle, never apnoea.

It reports breathing when the crib is empty

Likely cause. A fan, curtain, or other periodic movement in the radar field.

Fix. Aim the beam so only the baby's torso is in it. Remove or block periodic movement sources. Tighten the radar's range gating so distant movement is ignored.

No breathing rate reported (rate stays 0)

Likely cause. The UART frame parser does not match the module's protocol.

Fix. Modules differ. Read your radar's protocol document and adapt the parser to its actual frame format — the byte offsets shown are illustrative. Print the raw bytes to confirm you are receiving frames at all.

The alarm is too quiet to wake a sleeping parent

Likely cause. Under-powered alarm or poor siting.

Fix. Use a 100 dB piezo alarm sited where the parent sleeps, and test that it actually wakes them. The entire safety value of the device rests on the alarm being heard.

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

An I²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an I²C scanner sketch first — it should print the device address. Most breakout boards include 4.7 kΩ pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

Performance Optimisation

  • Keep the alarm path free of any network or display work — it must respond within a sample of detecting apnoea.
  • Filter the radar rate over a short window to reject single-frame artefacts, but not so long that it delays apnoea detection.
  • Dim the display and LEDs aggressively; the nursery must stay dark for the infant's sleep.
  • Replace every delay() with a millis() comparison — blocking delays are the single most common cause of dropped readings.
  • Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
  • Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
  • Use uint8_t / uint16_t where the range allows; on an 8-bit AVR a 32-bit add costs four times as much.
  • Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
  • Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
  • For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.
  • Profile before optimising — print micros() deltas around each stage and fix the slowest one first.

Safety Precautions

  • This device does not prevent SIDS. No consumer breathing monitor has been shown to. It must never be presented — to yourself or anyone else — as protection against sudden infant death.
  • The evidence-based measures reduce SIDS risk: back sleeping, a firm flat separate sleep surface, no loose bedding or soft objects, avoiding overheating, no smoke exposure, and breastfeeding. This device replaces none of them and must sit strictly on top of them.
  • Do not let the monitor create false reassurance that leads to relaxed safe-sleep practice. That is the specific way this class of device can cause net harm.
  • The local alarm is the only alert that must be relied upon. Never depend on a phone notification, which can be silenced, delayed or lost to a dropped connection.
  • Keep all cords and the mounting arm well out of the crib — a strangulation hazard is a real risk that a breathing monitor must not introduce.
  • This is not a medical device. For any genuine concern about an infant's breathing, seek medical care immediately.
  • Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
  • Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
  • Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.

Maintenance

  • Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
  • Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
  • Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
  • Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.

Future Improvements & Upgrades

A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.

  • Add contactless heart rate from the same radar — a 60 GHz module can resolve the smaller, faster cardiac movement, giving a second vital sign.
  • Add a reference validation against a clinically-used monitor to characterise the device's real sensitivity and false-alarm rate honestly.
  • Add battery backup so a power cut does not silently disable the monitor overnight.
  • Add room temperature monitoring, since overheating is an actual SIDS risk factor and a nursery too warm is worth flagging.
  • Add a trend log for a paediatrician, presenting respiration rate over nights in a form a clinician can actually use.
  • Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
  • Add over-the-air firmware updates so you never have to physically reach a deployed node again.
  • Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
  • Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
  • Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
  • Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.

Frequently Asked Questions

Will this protect my baby from SIDS?

No. This is the most important answer in this entire document. There is no evidence that consumer breathing monitors reduce sudden infant death syndrome, and paediatric bodies including the American Academy of Pediatrics do not recommend them for this purpose. Worse, there is real concern they cause false reassurance that leads parents to relax the practices that genuinely do reduce risk. Build this for awareness and reassurance if you wish, but never believe it protects against SIDS.

What actually reduces SIDS risk?

Evidence-based measures: placing the baby on their back to sleep, on a firm flat separate sleep surface, with no loose bedding, pillows or soft toys; avoiding overheating; avoiding smoke exposure; and breastfeeding. These are what the evidence supports. A monitor is not on that list.

Why contactless rather than a mattress pad?

Safety and reliability. A pad under the mattress can be defeated by the baby rolling to a different position, and anything attached to the baby is a hazard. Contactless radar sees the chest movement through the air with nothing on or under the infant, which is both safer and less easily displaced.

Why does it not alarm when the crib is empty?

Because an empty crib produces no movement, which is identical to apnoea on a movement sensor. Alarming then would be a false alarm every time you pick the baby up, and false alarms are exactly what make parents disable a monitor. The device gates the alarm on the baby actually being present in the field.

How do I choose the alarm window?

With your paediatrician. It is a genuine trade-off: too short and normal newborn periodic breathing (brief pauses that are entirely normal) triggers false alarms; too long and a real event is caught later. Fifteen seconds is a reasonable default that gives margin before the 20-second clinical apnoea threshold, but the right value is personal and medical.

Can I trust the phone notification if I am in another room?

Only as a backup, never as the primary alert. Wi-Fi drops, phones get silenced, notifications get delayed. The loud local alarm is the one thing that must always work, which is why it is driven directly by the microcontroller and functions with no network at all. Site it where you will hear it and rely on that.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. AAP, "Sleep-Related Infant Deaths: Updated Recommendations for a Safe Infant Sleeping Environment"American Academy of Pediatrics, 2022
  2. Bonafide et al., "Accuracy of Consumer Smartphone Apps and Monitors for Vital Signs in Infants"JAMA, 2017
  3. Seeed Studio MR60BHA1 60 GHz mmWave breathing and heartbeat sensorSeeed Studio
  4. Li et al., "A Review on Recent Advances in Doppler Radar Sensors for Noncontact Healthcare Monitoring"IEEE Trans. Microwave Theory, 2013
  5. Moon et al., "SIDS and Other Sleep-Related Infant Deaths" (technical report)Pediatrics, 2022
  6. HLK-LD2410 24 GHz human presence radar — datasheetHi-Link