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
| Setting | How it is used |
|---|---|
| Personal hydration tracking | The everyday case, where honest volume data is far more useful than a sip count. |
| Kidney stone prevention | Patients are often told to hit a specific daily fluid volume; measuring it is the only way to comply. |
| Elderly care | Dehydration is a common and serious problem in older adults and is frequently missed until it causes a fall or confusion. |
| Athletic training | Combined with body mass before and after exercise, this gives a real sweat-rate measurement. |
| Hot-climate outdoor work | A temperature-adjusted target and behind-schedule alerts have genuine safety value in heat. |
| Post-operative recovery | Fluid 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
| Attribute | Value |
|---|---|
| Difficulty level | Beginner |
| Estimated completion time | 6β9 hours |
| Indicative build cost | βΉ2,900 β βΉ3,800 |
| Primary discipline | Health & Wearables |
| Reference platform | ESP32 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.
| Component | Key specification | Qty | Approx. 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 DAC | 1 | βΉ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 SPS | 1 | βΉ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 heater | 1 | βΉ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 Hz | 1 | βΉ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Β²C | 1 | βΉ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 discharge | 1 | βΉ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 protection | 1 | βΉ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 grid | 1 | βΉ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 mm | 1 | βΉ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 plate | 1 | βΉ350 |
| 600 mAh LiPo cell + charging port A magnetic connector avoids a USB port that fills with water. | 3.7 V protected, magnetic charge connector | 1 | βΉ320 |
| Conformal coating / potting compound | Silicone, electronics grade | 1 | βΉ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
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| 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 DAC | 3.3 V logic / 5 V USB | UART, SPI, IΒ²C, IΒ²S, CAN, PWM | Datasheet |
| 5 kg load cell + HX711 24-bit ADC | Strain-gauge bridge, 1.0 mV/V output, HX711 128Γ gain, 10/80 SPS | 2.6β5.5 V | 2-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 heater | 2.4β5.5 V | IΒ²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 Hz | 2.0β3.6 V | IΒ²C / SPI | Datasheet |
| 0.96β³ SSD1306 OLED display | 128 Γ 64 monochrome, 1.3β3.3 V logic, 100 kHzβ400 kHz IΒ²C | 3.3β5 V | IΒ²C (0x3C) | Datasheet |
| 18650 Li-ion cell 3400 mAh + holder | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 3.0β4.2 V | Holder / spot-welded tabs | Datasheet |
| TP4056 Li-ion charger + DW01 protection | 1 A programmable CC/CV charge to 4.2 V Β±1 %, over-discharge and short protection | 4.5β5.5 V in | micro-USB / pads | Datasheet |
| Double-sided perfboard 7 Γ 9 cm + headers | FR-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.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA β size the regulator accordingly. |
| 5 kg load cell + HX711 24-bit ADC | 2.6β5.5 V | 1.5 | Mechanical mounting dominates accuracy β bolt it to a rigid plate, not plastic. |
| SHT31-D temperature + humidity sensor | 2.4β5.5 V | 1.5 | The built-in heater burns off condensation β essential for outdoor or greenhouse use. |
| ADXL345 3-axis accelerometer | 2.0β3.6 V | 0.14 | Built-in activity/free-fall interrupts let the MCU deep-sleep until something moves. |
| 0.96β³ SSD1306 OLED display | 3.3β5 V | 20 | Static images burn in β invert or scroll the screen periodically. |
| TP4056 Li-ion charger + DW01 protection | 4.5β5.5 V in | 1000 | Buy 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.jsonunder 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
dialoutgroup:sudo usermod -aG dialout $USERand 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
| Library | Why it is needed | Install |
|---|---|---|
| HX711 0.7.x | Bit-banged 24-bit ADC read with tare and calibration factor. | Library Manager β "HX711" by Bogdan Necula |
| Adafruit SSD1306 + GFX 2.5.x | Framebuffer and text/graphics primitives for the OLED. | Library Manager β "Adafruit SSD1306" |
| Preferences (NVS) bundled | Wear-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.
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.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| HX711 load cell amplifier | DT / SCK | GPIO 16 / 4 | Bit-banged 24-bit ADC |
| ADXL345 motion | SDA / SCL | GPIO 21 / 22 | IΒ²C at 0x53, wake source |
| ADXL345 INT1 | INT1 | GPIO 33 | Activity interrupt, RTC-capable |
| SHT31 temperature | SDA / SCL | GPIO 21 / 22 | Shared IΒ²C, 0x44 |
| SSD1306 OLED | SDA / SCL | GPIO 21 / 22 | Shared IΒ²C, 0x3C |
| Vibration motor | Transistor base | GPIO 25 | Reminder haptic |
| Button | NO | GPIO 32 | Tare / 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.
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.
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
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
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
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.
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.
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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);
}
Configuration & Calibration
Configuration steps
- Set
BODY_MASS_KGfor 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
calFactorwith a known mass β 500 g of water in a measuring jug works well. - Set
MIN_DRINK_MLat least 30 times your measured noise floor. 15 ml is comfortable for a 1 kg cell. - Adjust
WAKE_HOURandSLEEP_HOURto the user's actual day, or the expected curve will prompt at the wrong times. - Tune
REMIND_DEFICIT_MLand 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.
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 %.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.
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.
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.
| Test | What you should see |
|---|---|
| Place an empty bottle on the base and tare | Reading near 0 g, stable to within about 0.5 g. |
| Add 500 ml of water | Reading of 500 Β± 5 g once the stability gate opens. |
| Drink about 200 ml and set the bottle down | A drink event of roughly 200 ml logged two seconds after it becomes still. |
| Pick the bottle up and put it back without drinking | No event logged β the mass is unchanged and the readings while carried are discarded. |
| Refill the bottle | A refill logged, the reference reset, and no intake counted. |
| Check the progress bar mid-afternoon | The tick mark sits at the expected fraction for that hour, not at a flat proportion of the day. |
| Fall 300 ml behind the curve | One haptic reminder, then silence for 25 minutes regardless of how far behind you remain. |
| Raise the ambient temperature to 33 Β°C | The 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.
Troubleshooting: Common Errors & Fixes
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 amillis()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_twhere 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
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- HX711 24-bit ADC for weigh scales β datasheetAvia Semiconductor
- EFSA Panel, "Scientific Opinion on Dietary Reference Values for water"EFSA Journal, 2010
- Valtin, "Drink at least eight glasses of water a day. Really?"American Journal of Physiology, 2002
- Institute of Medicine β Dietary Reference Intakes for Water, Potassium, SodiumNational Academies
- Load cell mounting and Wheatstone bridge fundamentalsHBM
- Hew-Butler et al., "Statement of the Third International Exercise-Associated Hyponatremia Consensus"Clinical Journal of Sport Medicine, 2015