Siddhant Kumar
Project 021 Β· Health & Wearables

Hydration Reminder Bottle.

A bottle cap that weighs what you actually drank rather than counting how many times you picked it up, adjusts the daily target for temperature and activity, and reminds you only when you are genuinely behind.

Beginner 6–9 hours 35 min read SensorAppWellness
Jump to source Bill of materials
Hydration Reminder Bottle β€” reference build illustration MCU VCC Β· GND Β· SIG Β· NC
Difficulty
Beginner
Build time
6–9 hours
Indicative cost
β‚Ή2,900 – β‚Ή3,800
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Health & Wearables
Last updated
28 July 2026
Contents β€” 25 sections

Project Overview

A bottle cap that weighs what you actually drank rather than counting how many times you picked it up, adjusts the daily target for temperature and activity, and reminds you only when you are genuinely behind.

Most smart bottles count sips using an accelerometer and a tilt threshold. That approach fails immediately in normal use: it counts picking the bottle up to move it, misses a long drink as one event, and has no idea whether you swallowed 20 ml or 300 ml. The result is a number that looks like data and is not.

Weighing is the honest approach. A load cell in the base measures the bottle's mass continuously; a drop in mass between two stable readings is water that left the bottle. That distinguishes a 40 ml sip from a 300 ml gulp, ignores every pick-up that does not result in drinking, and β€” with a small amount of logic β€” distinguishes drinking from refilling, because refilling makes the mass go up.

The second design decision is the target. A fixed "two litres a day" is a persistent myth with weak evidential support; actual requirement varies with body mass, ambient temperature, activity and diet. The controller computes a target from body mass with adjustments for measured temperature and for activity inferred from a paired phone or a simple step input, which produces a number that at least responds to the things that genuinely change requirement.

Finally, the reminder policy. A bottle that buzzes hourly regardless is ignored within a week. This one compares your actual intake against a time-of-day-weighted expected curve and reminds only when you fall meaningfully behind β€” which in practice means a couple of prompts on a normal day and several on a hot one.

What this project does

  • Measures bottle mass continuously with a load cell in the base and converts changes to millilitres.
  • Distinguishes drinking from refilling, from setting the bottle down, and from being carried.
  • Computes a personalised daily target adjusted for body mass and ambient temperature.
  • Compares intake against a time-weighted expected curve and reminds only when genuinely behind.
  • Displays progress on a small OLED in the cap and logs every drink event.
  • Syncs to a phone over BLE with local buffering.
  • Runs for two to three weeks on a small cell through motion-triggered wake.

Real-World Applications

SettingHow it is used
Personal hydration trackingThe everyday case, where honest volume data is far more useful than a sip count.
Kidney stone preventionPatients are often told to hit a specific daily fluid volume; measuring it is the only way to comply.
Elderly careDehydration is a common and serious problem in older adults and is frequently missed until it causes a fall or confusion.
Athletic trainingCombined with body mass before and after exercise, this gives a real sweat-rate measurement.
Hot-climate outdoor workA temperature-adjusted target and behind-schedule alerts have genuine safety value in heat.
Post-operative recoveryFluid intake targets after surgery are common and adherence is usually unmeasured.

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

Features & Capabilities

  • Mass-based measurement β€” actual millilitres, not sip counts.
  • Refill detection from an increase in mass, which resets the reference without counting as intake.
  • Stability gating: mass is only read when the bottle has been still for two seconds.
  • Temperature-adjusted target using an on-board sensor, because requirement rises sharply in heat.
  • Time-weighted expected curve rather than a flat hourly target.
  • Motion-triggered wake so the device sleeps at microamps when the bottle is untouched.
  • Drink-event log with volume and timestamp, which is where the useful pattern lives.
  • Water-resistant cap assembly with the electronics fully potted.

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelBeginner
Estimated completion time6–9 hours
Indicative build costβ‚Ή2,900 – β‚Ή3,800
Primary disciplineHealth & Wearables
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Arduino C++ with state machines
  • Load cell calibration and the HX711 interface
  • Basic filtering and stability detection
  • BLE basics
  • Waterproofing and mechanical assembly

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
5 kg load cell + HX711 24-bit ADC
Mechanical mounting dominates accuracy β€” bolt it to a rigid plate, not plastic.
Strain-gauge bridge, 1.0 mV/V output, HX711 128Γ— gain, 10/80 SPS1β‚Ή320
SHT31-D temperature + humidity sensor
The built-in heater burns off condensation β€” essential for outdoor or greenhouse use.
βˆ’40 to +125 Β°C Β±0.2 Β°C, 0–100 %RH Β±2 %, 1 Hz–10 Hz, on-chip heater1β‚Ή620
ADXL345 3-axis accelerometer
Built-in activity/free-fall interrupts let the MCU deep-sleep until something moves.
Β±2/4/8/16 g, 13-bit, 0.004 g/LSB, tap and free-fall interrupts, 3200 Hz1β‚Ή220
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
18650 Li-ion cell 3400 mAh + holder
Never charge below 0 Β°C; always use a protected cell or a BMS.
3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge1β‚Ή450
TP4056 Li-ion charger + DW01 protection
Buy the version *with* protection ICs β€” the bare charger will over-discharge your cell.
1 A programmable CC/CV charge to 4.2 V Β±1 %, over-discharge and short protection1β‚Ή45
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
1 kg load cell (bar type)
A 1 kg cell suits a 750 ml bottle. A 5 kg cell wastes most of its range and resolution.
1 kg, 1.0 mV/V, 55 Γ— 12 Γ— 6 mm1β‚Ή260
Silicone-sealed base housing
The load cell must be rigidly fixed at one end and load the other β€” see the wiring notes.
IP54, machined or printed, with a rigid mounting plate1β‚Ή350
600 mAh LiPo cell + charging port
A magnetic connector avoids a USB port that fills with water.
3.7 V protected, magnetic charge connector1β‚Ή320
Conformal coating / potting compoundSilicone, electronics grade1β‚Ή200

Estimated total: β‚Ή3,545, 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
5 kg load cell + HX711 24-bit ADCStrain-gauge bridge, 1.0 mV/V output, HX711 128Γ— gain, 10/80 SPS2.6–5.5 V2-wire serial (bit-banged)Datasheet
SHT31-D temperature + humidity sensorβˆ’40 to +125 Β°C Β±0.2 Β°C, 0–100 %RH Β±2 %, 1 Hz–10 Hz, on-chip heater2.4–5.5 VIΒ²C (0x44/0x45)Datasheet
ADXL345 3-axis accelerometerΒ±2/4/8/16 g, 13-bit, 0.004 g/LSB, tap and free-fall interrupts, 3200 Hz2.0–3.6 VIΒ²C / SPIDatasheet
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
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V Β±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
Double-sided perfboard 7 Γ— 9 cm + headersFR-4, 0.1β€³ pitch, plated through-holes, 24 Γ— 18 gridβ€”β€”Datasheet

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.
5 kg load cell + HX711 24-bit ADC2.6–5.5 V1.5Mechanical mounting dominates accuracy β€” bolt it to a rigid plate, not plastic.
SHT31-D temperature + humidity sensor2.4–5.5 V1.5The built-in heater burns off condensation β€” essential for outdoor or greenhouse use.
ADXL345 3-axis accelerometer2.0–3.6 V0.14Built-in activity/free-fall interrupts let the MCU deep-sleep until something moves.
0.96β€³ SSD1306 OLED display3.3–5 V20Static images burn in β€” invert or scroll the screen periodically.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy the version *with* protection ICs β€” the bare charger will over-discharge your cell.

Summed typical draw is 1183.1399999999999 mA. With a 1.5Γ— design margin the supply should deliver at least 1800 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
HX711 0.7.xBit-banged 24-bit ADC read with tare and calibration factor.Library Manager β†’ "HX711" by Bogdan Necula
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.

Hydration Reminder Bottle β€” system block diagramFunctional block diagram of the Hydration Reminder Bottle system. SenseLoad cell + HX711bottle massADXL345stability + wakeSHT31ambient tempInterpretStability gatestill for 2 sDrink vs refillsign of changeTargetPersonal targetmass + tempExpected curvetime-weightedPromptHaptic reminderonly when behindBLE + OLEDprogressmass samplesvolume eventsdeficit
Hydration Reminder Bottle β€” 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.

Hydration Reminder Bottle β€” wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBHX711 load cell amplifierGPIO 16 / 4Bit-banged 24-bitADCADXL345 motionGPIO 21 / 22IΒ²C at 0x53, wakesourceADXL345 INT1GPIO 33Activity interrupt,RTC-capableSHT31 temperatureGPIO 21 / 22Shared IΒ²C, 0x44SSD1306 OLEDGPIO 21 / 22Shared IΒ²C, 0x3CVibration motorGPIO 25Reminder hapticButtonGPIO 32Tare / display wake
Hydration Reminder Bottle β€” wiring schematic
PeripheralPeripheral pinController pinSignal
HX711 load cell amplifierDT / SCKGPIO 16 / 4Bit-banged 24-bit ADC
ADXL345 motionSDA / SCLGPIO 21 / 22IΒ²C at 0x53, wake source
ADXL345 INT1INT1GPIO 33Activity interrupt, RTC-capable
SHT31 temperatureSDA / SCLGPIO 21 / 22Shared IΒ²C, 0x44
SSD1306 OLEDSDA / SCLGPIO 21 / 22Shared IΒ²C, 0x3C
Vibration motorTransistor baseGPIO 25Reminder haptic
ButtonNOGPIO 32Tare / display wake

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

  • The load cell must be rigidly fixed at one end and loaded at the other, with a gap so it can flex. Bolting both ends to the same rigid plate means it never bends and reads a constant value β€” this is the single most common load cell mounting error.
  • Use a 1 kg cell, not a 5 kg one. A full 750 ml bottle plus its own mass is around 1 kg; a 5 kg cell would use a fifth of its range and give a fifth of the resolution.
  • Keep the HX711 leads short and away from any switching. It amplifies microvolts, and even the OLED's charge pump can inject visible noise if the routing is careless.
  • Pot the entire electronics assembly in silicone. This device lives on a desk with an open water bottle on top of it and will get wet.
  • Use a magnetic charging connector rather than a USB port. A USB socket in the base of a water bottle fills with water and corrodes within weeks.
  • Mount the temperature sensor on the outside of the housing, away from the electronics. It should measure the room, not the enclosure.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
An ESP32 development board running the weighing, classification and reminder logic. 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.

Hydration Reminder Bottle β€” architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) Β· SHT31-D temperature + humidity sensorDriver layerhx711 Β· ssd1306 Β· preferencesApplication logicsampling loop Β· filtering Β· thresholds Β· state machinePresentation layerlocal display Β· serial console Β· logged output
Hydration Reminder Bottle β€” architecture stack

Working Principle

The measurement is straightforward: 1 ml of water has a mass of very nearly 1 g at room temperature, so a mass change in grams is a volume change in millilitres to within about 0.4 % over the normal temperature range. A 1 kg load cell with an HX711 resolves to a few tenths of a gram in practice, which is far better than needed for a measurement whose useful granularity is about 10 ml.

The engineering is in knowing when the reading is meaningful. A load cell in a bottle base reads garbage while the bottle is being carried, tilted, or set down β€” dynamic acceleration adds directly to the measured force. The solution is a stability gate: only accept a mass reading when the accelerometer has reported near-1 g total with low variance for two continuous seconds. Everything else is discarded.

Drinking versus refilling then falls out of the sign of the change between two stable readings. A decrease is water that left the bottle. An increase is a refill, which resets the reference without counting as intake. A change smaller than about 15 ml is noise or evaporation and is ignored. This is much more robust than it sounds, because the intervening carried-around period is simply not measured at all.

The daily target is where most hydration devices are weakest. The commonly repeated "eight glasses" or "two litres" figures have surprisingly weak evidential basis and take no account of body mass, climate or activity. A more defensible starting point is roughly 30–35 ml per kilogram of body mass per day, adjusted upward for ambient temperature above about 25 Β°C and for exercise. Even this is approximate β€” thirst is a reasonably good regulator in healthy adults β€” but it at least responds to the variables that genuinely matter.

The expected curve is what makes reminders tolerable. Intake should not be flat across the day: people wake dehydrated, drink most between mid-morning and early evening, and should taper before bed. Comparing actual intake against a cumulative curve weighted to that shape means the device prompts when you are genuinely behind, not merely because an hour has passed. On a normal day that is two or three prompts; on a hot day it is more, which is exactly the behaviour you want.

The maths behind it

Daily target from body mass and temperature

plainDaily target from body mass and temperature
Base:   V_base = mass_kg Γ— 33 ml

Temperature adjustment above 25 Β°C:
  V_temp = V_base Γ— (1 + 0.03 Γ— (T_mean βˆ’ 25))   for T > 25

Activity adjustment:
  V_total = V_temp + 500 ml per hour of vigorous exercise

Worked example β€” 70 kg, mean 32 Β°C, 1 h exercise:
  V_base  = 70 Γ— 33 = 2310 ml
  V_temp  = 2310 Γ— (1 + 0.03 Γ— 7) = 2795 ml
  V_total = 2795 + 500 = 3295 ml

Same person at 20 Β°C with no exercise: 2310 ml.
The difference β€” 43 % β€” is why a fixed target is poor.

Time-weighted expected curve

plainTime-weighted expected curve
Waking hours 07:00–23:00 (16 h). Weight intake toward
the middle of the day and taper before sleep.

  w(h) = sin(Ο€ Γ— (h βˆ’ 7) / 16)^0.7      for 7 ≀ h ≀ 23

Cumulative expected fraction:
  E(h) = Ξ£ w over [7, h]  /  Ξ£ w over [7, 23]

  09:00 β†’ 12 %
  12:00 β†’ 34 %
  15:00 β†’ 58 %
  18:00 β†’ 79 %
  21:00 β†’ 95 %

Prompt when  actual < E(h) Γ— target βˆ’ 250 ml.

Load cell resolution

plainLoad cell resolution
1 kg cell, 1.0 mV/V, excited at 5 V:
  full scale output = 5 mV
  per gram = 5 Β΅V

HX711 gain 128, Β±20 mV input range, 24-bit:
  LSB = 40 mV / 2^24 = 2.38 nV
  counts per gram = 5 Β΅V / 2.38 nV β‰ˆ 2100

Noise-limited usable resolution β‰ˆ Β±0.3 g

Minimum detectable drink: set at 15 ml, which is
50Γ— the noise floor β€” comfortably robust.

Program Flowchart

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

Hydration Reminder Bottle β€” firmware flowchartControl flow through the main program loop. Deep sleep until motion wakesthe deviceWait for the bottle to bestill for 2 sRead stable massMass decreased by morethan 15 ml?drink eventcheck for refillMass increased? Refill β€” resetreferenceLog volume, update daily totalBehind the expected curveby 250 ml?haptic reminderno promptUpdate display, sleep
Hydration Reminder Bottle β€” 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.

cpphydration-bottle.ino
/* ═══════════════════════════════════════════════════════════════
   Hydration Reminder Bottle β€” ESP32 + 1 kg load cell + ADXL345

   Measures actual volume drunk by weighing the bottle, and only
   reads mass when the accelerometer confirms the bottle has been
   still for two seconds. Reminds against a time-weighted expected
   curve rather than on a fixed timer.
   ══════════════════════════════════════════════════════════════════ */

#include <HX711.h>
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <Adafruit_ADXL345_U.h>
#include <Adafruit_SSD1306.h>
#include <Preferences.h>
#include <time.h>
#include <math.h>

#define PIN_HX_DT   16
#define PIN_HX_SCK   4
#define PIN_VIBE    25
#define PIN_BTN     32

#define BODY_MASS_KG      70.0f
#define ML_PER_KG         33.0f
#define MIN_DRINK_ML      15.0f
#define STABLE_MS       2000
#define STABLE_SIGMA_G     0.06f
#define REMIND_DEFICIT_ML 250.0f
#define REMIND_COOLDOWN_MS (25UL * 60UL * 1000UL)
#define WAKE_HOUR  7
#define SLEEP_HOUR 23

HX711            scale;
Adafruit_SHT31   sht = Adafruit_SHT31();
Adafruit_ADXL345_Unified accel(3);
Adafruit_SSD1306 oled(128, 32, &Wire, -1);
Preferences      prefs;

float   calFactor = 2100.0f;          // counts per gram
float   lastStableG = -1;
float   ambientC = 24;
float   tempSum = 0; uint16_t tempN = 0;
uint16_t drunkToday = 0;
uint32_t lastRemind = 0, stableSince = 0;
int     lastDay = -1;

/* ── stability from the accelerometer ───────────────────────── */
bool bottleStill() {
  static float hist[20]; static uint8_t h = 0;
  sensors_event_t e; accel.getEvent(&e);
  float mag = sqrtf(e.acceleration.x * e.acceleration.x +
                    e.acceleration.y * e.acceleration.y +
                    e.acceleration.z * e.acceleration.z) / 9.81f;
  hist[h] = mag; h = (h + 1) % 20;

  float mean = 0; for (float v : hist) mean += v; mean /= 20;
  float var = 0;  for (float v : hist) { float d = v - mean; var += d * d; }
  float sigma = sqrtf(var / 20);

  // Upright and still: magnitude near 1 g and low variance.
  bool still = sigma < STABLE_SIGMA_G && fabsf(mean - 1.0f) < 0.08f;
  if (!still) { stableSince = 0; return false; }
  if (!stableSince) { stableSince = millis(); return false; }
  return millis() - stableSince >= STABLE_MS;
}

/* ── mass ───────────────────────────────────────────────────── */
float readMassG() {
  if (!scale.is_ready()) return -1;
  long raw = scale.read_average(12);
  return (raw - scale.get_offset()) / calFactor;
}

/* ── targets ────────────────────────────────────────────────── */
float dailyTargetMl() {
  float meanT = tempN ? tempSum / tempN : ambientC;
  float base = BODY_MASS_KG * ML_PER_KG;
  if (meanT > 25.0f) base *= (1.0f + 0.03f * (meanT - 25.0f));
  return base;
}

// Cumulative fraction of the day's intake that should be done by hour h.
float expectedFraction(float h) {
  if (h <= WAKE_HOUR) return 0;
  if (h >= SLEEP_HOUR) return 1;
  const float span = SLEEP_HOUR - WAKE_HOUR;
  // Integrate w(t) = sin(pi*(t-7)/16)^0.7 numerically; 32 slices is plenty.
  auto w = [&](float t) { return powf(sinf((float)M_PI * (t - WAKE_HOUR) / span), 0.7f); };
  float total = 0, upTo = 0;
  for (int i = 0; i < 32; i++) {
    float t = WAKE_HOUR + span * (i + 0.5f) / 32.0f;
    float v = w(t);
    total += v;
    if (t <= h) upTo += v;
  }
  return total > 0 ? upTo / total : 0;
}

/* ── feedback ───────────────────────────────────────────────── */
void remind() {
  for (int i = 0; i < 2; i++) {
    digitalWrite(PIN_VIBE, HIGH); delay(220);
    digitalWrite(PIN_VIBE, LOW);  delay(200);
  }
}

void draw(float h) {
  float target = dailyTargetMl();
  float expected = expectedFraction(h) * target;

  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.setTextSize(2); oled.setCursor(0, 0);
  oled.printf("%u ml", drunkToday);
  oled.setTextSize(1);
  oled.setCursor(78, 6); oled.printf("/%0.0f", target);

  // Progress bar with a tick marking where you should be by now.
  int w = (int)(126.0f * fminf(1.0f, drunkToday / target));
  oled.drawRect(0, 22, 128, 9, SSD1306_WHITE);
  oled.fillRect(1, 23, w, 7, SSD1306_WHITE);
  int mark = (int)(126.0f * fminf(1.0f, expected / target));
  oled.drawFastVLine(mark, 20, 13, SSD1306_WHITE);
  oled.display();
}

/* ── setup / loop ───────────────────────────────────────────── */
void setup() {
  Serial.begin(115200);
  pinMode(PIN_VIBE, OUTPUT);
  pinMode(PIN_BTN, INPUT_PULLUP);

  scale.begin(PIN_HX_DT, PIN_HX_SCK);
  Wire.begin(21, 22);
  sht.begin(0x44);
  accel.begin(0x53);
  accel.setRange(ADXL345_RANGE_2_G);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  prefs.begin("hydro", false);
  calFactor  = prefs.getFloat("cal", 2100.0f);
  drunkToday = prefs.getUShort("today", 0);
  lastDay    = prefs.getInt("day", -1);

  delay(1200);
  scale.tare(20);                     // tare with an EMPTY base
  Serial.println("Hydration bottle ready");
}

void loop() {
  /* Long press tares, short press wakes the display. */
  if (digitalRead(PIN_BTN) == LOW) {
    uint32_t t0 = millis();
    while (digitalRead(PIN_BTN) == LOW && millis() - t0 < 3000) delay(20);
    if (millis() - t0 >= 2000) { scale.tare(20); lastStableG = -1; remind(); }
  }

  static uint32_t lastSlow = 0;
  if (millis() - lastSlow < 500) return;
  lastSlow = millis();

  float t = sht.readTemperature();
  if (!isnan(t)) { ambientC = t; tempSum += t; tempN++; }

  time_t now = time(nullptr);
  struct tm tmv; localtime_r(&now, &tmv);
  float h = tmv.tm_hour + tmv.tm_min / 60.0f;

  if (tmv.tm_yday != lastDay) {       // midnight rollover
    lastDay = tmv.tm_yday;
    drunkToday = 0;
    tempSum = 0; tempN = 0;
    prefs.putUShort("today", 0);
    prefs.putInt("day", lastDay);
  }

  if (!bottleStill()) return;         // readings while carried are meaningless

  float g = readMassG();
  if (g < 0) return;

  if (lastStableG < 0) { lastStableG = g; draw(h); return; }

  float delta = lastStableG - g;      // positive = water left the bottle

  if (delta > MIN_DRINK_ML) {
    drunkToday += (uint16_t)delta;
    prefs.putUShort("today", drunkToday);
    Serial.printf("drank %.0f ml, total %u ml\n", delta, drunkToday);
    lastStableG = g;
  } else if (delta < -MIN_DRINK_ML) {
    // Mass went up: a refill. Reset the reference, count nothing.
    Serial.printf("refill +%.0f ml\n", -delta);
    lastStableG = g;
  }

  /* Remind only when genuinely behind the expected curve. */
  float target = dailyTargetMl();
  float expected = expectedFraction(h) * target;
  if (h >= WAKE_HOUR && h < SLEEP_HOUR
      && expected - drunkToday > REMIND_DEFICIT_ML
      && millis() - lastRemind > REMIND_COOLDOWN_MS) {
    lastRemind = millis();
    remind();
    Serial.printf("reminder: %u of %.0f ml expected by now\n", drunkToday, expected);
  }

  draw(h);
}
bottleStill() before any mass readDynamic acceleration adds directly to the measured force, so a load cell reading while the bottle is being carried is meaningless. Requiring two seconds of low-variance, near-1 g stillness is what makes the measurement trustworthy.
delta = lastStableG βˆ’ gPositive means mass left the bottle β€” you drank it. Negative means mass arrived β€” a refill. Two lines of logic replace the entire sip-counting apparatus that other designs need, and they are correct rather than approximate.
Refill resets the reference without countingWithout this, refilling a bottle would register as a large negative drink or, worse, the subsequent drinking would be measured from the wrong baseline all day.
expectedFraction integrating sin^0.7The exponent shapes the curve so intake is weighted toward the middle of the day and tapers before sleep, which matches how people actually drink and avoids prompting at 22:30.
REMIND_COOLDOWN_MS 25 minutesEven when behind, prompting more than roughly every 25 minutes is nagging. The cooldown is what keeps the device on the desk rather than in a drawer.
scale.tare with an EMPTY baseThe tare must be taken with nothing on the load cell, so the measured mass includes the bottle itself. That is deliberate β€” the bottle mass is constant and cancels out of every delta.
read_average(12)The HX711 runs at 10 samples per second, so twelve averaged samples takes about 1.2 seconds. That is acceptable here because the stability gate has already established the bottle is not moving.

Configuration & Calibration

Configuration steps

  • Set BODY_MASS_KG for the user. The 33 ml/kg figure is a starting point; a clinician may specify a different target for a medical reason, in which case use theirs.
  • Calibrate calFactor with a known mass β€” 500 g of water in a measuring jug works well.
  • Set MIN_DRINK_ML at least 30 times your measured noise floor. 15 ml is comfortable for a 1 kg cell.
  • Adjust WAKE_HOUR and SLEEP_HOUR to the user's actual day, or the expected curve will prompt at the wrong times.
  • Tune REMIND_DEFICIT_ML and the cooldown together. Too sensitive and it nags; too permissive and it never prompts.

Calibration procedure

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

  1. Calibrate the load cell

    Tare with the base empty. Place a known mass β€” 500 ml of water weighed on a kitchen scale is ideal β€” and set calFactor = raw_counts / grams. Verify with a second, different mass; the two factors should agree within about 1 %.

  2. Measure the noise floor

    Leave a full bottle sitting still and log the mass for ten minutes. The peak-to-peak spread is your noise floor. Set the minimum drink threshold at least 30 times that value.

  3. Tune the stability gate

    Log the accelerometer sigma while the bottle sits on a desk, while someone types nearby, and while it is carried. The threshold must sit clearly above the desk value and below the carried value.

  4. Validate against a measuring jug

    Pour exactly 200 ml out of the bottle and check the logged event. Agreement within 5 ml confirms both the calibration and the stability gating.

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
Place an empty bottle on the base and tareReading near 0 g, stable to within about 0.5 g.
Add 500 ml of waterReading of 500 Β± 5 g once the stability gate opens.
Drink about 200 ml and set the bottle downA drink event of roughly 200 ml logged two seconds after it becomes still.
Pick the bottle up and put it back without drinkingNo event logged β€” the mass is unchanged and the readings while carried are discarded.
Refill the bottleA refill logged, the reference reset, and no intake counted.
Check the progress bar mid-afternoonThe tick mark sits at the expected fraction for that hour, not at a flat proportion of the day.
Fall 300 ml behind the curveOne haptic reminder, then silence for 25 minutes regardless of how far behind you remain.
Raise the ambient temperature to 33 Β°CThe daily target rises by roughly 25 %, and the expected curve rises with it.

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 wearable tracker. Hydration data becomes considerably more useful when combined with activity data from a device like this. 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

Mass readings drift steadily upward or downward

Likely cause. Temperature affecting the load cell, or mechanical creep in the mounting.

Fix. Some drift is inherent in aluminium cells. Because this design measures deltas between consecutive stable readings, slow drift is largely cancelled β€” but if it exceeds a few grams an hour, check that nothing is pressing on the cell and that the mounting screws are not slowly loosening.

Drinks are missed entirely

Likely cause. The stability gate never opens, so no reading is ever taken.

Fix. Log the accelerometer sigma on a desk. If it never drops below the threshold, the desk is vibrating (a nearby fan or a hollow table) or the threshold is too tight. Loosen it and lengthen the required stable period instead.

Spurious large drink events

Likely cause. A reading taken during a transient, or something briefly resting on the bottle.

Fix. Increase the stable-period requirement to three seconds and average more HX711 samples. Also reject implausible deltas β€” nobody drinks 600 ml in one go from a 750 ml bottle, so a cap on single-event volume is a cheap sanity check.

The load cell reads a constant value

Likely cause. Both ends bolted to the same rigid surface, so it cannot flex.

Fix. One end fixed, the other loaded, with a gap beneath. This is the most common load cell mounting error and it produces a perfectly stable, entirely useless reading.

Water damage after a few weeks

Likely cause. Unpotted electronics under an open water bottle.

Fix. Pot everything in silicone, use a magnetic charge connector rather than a USB socket, and seal the load cell cable entry. This device will get wet β€” design for it rather than hoping.

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.

Performance Optimisation

  • Use motion-triggered wake. The bottle is untouched for most of the day, and sleeping at microamps between interactions turns days of battery into weeks.
  • Average twelve HX711 samples per reading and only when the stability gate is open β€” the gate has already guaranteed the bottle is not moving, so the 1.2 seconds costs nothing.
  • Wake the display only on interaction. An always-on OLED is most of the power budget in a device that is looked at for a few seconds at a time.
  • 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.
  • 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

  • Do not treat the target as a medical instruction. Fluid requirement varies and some conditions β€” heart failure and certain kidney conditions in particular β€” require fluid restriction. Follow a clinician's target over any formula.
  • Over-hydration is real. Drinking far beyond thirst can cause hyponatraemia, which is dangerous. A device that encourages hitting a number regardless of thirst is not doing the user a favour.
  • Keep the lithium cell sealed and away from water, and use a protected cell.
  • Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 Β°C, and never leave a charging pack unattended on a wooden desk.
  • 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.
  • Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life β€” replace it.
  • 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 temperature measurement of the water itself so the bottle can tell you the drink is too hot, and so the volume conversion is exact.
  • Add activity integration from a phone or a fitness tracker so exercise adjusts the target automatically rather than by manual entry.
  • Add a UV-C sterilisation LED in the cap on a schedule β€” a genuinely useful addition for a bottle that is refilled repeatedly.
  • Add caffeine and alcohol logging with their diuretic adjustment, which meaningfully changes net hydration.
  • Move the load cell into the cap with a suspended inner vessel, so the bottle works anywhere rather than only on its base.
  • 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 connectivity β€” an ESP32 and an MQTT publish turn a local gadget into something you can graph, alert on and analyse over months.
  • 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

Why weigh rather than count sips?

Because a sip count is not a volume. An accelerometer with a tilt threshold cannot tell a 20 ml sip from a 300 ml gulp, counts every pick-up that does not result in drinking, and merges a long drink into one event. Weighing gives actual millilitres, which is the number you wanted in the first place.

Is two litres a day actually the right target?

Not as a universal figure. The commonly repeated "eight glasses" advice has surprisingly weak evidential basis, and actual requirement scales with body mass, ambient temperature, activity and diet β€” food contributes roughly 20 % of intake for most people. The 33 ml/kg starting point with temperature adjustment is more defensible, but for a healthy adult thirst remains a reasonably good regulator.

Does it work if I take the bottle out with me?

It measures what happens on the base. Drinking away from the base is invisible, and when you return the mass difference is attributed as one drink event at that moment β€” so the daily total is right but the timing is not. Moving the load cell into the cap with a suspended inner vessel solves this properly and is the obvious next version.

How accurate is it?

Within about 5 ml per event after calibration, which is far better than the 10 ml granularity that matters. The larger error source is behavioural, not electrical β€” drinks taken away from the base are timestamped wrongly.

Why does it not remind me every hour?

Because a device that prompts on a timer regardless of whether you need it gets ignored, and then it is worthless. Comparing against an expected curve means it prompts when you are genuinely behind β€” a couple of times on a normal day, more on a hot one. That is the difference between a useful device and a nagging one.

Can I use it for coffee or juice?

The mass measurement works for any liquid β€” density varies by a few percent at most. What changes is the hydration accounting: caffeine is a mild diuretic and alcohol a substantial one, so the net contribution differs. Logging drink type and applying an adjustment factor is a worthwhile addition.

References & Learning Resources

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

  1. HX711 24-bit ADC for weigh scales β€” datasheetAvia Semiconductor
  2. EFSA Panel, "Scientific Opinion on Dietary Reference Values for water"EFSA Journal, 2010
  3. Valtin, "Drink at least eight glasses of water a day. Really?"American Journal of Physiology, 2002
  4. Institute of Medicine β€” Dietary Reference Intakes for Water, Potassium, SodiumNational Academies
  5. Load cell mounting and Wheatstone bridge fundamentalsHBM
  6. Hew-Butler et al., "Statement of the Third International Exercise-Associated Hyponatremia Consensus"Clinical Journal of Sport Medicine, 2015