AquaWatch: Edge-AI and LoRaWAN-Based Water Quality Monitoring System for Rural India is an autonomous, low-cost early-warning solution designed to detect abnormal drinking-water quality conditions in rural water distribution networks, municipal pipelines, and storage facilities. The system integrates the Arduino UNO Q’s STM32U585 microcontroller and Qualcomm QRB2210 application processor to enable low-power sensor acquisition, image processing, and on-device AI inference. It combines three complementary monitoring approaches: computer vision using a USB micro-inspection camera and OpenCV, physical sensing using an ASAIR AZDM01 turbidity sensor and DS18B20 temperature sensor, and multispectral analysis using the AS7341 spectral sensor. The collected data is processed through a Python-based multimodal fusion pipeline to evaluate water-quality indicators, cross-check abnormal readings, and classify the observed condition as Safe, Warning, or Critical. LoRaWAN enables long-range transmission of alerts to a central monitoring station without requiring cellular connectivity at each monitoring node. Local MicroSD storage maintains sensor records and selected images for subsequent inspection and analysis. The modular architecture also supports future integration of pH, oxidation-reduction potential (ORP), and conductivity/TDS sensors. By combining physical measurements, optical analysis, computer vision, and edge intelligence, AquaWatch aims to improve contamination-event awareness, reduce false alarms caused by individual sensor anomalies, and support scalable drinking-water monitoring across rural India. The system is intended as an early-warning tool and does not replace laboratory testing or certified microbiological analysis for confirming drinking-water safety.
Component List:
| ID | Name | Designator | Quantity |
| 1 | Arduino UNO Q | BOARD | 1 |
| 4 | ASAIR AZDM01 Photoelectric Turbidity Sensor | SEN1 | 1 |
| 5 | Dallas DS18B20 Stainless Waterproof Temperature Sensor | SEN2 | 1 |
| 6 | AMS / Adafruit AS7341 10-Channel VIS/NIR Optical Spectrometer | SEN3 | 1 |
| 7 | USB camera(Psoc Edge E84 AI Kit camera) | CAM1 | 1 |
| 8 | Ebyte E78-900M22S LoRaWAN Transceiver | LoRa | 1 |
| 9 | 4.7kΩ Resistor (DS18B20 1-Wire Pull-Up to 3.3V) | RES1 | 1 |
| 10 | 10kΩ / 30kΩ resistor | RES2 /RES3 | 3 |
| 11 | USB Hub | Hub | 1 |
| 12 | 5V 2A DC Adapter | PWR | 1 |


Project Explanation Step By Step
AquaWatch is a low-cost, autonomous water qualitymonitoring node that watches drinking-water quality continuously and sends an alert over LoRaWAN when something looks wrong. It runs on an Arduino UNO Q and fuses three independent signals: physical sensing, multi- spectral analysis and computer vision. Because the node needs no cellular connection, it there is no recurring data cost. One LoRaWAN gateway can cover many nodes , so a central station can cater to multiple villages and towns.
The prototype classifies water as Safe, Warning or Critical, raises a hazard code when it detects contamination, and delivers a compact uplink to a LoRaWAN network server.We have used Chirpstack LNS for our project.
The Jal Jeevan Mission has brought piped water to millions of rural households. Safety is still fragile, because leaking, damaged or poorly separated water and sewer lines let sewage into the supply, especially in the monsoon and during intermittent supply.
The Bhagirathpura incident in Indore in late 2025 shows how fast this becomes an emergency: sewage entered a drinking-water pipeline, causing a large diarrhoeal outbreak and several deaths, and investigations later confirmed bacterial and faecal contamination.
Periodic sampling and laboratory testing leave a long gap between contamination happening and anyone finding out. What is needed is an inexpensive node that sits on a pipeline or storage point, watches continuously, flags abnormal signatures in near real time and reports over a long-range, no-subscription network.
A single sensor can be fooled by fouling, sediment or a stuck reading. AquaWatch cross-checks three modalities that fail in different ways, so one bad channel is less likely to cause a false alarm or a missed event.
i) Computer vision: A USB inspection camera looks at the water through a transparent flow cell. A contrast grid on the opposite wall acts as a controlled reference. The OpenCV pipeline measures:
- image sharpness using Laplacian variance (clear water preserves the grid lines, while particles, colloids, biological growth and flocs blur them),
- colour shift in CIE-Lab (ΔE) against a clean baseline,
- saturation changes and particle counts, which can indicate films, sheen or visible anomalies.
ii) Physical sensing: This uses the traditional physical sensors for measuring different water parameters like PH,Turbidity,temperature,Dissolved oxygen. For the current prototype we have only used a turbidity sensor(AZDM01) and a temperature sensor(DS18B20). AZDM01 photoelectric sensor measures turbidity using roughly 940 nm infrared transmission. DS18B20 waterproof probe supplies temperature for context and compensation. Interfaces for pH, ORP and TDS/conductivity are built into the firmware and pin map but are disabled in the current prototype (they report static baselines until connected).
iii)Multi-spectral analysis: The AS7341 is an 11-channel spectral sensor (about 350 to 1000 nm) with eight visible channels plus clear and NIR. AquaWatch reads the visible channels (415 to 680 nm) and the clear and NIR channels over I²C while a white LED lights the flow cell.
Contamination often changes the color and light absorption of water, and a spectrum carries more information than a single sensor reading. Multiple studies have used low-cost spectral sensing for water quality monitoring, for example a compact 350 to 950 nm spectrometer that estimated chlorophyll-a, total phosphorus, total nitrogen and COD [1]. With only eight visible channels, AquaWatch uses the AS7341 for relative changes against a clean-water baseline, not for laboratory-grade concentrations.
- Algal index (algae_ndai): a normalised difference between channels near chlorophyll’s red absorption and a longer-wavelength reference, in the style of chlorophyll indices such as NDCI. [F5/F8.]
- CDOM index (cdom_index): relative blue absorption against longer wavelengths, because dissolved organic matter absorbs mostly in the blue. [F1/F6]
Both act as relative flags and cross-check the camera and turbidity pillars.
Fusion and decision: Python code on the Linux core fuses the three pillars, computes a water-quality index (WQI, based on BIS IS 10500) and runs a set of municipal hazard rules. The result is a WQI score, an operational state (Safe, Warning or Critical) and a hazard code.
Coding Explanation and Configuration
AquaWatch is built on the Arduino UNO Q using a dual-processor heterogeneous architecture that divides workloads between real-time microcontroller firmware and Linux Edge-AI services:
- Real-Time Sensor Acquisition (STM32U585 Microcontroller — C++): The STM32 microcontroller continuously samples the analog Turbidity sensor, the 1-Wire DS18B20 Temperature probe, and the I²C AS7341 11-Channel Optical Spectrometer (415 nm to 910 nm). Raw sensor readings are cleaned using a two-stage digital filter (Median Filter to reject air-bubble spikes followed by an Exponential Moving Average filter). The MCU computes hardware spectral indices—Algae NDAI and CDOM Index—and transmits structured JSON telemetry to the Linux processor over the Arduino App Lab Bridge.
- Edge-AI & Three-Pillar Sensor Fusion (Qualcomm QRB2210 Linux — Python): The Linux processor fuses three independent sensing pillars in real time .
Pillar 1 : USB Camera & One-Shot Prototype Vision AI: Captures live video frames via OpenCV to extract a 6-dimensional perceptual feature vector (CIE Lab* color channels, Laplacian spatial gradient variance, high-pass particulate energy, and HSV surface saturation spread). It combines physical optical rules with Radial Basis Function (RBF) One-Shot Prototype Learning and Softmax probabilities.
Pillar 2 : Physicochemical Water Sensors & Multivariate Anomaly Detection: Evaluates temperature-compensated Turbidity (NTU) and Water Temperature (°C) alongside a weighted Z-score and Sigmoid multivariate anomaly detection model.
Pillar 3: AS7341 Multi-Spectral Analysis: Evaluates Chlorophyll/Algae NDAI (relative to the 0.60 threshold and 0.11 clean baseline) and Dissolved Organic Matter CDOM (relative to the 0.85 threshold and 0.75 clean baseline) into dynamic severity tiers (High, Medium, Low, and Clean).
All three pillars are fused into a single Water Quality Index (WQI, 0–100), displayed on a live FastAPI Web Dashboard (Port 8000), logged offline to SD storage, and transmitted as compact 15-byte binary LoRaWAN packets.
Connect the Arduino UNO Q to the computer through USB or over Network Mode, Open Arduino AppLab IDE.
Create a New Project.

Add the required sketch Libraries

Below is brief of the project files
Configuration Files
- app.yaml: Root Arduino App Lab manifest file. It defines the application metadata, exposes network port 8000 for the SCADA web server, and links the Python Linux runtime with the STM32 microcontroller sketch.
- sketch/sketch.yaml: Microcontroller build configuration file for Arduino App Lab. It specifies the target hardware core (arduino:zephyr:unoq) and required firmware libraries (Arduino_RouterBridge, OneWire, DallasTemperature, and Adafruit_AS7341).
- config/thresholds.json: Stores water quality safety limits aligned with BIS IS 10500:2012 drinking water standards (Turbidity NTU limits, Temperature bounds, Optical Clarity thresholds, and Color Shift ΔE*ab thresholds) along with WQI sub-index weights.
- config/calibration_profiles.json: Stores persistent One-Shot Calibration profiles learned directly from real water samples on the hardware, including the 6D visual feature vector, CIE Lab* baseline, Laplacian sharpness variance, and 11-channel AS7341 spectral readings.
- requirements.txt : Lists the Python dependencies required on the Qualcomm Linux processor: fastapi, uvicorn, opencv-python-headless, numpy, pydantic, websockets, and requests.
Arduino Sketches(Real time STM32 Core)
- sketch/sketch.ino: Main microcontroller firmware. Initializes all physical sensors, samples temperature, analog turbidity voltage, and AS7341 11-channel spectral counts (F1–F8, Clear, NIR), controls the sampling interval and registers Bridge RPC endpoints for Linux communication.
- sketch/CalibrationConfig.h: Header file containing hardware pin mappings, ADC reference constants, temperature-compensated turbidity equations, and the spectral formulas for Algae NDAI = (F5 – F8) / (F5 + F8) and CDOM Index = (F6 – F1) / (F6 + F1).
- sketch/SensorFilters.h: Implements digital signal conditioning using a sliding-window Median Filter (to eliminate transient electrical noise and air-bubble spikes) cascaded into an Exponential Moving Average (EMA) low-pass filter, along with hardware disconnect/fault detection.
Linux Edge-AI & Backend Services (python/ folder)
- python/main.py (and root main.py): Primary application entry point executed by Arduino App Lab. Launches the FastAPI web server in a background daemon thread and maintains the App.run() execution loop.
- python/dashboard_app.py: FastAPI web server and 1 Hz telemetry orchestrator. Coordinates sensor polling, camera frame analysis, and Edge-AI inference, streams live annotated MJPEG video (/video_feed), and provides REST API endpoints (/api/telemetry, /api/calibrate, and /api/sdcard).
- python/bridge_client.py: Inter-processor communication driver between the Qualcomm Linux CPU and STM32U585 MCU. Polls real-time sensor JSON data and sends actuator control commands (pump and alarm) over the Arduino Bridge / Serial RPC interface.
- python/contamination_engine.py: Core Three-Pillar Sensor Fusion Engine. Combines Camera Vision, Water Sensors, and AS7341 Spectrometer indices (classifying NDAI and CDOM relative to their 0.60 and 0.85 thresholds into High, Medium, Low, and Clean tiers), calculates the composite Water Quality Index (WQI 0–100), and outputs diagnostic hazard alerts.
- python/vision_inspector.py: OpenCV computer vision pipeline. Captures frames from the USB camera and calculates Optical Clarity % (via Laplacian variance sharpness), Discoloration ΔEab (in CIE Lab perceptual color space), suspended Particulate Count, and Surface Sheen detection.
- python/vision_ai_classifier.py: Lightweight Edge-AI visual classifier. Extracts a 6-dimensional perceptual feature vector from the flow-cell and surface regions of interest (CIE L*, a*, b*, Laplacian gradient variance, high-pass particulate energy, and HSV surface saturation spread). It combines physical optical scoring with One-Shot Prototype Learning (weighted Euclidean distance and Radial Basis Function similarity against saved exemplars) and Softmax normalization to classify water into Clean_Potable, Suspended_Sediment, Algae_Biofilm, Chemical_Discoloration, or Hydrocarbon_Sheen.
- python/sensor_anomaly_model.py: Multivariate statistical Edge-ML anomaly detector. Fuses physical sensor channels, optical vision metrics, and AS7341 spectral indices using one-sided normalized Z-scores, weighted Euclidean distance, and a logistic sigmoid function to compute a continuous anomaly score (0.0 to 1.0) and isolate single-probe drift faults.
- python/calibration_manager.py: One-Shot Calibration manager. Allows operators to calibrate clean local water baselines or teach new contamination types in a single click, persisting the learned 6D optical vectors and spectral baselines to config/calibration_profiles.json.
- python/lorawan_service.py: LoRaWAN telemetry service. Compresses key water quality metrics (WQI, turbidity, temperature, optical clarity, spectral NDAI, and hazard bitmask) into an ultra-compact 15-byte binary payload and transmits it over UART AT commands to a LoRaWAN radio module.
- python/sdcard_manager.py: Local offline storage manager. Logs time-series telemetry to CSV files and automatically saves timestamped camera snapshots when contamination events occur.
Web Dashboard Frontend (python/static/ and asset/ folders)
- python/static/index.html (and assets/index.html): Single-page dashboard layout featuring the real-time WQI gauge, live annotated camera feed, Three-Pillar Classification cards (USB Camera, Water Sensors, and AS7341 Spectrometer), 11-channel spectral bar chart, and One-Shot Calibration controls.
- python/static/app.js (and assets/app.js): Frontend JavaScript application. Polls /api/telemetry once per second, dynamically updates sensor cards, classification badges, and spectral bars, triggers audible browser alarms during critical hazards, and handles calibration requests.
- python/static/style.css (and assets/style.css): Responsive dark-theme stylesheet for the web interface, including color-coded severity badges (SAFE, WARNING, CRITICAL, OFFLINE) and wavelength-matched spectral channel bars.
ALGAE NDAI & CDOM INDEX CALCULATIONS (AS7341 SPECTROMETER)
1. Algae NDAI (Normalized Difference Algae Index)
- Principle: Chlorophyll-a in algae reflects Green light (F5 = 555 nm) and absorbs Red light (F8 = 680 nm).
- Formula: Raw NDAI = (F5 – F8) / (F5 + F8)
- Baseline Compensation: Delta NDAI = max(0, Raw NDAI – 0.11) (Clean Baseline = 0.11, Threshold = 0.60)
- Classification Tiers:
- >= 0.60: NDAI High (CRITICAL) — Exceeds threshold (Algae bloom detected)
- 0.38 to 0.59: NDAI High (WARNING) — Close to threshold (Elevated green/algae signature)
- 0.22 to 0.37: NDAI Medium (WARNING) — Moderately elevated
- 0.16 to 0.21: NDAI Low (SAFE) — Within safe limits
- < 0.16: Clean (SAFE) — Normal baseline
2. CDOM Index (Colored Dissolved Organic Matter)
- Principle: Dissolved organic matter, tannins, and sewage strongly absorb Violet light (F1 = 415 nm) while transmitting Yellow light (F6 = 590 nm).
- Formula: Raw CDOM = (F6 – F1) / (F6 + F1)
- Baseline Compensation: Delta CDOM = max(0, Raw CDOM – 0.75) (Clean Baseline = 0.75, Threshold = 0.85)
- Classification Tiers:
- >= 0.85: CDOM High (CRITICAL) — Exceeds threshold (Organic/sewage contamination)
- 0.81 to 0.84: CDOM High (WARNING) — Close to threshold
- 0.79 to 0.80: CDOM Medium (WARNING) — Moderately elevated
- < 0.79: Clean (SAFE) — Normal baseline
LoRaWAN- 15 Byte Payload Format.
- Byte 0 — Header & Hazard Byte (uint8, 1 Byte): – Bit 7 (MSB): Alert Flag (1 = Emergency Alert Required, 0 = Normal Heartbeat
- Byte 1 — Water Quality Index / WQI (uint8, 1 Byte): – Range: 0 to 100
- Bytes 2–3 — pH Level (uint16 Big-Endian, 2 Bytes): – Scaling: pH × 100 – Example: 742 (0x02E6) = 7.42 pH
- Bytes 4–5 — Turbidity (uint16 Big-Endian, 2 Bytes): – Scaling: Turbidity NTU × 10 – Example: 45 (0x002D) = 4.5 NTU
- Bytes 6–7 — Total Dissolved Solids / TDS (uint16 Big-Endian, 2 Bytes): – Scaling: 1 ppm per LSB (TDS ppm integer) – Example: 180 (0x00B4) = 180 ppm
- Bytes 8–9 — Oxidation-Reduction Potential / ORP (int16 Signed Big-Endian, 2 Bytes): – Scaling: 1 mV per LSB (supports both positive and negative mV) – Example: 675 (0x02A3) = +675 mV
- Bytes 10–11 — Water Temperature (int16 Signed Big-Endian, 2 Bytes): – Scaling: Temperature °C × 10 – Example: 215 (0x00D7) = 21.5 °C
- Byte 12 — Optical Clarity Percentage (uint8, 1 Byte): – Range: 0 to 100 % (from USB Camera Laplacian sharpness)
- Byte 13 — Suspended Particulate Count (uint8, 1 Byte): – Range: 0 to 255 particles (capped at 255)
- Byte 14 — Optical & Spectral Bitmask Flags (uint8, 1 Byte): – Bit 0: Surface Oil Sheen Flag (1 = Sheen detected by camera, 0 = None) – Bit 1: Discoloration Anomaly Flag (1 = Color shift ΔE*ab > 10.0, 0 = Normal) – Bit 2: AS7341 Algae NDAI Flag (1 = Algae NDAI threshold exceeded, 0 = Normal) – Bit 3: AS7341 CDOM Flag (1 = Organic CDOM threshold exceeded, 0 = Normal) – Bits 4–7: Reserved (0000)
Flow Diagram

Connection Explanation
The ASAIR AZDM01 turbidity sensor connects to analog pin A1 through a 10 kΩ/30 kΩ voltage divider connected to 3.3V power supply..
The DS18B20 temperature probe connects to digital pin D2 with a 4.7 kΩ pull-up resistor to 3.3V.
An Adafruit AS7341 spectrometer communicates over I2C (SDA/SCL), while optional pH, TDS, and ORP boards wire to pins A0, A2, and A3. The UVC camera connects directly to the Linux USB-Host port, and an Ebyte LoRaWAN modem uses UART (D0/D1) pins. The connection diagram is as below.


Testing
Start the application on Arduino AppLab

Open the dashboard.

If the camera is not appearing, then change the USB mode to host mode.

System Calibration
Put Clean Tap water or distilled water on the flow call and do a system calibration if it does not shows Potable WQI – 100



Click on send uplink button on the dashboard.
Check on ChirpStack LoraFrames , it should report as WQI of 100.

TESTING
TEST 1: Clear Water , Press the Take Sample button



Result: The system achieved a Water Quality Index (WQI) of 100, indicating clean water with no detected anomalies across vision, electrochemical, and spectral channels. The AS7341 reported a CDOM Index of Medium (0.80), likely attributable to the slight brown tint of the test water sample; this offset can be resolved through sensor-specific baseline calibration against a known reference sample. All readings were successfully transmitted over LoRaWAN, with the 15-byte binary payload confirmed received at the gateway as shown in the telemetry panel above.
TEST 2: Yellow Dye(Cooking Haldi mixed with Oil) , Press the Take Sample button


Result: As we can see that the camera classified this as Oil Sheen and the spectrometer classified it as CDOM high , the WQI was computed as 15.9 and categorized as Unsafe
TEST 3: Green Color Dye to simulate Algal growth, Press the Take Sample button


Result: Camera classified this again as Oil Sheen , this could be due to yellow hue, this can be corrected through more calibration and offset. The Spectrometer classified it correctly as NDAI High as the index was close to threshold. The WQI was computed as Unsafe (5.7).
TEST 4: We mixed mud into water and then took the sample.


Result: Camera classified this as algae growth , this could be attributed to the greenish hue,. The Spectrometer classified it correctly as CDOM High as the index was close to threshold. The WQI was computed as Unsafe (55.6).
TEST 5: We mixed red dyes into water simulating organic waste and then took the sample.



Result : Camera classified this as Oil. The Spectrometer classified it as CDOM High as the index was close to threshold. The WQI was computed as Unsafe (5.6).
TEST 6: To simulate turbid water we mixed corn flour into water and took the sample.


Result : Camera classified this correctly as Sediment/Murky. The Spectrometer classified it as CDOM High as the index was close to threshold. The WQI was computed as Unsafe (55.4).
Schematics

Limitations
- AquaWatch detects optical and physical proxies for contamination. It does not detect bacteria directly and does not replace laboratory testing. It is an early-warning system.
- pH, ORP and TDS/conductivity are not yet connected in the first prototype owing to high cost. These are valuable indicators of sewage ingress and are the first planned upgrade.
- The prototype was tested on a bench with dyes and organic waste, not on a live pipeline
Future Work
1. Physical Sensor Expansion: Complete 5-Probe Cluster: Mount the physical pH, TDS, and ORP probes alongside the existing Turbidity and Temperature sensors (firmware math and LoRaWAN channels are already implemented), also add Dissolved Oxygen (DO) and an in-line Water Flow Meter for volumetric usage tracking. Add a periodic clean-water rinse or miniature ultrasonic transducer to prevent biofilm fouling on submerged physical sensor heads.
2. Rugged Flow Cell: sealed, light-tight flow-cell enclosure to eliminate ambient daylight interference on the camera and AS7341 spectrometer.
3. Solar Power & Duty Cycling: Integrate a 10W solar panel with a LiFePO4 battery pack. • Power Duty Cycling: Put the node into deep sleep (< 50 mW), waking every 10–30 minutes sampling and LoRaWAN transmission cycle.
4. Alerting: Integrate alert through Whatsapp or SMS messaging with Chirpstack LoRa Application server: Send instant warning messages to Gram Panchayat/Municipality pump operators and village health workers whenever WQI drops or hazardous contaminants are detected.
References
1. Wang, Y., et al., “Development and Application of a Miniaturized Multispectral Detection System for Water Reflection Detection,” Sensors, MDPI, vol. 23, no. 14, 2023.
2. “Research on water quality detection integrating spectral analysis and automated control,” Spectrochimica Acta Part A: Molecular and Biomolecular Spectroscopy, vol. 339, p. 126260, Oct. 2025
3. AMS OSRAM AG, “AS7341 11-Channel Spectral Sensor: Optical Spectroscopy and Colorimetric Analysis for Environmental and Fluid Quality Applications,” Application Note AN000672, Premstaetten, Austria, 2021.
4. R. C. Gonzalez and R. E. Woods, Digital Image Processing, 4th ed. Pearson, 2018.
5. Commission Internationale de l’Éclairage (CIE), Colorimetry, 3rd ed., CIE 015:2004
6. C. M. Bishop, Pattern Recognition and Machine Learning. Springer, 2006.




Very interesting project. Exceptional use of IoT
Excellent innovation! 👏🌊 AquaWatch is a promising solution for real-time water quality monitoring using Edge AI and LoRaWAN, especially for rural India. This project has great potential to improve safe drinking water access through early detection and smart monitoring. Best wishes to the team! 🚀🇮🇳
Thanks Sir !!