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.
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
| Setting | How it is used |
|---|---|
| Elderly polypharmacy | The core case β several medications at several times, where confusion about what was already taken is common and consequential. |
| Post-discharge medication | The weeks after a hospital stay have the highest non-adherence and the highest readmission risk. |
| Chronic condition management | Diabetes, hypertension and epilepsy all depend on consistent timing rather than just consistent quantity. |
| Clinical trial compliance | A timestamped adherence log is far stronger evidence than a patient diary. |
| Care home rounds | Multiple dispensers with a central dashboard showing which residents have missed doses. |
| Cognitive impairment support | A 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
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 14β20 hours |
| Indicative build cost | βΉ5,600 β βΉ7,200 |
| 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 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.
| 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 |
| 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Β·cm | 1 | βΉ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 out | 1 | βΉ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 Β°C | 1 | βΉ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Β²C | 1 | βΉ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 out | 1 | βΉ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 diameter | 1 | βΉ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 % efficiency | 1 | βΉ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 barrel | 1 | βΉ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 grid | 1 | βΉ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 lugs | 1 | βΉ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 depth | 1 | βΉ450 |
| Neodymium magnet 5 Γ 2 mm | For the hall-effect home position | 1 | βΉ30 |
| Large confirm button + status LEDs | 16 mm illuminated, NO | 1 | βΉ140 |
| Manual release key switch A carer-held key is the right balance between safety and preventing accidental double dosing. | Keyed, 2-position | 1 | βΉ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
| 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 |
| A4988 stepper driver + NEMA 17 motor | 1.5 A/phase with heatsink, 1/16 microstepping, 8β35 V; NEMA 17 = 4.4 kgΒ·cm | 8β35 V | STEP/DIR | Datasheet |
| TCRT5000 IR reflectance sensor module | 1β8 mm optimum sensing gap, 950 nm emitter, analogue + digital out | 3.3β5 V | Analogue + digital | Datasheet |
| A3144 hall-effect switch | Unipolar, 3.5β24 V, open-collector output, 100 kHz, β40 to +85 Β°C | 4.5β24 V | Digital (needs pull-up) | 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 |
| DS3231 precision RTC + CR2032 backup | Β±2 ppm (Β±1 min/year), temperature-compensated crystal, alarms, 32 kHz out | 2.3β5.5 V | IΒ²C (0x68) | Datasheet |
| Active piezo buzzer 5 V | 85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter | 3β5 V | Digital / PWM | Datasheet |
| LM2596 adjustable buck converter module | 4.5β40 V in, 1.25β37 V out, 2 A (3 A peak), ~92 % efficiency | 4.5β40 V | Screw terminals + trimmer | Datasheet |
| 12 V 5 A SMPS adapter | 100β240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ 2.1 mm barrel | 12 V | DC barrel | Datasheet |
| Double-sided perfboard 7 Γ 9 cm + headers | FR-4, 0.1β³ pitch, plated through-holes, 24 Γ 18 grid | β | β | Datasheet |
| IP65 ABS junction enclosure 158 Γ 90 Γ 60 mm | IP65, 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.
| 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. |
| A4988 stepper driver + NEMA 17 motor | 8β35 V | 1500 | Set Vref = I_max Γ 8 Γ Rsense before the first move or you cook the driver. |
| TCRT5000 IR reflectance sensor module | 3.3β5 V | 20 | Ambient sunlight saturates it β shroud the sensor on outdoor robots. |
| A3144 hall-effect switch | 4.5β24 V | 9 | Unipolar β only one magnet pole triggers it. Flip the magnet if nothing happens. |
| 0.96β³ SSD1306 OLED display | 3.3β5 V | 20 | Static images burn in β invert or scroll the screen periodically. |
| DS3231 precision RTC + CR2032 backup | 2.3β5.5 V | 0.2 | Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell β cut that resistor. |
| Active piezo buzzer 5 V | 3β5 V | 30 | Active buzzers make tone on DC; passive ones need a PWM carrier. |
| LM2596 adjustable buck converter module | 4.5β40 V | 8 | Set the output voltage with no load connected before wiring the board. |
| 12 V 5 A SMPS adapter | 12 V | 5000 | Fuse 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.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 |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager β "PubSubClient" by Nick O'Leary |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager β "ArduinoJson" by Benoit Blanchon |
| 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 |
| NTPClient / configTime bundled | Wall-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.
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 |
|---|---|---|---|
| TCRT5000 dose sensor | AO | GPIO 34 | Analogue reflectance |
| TCRT5000 emitter | LED control | GPIO 32 | Pulsed for ambient subtraction |
| A3144 hall sensor | OUT | GPIO 35 | Home position, pull-up |
| Confirm button | NO | GPIO 33 | Pull-up |
| Manual release key | NO | GPIO 39 | Pull-up, logged when used |
| A4988 driver | STEP / DIR / EN | GPIO 25 / 26 / 27 | NEMA 17 carousel drive |
| Buzzer | + | GPIO 14 | Escalating alarm |
| Status LED ring | DIN | GPIO 12 | Green ready, amber due, red missed |
| DS3231 + OLED | SDA / SCL | GPIO 21 / 22 | Shared 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.
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 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
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
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
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.
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.
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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();
}
}
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_THRESHOLDfrom measurements: read the differential value with a compartment empty and with a typical tablet in it, and pick the midpoint. - Set
TAKE_WINDOW_MSfrom 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.
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.
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.
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.
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
| Topic / endpoint | Direction | Payload |
|---|---|---|
care/pillbox-01/dose | device β broker | JSON: event, dose, compartment, ts, escalation, taken, missed, adherence, remaining |
care/pillbox-01/cmd | broker β device | JSON: action = schedule | refill | home |
care/pillbox-01/status | device β 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.
| Test | What you should see |
|---|---|
| Power on | The carousel homes within one revolution and the display shows the next dose. |
| Read reflectance with a compartment empty and full | A differential of under 100 empty and over 1500 with a tablet β a clear separation. |
| Repeat in direct sunlight | Differential values within about 10 % of the dark-room values. Large variation means the pulsed subtraction is not working. |
| Trigger a scheduled dose | The carousel rotates smoothly to the next filled compartment, chimes, and the display shows "TAKE NOW". |
| Remove the tablet | Detection within about two seconds, a confirmation tone, and a taken event published. |
| Ignore a dose for 35 minutes | Reminders at 5 and 15 minutes, then a missed event and carer alert at 30. |
| Turn the manual key | The carousel unlocks and a manual-release event is logged β allowed, but recorded. |
| Power-cycle mid-schedule | The 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
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 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. - 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
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- WHO, "Adherence to Long-Term Therapies: Evidence for Action"World Health Organization
- TCRT5000 reflective optical sensor β datasheetVishay
- A4988 microstepping driver β datasheet and current limit settingAllegro / Pololu
- DS3231 extremely accurate RTC β datasheetAnalog Devices
- Checchi et al., "Electronic medication packaging devices and medication adherence: a systematic review"JAMA, 2014
- USP General Chapter <1079> β good storage and distribution practices for drug productsUnited States Pharmacopeia