/*
VITALINK | Simulacion de hardware v1.0 para Wokwi (ESP32)
--------------------------------------------------------
Componentes: ESP32, LCD 16x2 I2C, reloj DS1307 (sustituye
al DS3231 en Wokwi), HX711/celda virtual de 5 kg, interruptor
de puerta (sustituye reed switch), buzzer, 2 LED y 2 botones.
SIN LIBRERIAS EXTERNAS: solo usa Wire.h del nucleo Arduino.
Horarios: 08:00, 14:00, 20:00.
El DS1307 de diagram.json comienza a las 07:59:45 para que
la alarma de las 08:00 aparezca ~15 s despues de iniciar.
BOTON VERDE (GPIO 32): confirmar la toma cuando hay alarma.
BOTON AZUL (GPIO 33): activar alarma de prueba o, si esta
sonando, posponerla 60 segundos.
INTERRUPTOR (GPIO 27): izquierda=cerrado; derecha=abierto.
HX711: haz clic y cambia la carga en su control de Wokwi.
IMPORTANTE: abrir la caja, bajar el peso o pulsar confirmar
NO demuestra que la persona haya ingerido el medicamento.
Esta es una demostracion del hardware, NO un dispositivo medico.
*/
#include <Arduino.h>
#include <Wire.h>
// -------- Pines ESP32 (coinciden exactamente con diagram.json) --------
constexpr uint8_t PIN_SDA = 21;
constexpr uint8_t PIN_SCL = 22;
constexpr uint8_t PIN_HX_DT = 18;
constexpr uint8_t PIN_HX_SCK = 19;
constexpr uint8_t PIN_PUERTA = 27;
constexpr uint8_t PIN_LED_ROJO = 25;
constexpr uint8_t PIN_LED_VERDE= 26;
constexpr uint8_t PIN_BUZZER = 14;
constexpr uint8_t PIN_CONFIRMAR= 32;
constexpr uint8_t PIN_PRUEBA = 33;
constexpr uint8_t DIRECCION_LCD = 0x27;
constexpr uint8_t DIRECCION_RTC = 0x68;
// Solo ilustrativos: en el montaje fisico se debe calibrar la celda.
// El HX711 virtual de 5 kg en Wokwi usa aproximadamente 0..2100 cuentas.
constexpr float CUENTAS_POR_GRAMO = 2100.0f / 5000.0f;
constexpr float UMBRAL_RETIRO_G = 2.0f;
constexpr unsigned long TIEMPO_POSPONER_MS = 60000UL;
constexpr unsigned long TIEMPO_AVISO_OK_MS = 4000UL;
const uint8_t HORARIOS[][2] = {{8, 0}, {14, 0}, {20, 0}};
struct HoraRTC {
uint8_t segundo = 0;
uint8_t minuto = 0;
uint8_t hora = 0;
uint8_t dia = 0;
uint8_t mes = 0;
bool disponible = false;
};
HoraRTC reloj;
bool alarmaActiva = false;
bool puertaAbierta = false;
bool seAbrioDuranteAlarma = false;
bool posibleRetiro = false;
bool zumbadorEncendido = false;
bool confirmadoRecientemente = false;
bool avisoPospuesto = false;
bool pesoDisponible = false;
float pesoGramos = 0.0f;
float pesoInicialAlarma = 0.0f;
unsigned long pospuestoHasta = 0;
unsigned long confirmacionHasta = 0;
unsigned long ultimaLecturaReloj = 0;
unsigned long ultimaLecturaPeso = 0;
unsigned long ultimaPantalla = 0;
unsigned long ultimoSerial = 0;
uint32_t ultimaAlarmaProgramada = 0;
// ----------------------- LCD I2C sin bibliotecas extra -----------------
// PCF8574: P0=RS, P1=RW, P2=EN, P3=backlight, P4..P7=datos.
void lcdExpansor(uint8_t valor) {
Wire.beginTransmission(DIRECCION_LCD);
Wire.write(valor | 0x08); // Retroiluminacion encendida
Wire.endTransmission();
}
void lcdNibble(uint8_t nibbleYControl) {
lcdExpansor(nibbleYControl | 0x04); // Enable alto
delayMicroseconds(2);
lcdExpansor(nibbleYControl & (uint8_t)~0x04); // Enable bajo
delayMicroseconds(50);
}
void lcdEnviar(uint8_t valor, bool esDato) {
uint8_t modo = esDato ? 0x01 : 0x00;
lcdNibble((valor & 0xF0) | modo);
lcdNibble(((valor << 4) & 0xF0) | modo);
}
void lcdComando(uint8_t comando) {
lcdEnviar(comando, false);
if (comando == 0x01 || comando == 0x02) delay(2);
}
void lcdIniciar() {
delay(50);
lcdNibble(0x30); delay(5);
lcdNibble(0x30); delayMicroseconds(200);
lcdNibble(0x30); delayMicroseconds(200);
lcdNibble(0x20); // Bus de 4 bits
lcdComando(0x28); // 2 lineas
lcdComando(0x0C); // Pantalla visible, cursor apagado
lcdComando(0x06); // Incrementar posicion
lcdComando(0x01); // Limpiar
}
void lcdLinea(uint8_t fila, const char* mensaje) {
lcdComando(fila == 0 ? 0x80 : 0xC0);
for (uint8_t i = 0; i < 16; i++) {
char letra = mensaje[i];
if (letra == '\0') {
while (i < 16) { lcdEnviar(' ', true); i++; }
break;
}
lcdEnviar((uint8_t)letra, true);
}
}
// ----------------------- Reloj DS1307 por Wire --------------------------
uint8_t desdeBCD(uint8_t dato) {
return ((dato >> 4) * 10) + (dato & 0x0F);
}
bool leerRTC(HoraRTC& h) {
Wire.beginTransmission(DIRECCION_RTC);
Wire.write((uint8_t)0x00);
if (Wire.endTransmission(false) != 0) return false;
if (Wire.requestFrom(DIRECCION_RTC, (uint8_t)7) != 7) return false;
h.segundo = desdeBCD(Wire.read() & 0x7F);
h.minuto = desdeBCD(Wire.read() & 0x7F);
uint8_t regHora = Wire.read();
// El ejemplo usa el modo 24 h que trae el DS1307 virtual.
h.hora = desdeBCD(regHora & 0x3F);
Wire.read(); // Dia de la semana
h.dia = desdeBCD(Wire.read() & 0x3F);
h.mes = desdeBCD(Wire.read() & 0x1F);
Wire.read(); // Ano
h.disponible = true;
return true;
}
// ----------------------- HX711 por pulsos digitales --------------------
bool leerHX711(int32_t& lectura) {
if (digitalRead(PIN_HX_DT) == HIGH) return false; // Aun no listo
uint32_t dato = 0;
for (int i = 0; i < 24; i++) {
digitalWrite(PIN_HX_SCK, HIGH);
delayMicroseconds(2);
dato = (dato << 1) | (digitalRead(PIN_HX_DT) ? 1U : 0U);
digitalWrite(PIN_HX_SCK, LOW);
delayMicroseconds(2);
}
// Pulso 25: seleccionar canal A con ganancia de 128.
digitalWrite(PIN_HX_SCK, HIGH);
delayMicroseconds(2);
digitalWrite(PIN_HX_SCK, LOW);
delayMicroseconds(2);
// Extender signo de 24 a 32 bits.
if (dato & 0x800000UL) dato |= 0xFF000000UL;
lectura = static_cast<int32_t>(dato);
return true;
}
// ----------------------- Logica de recordatorios -----------------------
void apagarZumbador() {
if (zumbadorEncendido) {
noTone(PIN_BUZZER);
zumbadorEncendido = false;
}
}
void iniciarAlarma(const char* motivo) {
alarmaActiva = true;
avisoPospuesto = false;
confirmadoRecientemente = false;
seAbrioDuranteAlarma = false;
posibleRetiro = false;
pesoInicialAlarma = pesoGramos;
Serial.print("[VITALINK] ALARMA: ");
Serial.println(motivo);
Serial.println("Abre el compartimento y pulsa CONFIRMAR cuando corresponda.");
}
void confirmarAlarma() {
if (!alarmaActiva) return;
alarmaActiva = false;
avisoPospuesto = false;
confirmadoRecientemente = true;
confirmacionHasta = millis() + TIEMPO_AVISO_OK_MS;
apagarZumbador();
Serial.println("[VITALINK] Confirmacion manual registrada.");
if (seAbrioDuranteAlarma) Serial.println("[VITALINK] Se detecto apertura de tapa.");
if (posibleRetiro) Serial.println("[VITALINK] Se detecto posible retiro por cambio de peso.");
Serial.println("NOTA: estos eventos NO verifican ingestion.");
}
void posponerAlarma() {
if (!alarmaActiva) return;
alarmaActiva = false;
avisoPospuesto = true;
pospuestoHasta = millis() + TIEMPO_POSPONER_MS;
apagarZumbador();
Serial.println("[VITALINK] Alarma pospuesta 60 segundos.");
}
void comprobarHorarios() {
if (!reloj.disponible || alarmaActiva || avisoPospuesto) return;
for (const auto& h : HORARIOS) {
if (reloj.hora == h[0] && reloj.minuto == h[1]) {
// Una sola activacion por mes/dia/hora/minuto.
uint32_t clave = ((uint32_t)reloj.mes * 1000000UL)
+ ((uint32_t)reloj.dia * 10000UL)
+ ((uint32_t)reloj.hora * 100UL)
+ reloj.minuto;
if (clave != ultimaAlarmaProgramada) {
ultimaAlarmaProgramada = clave;
iniciarAlarma("Horario programado");
}
break;
}
}
}
void actualizarZumbador() {
const bool sonar = alarmaActiva && ((millis() % 1300UL) < 210UL);
if (sonar && !zumbadorEncendido) {
tone(PIN_BUZZER, 950);
zumbadorEncendido = true;
} else if (!sonar && zumbadorEncendido) {
apagarZumbador();
}
}
void actualizarPantalla() {
char fila0[17];
char fila1[17];
unsigned long ahora = millis();
if (alarmaActiva) {
snprintf(fila0, sizeof(fila0), "HORA DE LA TOMA");
if (posibleRetiro) {
snprintf(fila1, sizeof(fila1), "POSIBLE RETIRO");
} else if (puertaAbierta) {
snprintf(fila1, sizeof(fila1), "TAPA ABIERTA");
} else {
snprintf(fila1, sizeof(fila1), "ABRE Y CONFIRMA");
}
} else if (avisoPospuesto) {
snprintf(fila0, sizeof(fila0), "TOMA POSPUESTA");
unsigned long restante = (int32_t)(pospuestoHasta - ahora) > 0
? (pospuestoHasta - ahora + 999UL) / 1000UL : 0;
snprintf(fila1, sizeof(fila1), "REAVISO EN %lus", restante);
} else if (confirmadoRecientemente && (int32_t)(confirmacionHasta - ahora) > 0) {
snprintf(fila0, sizeof(fila0), "TOMA CONFIRMADA");
snprintf(fila1, sizeof(fila1), "REGISTRO MANUAL");
} else {
confirmadoRecientemente = false;
if (reloj.disponible) {
snprintf(fila0, sizeof(fila0), "VITALINK %02u:%02u",
reloj.hora, reloj.minuto);
} else {
snprintf(fila0, sizeof(fila0), "VITALINK SIN RTC");
}
if ((ahora / 3000UL) % 2 == 0) {
snprintf(fila1, sizeof(fila1), "%s", puertaAbierta ? "TAPA ABIERTA" : "TAPA CERRADA");
} else if (pesoDisponible) {
snprintf(fila1, sizeof(fila1), "PESO: %6.1f g", pesoGramos);
} else {
snprintf(fila1, sizeof(fila1), "LEYENDO HX711...");
}
}
lcdLinea(0, fila0);
lcdLinea(1, fila1);
}
void setup() {
Serial.begin(115200);
pinMode(PIN_LED_ROJO, OUTPUT);
pinMode(PIN_LED_VERDE, OUTPUT);
pinMode(PIN_BUZZER, OUTPUT);
pinMode(PIN_PUERTA, INPUT_PULLUP);
pinMode(PIN_CONFIRMAR, INPUT_PULLUP);
pinMode(PIN_PRUEBA, INPUT_PULLUP);
pinMode(PIN_HX_DT, INPUT);
pinMode(PIN_HX_SCK, OUTPUT);
digitalWrite(PIN_HX_SCK, LOW);
digitalWrite(PIN_LED_ROJO, LOW);
digitalWrite(PIN_LED_VERDE, HIGH);
Wire.begin(PIN_SDA, PIN_SCL);
Wire.setClock(100000);
lcdIniciar();
lcdLinea(0, "VITALINK - INICIO");
lcdLinea(1, "SIMULADOR WOKWI");
Serial.println("===============================================");
Serial.println("VITALINK - SIMULACION DE HARDWARE (ESP32)");
Serial.println("Horarios: 08:00, 14:00 y 20:00");
Serial.println("Boton azul: PRUEBA de alarma / POSPONER 60s");
Serial.println("Boton verde: CONFIRMAR toma manualmente");
Serial.println("Interruptor: IZQUIERDA cerrado, DERECHA abierto");
Serial.println("HX711 virtual: modifica la carga desde Wokwi");
Serial.println("===============================================");
delay(350);
}
void loop() {
unsigned long ahora = millis();
// Entradas: interruptor y botones. Bounce desactivado en el JSON.
puertaAbierta = digitalRead(PIN_PUERTA) == HIGH;
if (alarmaActiva && puertaAbierta) seAbrioDuranteAlarma = true;
static bool confirmarAntes = false;
static bool pruebaAntes = false;
bool confirmarAhora = digitalRead(PIN_CONFIRMAR) == LOW;
bool pruebaAhora = digitalRead(PIN_PRUEBA) == LOW;
if (confirmarAhora && !confirmarAntes) confirmarAlarma();
if (pruebaAhora && !pruebaAntes) {
if (alarmaActiva) posponerAlarma();
else iniciarAlarma("Prueba manual");
}
confirmarAntes = confirmarAhora;
pruebaAntes = pruebaAhora;
if (ahora - ultimaLecturaReloj >= 250UL) {
ultimaLecturaReloj = ahora;
reloj.disponible = leerRTC(reloj);
comprobarHorarios();
}
if (ahora - ultimaLecturaPeso >= 110UL) {
ultimaLecturaPeso = ahora;
int32_t cuentas;
if (leerHX711(cuentas)) {
// Escala ilustrativa del modelo HX711 virtual de 5 kg.
pesoGramos = (float)cuentas / CUENTAS_POR_GRAMO;
if (pesoGramos < 0.0f) pesoGramos = 0.0f;
pesoDisponible = true;
if (alarmaActiva && seAbrioDuranteAlarma &&
(pesoInicialAlarma - pesoGramos >= UMBRAL_RETIRO_G)) {
posibleRetiro = true;
}
}
}
if (avisoPospuesto && (int32_t)(ahora - pospuestoHasta) >= 0) {
avisoPospuesto = false;
iniciarAlarma("Fin de posposicion de 60 s");
}
digitalWrite(PIN_LED_ROJO, alarmaActiva ? HIGH : LOW);
digitalWrite(PIN_LED_VERDE, alarmaActiva ? LOW : HIGH);
actualizarZumbador();
if (ahora - ultimaPantalla >= 350UL) {
ultimaPantalla = ahora;
actualizarPantalla();
}
if (ahora - ultimoSerial >= 1500UL) {
ultimoSerial = ahora;
Serial.printf("RTC %02u:%02u:%02u | puerta=%s | peso=%.1f g | alarma=%s | posibleRetiro=%s\n",
reloj.hora, reloj.minuto, reloj.segundo,
puertaAbierta ? "ABIERTA" : "CERRADA", pesoGramos,
alarmaActiva ? "SI" : "NO", posibleRetiro ? "SI" : "NO");
}
delay(10);
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4