Community project

Portable Mercury Level Reader

Photo of Portable Mercury Level Reader
Generated with AI

Mateo Barron

Published November 23, 2026

This portable mercury level reader uses a TCS3200 color sensor to optically detect mercury concentration on reactive test strips. The ESP32 microcontroller processes the sensor data, provides visual feedback through an RGB LED, and delivers audio alerts through a small amplified speaker. The entire system runs from a standard USB power bank, making it suitable for field measurements.

This guide provides the wiring diagram, complete parts list, and firmware to get started. Assembly involves setting up a light-sealed chamber for the sensor, connecting the control buttons and indicator LED, wiring the audio output stage, and calibrating the optical readings against known reference strips. The firmware includes data logging, web server access for remote monitoring, and audio tone feedback scaled to detected levels.

Wiring diagram

Loading diagram…

Gather all the parts

QtyComponent
1

TCS3200 breakout with OE rated for 3.3 V

TCS3200 breakout with OE rated for 3.3 V

1

PAM8403 stereo module

PAM8403 stereo module

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

10kΩ Potentiometer

10 kΩ lineal

10 kΩ linear (B10K) rotary potentiometer in the common 16 mm panel style: metal can, M7 threaded bushing for mounting through a panel, a 6 mm knurled split shaft for push-on knobs, and three PCB pins in a row 5 mm apart. Connect the outer pins across 3.3 V or 5 V and ground; the middle wiper pin then gives an adjustable voltage for an ADC input over about 300° of rotation.

1

10 µF 10 V electrolytic audio coupling capacitor

Polarized capacitor with positive lead toward DAC

1

Electrolytic Capacitor

100 µ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

Rgb Led

Discrete four-pin common-cathode RGB LED with separate red, green, and blue anodes. Each colour channel needs its own current-limit resistor and can be PWM-dimmed from separate MCU GPIO pins.

1

Resistor

220 Ω

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

1

Resistor

220 Ω

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

1

Resistor

220 Ω

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

1

Push Button

Momentary push button switch

1

Push Button

Momentary push button switch

1

USB power bank 5 V 2 A

USB power bank 5 V 2 A

Assemble it in 5 steps

1. Preparar la cámara oscura

Coloca el TCS3200 con su iluminación fija frente al soporte de la tira. Cierra la cámara para bloquear la luz ambiente y mantén seco el sensor.

2. Conectar botones y luces

Con la alimentación desconectada, sigue el esquema. Cada color del LED lleva su resistencia de 220 ohmios. Conecta el cátodo común y un lado de cada pulsador a GND.

3. Conectar audio

Conecta el positivo del capacitor de 10 µF al DAC y el negativo al extremo alto del potenciómetro. Lleva el cursor a L y el otro extremo a tierra. Une ambas tierras del amplificador a GND. Pon el capacitor de 100 µF cerca de la alimentación del amplificador, con positivo a 5 V.

  • Conecta el parlante solo entre L+ y L−. No aterrices ninguna salida BTL. Empieza con el volumen al mínimo.

4. Alimentar con el power bank

Usa un power bank USB regulado de 5 V y 2 A. El esquema muestra alimentación por VIN (riel de 5 V); para conectar el USB del ordenador primero desconecta la fuente externa de VIN y deja el amplificador desconectado durante la programación.

  • No conectes 5 V a 3V3 ni a ningún GPIO. No alimentes VIN y USB simultáneamente.

5. Leer la tira reactiva por reflexión

Usa una tira SenSafe Boris Mercury Check 480049. Coloca la zona reactiva frente al sensor y su luz, con un tope para repetir distancia y orientación. Sigue los tiempos y la carta del envase. Para el blanco usa una tira nueva del mismo lote procesada con agua de referencia sin mercurio. Para cada muestra usa otra tira. No mojes el sensor; la tira no lleva cables. El LED solo indica cambio óptico, no concentración.

  • Otros metales y oxidantes pueden interferir. Un resultado negativo no demuestra potabilidad. No prepares patrones de mercurio en casa.

Review all connections

1. Connections between "color" and "ESP32"

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

2. Connections between "amp" and "ESP32"

FunctionampESP32
power5V5V
groundGNDGND
groundRGND
analogL → 10kΩ Potentiometer WIPEREXT

3. Connections between "speaker" and "ESP32"

FunctionspeakerESP32
analogPOS → PAM8403 stereo module L+EXT
analogNEG → PAM8403 stereo module L-EXT

4. Connections between "vol" and "ESP32"

FunctionvolESP32
groundGNDGND

5. Connections between "couple" and "ESP32"

FunctioncoupleESP32
analog+GPIO 25
analog- → 10kΩ Potentiometer VCCEXT

6. Connections between "bulk" and "ESP32"

FunctionbulkESP32
power+5V
ground-GND

7. Connections between "rgb" and "ESP32"

FunctionrgbESP32
groundGNDGND

8. Connections between "resR" and "ESP32"

FunctionresRESP32
digitalP1GPIO 32
digitalP2 → Rgb Led REXT

9. Connections between "resG" and "ESP32"

FunctionresGESP32
digitalP1GPIO 33
digitalP2 → Rgb Led GEXT

10. Connections between "resB" and "ESP32"

FunctionresBESP32
digitalP1GPIO 23
digitalP2 → Rgb Led BEXT

11. Connections between "measure" and "ESP32"

FunctionmeasureESP32
groundGNDGND
digitalSIGNALGPIO 4

12. Connections between "blank" and "ESP32"

FunctionblankESP32
groundGNDGND
digitalSIGNALGPIO 13

13. Connections between "bank" and "ESP32"

FunctionbankESP32
powerVBUS5V
groundGNDGND

Deploy the firmware

#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <esp_timer.h>
#include <driver/pcnt.h>

// Umbral de demostración óptica, no calibrado para mercurio.
constexpr float OPTICAL_LIMIT=0.05f;
constexpr char VERSION[]="optico-sin-calibrar-v1";
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;

struct RGB {float hz[3];};
struct Record {
  uint64_t seq;
  float a;
  RGB raw,blank;
  char version[32];
  uint8_t level;
};
Record ring[HISTORY]{};
Record latest{};
RGB reference{}, reading{};
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 sum=0;
int64_t mark=0;
bool blankJob=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)?12:-12);
  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[]={"SIN CAMBIO ÓPTICO APRECIABLE","CAMBIO ÓPTICO"};
void lights(int level) {
  digitalWrite(RED,level==2); digitalWrite(GREEN,LOW); digitalWrite(BLUE,level==1);
}
bool valid(RGB r) {
  for(float f:r.hz) if(!isfinite(f)||f<=0) return false;
  return true;
}
void complete() {
  lights(-1);
  if(!valid(reading)) {status="Sin señal RGB: revise tubo, luz y cableado"; return;}
  if(blankJob) {
    if(!storage || flash.putBytes("blank",&reading,sizeof reading)!=sizeof reading) {
      status="No se pudo guardar el blanco"; return;
    }
    reference=reading; calibrated=true; status="Blanco guardado";
    return;
  }
  Record r{};
  r.raw=reading; r.blank=reference;
  r.a=-log10f(reading.hz[1]/reference.hz[1]);
  // Compara los tres canales: no se presupone que la tira sea magenta.
  float change=0;
  for(int i=0;i<3;++i) change=fmaxf(change,fabsf(log10f(r.raw.hz[i]/r.blank.hz[i])));
  r.level=change>=OPTICAL_LIMIT ? 1 : 0;
  snprintf(r.version,sizeof r.version,"%s",VERSION);
  r.seq=++sequence;
  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=saved?"Lectura óptica":"Lectura óptica; no guardada en flash";
  lights(r.level); if(r.level) play(1);
  Serial.printf("RGB Hz %.1f %.1f %.1f; A=%.4f; cambio óptico %.4g\n",r.raw.hz[0],r.raw.hz[1],r.raw.hz[2],r.a,change);
}
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) {
  if(stage!=IDLE) return;
  lights(-1);
  if(!sensor){status="Contador no disponible";return;}
  if(!isBlank&&!calibrated){status="Calibre el blanco primero";return;}
  blankJob=isBlank; channel=0; windows=0; sum=0;
  status=isBlank?"Leyendo blanco":"Leyendo muestra";
  selectFilter();
}
void measureTick() {
  int64_t now=esp_timer_get_time();
  if(stage==SETTLE && now-mark>=4000) {
    pcnt_counter_clear(PCNT_UNIT_0); pcnt_counter_resume(PCNT_UNIT_0);
    mark=esp_timer_get_time(); stage=COUNT;
  } else if(stage==COUNT && now-mark>=25000) {
    pcnt_counter_pause(PCNT_UNIT_0);
    int64_t elapsed=esp_timer_get_time()-mark;
    int16_t edges=0; pcnt_get_counter_value(PCNT_UNIT_0,&edges);
    if(elapsed>100000 || edges<=0 || edges>=29000){status="Señal inválida o ventana interrumpida: repita"; stage=IDLE;return;}
    sum+=edges*1000000.0f/elapsed;
    if(++windows==N) {
      reading.hz[channel]=sum/N; sum=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";
  String s="{\"device_id\":\""+device+"\",\"timestamp\":null,\"lat\":null,\"lon\":null,\"hg_ug_L_est\":null";
  s+=String(",\"level\":\"")+levels[r.level]+"\",\"absorbance_green\":"+String(r.a,5);
  return s+",\"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>El LED azul indica un cambio de color frente al blanco. No mide mercurio ni determina si el agua es potable.</p><p>Use los botones físicos. Frecuencias RGB en Hz.</p><p id="estado"></p><pre id="datos"></pre><a href="/history">Historial JSON</a><script>async function tick(){try{estado.textContent=await (await fetch('/status',{cache:'no-store'})).text();let d=await (await fetch('/data',{cache:'no-store'})).json();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";
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 %
  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);
  dacWrite(DAC,128);
  esp_timer_create_args_t timer{};timer.callback=audioTick;timer.name="voz";
  esp_timer_create(&timer,&audioTimer);
  storage=flash.begin("biohg-opt1",false);
  if(storage){
    calibrated=flash.getBytesLength("blank")==sizeof reference &&
      flash.getBytes("blank",&reference,sizeof reference)==sizeof reference && valid(reference);
    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<2){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("/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();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