Community project

Portable Mercury Detection System

Photo of Portable Mercury Detection System
Generated with AI

Mateo Barron

Published November 26, 2026

This project builds a portable mercury detection system using an ESP32 microcontroller and a TCS3200 color sensor to identify mercury presence through optical analysis. The system processes color frequency data, applies calibrated detection algorithms, and provides real-time feedback through audio alerts and LED indicators, making it suitable for field testing and environmental monitoring applications.

The guide includes a complete wiring diagram showing connections between the ESP32, TCS3200 sensor module, PAM8403 audio amplifier, speaker, control potentiometer, push button, and indicator LEDs. Assembly steps cover power distribution and decoupling, microcontroller setup with user controls, optical sensor calibration, and audio-visual alert configuration. Firmware is provided with configurable detection thresholds and optional light-sensing validation to ensure measurement reliability.

Wiring diagram

Wiring diagram for Portable Mercury Detection System
Loading diagram…

Gather all the parts

QtyComponent
1

TCS3200 Color Sensor Module (3.3 V)

TCS3200 breakout operated from 3.3 V

1

PAM8403 Stereo Amplifier Module

5 V stereo module, left BTL channel only.

1

8Ω Speaker

8 Ω / 3 W

Generic small 8Ω 0.5-3W loudspeaker (~28mm typical). Pair with an I2S amp (MAX98357A) or class-D amp (TPA3116D2) for usable volume; do not drive directly from a GPIO pin. Audio output for music/voice playback.

1

10 kΩ Linear Potentiometer

10 kΩ linear

Passive audio voltage divider

1

LED

Green

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

220 Ω / ¼ W

Through-hole resistor (current-limiting in series with an LED)

1

LED

Blue

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

220 Ω / ¼ W

Through-hole resistor (current-limiting in series with an LED)

1

LED

Red

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

220 Ω / ¼ W

Through-hole resistor (current-limiting in series with an LED)

1

Push Button

BLANK

Momentary push button switch

1

Push Button

MEASURE

Momentary push button switch

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

1

Electrolytic Capacitor

10 µF / 10 V

Radial aluminium electrolytic capacitor bought by value and voltage rating, such as 10 µF, 100 µF or 1000 µF 10 V. It is polarised: the + lead goes to the higher voltage and the - lead, marked by the stripe on the sleeve, to the lower voltage or ground. It is mostly used for bulk filtering across a power rail, with a voltage rating comfortably above the rail.

1

Ceramic Capacitor

1 µF / 10 V

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

Assemble it in 4 steps

1. 1. Alimentación y desacoplo

Con la alimentación apagada, prepara un riel común de masa y uno de 5 V. Lleva 5 V regulados de una fuente externa a VIN y al PAM8403 en paralelo. Pon C2 cerca del amplificador, positivo a 5 V. Pon C1 entre 3V3 y masa cerca del sensor.

  • No conectes a la vez 5 V externos a VIN y el USB del ESP32. Desconecta la fuente externa antes de conectar el ordenador.

2. 2. Microcontrolador ESP32 y controles

Conecta BLANK entre GPIO13 y GND y MEASURE entre GPIO4 y GND. En pulsadores de cuatro patas, usa contactos que solo se unan al pulsar. El firmware debe activar las resistencias internas pull-up.

3. 3. Sensor óptico TCS3200

Alimenta el sensor con 3V3, no con 5 V. Cablea S0/S1/S2/S3 a GPIO18/19/21/22 y OUT a GPIO27. Aísla el sensor de la luz ambiente y mantén fija la posición de la muestra. Si tu módulo expone OE, llévalo a GND para habilitar la salida.

4. 4. Audio PAM8403 e indicadores LED

Conecta GPIO25 y GND a los extremos del potenciómetro. Lleva el cursor a IN_L a través de C3. Conecta el parlante solo entre L+ y L−. Conecta GPIO33 al LED verde, GPIO23 al azul y GPIO32 al rojo, cada uno con su resistencia de 220 Ω en serie y el cátodo a GND. Coloca los indicadores fuera del compartimento de medición.

  • Nunca conectes L− ni L+ a GND ni unas las salidas izquierda y derecha. Empieza con el volumen al mínimo.

Review all connections

1. Connections between "U3" and "ESP32"

FunctionU3ESP32
power5VVIN
groundGNDGND
analogOUT_L+ → 8Ω Speaker POSEXT
analogOUT_L- → 8Ω Speaker NEGEXT

2. Connections between "C1" and "ESP32"

FunctionC1ESP32
power13V3
ground2GND

3. Connections between "C2" and "ESP32"

FunctionC2ESP32
power+VIN
ground-GND

4. Connections between "SW1" and "ESP32"

FunctionSW1ESP32
digitalSIGNALGPIO 13
groundGNDGND

5. Connections between "SW2" and "ESP32"

FunctionSW2ESP32
digitalSIGNALGPIO 4
groundGNDGND

6. Connections between "U2" and "ESP32"

FunctionU2ESP32
powerVCC3V3
groundGNDGND
digitalS0GPIO 18
digitalS1GPIO 19
digitalS2GPIO 21
digitalS3GPIO 22
digitalOUTGPIO 27

7. Connections between "RV1" and "ESP32"

FunctionRV1ESP32
analogCWGPIO 25
groundGNDGND
analogWIPER → Ceramic Capacitor 1EXT

8. Connections between "C3" and "ESP32"

FunctionC3ESP32
digital2 → PAM8403 Stereo Amplifier Module IN_LEXT

9. Connections between "R1" and "ESP32"

FunctionR1ESP32
digitalP1GPIO 33
digitalP2 → LED ANODEEXT

10. Connections between "R2" and "ESP32"

FunctionR2ESP32
digitalP1GPIO 23
digitalP2 → LED ANODEEXT

11. Connections between "R3" and "ESP32"

FunctionR3ESP32
digitalP1GPIO 32
digitalP2 → LED ANODEEXT

12. Connections between "D1" and "ESP32"

FunctionD1ESP32
groundGNDGND

13. Connections between "D2" and "ESP32"

FunctionD2ESP32
groundGNDGND

14. Connections between "D3" and "ESP32"

FunctionD3ESP32
groundGNDGND

Deploy the firmware

#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <time.h>
#include <sys/time.h>
#include <esp_timer.h>
#include <esp_idf_version.h>
#if ESP_IDF_VERSION_MAJOR >= 5
#include <driver/pulse_cnt.h>
pcnt_unit_handle_t unit=nullptr;
pcnt_channel_handle_t input=nullptr;
#else
#include <driver/pcnt.h>
#endif

// Ejemplos: sustituir con una curva validada para el montaje y reactivo.
constexpr bool VALIDATED=false, DEMO=false;
constexpr float SLOPE=.1f, OFFSET=.05f, MIN_C=.1f, MAX_C=20.f;
constexpr float LOW_LIMIT=1.f, HIGH_LIMIT=6.f, MAX_CV=.03f;
constexpr char VERSION[]="rgb-normalizado-v2";
constexpr int S0=18,S1=19,S2=21,S3=22,OUT=27,DAC=25;
constexpr int RED=32,GREEN=33,BLUE=23,MEASURE=4,BLANK=13;
constexpr unsigned N=10, HISTORY=50;

// [NUEVO] Fotorresistencia como centinela de la cámara: detecta tapa abierta o luz externa.
// Divisor: 3V3 - LDR - GPIO34 - R_FIJA - GND. GPIO34 es ADC1 (sirve con Wi-Fi activo).
constexpr bool USE_LDR=false;
constexpr int LDR_PIN=34;
constexpr float LDR_RFIXED=10000.f;   // ohm; usa un valor cercano a la resistencia del LDR con la cámara cerrada
constexpr float LDR_MAX_SHIFT=.10f;   // variación máxima (log10 de la resistencia) respecto al blanco

struct RGB {float hz[3];};
struct Record {
  uint64_t seq;
  float a, corrected, c;
  RGB cv, blankCV;
  double lat,lon;
  int64_t utc;
  char id[33];
  bool demo;
  RGB raw,blank;
  float ldr;            // [NUEVO] variación del LDR frente al blanco (NaN si no disponible)
  char version[32];
  uint8_t level;
};
Record ring[HISTORY]{};
Record latest{};
RGB reference{}, reading{}, cv{}, blankCV{};
float ldrRef=NAN;       // [NUEVO] log10(R_ldr) medido junto con el blanco
uint32_t blankAt=0;
String nextId;
double nextLat=NAN,nextLon=NAN;
uint64_t sequence=0;
Preferences flash;
WebServer server(80);
String device, status="Sin medición";
bool calibrated=false, storage=false, sensor=false;

// El periférico PCNT cuenta los flancos sin ocupar la CPU.
enum Stage {IDLE, SETTLE, COUNT};
Stage stage=IDLE;
int channel=0;
unsigned windows=0;
float mean=0,m2=0;
int64_t mark=0;
bool blankJob=false, probing=false, armed=false;
unsigned opticalHits=0;
uint32_t lastProbe=0, lastLed=0;
bool ledOnly=false;

// El temporizador de audio usa su propia tarea; la web sigue atendiendo.
esp_timer_handle_t audioTimer=nullptr;
uint32_t sample=0;
int voice=0;
void audioTick(void*) {
  unsigned notes=voice+1;
  if(sample >= notes*1600) {
    dacWrite(DAC,128);
    esp_timer_stop(audioTimer);
    return;
  }
  uint8_t out=128;
  if(sample%1600<1120) out=128+(((sample*(440+voice*220)/4000)&1)?36:-36);
  dacWrite(DAC,out);
  ++sample;
}
void play(int level) {
  if(!audioTimer || esp_timer_is_active(audioTimer)) return;
  voice=level; sample=0;
  esp_timer_start_periodic(audioTimer,125);
}

const char *levels[]={"BAJO","MODERADO","CRÍTICO","SIN ESTIMACIÓN","INESTABLE","FUERA DE RANGO"};
void lights(int level) {
  const int pins[]={GREEN,BLUE,RED};
  for(int i=0;i<3;++i) if(i!=level) digitalWrite(pins[i],LOW);
  if(level>=0 && level<3) digitalWrite(pins[level],HIGH);
}
float worst(RGB x){return fmaxf(x.hz[0],fmaxf(x.hz[1],x.hz[2]));}

// [NUEVO] log10 de la resistencia del LDR (promedio de 64 lecturas). NaN si el divisor está abierto o en corto.
float ldrRead(){
  uint32_t acc=0;
  for(int i=0;i<64;++i){acc+=analogReadMilliVolts(LDR_PIN);delayMicroseconds(200);}
  float mv=acc/64.f;
  if(mv<80.f||mv>3100.f) return NAN;
  return log10f(LDR_RFIXED*(3300.f-mv)/mv);
}
// [NUEVO] true si la luz de la cámara cambió demasiado respecto al blanco (tapa abierta o luz externa).
bool ldrBad(float &shift){
  shift=NAN;
  if(!USE_LDR||!isfinite(ldrRef)) return false;
  float now=ldrRead();
  if(!isfinite(now)) return false;
  shift=now-ldrRef;
  return fabsf(shift)>LDR_MAX_SHIFT;
}

void complete() {
  if(blankJob) {
    if(worst(cv)>MAX_CV){status="Blanco inestable: repita";return;}
    reference=reading; blankCV=cv; calibrated=true; blankAt=millis();
    status="Blanco listo (30 minutos)";
    if(USE_LDR){
      ldrRef=ldrRead();   // [NUEVO] referencia del LDR con la cámara cerrada
      if(!isfinite(ldrRef)) status+="; LDR sin señal: revise el cableado";
    }
    return;
  }
  float lshift=NAN; bool lbad=ldrBad(lshift);   // [NUEVO]
  float optical=0;
  for(int i=0;i<3;++i) optical+=fmaxf(0.f,-log10f(reading.hz[i]/reference.hz[i]))/3.f;
  lights(worst(cv)>MAX_CV || lbad || !isfinite(optical) ? -1 : optical<.05f ? 0 : optical<.20f ? 1 : 2);
  if(ledOnly) return;
  if(probing){
    float change=-log10f((reading.hz[1]/reference.hz[1]) /
      sqrtf((reading.hz[0]/reference.hz[0])*(reading.hz[2]/reference.hz[2])));
    opticalHits=(worst(cv)<=MAX_CV && fabsf(change)>=0.07f && !lbad)?opticalHits+1:0;
    if(opticalHits<2){status=lbad?"Luz externa o tapa abierta: cierre la cámara":"Esperando cambio óptico estable";return;}
    armed=false; // Una lectura por muestra; no confundir cambio óptico con detección de Hg.
  }
  Record r{};
  r.raw=reading; r.blank=reference; r.cv=cv; r.blankCV=blankCV; r.ldr=lshift;
  r.lat=nextLat; r.lon=nextLon; nextLat=nextLon=NAN;
  time_t now=time(nullptr); r.utc=now>=1700000000?now:0;
  r.a=-log10f(reading.hz[1]/reference.hz[1]);
  // R y B estiman variaciones comunes de brillo; no identifican interferentes.
  float common=-.5f*(log10f(reading.hz[0]/reference.hz[0])+log10f(reading.hz[2]/reference.hz[2]));
  r.corrected=r.a-common; r.c=NAN; r.demo=DEMO&&!VALIDATED; r.level=3;
  if(worst(cv)>MAX_CV || fabsf(common)>.12f || lbad) r.level=4;
  else if(VALIDATED || DEMO){
    float c=powf(10,(r.corrected-OFFSET)/SLOPE);
    if(!isfinite(c)||c<MIN_C||c>MAX_C) r.level=5;
    else {if(VALIDATED)r.c=c; r.level=c<LOW_LIMIT?0:c<=HIGH_LIMIT?1:2;}
  }
  snprintf(r.version,sizeof r.version,"%s",VERSION);
  r.seq=++sequence;
  if(nextId.length()) snprintf(r.id,sizeof r.id,"%s",nextId.c_str());
  else snprintf(r.id,sizeof r.id,"%llu",(unsigned long long)r.seq);
  nextId="";
  unsigned slot=(r.seq-1)%HISTORY;
  char key[8]; snprintf(key,sizeof key,"r%u",slot);
  ring[slot]=latest=r;
  bool saved=storage && flash.putBytes(key,&r,sizeof r)==sizeof r;
  status=r.demo?"DEMO: ":""; status+=levels[r.level];
  if(lbad) status+=" (luz externa o tapa abierta: repita con la cámara cerrada)";
  else if(USE_LDR && !isfinite(lshift)) status+=" (LDR sin señal: revise el cableado)";
  if(!saved)status+="; no guardada";
  if(r.level<3) play(r.level);
  Serial.printf("A corregida %.4f; CV máximo %.3f; LDR %.3f; %s\n",r.corrected,worst(cv),lshift,status.c_str());
}
void selectFilter() {
  // TCS3200: rojo 00, verde 11, azul 01.
  digitalWrite(S2,channel==1); digitalWrite(S3,channel!=0);
  mark=esp_timer_get_time(); stage=SETTLE;
}
void start(bool isBlank, bool probe=false, bool refresh=false) {
  if(stage!=IDLE) return;
  if(!probe && !refresh) armed=false;
  if(isBlank) lights(-1);
  ledOnly=refresh;
  probing=probe;
  if(!sensor){status="Contador no disponible";return;}
  if(!isBlank&&(!calibrated||millis()-blankAt>=1800000UL)){status="Calibre el blanco primero";return;}
  if(isBlank)calibrated=false;
  blankJob=isBlank; channel=0; windows=0; mean=m2=0;
  if(!refresh) status=isBlank?"Leyendo blanco":"Leyendo muestra";
  selectFilter();
}
void measureTick() {
  int64_t now=esp_timer_get_time();
  if(stage==SETTLE && now-mark>=4000) {
#if ESP_IDF_VERSION_MAJOR >= 5
    pcnt_unit_clear_count(unit); pcnt_unit_start(unit);
#else
    pcnt_counter_clear(PCNT_UNIT_0); pcnt_counter_resume(PCNT_UNIT_0);
#endif
    mark=esp_timer_get_time(); stage=COUNT;
  } else if(stage==COUNT && now-mark>=25000) {
#if ESP_IDF_VERSION_MAJOR >= 5
    pcnt_unit_stop(unit);
    int edges=0; pcnt_unit_get_count(unit,&edges);
#else
    pcnt_counter_pause(PCNT_UNIT_0);
    int16_t edges=0; pcnt_get_counter_value(PCNT_UNIT_0,&edges);
#endif
    int64_t elapsed=esp_timer_get_time()-mark;
    if(elapsed>100000 || edges<=0 || edges>=29000){status="Señal inválida o ventana interrumpida: repita"; stage=IDLE;opticalHits=0;lights(-1);return;}
    // Media y varianza de Welford, sin guardar las ventanas.
    float hz=edges*1000000.f/elapsed, delta=hz-mean;
    mean+=delta/++windows; m2+=delta*(hz-mean);
    if(windows==N) {
      reading.hz[channel]=mean;
      cv.hz[channel]=sqrtf(fmaxf(0,m2/(N-1)))/mean;
      mean=m2=0;windows=0;
      if(++channel==3){stage=IDLE;complete();return;}
    }
    selectFilter();
  }
}
struct Button {int pin; bool raw=HIGH,stable=HIGH;uint32_t changed=0;
  explicit Button(int p):pin(p){}
  bool pressed(){bool b=digitalRead(pin);uint32_t now=millis();
    if(b!=raw){raw=b;changed=now;}
    if(raw!=stable && now-changed>=35){stable=raw;return !stable;}
    return false;
  }
};
Button bMeasure(MEASURE),bBlank(BLANK);
String rgbJson(const RGB &r){return String("{\"r\":")+String(r.hz[0],2)+",\"g\":"+String(r.hz[1],2)+",\"b\":"+String(r.hz[2],2)+"}";}
String json(const Record &r){
  if(!r.seq)return "null";
  auto num=[](double v,int n){return isfinite(v)?String(v,n):String("null");};
  String stamp="null";
  if(r.utc){time_t t=r.utc; struct tm dt{}; char buf[32];
    if(gmtime_r(&t,&dt)&&strftime(buf,sizeof buf,"%Y-%m-%dT%H:%M:%SZ",&dt))stamp=String("\"")+buf+"\"";
  }
  String s="{\"device_id\":\""+device+"\",\"sample_id\":\""+r.id+"\",\"timestamp\":"+stamp;
  s+=",\"lat\":"+num(r.lat,6)+",\"lon\":"+num(r.lon,6)+",\"hg_ug_L_est\":"+num(r.c,4);
  s+=String(",\"demo\":")+(r.demo?"true":"false");
  s+=",\"absorbance_corrected\":"+num(r.corrected,5)+",\"cv_rgb\":"+rgbJson(r.cv)+",\"blank_cv_rgb\":"+rgbJson(r.blankCV);
  s+=",\"ldr_shift\":"+num(r.ldr,4);
  s+=String(",\"level\":\"")+levels[r.level]+"\",\"absorbance_green\":"+String(r.a,5);
  return s+",\"sequence\":"+String((unsigned long long)r.seq)+",\"raw_rgb\":"+rgbJson(r.raw)+",\"blank_rgb\":"+rgbJson(r.blank)+",\"calibration_version\":\""+r.version+"\"}";
}
const char PAGE[] PROGMEM=R"HTML(<!doctype html><html lang="es"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>BioHg</title><h1>BioHg — demostración</h1><p>Sin curva validada no hay estimación de mercurio. No determina potabilidad.</p><p>Use los botones físicos. Frecuencias RGB en Hz.</p><form id="meta">ID <input name="id" maxlength="32"> Latitud <input name="lat"> Longitud <input name="lon"> <button>Preparar muestra y sincronizar hora</button></form><button id="arm">Armar lectura óptica (una muestra)</button>
<button id="audio">Activar voz Gemini</button>
<p>Gemini es opcional: envía solo datos ópticos y el resultado local. Requiere Internet en el navegador. No modifica la medición ni la alarma.</p>
<input id="key" type="password" autocomplete="off" placeholder="Clave de Gemini"><button id="ask">Consultar última lectura</button><p id="ai"></p><p id="tts"></p><audio id="clip" controls></audio>
<p id="msg"></p><p id="estado"></p><pre id="datos"></pre><a href="/history">Historial JSON</a><script>
let current=null, spoken=null, enabled=false, url=null, generation=0;
const TTS_MODEL='gemini-3.1-flash-tts-preview'; // si la API responde 404, prueba otro modelo TTS disponible en tu cuenta
const tts=document.getElementById('tts'), clip=document.getElementById('clip');
async function say(text){
 const token=++generation;
 clip.pause();clip.removeAttribute('src');clip.load();
 if(url){URL.revokeObjectURL(url);url=null;}
 tts.textContent='Generando voz…';
 try{
  const res=await fetch('https://generativelanguage.googleapis.com/v1beta/models/'+TTS_MODEL+':generateContent',{
   method:'POST',headers:{'Content-Type':'application/json','x-goog-api-key':key.value.trim()},
   body:JSON.stringify({contents:[{parts:[{text:'Lee literalmente en español, sin añadir nada: '+text}]}],generationConfig:{responseModalities:['AUDIO'],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:'Kore'}}}}}),signal:AbortSignal.timeout(25000)});
  if(!res.ok)throw Error('HTTP '+res.status);
  const out=await res.json(), part=out.candidates?.[0]?.content?.parts?.find(p=>p.inlineData?.data)?.inlineData;
  if(!part || !/^audio\/(L16|pcm)\b/i.test(part.mimeType))throw Error('Formato de audio inesperado: '+(part&&part.mimeType));
  const rate=Number(/rate=(\d+)/i.exec(part.mimeType)?.[1]||24000);
  const raw=Uint8Array.from(atob(part.data),c=>c.charCodeAt(0));
  if(!raw.length || raw.length%2 || rate<8000 || rate>48000)throw Error('PCM inválido');
  if(token!==generation)return;
  // Cabecera WAV para PCM mono de 16 bits devuelto por Gemini.
  const h=new DataView(new ArrayBuffer(44));
  for(const [pos,tag] of [[0,'RIFF'],[8,'WAVE'],[12,'fmt '],[36,'data']])
   for(let i=0;i<4;i++)h.setUint8(pos+i,tag.charCodeAt(i));
  for(const [pos,n] of [[4,36+raw.length],[16,16],[24,rate],[28,rate*2],[40,raw.length]])h.setUint32(pos,n,true);
  for(const [pos,n] of [[20,1],[22,1],[32,2],[34,16]])h.setUint16(pos,n,true);
  url=URL.createObjectURL(new Blob([h.buffer,raw],{type:'audio/wav'}));clip.src=url;
  try{await clip.play();if(token===generation)tts.textContent='Voz Gemini lista.';}
  catch{if(token===generation)tts.textContent='Pulsa reproducir para escuchar la voz.';}
 }catch(e){if(token===generation)tts.textContent='Voz Gemini no disponible: '+e.message+'. El circuito conserva sus tonos locales.';}
}
audio.onclick=()=>{
 if(!key.value.trim()){tts.textContent='Introduce tu clave Gemini.';return;}
 enabled=true;say('Prueba de voz de BioHg. Esto no es una medición.');
};
arm.onclick=async()=>{try{msg.textContent=await(await fetch('/arm',{method:'POST'})).text();}catch{msg.textContent='Sin conexión local';}};
ask.onclick=async()=>{
 const d=current,k=key.value.trim(); if(!d||!k){ai.textContent='Se necesita una lectura y una clave';return;}
 ask.disabled=true;ai.textContent='Consultando…';
 try{
  const data={rgb:d.raw_rgb,blanco:d.blank_rgb,variacion:d.cv_rgb,hg:d.hg_ug_L_est,nivel:d.level,demo:d.demo};
  const res=await fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent',{
   method:'POST',headers:{'Content-Type':'application/json','x-goog-api-key':k},
   body:JSON.stringify({contents:[{parts:[{text:'Resume en español la calidad óptica del registro. No reclasifiques, no estimes valores faltantes, no des consejos sanitarios. Datos: '+JSON.stringify(data)}]}]}),signal:AbortSignal.timeout(12000)});
  if(!res.ok)throw Error('HTTP '+res.status);
  const out=await res.json();ai.textContent='Comentario de Gemini (registro '+d.sequence+'): '+(out.candidates?.[0]?.content?.parts?.[0]?.text||'Sin respuesta');
 }catch(e){ai.textContent='Gemini no disponible: '+e.message+'. La lectura local no cambia.';}finally{ask.disabled=false;}
};
meta.onsubmit=async e=>{e.preventDefault();let p=new URLSearchParams(new FormData(meta));p.set('utc',Math.floor(Date.now()/1000));try{msg.textContent=await(await fetch('/sample',{method:'POST',body:p})).text();}catch(e){msg.textContent='Sin conexión';}};async function tick(){try{estado.textContent=await (await fetch('/status',{cache:'no-store'})).text();let d=await (await fetch('/data',{cache:'no-store'})).json();current=d;
if(d && d.sequence!==spoken){
 // La voz se dice si hay estimación validada, o en modo DEMO anteponiendo que es una demostración.
 if(enabled && (d.demo || Number.isFinite(d.hg_ug_L_est))){
  const phrases={BAJO:'Nivel bajo estimado. Esto no confirma que el agua sea potable.',MODERADO:'Nivel moderado estimado. Precaución.',CRÍTICO:'Nivel elevado estimado. No use esta agua.'};
  if(phrases[d.level])say((d.demo?'Modo demostración, no es una medición de mercurio. ':'')+phrases[d.level]);
 }
 spoken=d.sequence;
}
datos.textContent=d?JSON.stringify(d,null,2):'Aún no hay mediciones';}catch(e){estado.textContent='Sin conexión';}setTimeout(tick,1500);}tick();</script></html>)HTML";
bool coord(String text,double max,double &value){
  char *end; value=strtod(text.c_str(),&end);
  return end!=text.c_str() && !*end && isfinite(value) && fabs(value)<=max;
}
void metadata(){
  if(stage!=IDLE){server.send(409,"text/plain","Lectura en curso");return;}
  String id=server.arg("id"), lat=server.arg("lat"), lon=server.arg("lon");
  double x=NAN,y=NAN;
  bool ok=id.length()<=32;
  for(char c:id) if(!isalnum((unsigned char)c)&&c!='-'&&c!='_')ok=false;
  if(lat.length()||lon.length())ok=ok&&coord(lat,90,x)&&coord(lon,180,y);
  long long utc=strtoll(server.arg("utc").c_str(),nullptr,10);
  if(!ok||utc<1700000000LL||utc>2147483647LL){server.send(400,"text/plain","Revise ID, coordenadas y reloj");return;}
  struct timeval tv{}; tv.tv_sec=utc; settimeofday(&tv,nullptr);
  nextId=id;nextLat=x;nextLon=y;
  server.send(200,"text/plain; charset=utf-8","Datos listos: pulse MEDIR");
}
void setup(){
  Serial.begin(115200);
  for(int p:{S0,S1,S2,S3,RED,GREEN,BLUE})pinMode(p,OUTPUT);
  pinMode(MEASURE,INPUT_PULLUP);pinMode(BLANK,INPUT_PULLUP);
  digitalWrite(S0,HIGH);digitalWrite(S1,LOW); // 20 %
  lights(-1);
  if(USE_LDR) analogSetPinAttenuation(LDR_PIN,ADC_11db);  // [NUEVO] rango de lectura hasta ~3,1 V
#if ESP_IDF_VERSION_MAJOR >= 5
  pcnt_unit_config_t uc{}; uc.low_limit=-1; uc.high_limit=30000;
  pcnt_chan_config_t cc{}; cc.edge_gpio_num=OUT; cc.level_gpio_num=-1;
  sensor=pcnt_new_unit(&uc,&unit)==ESP_OK && pcnt_new_channel(unit,&cc,&input)==ESP_OK &&
    pcnt_channel_set_edge_action(input,PCNT_CHANNEL_EDGE_ACTION_INCREASE,PCNT_CHANNEL_EDGE_ACTION_HOLD)==ESP_OK &&
    pcnt_unit_enable(unit)==ESP_OK;
#else
  pcnt_config_t cfg{};
  cfg.pulse_gpio_num=OUT;cfg.ctrl_gpio_num=PCNT_PIN_NOT_USED;
  cfg.pos_mode=PCNT_COUNT_INC;cfg.neg_mode=PCNT_COUNT_DIS;
  cfg.lctrl_mode=cfg.hctrl_mode=PCNT_MODE_KEEP;
  cfg.counter_h_lim=30000;cfg.counter_l_lim=-1;
  cfg.unit=PCNT_UNIT_0;cfg.channel=PCNT_CHANNEL_0;
  sensor=pcnt_unit_config(&cfg)==ESP_OK;
  pcnt_counter_pause(PCNT_UNIT_0);
#endif
  dacWrite(DAC,128);
  esp_timer_create_args_t timer{};timer.callback=audioTick;timer.name="voz";
  esp_timer_create(&timer,&audioTimer);
  storage=flash.begin("biohg-opt2",false);   // [IMPORTANTE] no cambies este nombre: los registros viejos se reemplazan solos
  if(storage){
    for(unsigned i=0;i<HISTORY;++i){
      char key[8];snprintf(key,sizeof key,"r%u",i);
      auto &r=ring[i];
      if(flash.getBytesLength(key)==sizeof r && flash.getBytes(key,&r,sizeof r)==sizeof r &&
         r.seq && (r.seq-1)%HISTORY==i && r.level<6){if(r.seq>sequence){sequence=r.seq;latest=r;}}
      else r={};
    }
  }
  status=calibrated?"Blanco disponible":"Calibre el blanco primero";
  char id[24];snprintf(id,sizeof id,"BioHg-%012llX",(unsigned long long)ESP.getEfuseMac());device=id;
  WiFi.mode(WIFI_AP);WiFi.softAP("BioHg-ESP32","BioHg-demo-32");
  server.on("/",[]{server.send_P(200,"text/html; charset=utf-8",PAGE);});
  server.on("/sample",HTTP_POST,metadata);
  server.on("/arm",HTTP_POST,[]{
    if(stage!=IDLE || !sensor || !calibrated || millis()-blankAt>=1800000UL){server.send(409,"text/plain","Calibre el blanco y espere a que termine la lectura");return;}
    armed=true; opticalHits=0; lastProbe=millis(); status="Esperando cambio óptico estable";
    server.send(200,"text/plain; charset=utf-8",status);
  });
  server.on("/status",[]{server.send(200,"text/plain; charset=utf-8",status);});
  server.on("/data",[]{server.send(200,"application/json",json(latest));});
  server.on("/history",[]{
    String result="[";result.reserve(22000);
    for(unsigned n=0;n<HISTORY && n<sequence;++n){uint64_t seq=sequence-n;
      const Record &r=ring[(seq-1)%HISTORY];
      if(r.seq==seq){if(result.length()>1)result+=',';result+=json(r);}
    }
    server.send(200,"application/json",result+"]");
  });
  server.begin();Serial.println(WiFi.softAPIP());
}
void loop(){
  bool blank=bBlank.pressed(), sample=bMeasure.pressed();
  if(blank)start(true);else if(sample)start(false);
  measureTick();
  if(armed && stage==IDLE){
    if(millis()-blankAt>=1800000UL){armed=false;status="Blanco caducado";}
    else if(millis()-lastProbe>=1500){lastProbe=millis();start(false,true);}
  }
  if(calibrated && stage==IDLE){
    if(millis()-blankAt>=1800000UL){calibrated=false;lights(-1);status="Blanco caducado";}
    else if(!armed && millis()-lastLed>=1500){lastLed=millis();start(false,false,true);}
  }
  server.handleClient();
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik