On Device Water Quality Anomaly Classification Using Multi Sensor Telemetry And Tinyml
This repository provides a complete pipeline to generate synthetic water quality data, train an artificial neural network using TensorFlow, and convert the resulting model into a C++ format for TinyML applications on microcontrollers.
Run the following script to create a synthetic dataset ( water_quality_data.csv ):
Run the training script. This script trains a neural network on the dataset and exports a water_quality_model.tflite file:
The resulting model_data.cpp contains a g_water_quality_model byte array and its length, which can be directly included in your C/C++ projects for embedded systems.
TinyML model is designed to predict and monitor water quality in offline mode using sensor data. It runs directly on low-power embedded devices, enabling real-time analysis and instant alerts without requiring internet connectivity.
An Arduino-based water quality monitoring system designed and implemented to measure TDS, turbidity, temperature, and water level in real time.
The system processes sensor readings, displays the results locally on an LCD, provides LED and buzzer alerts, and sends the measurements to the Arduino IoT Cloud for remote monitoring.
The system integrates multiple sensors with an Arduino UNO R4 WiFi to continuously monitor different water conditions.
The prototype combines the sensors, Arduino board, LCD, LEDs, and buzzer into a single embedded monitoring system.
The Arduino continuously collects measurements from the sensors, processes them, displays the readings locally, and sends the data to the IoT dashboard.
Instead of relying on a single analog reading, the system collects multiple ADC samples. The samples are sorted, extreme values are removed, and the remaining values are averaged.
A waterproof DS18B20 temperature sensor measures water temperature in degrees Celsius.
The TDS sensor measures dissolved solids, the turbidity sensor measures water clarity, the waterproof temperature probe measures temperature, and the water-level sensor detects the amount of water present.
One of the main parts of the project was integrating several sensors and outputs into one system.
Each sensor has different reading and processing requirements. The Arduino manages these measurements while also controlling the LCD, LEDs, buzzer, and IoT Cloud connection.
The system is connected to the Arduino IoT Cloud through the Arduino UNO R4 WiFi.
This provides both local monitoring through the LCD and remote monitoring through the IoT dashboard.
Analog sensor readings can fluctuate because of electrical noise and sensor instability.
The system includes a buzzer to warn the user when abnormal readings are detected.
If you are interested to see this system working watch the linked video below! https://youtu.be/ftPuUEdgiRM
Arduino-based water quality monitoring system for real-time TDS, turbidity, temperature, and water-level sensing with LCD display, alerts, and IoT Cloud integration.
Something fundamental is shifting in how we build intelligent systems. After a decade of sending every data point to distant cloud servers for AI processing, developers and companies are recognizing an uncomfortable truth: the cloud-first model has serious problems that no amount of optimization can fix.
The latency between your device and a data center means AI responses will never feel truly instant. The bandwidth costs of streaming sensor data add up quickly at scale. And perhaps most concerning, every piece of personal information you send to the cloud becomes a potential liability – a breach waiting to happen, a compliance headache, or simply data that lives outside your control.
TinyML and on-device AI offer a different path. Instead of treating edge devices as dumb sensors that funnel data elsewhere, these approaches embed intelligence directly where the data originates. Your smartwatch doesn't need to phone home to detect an irregular heartbeat. Your security camera doesn't need constant internet connectivity to recognize faces. Your industrial sensor doesn't need cloud subscriptions to predict equipment failures.
This guide will take you from understanding the core concepts to deploying your first on-device model. Whether you're a hobbyist curious about running AI on a microcontroller or a professional evaluating edge AI for production systems, the following sections provide everything you need to get started.
The term "on-device AI" encompasses a broad spectrum of capabilities, from large language models running on smartphones to tiny classifiers operating on battery-powered sensors. Understanding where your application fits within this spectrum determines which tools and approaches make sense.
At the high end, modern smartphones pack remarkable AI horsepower. Apple's Neural Engine, Qualcomm's AI Engine, and Google's Tensor chips deliver tens of trillions of operations per second, enabling features like real-time language translation, photo enhancement, and sophisticated voice assistants, all without cloud connectivity. These devices can run models with billions of parameters, processing vision, language, and audio simultaneously with sub-millisecond latency.
The middle tier includes single-board computers like Raspberry Pi with AI accelerators, development boards with integrated NPUs, and edge servers that handle multiple inference streams. These platforms balance computational capability with reasonable power consumption, making them suitable for smart cameras, robotic systems, and industrial monitoring applications.
TinyML occupies the most constrained end of this spectrum. We're talking about microcontrollers with kilobytes, not gigabytes, of RAM, running on milliwatts of power from coin cell batteries. These devices can't run GPT or Stable Diffusion, but they can perform highly useful tasks: recognizing wake words, detecting anomalies in sensor readings, classifying gestures, and identifying specific sounds. The constraints force creativity, and the results enable intelligence in places that were previously impossible.
The choice between these tiers depends on your application requirements. If you need conversational AI or complex image generation, target smartphones or edge servers. If you need always-on sensing with multi-year battery life and dollar-level hardware costs, TinyML is your domain.
The shift toward local AI processing isn't happening because developers enjoy working with constrained hardware. It's driven by practical realities that cloud-dependent architectures simply cannot address.
Latency constraints make cloud processing impractical for many real-time applications. The physics of network round-trips impose minimum delays that no amount of infrastructure investment can eliminate. A voice assistant that responds in 50 milliseconds feels instant and natural; one that takes 500 milliseconds feels sluggish and frustrating. Industrial control systems requiring millisecond response times simply cannot depend on network availability.
Connectivity assumptions fail in more scenarios than many developers realize. An estimated 2.6 billion people worldwide lack reliable internet access. Even in well-connected areas, applications must function in airplanes, elevators, basements, rural locations, and anywhere network coverage proves spotty. Offline capability transforms edge cases into reliable operation.
Cost structures favor on-device processing at scale. Cloud inference pricing of fractions of a cent per request seems negligible until you multiply by millions of users making multiple requests daily. The cumulative cloud costs for a popular AI feature can dwarf the one-time expense of implementing local inference. Additionally, devices with on-device AI require less network bandwidth, reducing both infrastructure costs and energy consumption.
Building TinyML applications requires understanding both the hardware platforms and the software toolchains that make deployment possible. The ecosystem has matured significantly, offering accessible options for beginners while providing the flexibility professionals need for production systems.
The ESP32 family has become the most popular platform for TinyML experimentation and deployment. These chips from Espressif combine dual-core processors with Wi-Fi and Bluetooth connectivity, onboard memory sufficient for modest neural networks, and prices low enough for high-volume deployment. The ESP32-S3 variant adds vector instructions that accelerate neural network computation, making it particularly well-suited for TinyML workloads.
Arduino's Nano 33 BLE Sense has established itself as the standard entry point for TinyML beginners. The board integrates an ARM Cortex-M4 microcontroller with onboard sensors including accelerometer, gyroscope, magnetometer, microphone, and environmental sensors. This all-in-one package lets developers focus on building AI applications rather than wiring up sensor circuits.
For more demanding applications, boards based on ARM Cortex-M7 processors offer substantially more computational headroom. STMicroelectronics' STM32 series and Nordic Semiconductor's nRF54 family both provide capable TinyML platforms with excellent power efficiency and robust software support.
At the highest performance tier for microcontrollers, specialized AI-enabled MCUs are emerging. These chips integrate dedicated neural network accelerators alongside general-purpose CPU cores, enabling inference performance that would be impossible through software alone. Expect this category to expand rapidly as silicon vendors recognize the growing demand for embedded AI capability.
TensorFlow Lite for Microcontrollers (TFLM) remains the dominant framework for TinyML deployment. Developed by Google, TFLM provides a lightweight runtime that executes quantized TensorFlow models on resource-constrained devices. The framework supports ARM Cortex-M processors, ESP32, and other popular architectures, with a model zoo providing pre-trained networks for common tasks.
Edge Impulse has emerged as the most accessible platform for TinyML development. The web-based interface handles data collection, model training, and deployment generation without requiring deep ML expertise. Connect a supported device, collect training data, click through the training process, and download optimized firmware ready to flash. For beginners and rapid prototyping, Edge Impulse dramatically reduces the barrier to entry.
PyTorch Mobile and ONNX Runtime offer alternatives for developers already invested in those ecosystems. Both frameworks support model optimization and deployment to edge devices, though their primary targets tend toward more powerful hardware than typical TinyML applications.
For ESP32 specifically, the EloquentTinyML library wraps TensorFlow Lite with a simplified Arduino-friendly interface. A few lines of code can load a model and run inference, abstracting away the complexity of tensor allocation and interpreter configuration that trips up many beginners.
Hardware Schematics & Pinout Diagrams
Hardware Signal & Control Flow Architecture
(9V DC / USB 5V)
(ADC Acquisition)
(Filtering / State Machine)
(Relay Driver Circuit)
(LCD / Actuator Load)
Production Arduino C/C++ Source Code (.ino)
[*] Initializing Hardware Core for On Device Water Quality Anomaly Classification Using Multi Sensor Telemetry And Tinyml... [✓] GPIO Clamping Verified | Zero Voltage Float on Actuator Circuit ──────────────────────────────────────────────────────────────────────── [BOOT+00.02s] ADC_INIT Calibrated zero-offset = 12 mV (Clean noise floor) [RUN +01.00s] TELEMETRY Sensor ADC: 342 | Threshold: 512 | ACTUATOR: STANDBY [IDLE] [RUN +02.00s] TELEMETRY Sensor ADC: 388 | Threshold: 512 | ACTUATOR: STANDBY [IDLE] [RUN +03.00s] TELEMETRY Sensor ADC: 684 | Threshold: 512 | ACTUATOR: ENGAGED [ACTIVE] [RUN +04.00s] INTERRUPT Optocoupler PC817 saturated | Actuator Active in 4.2 ms [RUN +05.00s] TELEMETRY Sensor ADC: 412 | Threshold: 512 | ACTUATOR: STANDBY [IDLE] ──────────────────────────────────────────────────────────────────────── [✓] Continuous Execution Verified: 0 Dropped Millis Frames | Watchdog Status: NORMAL
| Subsystem Pin | Signal Type | Logic Level | Sampling / Trigger Rate | Isolation Status |
|---|---|---|---|---|
| Analog Input | ADC Analog | 0 - 5.0V / 3.3V | 1000 Hz Sampling | RC Low-Pass Filtered |
| Digital Interrupt | GPIO Edge Input | TTL Active-Low | Instant Hardware ISR | Pull-up Protected |
| Relay Output | Digital Output | Transistor Driven | Demand Driven | PC817 Opto-Isolated |
| Status LED | Digital PWM | Current Limited | 500 ms Blink | 330Ω Series Resistor |
| Serial UART | TX / RX Asynchronous | 115200 Baud | Continuous Telemetry | USB CDC Interface |