Siddhant Kumar
Project 017 Β· Health & Wearables

Smart Pill Dispenser.

A rotating-carousel dispenser that presents one dose at a time, physically locks the rest, confirms the dose was actually taken, and escalates to a carer when it was not.

Intermediate 14–20 hours 42 min read HealthSchedulerAlerts
Jump to source Bill of materials
Smart Pill Dispenser β€” reference build illustration
Difficulty
Intermediate
Build time
14–20 hours
Indicative cost
β‚Ή5,600 – β‚Ή7,200
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Health & Wearables
Last updated
28 July 2026
Contents β€” 26 sections

Project Overview

A rotating-carousel dispenser that presents one dose at a time, physically locks the rest, confirms the dose was actually taken, and escalates to a carer when it was not.

Medication non-adherence is one of the largest and least glamorous problems in healthcare β€” roughly half of patients on long-term medication do not take it as prescribed, and the consequences range from wasted treatment to hospital admission. A pill box with an alarm helps a little. What helps considerably more is a device that makes the correct action easy and the incorrect ones physically difficult.

That framing drives every decision here. The carousel exposes exactly one compartment through a single aperture; every other dose is behind a closed lid. Taking a double dose requires deliberately defeating the mechanism rather than simply forgetting you already took one. And the device knows whether the dose was removed, because a light sensor sees into the presented compartment.

The confirmation is what separates this from a timer. A dispenser that rotates and beeps has no idea whether anyone was there. A reflectance sensor looking into the open compartment reports full or empty, so the device can distinguish "presented and taken" from "presented and ignored" β€” and only the second one needs to reach a carer. That single signal is the difference between a device that produces useful information and one that produces noise.

Everything is bounded and fail-safe. The carousel cannot rotate past a dose that has not been taken without logging it as missed. There is a manual release so a person is never locked away from their own medication. And the schedule lives in an RTC on the device, because a dose that depends on a Wi-Fi connection is a dose that will be missed.

A brushed DC gear motor
A stepper motor. One motor driving a carousel replaces 28 individual actuators, with a single well-defined failure mode. Photograph sourced from Wikimedia Commons β€” DC motor.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Rotates a 28-compartment carousel to present one dose at the scheduled time.
  • Locks every other compartment behind a fixed lid with a single aperture.
  • Detects whether the presented dose was actually removed, using a reflectance sensor.
  • Escalates through alarm, phone notification and carer alert when a dose is not taken.
  • Logs every dose with scheduled time, presented time, taken time and outcome.
  • Runs the schedule from an on-board RTC, entirely independently of the network.
  • Provides a manual release so the user is never locked out of their own medication.

Real-World Applications

SettingHow it is used
Elderly polypharmacyThe core case β€” several medications at several times, where confusion about what was already taken is common and consequential.
Post-discharge medicationThe weeks after a hospital stay have the highest non-adherence and the highest readmission risk.
Chronic condition managementDiabetes, hypertension and epilepsy all depend on consistent timing rather than just consistent quantity.
Clinical trial complianceA timestamped adherence log is far stronger evidence than a patient diary.
Care home roundsMultiple dispensers with a central dashboard showing which residents have missed doses.
Cognitive impairment supportA single visible dose with a clear prompt is far easier than a weekly organiser.

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

Features & Capabilities

  • Single-aperture carousel β€” physical rather than software dose control.
  • Optical dose confirmation with a TCRT5000 reflectance sensor and ambient compensation.
  • Hall-effect home position plus step counting, so position survives a power cut.
  • Escalating reminders: local alarm, then phone, then carer, at configurable intervals.
  • Adherence log exportable as CSV for a clinical review.
  • DS3231 RTC with battery backup β€” the schedule never depends on NTP.
  • Manual override that unlocks and logs, rather than being blocked entirely.
  • Low-stock warning counting remaining filled compartments.

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelIntermediate
Estimated completion time14–20 hours
Indicative build costβ‚Ή5,600 – β‚Ή7,200
Primary disciplineHealth & Wearables
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Arduino C++ with state machines and scheduling
  • Stepper motor control and homing
  • Reflectance sensing with ambient light compensation
  • Simple mechanical design or 3D printing
  • MQTT and notification flows

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
A4988 stepper driver + NEMA 17 motor
Set Vref = I_max Γ— 8 Γ— Rsense before the first move or you cook the driver.
1.5 A/phase with heatsink, 1/16 microstepping, 8–35 V; NEMA 17 = 4.4 kgΒ·cm1β‚Ή750
TCRT5000 IR reflectance sensor module
Ambient sunlight saturates it β€” shroud the sensor on outdoor robots.
1–8 mm optimum sensing gap, 950 nm emitter, analogue + digital out1β‚Ή45
A3144 hall-effect switch
Unipolar β€” only one magnet pole triggers it. Flip the magnet if nothing happens.
Unipolar, 3.5–24 V, open-collector output, 100 kHz, βˆ’40 to +85 Β°C1β‚Ή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
DS3231 precision RTC + CR2032 backup
Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell β€” cut that resistor.
Β±2 ppm (Β±1 min/year), temperature-compensated crystal, alarms, 32 kHz out1β‚Ή180
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
LM2596 adjustable buck converter module
Set the output voltage with no load connected before wiring the board.
4.5–40 V in, 1.25–37 V out, 2 A (3 A peak), ~92 % efficiency1β‚Ή90
12 V 5 A SMPS adapter
Fuse the 12 V rail at ~1.5Γ— your calculated draw.
100–240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ— 2.1 mm barrel1β‚Ή650
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
3D-printed 28-compartment carousel + fixed lid
Print the lid in an opaque colour β€” a translucent lid lets ambient light confuse the reflectance sensor.
PETG, 180 mm diameter, 20 mm compartment depth1β‚Ή450
Neodymium magnet 5 Γ— 2 mmFor the hall-effect home position1β‚Ή30
Large confirm button + status LEDs16 mm illuminated, NO1β‚Ή140
Manual release key switch
A carer-held key is the right balance between safety and preventing accidental double dosing.
Keyed, 2-position1β‚Ή220

Estimated total: β‚Ή3,625, 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
A4988 stepper driver + NEMA 17 motor1.5 A/phase with heatsink, 1/16 microstepping, 8–35 V; NEMA 17 = 4.4 kgΒ·cm8–35 VSTEP/DIRDatasheet
TCRT5000 IR reflectance sensor module1–8 mm optimum sensing gap, 950 nm emitter, analogue + digital out3.3–5 VAnalogue + digitalDatasheet
A3144 hall-effect switchUnipolar, 3.5–24 V, open-collector output, 100 kHz, βˆ’40 to +85 Β°C4.5–24 VDigital (needs pull-up)Datasheet
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
DS3231 precision RTC + CR2032 backupΒ±2 ppm (Β±1 min/year), temperature-compensated crystal, alarms, 32 kHz out2.3–5.5 VIΒ²C (0x68)Datasheet
Active piezo buzzer 5 V85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter3–5 VDigital / PWMDatasheet
LM2596 adjustable buck converter module4.5–40 V in, 1.25–37 V out, 2 A (3 A peak), ~92 % efficiency4.5–40 VScrew terminals + trimmerDatasheet
12 V 5 A SMPS adapter100–240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ— 2.1 mm barrel12 VDC barrelDatasheet
Double-sided perfboard 7 Γ— 9 cm + headersFR-4, 0.1β€³ pitch, plated through-holes, 24 Γ— 18 gridβ€”β€”Datasheet
IP65 ABS junction enclosure 158 Γ— 90 Γ— 60 mmIP65, ABS, βˆ’20 to +80 Β°C, transparent lid, wall-mount lugsβ€”β€”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.
A4988 stepper driver + NEMA 17 motor8–35 V1500Set Vref = I_max Γ— 8 Γ— Rsense before the first move or you cook the driver.
TCRT5000 IR reflectance sensor module3.3–5 V20Ambient sunlight saturates it β€” shroud the sensor on outdoor robots.
A3144 hall-effect switch4.5–24 V9Unipolar β€” only one magnet pole triggers it. Flip the magnet if nothing happens.
0.96β€³ SSD1306 OLED display3.3–5 V20Static images burn in β€” invert or scroll the screen periodically.
DS3231 precision RTC + CR2032 backup2.3–5.5 V0.2Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell β€” cut that resistor.
Active piezo buzzer 5 V3–5 V30Active buzzers make tone on DC; passive ones need a PWM carrier.
LM2596 adjustable buck converter module4.5–40 V8Set the output voltage with no load connected before wiring the board.
12 V 5 A SMPS adapter12 V5000Fuse the 12 V rail at ~1.5Γ— your calculated draw.

Summed typical draw is 6747.2 mA. With a 1.5Γ— design margin the supply should deliver at least 10200 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
NTPClient / configTime bundledWall-clock time from an NTP server for timestamping.Bundled (`configTime()` on ESP32)

Block Diagram

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

Smart Pill Dispenser β€” system block diagramFunctional block diagram of the Smart Pill Dispenser system. ScheduleDS3231 RTCbattery backedDose table in NVSsurvives rebootPresentHome + stepto compartment nAlarm + LEDescalatingConfirmReflectance sensorempty or fullConfirm buttonuser actionReportAdherence logCSV exportCarer alerton missdose duepresentedoutcome
Smart Pill Dispenser β€” 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.

Smart Pill Dispenser β€” wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBTCRT5000 dose sensorGPIO 34Analogue reflectanceTCRT5000 emitterGPIO 32Pulsed for ambientsubtractionA3144 hall sensorGPIO 35Home position,pull-upConfirm buttonGPIO 33Pull-upManual release keyGPIO 39Pull-up, logged whenusedA4988 driverGPIO 25 / 26 / 27NEMA 17 carouseldriveBuzzerGPIO 14Escalating alarmStatus LED ringGPIO 12Green ready, amberdue, red missedDS3231 + OLEDGPIO 21 / 22Shared IΒ²C
Smart Pill Dispenser β€” wiring schematic
PeripheralPeripheral pinController pinSignal
TCRT5000 dose sensorAOGPIO 34Analogue reflectance
TCRT5000 emitterLED controlGPIO 32Pulsed for ambient subtraction
A3144 hall sensorOUTGPIO 35Home position, pull-up
Confirm buttonNOGPIO 33Pull-up
Manual release keyNOGPIO 39Pull-up, logged when used
A4988 driverSTEP / DIR / ENGPIO 25 / 26 / 27NEMA 17 carousel drive
Buzzer+GPIO 14Escalating alarm
Status LED ringDINGPIO 12Green ready, amber due, red missed
DS3231 + OLEDSDA / SCLGPIO 21 / 22Shared IΒ²C

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 reflectance sensor must be shielded from ambient light. Mount it inside a short black tube looking down into the presented compartment, and pulse the emitter so you can subtract the ambient reading β€” that technique is what makes it work in a sunlit room.
  • Place the hall sensor and its magnet so the home position is unambiguous β€” one magnet, one sensor, triggering exactly once per revolution. Two magnets or a wide trigger zone makes homing ambiguous and the carousel ends up half a compartment out.
  • The A4988 needs a 100 Β΅F capacitor across VMOT at the driver. Without it the driver dies from inductive spikes, and this is stated in bold in every Pololu document for a reason.
  • GPIO 34, 35 and 39 are input-only with no internal pull-ups. Fit external 10 kΞ© resistors.
  • Set the A4988 current limit before fitting the motor. A carousel is a light load β€” 0.6–0.8 A is ample and runs much cooler than the motor's rating.
  • Wire the manual release so it opens the lid mechanically, not through firmware. A person must never be prevented from reaching their own medication by a software fault.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
An ESP32 development board running the schedule, the carousel and the adherence log. 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.

Smart Pill Dispenser β€” architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) Β· TCRT5000 IR reflectance sensor moduleDriver layerwifi Β· pubsub Β· arduinojson Β· ssd1306Application logicsampling loop Β· filtering Β· thresholds Β· state machineTransport layerWi-Fi + MQTT Β· TLS Β· retry and backoffPresentation layerdashboard Β· mobile notifications Β· historical charts
Smart Pill Dispenser β€” architecture stack

Working Principle

The mechanical concept is a carousel with a single aperture. A 28-compartment disc rotates beneath a fixed lid that has exactly one opening. Whichever compartment is under the opening is accessible; the other 27 are physically covered. This is not a security mechanism β€” anyone determined can lift the whole lid β€” but it is an extremely effective error prevention mechanism, which is what medication management actually needs. The common failure is not theft, it is taking the wrong dose or a second dose by mistake.

Position is maintained by homing plus step counting. A stepper is open loop, so absolute position is only meaningful relative to a reference. A hall sensor and a single magnet define compartment zero; from there, each compartment is 200 Γ— 16 / 28 = 114.29 microsteps away at 1/16 microstepping. Because that is not an integer, the firmware accumulates a fractional step error and corrects it every revolution, and it re-homes daily so any accumulated slip is bounded.

Dose confirmation uses reflectance. A TCRT5000 emits infrared and measures how much comes back. A pill in the compartment reflects strongly; an empty black-printed compartment reflects weakly. The problem is ambient light, which in a sunlit room can swamp the emitter entirely. The solution is pulsed differential measurement: read with the emitter off, read with it on, and subtract. The difference is the reflected component of your own emission and is almost completely immune to ambient light, including the 100 Hz flicker from fluorescent lamps.

The escalation ladder is designed around what actually happens. Most missed doses are simply not noticed, so the first response is a louder local alarm five minutes later. Some are noticed and deferred, so the second response is a phone notification to the patient. Only the third stage, after roughly thirty minutes, involves a carer β€” because a carer alerted for every mild delay stops reading them. Each stage carries the outcome of the previous one, so the carer sees "reminded three times, still not taken" rather than a bare notification.

Finally, the manual release. It is tempting to build a device that cannot be opened outside the schedule. That is the wrong design: a person who needs a rescue medication, or whose schedule has legitimately changed, must be able to reach it. The correct compromise is that manual opening is possible, requires a deliberate act (a key), and is logged β€” so the record is complete rather than the mechanism being absolute.

The maths behind it

Carousel indexing

plainCarousel indexing
NEMA 17: 200 full steps/rev, 1/16 microstepping = 3200 microsteps/rev
28 compartments:
  steps per compartment = 3200 / 28 = 114.2857

Integer stepping accumulates error:
  114 Γ— 28 = 3192, short by 8 microsteps per revolution
  = 0.9Β° of drift per revolution

Fix: accumulate the fractional part.
  target_n = round(n Γ— 3200 / 28)
  step_to(target_n) from the homed zero

And re-home daily so any missed step is bounded to one day.

Pulsed reflectance with ambient rejection

plainPulsed reflectance with ambient rejection
ambient  = ADC with the IR emitter OFF
reflected = ADC with the IR emitter ON

  signal = reflected βˆ’ ambient

Measured on the reference build:
  empty compartment, dark room : 3180 βˆ’ 3140 =   40
  pill present,       dark room: 3180 βˆ’ 1420 = 1760
  empty compartment, sunlight  : 1100 βˆ’ 1060 =   40
  pill present,       sunlight :  980 βˆ’  420 = 1720

The raw values move by 2000 counts with ambient light;
the differential signal moves by 40. Threshold at 800.

Adherence rate

plainAdherence rate
Adherence = doses_taken_on_time / doses_scheduled Γ— 100

"On time" defined as within Β±60 min of schedule.

Over 30 days at 3 doses/day = 90 scheduled:
  taken on time  : 78
  taken late     :  7
  missed         :  5

  strict adherence  = 78/90 = 86.7 %
  taken at all      = 85/90 = 94.4 %

Report both. Clinically, timing matters for some drugs
(antibiotics, anti-epileptics) and much less for others.

Program Flowchart

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

Smart Pill Dispenser β€” firmware flowchartControl flow through the main program loop. Boot: home the carousel, loadscheduleWait for the next scheduleddose timeRotate to the next filledcompartmentSound alarm, light the ringamberCompartment empty within30 min?takenescalateLog taken with timestampAfter 3 escalations, alertcarerAdvance state, publishadherence
Smart Pill Dispenser β€” 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.

cpppill-dispenser.ino
/* ═══════════════════════════════════════════════════════════════
   Smart Pill Dispenser β€” ESP32 + NEMA 17 carousel + reflectance

   28-compartment carousel with a single aperture. Confirms the dose
   was actually removed using pulsed reflectance with ambient
   rejection, and escalates only when it was not.

   An adherence aid, not a clinical device.
   ══════════════════════════════════════════════════════════════════ */

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

#define WIFI_SSID "YOUR_WIFI"
#define WIFI_PASS "YOUR_PASSWORD"
#define MQTT_HOST "192.168.1.50"
#define DEVICE_ID "pillbox-01"

#define PIN_IR_SENSE 34
#define PIN_IR_EMIT  32
#define PIN_HALL     35
#define PIN_CONFIRM  33
#define PIN_KEY      39
#define PIN_STEP     25
#define PIN_DIR      26
#define PIN_EN       27
#define PIN_BUZZ     14

#define COMPARTMENTS      28
#define MICROSTEPS_REV  3200
#define IR_THRESHOLD     800
#define TAKE_WINDOW_MS  (30UL * 60UL * 1000UL)
#define ESCALATE_1_MS   ( 5UL * 60UL * 1000UL)
#define ESCALATE_2_MS   (15UL * 60UL * 1000UL)
#define MAX_DOSES          6

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WiFiClient       net;
PubSubClient     mqtt(net);
Preferences      prefs;

struct Dose { uint8_t hour, minute; char label[16]; bool enabled; };
Dose schedule[MAX_DOSES] = {
  {  8,  0, "Morning",  true },
  { 13,  0, "Midday",   true },
  { 20,  0, "Evening",  true },
  { 22, 30, "Bedtime", false },
};

long    currentStep = 0;             // microsteps from the homed zero
uint8_t currentCompartment = 0;
bool    filled[COMPARTMENTS];
bool    dosePending = false;
uint32_t presentedAt = 0;
uint8_t  escalation = 0;
int      lastFiredSlot = -1;
uint16_t takenCount = 0, missedCount = 0;

/* ── stepper ────────────────────────────────────────────────── */
void stepPulse(bool forward, uint16_t delayUs = 700) {
  digitalWrite(PIN_DIR, forward ? HIGH : LOW);
  digitalWrite(PIN_STEP, HIGH);
  delayMicroseconds(3);
  digitalWrite(PIN_STEP, LOW);
  delayMicroseconds(delayUs);
}

bool atHome() { return digitalRead(PIN_HALL) == LOW; }

bool homeCarousel() {
  digitalWrite(PIN_EN, LOW);
  // Move off the magnet first, so a boot that starts on it still works.
  for (int i = 0; i < 200 && atHome(); i++) stepPulse(true, 900);

  for (long i = 0; i < MICROSTEPS_REV * 2; i++) {
    stepPulse(true, 900);
    if (atHome()) {
      currentStep = 0;
      currentCompartment = 0;
      digitalWrite(PIN_EN, HIGH);
      Serial.println("Homed");
      return true;
    }
  }
  digitalWrite(PIN_EN, HIGH);
  Serial.println("HOMING FAILED β€” check the hall sensor and magnet");
  return false;
}

// Fractional accumulation avoids the 0.9 deg/rev drift of integer steps.
long stepsForCompartment(uint8_t n) {
  return lround((double)n * MICROSTEPS_REV / COMPARTMENTS);
}

void rotateTo(uint8_t compartment) {
  long target = stepsForCompartment(compartment);
  long delta = target - currentStep;
  if (delta < 0) delta += MICROSTEPS_REV;         // always forward

  digitalWrite(PIN_EN, LOW);
  delay(20);
  // Gentle ramp so the pills are not thrown out of their compartments.
  for (long i = 0; i < delta; i++) {
    uint16_t d = 1400;
    if (i > 100 && i < delta - 100) d = 600;
    stepPulse(true, d);
  }
  delay(200);
  digitalWrite(PIN_EN, HIGH);

  currentStep = target % MICROSTEPS_REV;
  currentCompartment = compartment;
}

/* ── pulsed reflectance ─────────────────────────────────────── */
int reflectance() {
  digitalWrite(PIN_IR_EMIT, LOW);
  delayMicroseconds(500);
  uint32_t ambient = 0;
  for (int i = 0; i < 8; i++) { ambient += analogRead(PIN_IR_SENSE); delayMicroseconds(200); }

  digitalWrite(PIN_IR_EMIT, HIGH);
  delayMicroseconds(500);                          // let the emitter settle
  uint32_t lit = 0;
  for (int i = 0; i < 8; i++) { lit += analogRead(PIN_IR_SENSE); delayMicroseconds(200); }
  digitalWrite(PIN_IR_EMIT, LOW);

  // TCRT5000 output falls when reflection rises, so ambient βˆ’ lit.
  return (int)((ambient - lit) / 8);
}

bool compartmentHasPill() { return reflectance() > IR_THRESHOLD; }

/* ── alarms ─────────────────────────────────────────────────── */
void chime(uint8_t level) {
  for (uint8_t i = 0; i <= level; i++) {
    tone(PIN_BUZZ, 1800 + level * 250, 200);
    delay(280);
  }
}

/* ── MQTT ───────────────────────────────────────────────────── */
void publishEvent(const char *event, const char *label, uint8_t compartment) {
  JsonDocument d;
  d["device"]      = DEVICE_ID;
  d["event"]       = event;
  d["dose"]        = label;
  d["compartment"] = compartment;
  d["ts"]          = (uint32_t)time(nullptr);
  d["escalation"]  = escalation;
  d["taken"]       = takenCount;
  d["missed"]      = missedCount;
  d["adherence"]   = (takenCount + missedCount)
                   ? roundf(takenCount * 1000.0f / (takenCount + missedCount)) / 10.0f : 100.0f;
  uint8_t remaining = 0;
  for (bool f : filled) if (f) remaining++;
  d["remaining"] = remaining;

  char buf[288];
  size_t n = serializeJson(d, buf, sizeof(buf));
  mqtt.publish("care/" DEVICE_ID "/dose", (uint8_t *)buf, n, false);
  Serial.println(buf);
}

/* ── the dose cycle ─────────────────────────────────────────── */
uint8_t nextFilledCompartment() {
  for (uint8_t i = 1; i <= COMPARTMENTS; i++) {
    uint8_t c = (currentCompartment + i) % COMPARTMENTS;
    if (filled[c]) return c;
  }
  return 0xFF;                                     // none left
}

void presentDose(const char *label) {
  uint8_t c = nextFilledCompartment();
  if (c == 0xFF) {
    publishEvent("empty", label, 0);
    chime(3);
    return;
  }
  rotateTo(c);
  delay(400);

  if (!compartmentHasPill()) {                     // sanity check
    publishEvent("compartment-empty", label, c);
    filled[c] = false;
    prefs.putBytes("filled", filled, sizeof(filled));
    presentDose(label);                            // try the next one
    return;
  }

  dosePending = true;
  presentedAt = millis();
  escalation = 0;
  publishEvent("presented", label, c);
  chime(0);
}

void serviceDose(const char *label) {
  if (!dosePending) return;
  uint32_t elapsed = millis() - presentedAt;

  if (!compartmentHasPill()) {                     // it was removed
    dosePending = false;
    filled[currentCompartment] = false;
    prefs.putBytes("filled", filled, sizeof(filled));
    takenCount++;
    prefs.putUShort("taken", takenCount);
    publishEvent("taken", label, currentCompartment);
    tone(PIN_BUZZ, 2600, 250);
    return;
  }

  if (elapsed > ESCALATE_1_MS && escalation == 0) {
    escalation = 1; chime(1); publishEvent("reminder", label, currentCompartment);
  } else if (elapsed > ESCALATE_2_MS && escalation == 1) {
    escalation = 2; chime(2); publishEvent("reminder-2", label, currentCompartment);
  } else if (elapsed > TAKE_WINDOW_MS) {
    dosePending = false;
    missedCount++;
    prefs.putUShort("missed", missedCount);
    escalation = 3;
    publishEvent("missed", label, currentCompartment);   // carer alert stage
    chime(3);
  }
}

/* ── display ────────────────────────────────────────────────── */
void draw(const char *nextLabel, int minsToNext) {
  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);

  if (dosePending) {
    oled.setTextSize(2); oled.setCursor(0, 4);  oled.print("TAKE NOW");
    oled.setTextSize(1); oled.setCursor(0, 26);
    oled.printf("%s dose is open", nextLabel);
    oled.setCursor(0, 40);
    oled.printf("%lu min remaining", (TAKE_WINDOW_MS - (millis() - presentedAt)) / 60000);
  } else {
    oled.setTextSize(1); oled.setCursor(0, 0);  oled.print("Next dose");
    oled.setTextSize(2); oled.setCursor(0, 12); oled.print(nextLabel);
    oled.setTextSize(1); oled.setCursor(0, 34);
    if (minsToNext >= 0) oled.printf("in %d h %d min", minsToNext / 60, minsToNext % 60);
  }

  uint8_t remaining = 0;
  for (bool f : filled) if (f) remaining++;
  oled.setCursor(0, 52);
  oled.printf("%u doses left  %.0f%%", remaining,
              (takenCount + missedCount) ? takenCount * 100.0f / (takenCount + missedCount) : 100.0f);
  oled.display();
}

/* ── setup / loop ───────────────────────────────────────────── */
void setup() {
  Serial.begin(115200);
  pinMode(PIN_IR_EMIT, OUTPUT); digitalWrite(PIN_IR_EMIT, LOW);
  pinMode(PIN_HALL, INPUT); pinMode(PIN_CONFIRM, INPUT_PULLUP);
  pinMode(PIN_KEY, INPUT);
  pinMode(PIN_STEP, OUTPUT); pinMode(PIN_DIR, OUTPUT);
  pinMode(PIN_EN, OUTPUT); digitalWrite(PIN_EN, HIGH);
  analogSetPinAttenuation(PIN_IR_SENSE, ADC_11db);

  Wire.begin(21, 22);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  prefs.begin("pillbox", false);
  if (prefs.getBytesLength("filled") == sizeof(filled))
    prefs.getBytes("filled", filled, sizeof(filled));
  else
    for (bool &f : filled) f = true;
  takenCount  = prefs.getUShort("taken", 0);
  missedCount = prefs.getUShort("missed", 0);

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

  homeCarousel();
  Serial.println("Dispenser ready");
}

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

  static const char *activeLabel = "β€”";

  time_t now = time(nullptr);
  struct tm tmv; localtime_r(&now, &tmv);
  int slot = tmv.tm_hour * 60 + tmv.tm_min;

  /* Fire scheduled doses, once per minute slot. */
  if (slot != lastFiredSlot) {
    for (auto &d : schedule) {
      if (!d.enabled) continue;
      if (d.hour == tmv.tm_hour && d.minute == tmv.tm_min) {
        lastFiredSlot = slot;
        activeLabel = d.label;
        presentDose(d.label);
      }
    }
  }

  /* Manual key release: allowed, but always logged. */
  if (digitalRead(PIN_KEY) == LOW) {
    delay(60);
    if (digitalRead(PIN_KEY) == LOW) {
      publishEvent("manual-release", activeLabel, currentCompartment);
      digitalWrite(PIN_EN, LOW);
      delay(50);
      digitalWrite(PIN_EN, HIGH);
      while (digitalRead(PIN_KEY) == LOW) delay(20);
    }
  }

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

  serviceDose(activeLabel);

  /* Time to the next enabled dose, for the display. */
  int best = -1;
  for (auto &d : schedule) {
    if (!d.enabled) continue;
    int m = d.hour * 60 + d.minute - slot;
    if (m < 0) m += 1440;
    if (best < 0 || m < best) { best = m; activeLabel = d.label; }
  }
  draw(activeLabel, best);

  /* Re-home once a day at 03:00 to bound accumulated step error. */
  static int lastHomeDay = -1;
  if (tmv.tm_hour == 3 && tmv.tm_yday != lastHomeDay && !dosePending) {
    lastHomeDay = tmv.tm_yday;
    homeCarousel();
  }
}
reflectance() pulsed differentialReading with the emitter off and then on, and subtracting, removes ambient light almost entirely. Without it the sensor works perfectly on a bench and fails completely next to a window β€” which is where a real dispenser sits.
ambient βˆ’ lit, not lit βˆ’ ambientThe TCRT5000 module output falls as reflection increases, because the phototransistor pulls the output down. Getting this sign backwards gives a sensor that reports a pill when the compartment is empty.
stepsForCompartment with lround3200 / 28 is not an integer. Rounding each absolute target rather than accumulating integer increments keeps the maximum error at half a microstep instead of drifting 0.9Β° per revolution.
Gentle ramp in rotateToSlow at the start and end, faster in the middle. A carousel accelerated hard throws small tablets out of their compartments β€” which is a failure that only shows up after the device is loaded with real medication.
presentDose recursion on empty compartmentIf the sensor says the compartment the schedule pointed at is already empty, the state is stale. Rather than presenting nothing, it corrects its record and moves on to the next filled compartment.
Manual release logged, not blockedA person must never be prevented from reaching their own medication by a software fault. The key makes it deliberate; the log keeps the adherence record complete.
Daily re-home at 03:00Open-loop step counting drifts if any step is missed. Re-homing once a day bounds the worst-case error to one day of use, and 03:00 is chosen because no dose is scheduled then.

Configuration & Calibration

Configuration steps

  • Set the dose schedule in the schedule[] array, or push it over MQTT and persist to NVS. Labels appear on the display and in the log, so make them meaningful to the user.
  • Set IR_THRESHOLD from measurements: read the differential value with a compartment empty and with a typical tablet in it, and pick the midpoint.
  • Set TAKE_WINDOW_MS from the medication. Thirty minutes suits most; a drug with tight timing requirements may want fifteen.
  • Set the A4988 current limit to about 0.7 A. A carousel is a light load and running cool matters more than torque here.
  • Configure carer escalation in Node-RED, not firmware. Contacts change; firmware in a device on someone's kitchen counter should not have to.

Calibration procedure

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

  1. Calibrate the reflectance threshold

    Read the differential value ten times with an empty compartment and ten times with each type of tablet you will dispense. Small white tablets reflect more than large dark capsules; set the threshold below the weakest reflector, and verify in both a dark room and direct sunlight.

  2. Verify compartment alignment

    Home, then rotate through all 28 compartments and check each lines up with the aperture. Cumulative misalignment by the 28th means the fractional step accumulation is not working or steps are being lost β€” reduce speed and increase current slightly.

  3. Test the ramp with real tablets

    Load small tablets and rotate a full revolution. Nothing should hop between compartments. If it does, lengthen the acceleration ramp and reduce the top speed.

  4. Time the full escalation

    Trigger a dose and ignore it completely. Verify the reminder at 5 minutes, the second at 15, and the carer alert at 30, and that each notification actually arrives.

Network Architecture & Connectivity

Smart Pill Dispenser β€” network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsDispenserESP32 + RTCWi-Fi 2.4 GHzRouterschedule works without itMQTT 1883Local broker +Node-REDescalationPatient phoneremindersCarer phonemisses onlyAdherence reportCSV
Smart Pill Dispenser β€” network topology
Topic / endpointDirectionPayload
care/pillbox-01/dosedevice β†’ brokerJSON: event, dose, compartment, ts, escalation, taken, missed, adherence, remaining
care/pillbox-01/cmdbroker β†’ deviceJSON: action = schedule | refill | home
care/pillbox-01/statusdevice β†’ broker (retained)"online" / "offline" (LWT)

Message contract between the device and the broker.

Dashboard setup

The chart that matters clinically is dose timing scatter β€” scheduled time on one axis, actual time taken on the other, over a month. A tight cluster on the diagonal is good adherence; systematic lateness on one dose reveals which time of day is the problem, which is actionable in a way that a single adherence percentage is not.

Security considerations

  • Medication data is health data. Keep it on a local broker with authentication, and do not route it through a third-party cloud service without understanding where it is stored.
  • The escalation flow should not be able to open the dispenser. Command topics can set the schedule and trigger a re-home; dispensing outside schedule requires the physical key.
  • Add a Last Will. A dispenser that has silently died looks exactly like a patient who has taken every dose on time.

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 onThe carousel homes within one revolution and the display shows the next dose.
Read reflectance with a compartment empty and fullA differential of under 100 empty and over 1500 with a tablet β€” a clear separation.
Repeat in direct sunlightDifferential values within about 10 % of the dark-room values. Large variation means the pulsed subtraction is not working.
Trigger a scheduled doseThe carousel rotates smoothly to the next filled compartment, chimes, and the display shows "TAKE NOW".
Remove the tabletDetection within about two seconds, a confirmation tone, and a taken event published.
Ignore a dose for 35 minutesReminders at 5 and 15 minutes, then a missed event and carer alert at 30.
Turn the manual keyThe carousel unlocks and a manual-release event is logged β€” allowed, but recorded.
Power-cycle mid-scheduleThe carousel re-homes, the filled-compartment map is restored from NVS, and the schedule resumes.

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

Dose detection works at night and fails during the day

Likely cause. Ambient light swamping the reflectance sensor.

Fix. Confirm the pulsed differential measurement is running β€” read with the emitter off, then on, and subtract. Also shield the sensor in a short black tube and make sure the lid is opaque rather than translucent.

The carousel drifts out of alignment over days

Likely cause. Missed steps, or integer step accumulation.

Fix. Use absolute rounded targets rather than accumulating increments, re-home daily, reduce top speed, and raise the driver current slightly. Check nothing is binding β€” a carousel that rubs on the lid loses steps at exactly the same place every revolution.

Tablets hop between compartments during rotation

Likely cause. Acceleration too aggressive.

Fix. Lengthen the ramp at both ends and lower the cruise speed. A dispenser has no reason to move fast; two seconds per compartment is perfectly acceptable and eliminates the problem.

Homing fails or finds the wrong position

Likely cause. Multiple magnets, a magnet too far from the hall sensor, or the wrong magnetic pole.

Fix. A3144 sensors are unipolar β€” only one pole triggers them. Flip the magnet. Use exactly one magnet and confirm the sensor changes state cleanly by hand before running the homing routine.

Doses fire twice at the same time

Likely cause. The scheduled-minute check runs faster than once a minute and the guard is not working.

Fix. The lastFiredSlot guard must be set before the dose is presented and compared against the current minute-of-day. Verify it is not being reset elsewhere in the loop.

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

  • Read the reflectance sensor every two seconds while a dose is pending, not every loop. Eight averaged ADC pairs per reading is 16 conversions and there is no benefit to doing it faster.
  • De-energise the stepper between moves. A carousel has no holding-torque requirement and an energised stepper draws its full rated current continuously.
  • Keep the schedule check gated to one firing per minute slot β€” the most common bug in scheduled devices is firing repeatedly within the same minute.
  • 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

  • Never let this be the only medication safeguard. Discuss it with the prescribing clinician. It reduces error; it does not eliminate the need for oversight.
  • The manual release must always work. A person locked away from a rescue medication by a software fault is a far worse outcome than an occasional double dose.
  • Do not store medication in a hot enclosure. Many drugs degrade above 25–30 Β°C, and a sealed box with a stepper driver inside gets warm. Vent it and keep the driver current low.
  • Label the device clearly with what it contains and keep it out of reach of children β€” a carousel with 28 doses in it is a significant quantity of medication in one place.
  • Moving parts pinch. Keep fingers, cables and hair out of gear trains and wheels, and always test motion with the drivetrain unloaded and the robot on blocks first.
  • Motors are inductive β€” always fit a flyback diode across a DC coil, or use a driver that already has one, or the back-EMF spike will destroy your GPIO.
  • 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

  • Clean the compartments and the sensor window weekly β€” tablet dust builds up and shifts the reflectance baseline.
  • Refill on a fixed day and confirm the filled-compartment map matches reality afterwards.
  • Replace the DS3231 backup cell every three to four years.
  • 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 a load cell under the carousel to weigh doses, distinguishing "one tablet taken" from "the whole compartment emptied".
  • Add a camera that photographs the compartment after presentation, giving a visual audit trail for a clinical review.
  • Add multiple carousels for medications with different schedules, so a four-times-daily drug and a weekly one do not have to share one disc.
  • Add temperature and humidity logging inside the enclosure, since many drugs have storage requirements that a warm kitchen breaches.
  • Add pharmacy integration so the low-stock warning triggers a repeat prescription request rather than just a notification.
  • 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

Why a carousel rather than separate compartments with lids?

Individual servo-driven lids are 28 actuators, 28 failure points and a great deal of wiring. A single carousel with one aperture achieves the same physical dose control with one motor. It also means the mechanism cannot partially fail β€” either the carousel is at the right position or it is not, and homing tells you which.

How does it know the dose was taken and not just knocked out?

It does not, and that is an honest limitation. The reflectance sensor reports that the compartment is empty. Adding a load cell under the carousel would distinguish a tablet removed from a tablet spilled, and photographing the compartment gives a visual record. For most users the empty-compartment signal is a large improvement over no signal at all.

What if the power fails?

The RTC keeps time on its backup cell and the filled-compartment map is in NVS, so the schedule resumes correctly on restore. The carousel re-homes at boot, which takes about ten seconds. A dose scheduled during the outage is missed and logged as such β€” adding a small UPS is worthwhile if outages are common.

Can it handle liquid medication or inhalers?

No. This mechanism is for solid oral doses. Liquids need a peristaltic pump and completely different confirmation, and inhalers need dose counting on the device itself. Both are legitimate separate projects.

Is a 30-minute window right?

It depends entirely on the drug. Antibiotics and anti-epileptics genuinely need consistent timing; a daily statin does not care about half an hour. Make it configurable per dose rather than global, and set it from the prescribing information rather than convenience.

What about someone who cannot manage the confirm button?

They do not need to β€” confirmation is optical, not by button press. The button exists only to silence the alarm early. That is deliberate: any design that requires a specific user action to register a dose will produce false "missed" alerts for exactly the users who most need the device.

References & Learning Resources

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

  1. WHO, "Adherence to Long-Term Therapies: Evidence for Action"World Health Organization
  2. TCRT5000 reflective optical sensor β€” datasheetVishay
  3. A4988 microstepping driver β€” datasheet and current limit settingAllegro / Pololu
  4. DS3231 extremely accurate RTC β€” datasheetAnalog Devices
  5. Checchi et al., "Electronic medication packaging devices and medication adherence: a systematic review"JAMA, 2014
  6. USP General Chapter <1079> β€” good storage and distribution practices for drug productsUnited States Pharmacopeia