Implementing Remote CCTV Access Using Ngrok Tunnel for ESP32-CAM Monitoring
While local Wi-Fi streaming is sufficient for internal monitoring, remote access becomes essential when surveillance needs to be accessed outside the local network. In this project, remote monitoring was implemented using Ngrok tunneling to expose the ESP32-CAM stream securely over the internet.
This approach eliminates the need for complex router port forwarding configuration and allows quick deployment in dynamic IP environments.
Local Streaming Architecture
By default, ESP32-CAM hosts a local HTTP video stream accessible via:
http://192.168.x.x:81
The IP address is obtained from the Android setup interface.
In local mode:
Device and smartphone must be on the same Wi-Fi network
Local Host option remains enabled
Video streaming occurs via internal LAN
However, this limits access to the same network.
Remote Access Challenge
Problems with direct remote access:
Dynamic public IP from ISP
Router port forwarding complexity
Security risk when exposing raw ports
Firewall restrictions
To solve this, Ngrok was used as a secure HTTP tunnel.
Ngrok Tunneling Configuration
ctREDIsAAAAASUVORK5CYII=
The setup process follows the procedure shown:
Create an Ngrok account
Download ngrok executable
Authenticate using authtoken
Run command:
ngrok http 192.168.xx.xx:81
This creates a secure public forwarding URL.
Once active, Ngrok generates a public HTTPS address such as:
https://xxxx-xx-xx-xx.ngrok.io
This URL is then entered into the Android app under the server configuration menu.
Switching from Local to Online Mode
In the Android interface:
Disable Local Host
Enter Ngrok forwarding URL
Save configuration
Restart streaming
After this, the CCTV stream becomes accessible externally.
The device and PC running Ngrok must be on the same network.
Security Considerations
Although Ngrok simplifies remote access, several precautions are necessary:
Use HTTPS forwarding
Avoid publishing raw IP address
Protect Firebase rules properly
Disable open read/write access in production
Use strong Wi-Fi credentials
Limit Ngrok session exposure
For industrial deployment, dedicated cloud hosting or reverse proxy services would be recommended.
Network Stability and Performance
Key implementation considerations:
Maintain stable LAN connection
Ensure sufficient upload bandwidth
Avoid excessive frame resolution
Monitor latency during streaming
Restart Ngrok tunnel if session expires
Ngrok free sessions typically reset periodically, so persistent monitoring may require automation.
Engineering Insight
This remote monitoring architecture demonstrates how embedded devices can extend beyond LAN constraints using tunneling services.
By integrating:
ESP32-CAM local HTTP server
Ngrok secure forwarding
Android remote configuration
Firebase synchronization
The system becomes a flexible IoT surveillance platform suitable for home, laboratory, and small industrial use.
Conclusion
Implementing Ngrok-based tunneling transforms a local ESP32-CAM CCTV system into a remotely accessible surveillance device without complex router configuration.
This approach provides a fast deployment solution for remote monitoring while maintaining modular firmware architecture between streaming, motion detection, and cloud synchronization.
#IoTProject#
#ESP32CAM#
#NgrokTunnel#
#RemoteAccess#
#EmbeddedNetworking#
#SmartCCTV#
#HTTPSTunnel#
#WiFiSecurity#
#AndroidMonitoring#
Designing a Wi-Fi CCTV Camera Using ESP32-CAM with PIR Motion Detection and Firebase Integration
The ESP32-CAM module enables compact and cost-effective smart surveillance systems by combining Wi-Fi connectivity and camera streaming in a single microcontroller board. In this project, a Wi-Fi CCTV camera was developed with motion detection, Firebase cloud integration, Android monitoring, and SD card recording capability.
This system was designed not only for local monitoring, but also for cloud synchronization and remote configuration.
Hardware Architecture
The core of the system is the AI Thinker ESP32-CAM board configured via Arduino IDE.
The hardware components include:
ESP32-CAM
PIR motion sensor
Buzzer alarm
Push button (Setup/Reset)
5V regulated adaptor
SD card storage
The wiring architecture is illustrated in the wiring diagram, showing:
PIR output connected to ESP32-CAM GPIO
Buzzer driven through transistor stage
External buttons for programming and setup
5VDC regulated supply
Board component placement is detailed in the board layout section, clearly identifying PIR, buzzer, supply adaptor input, and button.
Motion Detection and Alarm Logic
The PIR sensor continuously monitors environmental movement. When motion is detected:
ESP32-CAM sets motion flag.
Buzzer alarm activates.
Motion status is written to Firebase.
Android app displays detection notification.
Optional SD card recording is triggered.
The Android application interface shows:
Motion Detection toggle
Buzzer enable/disable
SD recording control
Video streaming window
To prevent repeated triggers, the system requires manual reset after detection.
Firebase Realtime Database Integration
Cloud integration is implemented through Firebase Realtime Database setup.
The process includes:
Creating Firebase project
Enabling Realtime Database
Configuring database rules (read/write true)
Importing JSON structure
Retrieving Firebase host and database secret
These credentials are configured inside the ESP32 firmware and Android application.
The system updates:
Motion status
Device state
Alarm flags
This enables real-time cloud synchronization.
Android Application (Kodular)
The Android application is developed using Kodular.
Configuration steps include:
Importing .aia project
Setting Firebase URL and secret
Building APK file
The app provides:
Live video streaming
Motion detection control
Alarm control
SD card recording activation
Device setup interface
Offline and Setup Mode
If Wi-Fi is unavailable for 30 seconds, the device enters offline mode.
In offline mode:
Local streaming remains active
SD recording continues
Cloud synchronization pauses
The setup procedure includes boot-time button press to enter configuration mode, allowing users to configure Wi-Fi SSID, password, and Firebase credentials.
Enclosure and Deployment
The panel box installation shows:
Front PIR window
Camera lens opening
SD card access
External reset button
5V adaptor input
This transforms the system from a development prototype into a deployable surveillance unit.
Engineering Considerations
Key design considerations:
Separate motion detection logic from streaming loop
Use transistor driver for buzzer stability
Avoid excessive Firebase writes
Implement auto-reconnect Wi-Fi logic
Maintain SD recording independent of cloud status
This architecture ensures reliable operation in both local and connected environments.
Conclusion
The Wi-Fi CCTV Camera using ESP32-CAM demonstrates a practical IoT-based surveillance solution integrating motion detection, cloud database synchronization, Android monitoring, and SD card recording.
By combining embedded firmware, cloud backend, and mobile interface, this project provides a scalable and cost-effective smart security platform suitable for home and small industrial applications.
#IoTProject#
#ESP32CAM#
#WiFiCCTV#
#FirebaseRealtimeDatabase#
#PIRSensor#
#EmbeddedSystem#
#AndroidMonitoring#
#Kodular#
#SmartSecurity#
#MotionDetection#
Designing an IoT-Based ESD Wrist Strap Tester with RFID Authentication Using ESP8266
Electrostatic Discharge (ESD) protection is critical in electronic manufacturing environments where sensitive components are handled. A faulty wrist strap or improper grounding can silently damage microcontrollers, sensors, and communication modules.
To improve traceability and operational safety, an IoT-based ESD wrist strap tester was developed using ESP8266 with RFID authentication and web-based logging.
This system ensures that only registered personnel can perform ESD checks while automatically recording test results to a centralized database.
System Architecture Overview
The complete hardware architecture is shown in the wiring diagram. The system consists of:
ESP8266 (NodeMCU) as main controller
Anti-Static Tester (HAKKO 498 type interface)
DC Voltage Sensor module
RFID RC522 module
Relay module
Buzzer and LED indicators
PIR sensor (presence detection)
12V DC power input with voltage regulation
The ESP8266 acts as the central processing unit, coordinating authentication, test execution, data acquisition, and web communication.
RFID-Based Authentication
Before an ESD test can be performed, the user must scan an RFID card. The RC522 module reads the card UID and sends it to the ESP8266.
If the UID matches a registered user in the database:
User identity is displayed on the web interface
ESD test is enabled
Test result is logged
The operation interface shows the wrist strap tester display and user data fields, including:
Badge number
Name
Division
Test result
This ensures traceability and accountability in industrial environments.
ESD Measurement Integration
The Anti-Static Tester output is connected to a DC Voltage Sensor module, which conditions the signal before it is read by the ESP8266 analog input.
The measurement flow is:
User connects wrist strap
Relay activates test path
Anti-static tester measures grounding condition
Voltage sensor captures test output
ESP8266 evaluates result
LED and buzzer indicate PASS or FAIL
This indirect sensing approach ensures electrical isolation and system protection.
Web-Based IoT Logging
The ESP8266 connects to a 2.4 GHz WiFi access point and sends data to a local server hosted using XAMPP.
Database is created in MySQL
SQL file is imported
PHP web interface handles login and employee management
Admin can register new RFID cards
Each ESD test result is recorded in the database, enabling monitoring and reporting.
Relay and Interlock Preparation
The relay module shown in the wiring diagram is used to control the test activation path.
The system is designed so that:
No authentication → Relay remains disabled
Fault condition → Test blocked
Power reset → System returns to safe state
This structure prepares the system for more advanced interlock handling logic, which will be discussed in the next article.
Electrical Protection and Stability
Because ESD testing environments involve high transient energy, several protective measures are implemented:
Dedicated 12V input with regulation
Diode protection on sensing line
Proper grounding between modules
Isolation via relay
Stable 3.3V supply for RC522
These design decisions improve noise immunity and prevent false triggering.
Engineering Considerations
Key principles implemented in this system include:
· Authentication before activation
· Digital logging of all test results
· Hardware protection against voltage spikes
· Modular separation between sensing, control, and networking layers
This approach transforms a simple wrist strap tester into a smart industrial compliance system.
Conclusion
The IoT-based ESD wrist strap tester demonstrates how embedded systems can enhance industrial safety procedures. By combining RFID authentication, voltage sensing, relay control, and web-based logging, the system ensures controlled testing, traceable results, and improved operational discipline.
This project highlights the integration of embedded firmware, hardware protection, and IoT infrastructure within a real industrial application.
#ESDTester##ElectrostaticDischarge##IndustrialSafety##ESP8266##RFID##IoTProject##EmbeddedSystem##IndustrialAutomation##RelayControl##MySQLDatabase#
Implementing Server–Client Synchronization for Multi-Panel LED Display Systems Using ESP8266
In large-scale timing applications such as sports competitions, a single LED display panel is often insufficient. To improve visibility across wider areas, multiple synchronized display units are required. In the WiFi-based LED countdown project, a server–client architecture was implemented using ESP8266 modules to ensure synchronized timing across multiple P10 LED panels.
This article explains how synchronization was achieved and the engineering considerations behind it.
System Architecture
The system consists of:
One Main Unit (Server)
One or more Client Units (Slave Displays)
WiFi network (Access Point mode)
The main device generates the countdown logic and broadcasts timing data. Client units do not compute countdown independently. Instead, they receive synchronized timing parameters from the server.
This prevents drift between displays.
Why Server–Client Instead of Independent Timers?
If each device runs its own internal countdown:
Clock drift may occur
Pause/Resume may desynchronize
Network delay may cause mismatch
Reset timing may differ
By centralizing logic in the server:
Only one authoritative timer exists
All displays follow the same reference
State changes propagate simultaneously
This ensures deterministic synchronization.
Communication Strategy
The ESP8266 server operates in WiFi mode and handles:
Timer start
Pause
Reset
Brightness setting
Running text updates
Client configuration step, where each slave device connects to the server using:
SSID
Password
Device ID
Once connected, clients listen for timing packets.
Data Synchronization Logic
Instead of transmitting every second tick, the server sends:
Initial countdown value
State command (RUN / PAUSE / RESET)
Periodic synchronization update
Clients use:
Received time reference
Local timer interrupt
Periodic correction from server
If discrepancy is detected, the client adjusts its timer to match the server.
This reduces network traffic while maintaining accuracy.
Handling Network Instability
WiFi-based systems are susceptible to:
Packet loss
Temporary disconnection
Signal interference
To mitigate this:
Clients reconnect automatically
Timeout detection triggers re-synchronization
Countdown state is revalidated after reconnection
This ensures system reliability even in unstable environments.
Engineering Challenges
During implementation, several issues were encountered:
Display update blocking network handling
Timing jitter during heavy WiFi traffic
Delayed synchronization when multiple clients connected
Solutions included:
Non-blocking firmware structure
Lightweight synchronization packets
Separation between display refresh and WiFi tasks
Conclusion
The server–client synchronization architecture transforms a simple LED timer into a scalable multi-display system. By centralizing timing control and distributing synchronized updates, the system achieves reliable operation across multiple panels.
This approach can be extended to industrial dashboards, production counters, and large event displays.
#LEDProject##ESP8266##ServerClient##WiFiSynchronization##P10Display##LEDMatrix##HUB12##EmbeddedNetworking##MultiPanelDisplay##IndustrialDisplay#
Designing a WiFi-Based LED Countdown Timer Using ESP8266 and P10 Display
LED display systems are widely used in sports arenas, event stages, and industrial environments for visual timing and status indication. In this project, a WiFi-based LED countdown timer was developed using the ESP8266 microcontroller and P10 LED display panels, specifically designed for archery timing applications.
The system supports remote configuration via Android application and synchronized server–client operation for multi-panel deployment.
System Architecture Overview
The LED countdown timer consists of:
ESP8266 (NodeMCU) as main controller
P10 LED display panel (HUB12 interface)
5V high-current power supply
Buzzer module
Manual push button
Android WiFi-based control application
The ESP8266 manages timing logic, WiFi communication, and LED refresh operations simultaneously. Proper separation of display refresh and network handling is critical to maintain flicker-free output.
Hardware Wiring and Power Considerations
As illustrated in the wiring diagram, the ESP8266 connects to the P10 LED panel through a 16-pin HUB12 connector. Correct pin mapping ensures proper row scanning and multiplexed LED control.
Important hardware considerations include:
Common ground between ESP8266 and LED panel
Dedicated 5V supply (recommended ≥2A) for stable brightness
USB 5V input for programming and debugging
Buzzer connected to digital output for countdown alert
Push button for manual control
Because P10 panels draw significant current during refresh cycles, voltage stability and short power wiring are essential to prevent flicker and brightness fluctuation.
LED Display Control
The P10 display operates using multiplexed scanning. The firmware controls:
Display refresh timing
Brightness level
Character rendering
Countdown visualization
To avoid flicker:
Refresh cycles must run at sufficient frequency
WiFi tasks must not block display routines
Delay functions must be avoided in main loop
A non-blocking structure ensures smooth LED updates while maintaining WiFi responsiveness.
Countdown Logic Implementation
The timer supports:
Hour, minute, second configuration
Start / Pause / Resume
Reset function
Running text display
The countdown process follows:
Store initial time value
Decrement time every second using internal timing
Update LED display buffer
Activate buzzer when timer reaches zero
State management prevents unintended decrement when paused.
WiFi-Based Control
The ESP8266 operates in WiFi access point mode, allowing Android devices to connect directly. Based on the configuration guide, users can:
Set device SSID and password
Configure timer parameters
Adjust brightness
Modify running text
Restart device to apply settings
When configuration changes occur, the system performs a controlled restart to ensure stable reconnection.
Server–Client Synchronization
The system supports multi-device synchronization:
Main device (Server)
Secondary display units (Client/Slave)
Client configuration describe how slave devices connect to the main controller via WiFi credentials and device ID.
This architecture enables synchronized countdown display across multiple LED panels, suitable for large competition fields.
Engineering Challenges
Several technical challenges were addressed during development:
LED flicker caused by insufficient refresh rate
WiFi instability during heavy display update
Power supply noise affecting brightness
Synchronization delay between server and client units
Through firmware optimization and stable power management, the system achieved reliable and consistent performance.
Conclusion
This WiFi-based LED countdown timer demonstrates how ESP8266 can be integrated with high-current P10 LED panels to create a remotely configurable and scalable timing system.
By combining embedded timing logic, wireless configuration, and server–client synchronization, the design is suitable for sports competitions, event timing, and public display applications.
#LEDProject##P10Display##ESP8266##WiFiDisplay##CountdownTimer##LEDMatrix##HUB12##EmbeddedSystem##ArduinoIDE##IndustrialDisplay#
Calibrating RGB Sensors for Accurate Color Classification in Conveyor Systems
Color-based sorting systems rely heavily on accurate sensor calibration. In the mini conveyor sorting project, the TCS34725 RGB sensor was used to detect object color before classification. However, raw RGB readings are highly sensitive to lighting conditions, surface reflectivity, and object distance.
Without proper calibration, misclassification becomes frequent, especially under varying ambient light.
Understanding Raw RGB Output
The TCS34725 sensor provides:
Red (R)
Green (G)
Blue (B)
Clear (C)
Raw values alone are not sufficient for direct classification. Different materials reflect light differently, and ambient lighting significantly influences readings.
During early testing, identical objects produced inconsistent values under different room lighting conditions.
Calibration Procedure
Calibration was performed in a controlled setup:
Conveyor stopped to stabilize object position
Each reference object (Red, Green, Blue) placed under sensor
Multiple samples collected
Average RGB values recorded
Threshold ranges defined
Instead of fixed exact values, upper and lower tolerance boundaries were created.
Example threshold approach:
RED if: R > G and R > B and R > 120
GREEN if: G dominant and G > threshold
BLUE if: B dominant and B > threshold
Using dominance logic reduces dependency on absolute values.
Ambient Light Compensation
To reduce lighting influence:
Sensor mounted at fixed distance
Shielded from external light using enclosure
Calibration performed under operational lighting conditions
Clear channel value monitored to normalize RGB
Optional normalization technique:
R_norm = R / C
G_norm = G / C
B_norm = B / C
This improves consistency across lighting variations.
Filtering and Stability
Noise and vibration caused value fluctuation while objects were moving.
To improve stability:
Multiple readings averaged
Short delay before classification
Conveyor speed limited during detection zone
Filtering prevents rapid state switching between color categories.
Integration with Sorting Logic
After calibration, RGB classification feeds into:
Servo selection
Object counter increment
LabVIEW display update
Only when stable classification persists for defined delay does sorting trigger.
This avoids mis-sorting due to transient noise.
Engineering Insight
Proper calibration transforms a simple RGB sensor into a reliable classification tool. Instead of relying on fixed values, combining dominance logic, threshold ranges, normalization, and filtering significantly improves sorting accuracy.
In automation systems, sensor calibration is not optional it is essential for consistent performance.
#RGBSensor##TCS34725##ColorDetection##SensorCalibration##EmbeddedSystem##AutomationSystem##ConveyorSystem##Arduino##Mechatronics##IndustrialAutomation#
Designing a Structured Serial Communication Between Arduino and LabVIEW for Conveyor Automation
In the mini conveyor sorting system, LabVIEW acts as a Human-Machine Interface (HMI) that receives real-time data from Arduino Nano and transmits control commands back to the embedded controller. The communication is implemented using USB serial and VISA-based data handling.
Serial Communication Architecture
As shown in the LabVIEW block diagram, communication begins with:
VISA Configure Serial Port
Baud rate configuration
USB port selection
The system continuously monitors the serial buffer using Bytes at Port, ensuring that LabVIEW only reads available data.
This prevents partial-frame parsing and buffer overflow.
Data Reception and Parsing
Arduino transmits sensor data as raw comma-separated numeric values.
In LabVIEW:
VISA Read captures the full string.
Match Pattern validates data frame termination.
Scan From String converts CSV string into numeric values.
Parsed values are mapped to:
RED
GREEN
BLUE
OTHERS
HEIGHT (CM)
Conveyor Status
The block diagram clearly shows numeric conversion blocks feeding into indicator terminals such as:
RED COUNT
GREEN COUNT
BLUE COUNT
OTHERS COUNT
This structured parsing ensures consistent UI updates.
Indicator and State Handling
The block diagram uses Case Structures to control:
RUN indicator
STOP indicator
Color detection state (True/False logic)
Object detection validation
When detection is TRUE, the corresponding case block activates:
Color LED indicator
Counter increment logic
This prevents false increments during idle conditions.
Parameter Transmission from LabVIEW to Arduino
The right side of the block diagram shows numeric controls for:
Conveyor Speed
Minimum Height Detect
Minimum Height Object
Maximum Height Object
Delay Check
When RUN or STOP buttons are pressed, LabVIEW transmits command strings via VISA Write.
Commands include:
Start operation
Stop operation
Reset counter
Speed update
The RESET COUNT button triggers a confirmation dialog before sending reset command.
Communication Stability Measures
Based on the implementation:
Data reading only occurs when "Read" boolean is TRUE.
Transmission is separated from parsing loop.
Case structures isolate command execution from monitoring logic.
Baud rate is configurable from the front panel.
This design prevents:
Data overlap
Blocking UI execution
Serial buffer corruption
Engineering Insight
The integration of VISA Read, Scan From String, and structured case logic provides:
Deterministic parsing
Real-time visualization
Stable bidirectional control
Clean separation between monitoring and command logic
This architecture demonstrates a practical approach to PC-based industrial automation using LabVIEW and embedded controllers.
#Arduino#
#LabVIEW#
#EmbeddedSystem#
#SerialCommunication#
#IndustrialAutomation#
#HMI#
#AutomationSystem#
#ConveyorSystem#LabVIEW#
#EmbeddedSystem#
#SerialCommunication#
#IndustrialAutomation#
#HMI#
#AutomationSystem#
#ConveyorSystem#
Designing a Color and Height-Based Mini Conveyor Sorting System with LabVIEW Interface
This project presents the development of a mini conveyor sorting system capable of classifying objects based on color and height. The system integrates embedded control, sensor processing, and LabVIEW-based monitoring into a compact automation platform.
Unlike simple color-only sorting systems, this design combines RGB detection and ultrasonic height measurement to improve classification accuracy.
System Architecture Overview
Based on the wiring architecture the system consists of:
Arduino Nano (main controller)
TCS34725 RGB sensor
HC-SR04 ultrasonic sensor
Stepper motor with DRV8825 driver
Three servo motors (Red, Green, Blue diverters)
12V power supply + DC step-down converter
Industrial push buttons and emergency stop
LabVIEW HMI interface
The conveyor transports objects under the RGB sensor for color detection, while the ultrasonic sensor measures object height before classification.
RGB Sensor Calibration
Calibration of the TCS34725 sensor is performed as described
Steps include:
Upload RGB calibration program
Place red, green, and blue sample objects
Read RGB values via Serial Monitor
Store threshold values in the firmware
Example configuration:
uint16_t color_limit[] = {120, 110, 105};
Proper calibration is critical to minimize misclassification due to ambient lighting.
Height Detection Integration
The ultrasonic sensor ensures that only objects within specified height limits are processed.
Configurable parameters include:
Minimum height detection (3–10 cm)
Maximum height object limit
Delay check (minimum 1 second)
This prevents false detection from small debris or oversized objects.
Motor and Actuator Control
The stepper motor drives the conveyor using a DRV8825 driver. Speed control is adjustable via LabVIEW (0–100%).
Each color category is assigned to a dedicated servo motor:
Servo Red
Servo Green
Servo Blue
Once classification is complete, the corresponding servo diverts the object into the correct bin.
LabVIEW Human-Machine Interface
The LabVIEW provides:
Conveyor status (Stop/Running indicator)
USB port & baud rate configuration
Real-time color detection display
Object counting per category
Speed control slider
Reset counting function
Communication is performed via serial USB.
Bidirectional control allows:
Start/Stop system
Reset system
Adjust detection parameters
Industrial Safety Features
The control panel includes:
Red Stop button
Green Run button
Emergency stop switch
Status indicator lamps
The emergency button disconnects the main power and locks the system.
Engineering Challenges
During development, the following issues were addressed:
RGB variation due to lighting
Timing synchronization between detection and servo actuation
Stepper motor vibration
Communication delay with LabVIEW
Object spacing control
By calibrating delay parameters and refining firmware logic, sorting accuracy improved significantly.
** www.muhilham.com
** www.embeddetronics.com
#automation# #Embedded#
Implementing Fuzzy Logic on ESP32 for Weight Anomaly Detection in Smart Shelf Systems
Detecting abnormal item removal in automated storage systems requires more than simple threshold comparison. In the Smart Shoes Shelves System, a fuzzy logic-based weight monitoring algorithm was implemented on ESP32 to improve anomaly detection accuracy.
Unlike conventional systems that trigger alarms when weight drops below a fixed limit, this design evaluates both weight deviation and rate of change to reduce false positives caused by vibration, gradual handling, or sensor noise.
System Architecture Overview
The hardware consists of:
ESP32 microcontroller
Load cell sensor
HX711 24-bit ADC amplifier
LCD 16x2 I2C
Buzzer alarm
Firebase integration
The board layout and component placement are shown in the Board Details section, highlighting integration between sensor input, LCD interface, and ESP32 core processing.
The system continuously measures weight (Present Value / PV) and compares it to a stored setpoint (SP).
Mathematical Foundation
The fuzzy system is based on two input variables:
Error:
Delta Error:
Where:
SP = Setpoint weight
PV = Current measured weight
ΔE = Rate of weight change
This allows detection of sudden removal events versus gradual user interaction.
Membership Function Design & Rule Base Implementation
Error membership sets:
NB (Negative Big)
NS (Negative Small)
ZO (Zero)
PS (Positive Small)
PB (Positive Big)
Delta Error membership sets:
NB
NS
ZO
PS
PB
The interval resolution used:
Error interval = 0.5
Delta error interval = 0.2
Triangular membership functions were used for smooth transitions between states.
This prevents rigid decision boundaries.
The rule evaluation matrix defines output behavior:
Output categories:
Normal
Warning + Notification
Alarm & Notifications
Example rule:
IF Error = NB
AND Delta Error = NB
THEN Output = Alarm & Notification
This rule detects sudden significant weight removal.
Defuzzification is implemented using a singleton method with output values:
0 → Normal
-1 → Warning
-2 → Alarm
Firmware Implementation on ESP32
Implementation steps:
Read HX711 value
Apply filtering (moving average)
Compute error and delta error
Calculate membership degrees
Evaluate fuzzy rules
Compute weighted output
Trigger buzzer and Firebase alert
The calibration process ensures accurate weight measurement before fuzzy evaluation begins.
System Behavior
When a correct item is removed through the application interface, the setpoint is updated dynamically.
However, if weight changes without proper command sequence, the fuzzy engine evaluates the anomaly and activates the alarm state.
This dynamic adaptation significantly reduces false alarms compared to static threshold methods.
Engineering Insight
The integration of fuzzy logic into an embedded IoT platform demonstrates how lightweight AI techniques can enhance reliability in real-world systems.
Instead of binary logic, the system operates using graded decision-making, making it more robust against:
Mechanical vibration
Sensor drift
Gradual load changes
Minor noise fluctuation
This approach bridges classical embedded programming with intelligent decision systems, suitable for smart inventory, anti-theft storage, and automated monitoring environments.
#AI# #Fuzzy# #Embedded#
Designing a Multi-Socket IoT Energy Monitoring and Control System
Expanding from a single-socket prototype to a multi-socket IoT energy monitoring system introduces significant architectural and safety challenges. In this version, the system supports four independent AC outputs, each equipped with its own energy measurement and control channel.
This transition required redesigning both the hardware layout and firmware structure to maintain stability, isolation, and scalability.
System Architecture Overview
The multi-socket version integrates:
ESP32 as central controller
Four PZEM-004T energy modules
4-channel relay module
IC 4051 multiplexer
220VAC to 5V switching power supply
Firebase Realtime Database integration
The complete wiring structure is shown in the wiring diagram, where each load channel is measured independently and routed through its own relay.
Independent Channel Design
Each socket includes:
Dedicated current transformers
Independent voltage measurement
Separate energy accumulation
Individual alert threshold
The firmware stores data in structured nodes:
device1/socket1/voltage
device1/socket2/voltage
device1/socket3/voltage
device1/socket4/voltage
This ensures per-load monitoring and simplifies cloud-side analysis.
Hardware Layout and Isolation
From the board layout, several critical design considerations can be observed:
Clear separation between AC high-voltage section and low-voltage logic section
Dedicated 5V supply module for ESP32 and relay drivers
Use of IC multiplexer (4051) to manage multiple measurement inputs
Relay driver isolation to protect GPIO pins
When multiple relays operate simultaneously, switching noise increases significantly. To mitigate this:
Decoupling capacitors are placed near ESP32 supply lines
Proper grounding strategy is implemented
Relay flyback protection is included
These measures prevent ADC instability and WiFi communication drops.
Panel and Mechanical Design
The enclosure layout demonstrates practical installation considerations:
Four front-access sockets
Dedicated AC input connector
Master ON/OFF switch
Internal spacing for airflow
Thermal management becomes important when multiple loads operate simultaneously. Proper cable routing and spacing reduce overheating risk.
Firmware Scaling Strategy
The firmware was redesigned using channel abstraction rather than duplicating logic.
Instead of writing separate code blocks per socket, a structured array approach is used:
Measurement array per channel
Alert threshold per channel
Relay status per channel
Sampling is performed sequentially to avoid communication congestion.
This approach improves maintainability and enables future expansion beyond four sockets.
Cloud Synchronization Model
Firebase integration allows each socket to publish:
Voltage
Current
Power
Energy
Cost
Alert flag
The Android interface displays real-time data per socket.
This architecture supports:
Per-load monitoring
Independent billing estimation
Remote supervision
Scalable IoT deployment
Design Lessons
Moving to multi-channel AC monitoring significantly increases complexity in:
Electrical safety
Signal integrity
EMI handling
Thermal management
Firmware modularity
A scalable IoT energy system must be designed with isolation, noise control, and structured data handling from the beginning.
This multi-socket implementation represents the evolution from a simple monitoring prototype into a structured smart power management platform suitable for laboratory, workshop, or small industrial applications.
#power meter#
#internetofthings# #Embedded#
Comparing IoT Platforms for kWh Energy Monitoring: Firebase vs Telegram vs Blynk
After implementing the core hardware and firmware for the IoT-based kWh monitoring system, the next major challenge was selecting the most suitable cloud and user interaction platform. Over several iterations, I tested three different approaches: Firebase Realtime Database, Telegram Bot integration, and Blynk IoT dashboard.
Each platform offers distinct advantages and trade-offs depending on system requirements, scalability, and deployment environment.
1. Firebase Realtime Database
Firebase was used as a structured cloud backend for real-time data synchronization.
Strengths:
Structured JSON-based database
Real-time synchronization
Scalable for multiple devices
Suitable for custom Android applications
Firebase allows clean separation between measurement logic and cloud storage. Data such as voltage, current, power, energy, cost, and alert flags can be stored in a hierarchical tree structure.
Because it operates over HTTPS, it provides relatively secure communication. It is well-suited for systems requiring long-term historical logging and structured data management.
Limitations:
Requires database configuration
Requires authentication token handling
Slightly more complex setup
Firebase is ideal when building a structured IoT ecosystem with custom front-end applications.
2. Telegram Bot with Google Sheets Logging
The Telegram version focuses on command-based monitoring and notification.
Strengths:
No dedicated mobile app required
Simple user interaction via chat commands
Easy alert notification
Google Sheets integration for logging
Users can send commands such as /info or /logs to retrieve real-time energy data. When energy thresholds are exceeded, instant notifications can be sent automatically.
Google Sheets integration provides simple historical logging without complex database setup.
Limitations:
Less structured compared to Firebase
Command-based interaction is less visual
Dependent on Telegram server availability
This approach is effective for lightweight monitoring systems or quick deployment scenarios.
3. Blynk IoT Dashboard
Blynk provides a graphical dashboard interface for IoT devices.
Strengths:
Real-time graphical widgets
Built-in notifications
Minimal backend setup
User-friendly mobile interface
It allows fast visualization of voltage, current, power, and energy values using gauges and charts.
Limitations:
Dependency on third-party platform
Limited customization compared to full backend control
Long-term scalability may require subscription plans
Blynk is suitable for rapid prototyping and demonstration purposes.
4. Technical Comparison Summary
From an engineering perspective:
Firebase provides structured and scalable backend control.
Telegram offers simplicity and direct notification capability.
Blynk emphasizes user-friendly visualization.
For long-term deployment and multi-device systems, Firebase is the most flexible. For alert-based monitoring, Telegram is efficient. For quick UI development, Blynk is practical.
5. Technical Comparison Table
Feature
Firebase Realtime DB
Telegram + Google Sheet
Blynk IoT
Data Structure
Hierarchical JSON
Flat log-based
Widget-based
Real-Time Update
Yes
On request / event-based
Yes
Historical Logging
Full database
Google Sheets logging
Limited / dashboard-based
Alert Notification
Via cloud logic
Direct chat notification
Built-in notification
UI Customization
Fully customizable (custom app)
Command-based
Predefined widgets
Setup Complexity
Medium–High
Medium
Low
Scalability
High
Medium
Medium
Platform Dependency
Google Firebase
Telegram + Google
Blynk Cloud
Suitable For
Structured IoT systems
Lightweight alert system
Rapid prototyping & demo
6. Final Insight
Selecting an IoT platform is not purely a technical decision; it depends on the balance between control, scalability, simplicity, and maintenance.
Through iterative development, this kWh monitoring system evolved from simple remote display to a modular IoT architecture capable of adapting to different cloud ecosystems without modifying the core energy calculation firmware.
#Embedded# #ESP32# #iot# #internetofthings# #firebase# #android# #telegram# #blynk#
Implementing Energy Calculation and Data Logging on ESP32 for IoT kWh Monitoring
After completing the hardware architecture of the single-socket IoT energy meter, the next critical stage was implementing reliable energy calculation and data handling on the ESP32.
Unlike simple voltage or current monitoring, a kWh system must continuously compute power and accumulate energy over time. This requires careful handling of sampling intervals, communication reliability, and data persistence.
Reading Electrical Parameters
The system uses the PZEM-004T module to obtain:
Voltage (V)
Current (A)
Active Power (W)
Energy (kWh)
Frequency (Hz)
Communication between ESP32 and PZEM is handled via UART.
A periodic polling method is implemented to read data every defined interval (typically 1–2 seconds).
To avoid unstable readings:
Invalid responses are filtered
Communication timeout is monitored
Re-read attempts are implemented if data is corrupted
This ensures stable long-term monitoring.
Energy Accumulation Strategy
Although the PZEM module provides accumulated energy internally, I implemented additional logic on the ESP32 for:
Energy reset functionality
Session-based energy tracking
Cost calculation (based on Rp/kWh tariff)
Energy cost is calculated using:
Cost = Energy (kWh) × Tariff (Rp/kWh)
The tariff value can be configured remotely depending on the electricity pricing scheme.
WiFi Connectivity Handling
Because the device operates in real environments, WiFi stability cannot be assumed.
The firmware includes:
Auto-reconnect routine
Offline detection (fallback to local LCD monitoring)
Timeout-based retry logic
If WiFi is unavailable for a defined period, the system continues measuring locally and resumes cloud synchronization once the connection is restored.
Data Logging Architecture
All measurement data is transmitted to Firebase Realtime Database using HTTPS-based secure communication.
The structured data tree includes:
voltage
current
power
energy
cost
alert
timestamp
Each measurement cycle updates the corresponding fields in the database. Separating measurement logic from communication logic ensures modular firmware design.
This architecture allows:
Real-time remote monitoring
Historical data visualization
Cloud-based alert evaluation
Scalability for multiple devices
By isolating the Firebase client functions from core measurement routines, the firmware remains adaptable for future platform expansion without modifying the energy calculation engine.
Relay Control Logic (Threshold-Based Warning System)
Instead, a threshold-based warning mechanism is implemented.
When:
Energy ≥ Configured Limit
The system will:
· Set an alert flag in Firebase
· Display warning information on the LCD
· Trigger remote notification via the cloud layer
The load remains active unless manually switched OFF.
This design choice improves safety and avoids unintended service interruption while still providing preventive energy monitoring.
Design Lessons
Accurate kWh monitoring is not only about measuring voltage and current. It requires:
Stable communication
Robust error handling
Persistent data logic
Proper integration between measurement and cloud layer
This firmware architecture became the backbone for the multi-socket and advanced IoT versions developed afterward.
#Embedded# #ESP32# #iot# #internet of things# #firebase# #kwh meter#
Hardware Architecture of My IoT-Based Single-Socket kWh Energy Monitoring System
Monitoring electrical energy consumption at the socket level provides valuable insight into real-time power usage, cost estimation, and load behavior. In this project, I designed a single-socket IoT-based kWh monitoring system capable of measuring voltage, current, power, and accumulated energy, while transmitting data over WiFi for remote monitoring.
This first version focuses on a compact single-output architecture using ESP32 and a PZEM-based energy measurement module.
System Overview
The hardware consists of the following main blocks:
ESP32 microcontroller (main controller with WiFi)
PZEM-004T energy measurement module
AC-DC power supply (220VAC to 5VDC)
High-power relay for load control
LCD 16x2 display for local monitoring
Terminal block for AC input/output
The internal board layout and power separation can be seen in the device assembly documentation:
Energy Measurement Module
For accurate measurement of voltage, current, power, and accumulated energy (kWh), I used the PZEM-004T module. This module simplifies high-voltage measurement because it provides built-in isolation between the AC line and the low-voltage microcontroller side.
Key specifications include:
Voltage measurement up to 260VAC
Current measurement up to 100A (using CT)
Frequency range 45–65Hz
Using a dedicated metering module reduces ADC complexity and improves reliability compared to raw analog sensing.
Power Supply and Isolation
The system operates from a 220VAC input. A compact AC-DC converter module steps down the voltage to 5VDC, which powers the ESP32, relay driver, and LCD.
Important hardware considerations:
Clear separation between high-voltage AC section and low-voltage logic section
Proper terminal block insulation
Short wiring between PSU and ESP32
Adequate spacing to reduce electrical noise
Even in prototype form (matrix board), I ensured physical separation between AC terminals and control circuitry to minimize risk and interference.
Load Control Section
A high-power relay is used to control the socket output. The relay allows:
Remote ON/OFF switching
Automatic cut-off based on energy limit
Integration with IoT platforms for smart control
The relay driver circuit includes proper transistor switching and flyback protection to ensure ESP32 safety.
Local Monitoring Interface
A 16x2 LCD is used to display:
Voltage (V)
Current (A)
Power (W)
Energy (kWh)
This ensures the device remains functional even without internet connectivity.
Design Lessons
Designing an AC-powered IoT device requires careful attention to isolation, grounding, and layout discipline. Even small wiring mistakes can introduce noise into measurement readings.
Although this version was built as a prototype, migrating to a properly manufactured PCB would significantly improve safety, signal integrity, and long-term reliability.
This single-socket design became the foundation for more advanced multi-socket and cloud-integrated versions developed later.
#Embedded# #ESP32# #PZEM# #Energy Monitor#
Designing an IoT-Based RFID Inventory Management System Using ESP Module and RC522
This project presents the development of an IoT-based RFID Inventory Management System designed for real-time inbound, outbound, and stock checking processes. The system integrates an ESP32 microcontroller with an MFRC522 RFID reader module and communicates directly with a web-based inventory platform via WiFi.
System Architecture
The core controller is the ESP32, selected for its built-in WiFi capability, dual-core processing, and stable SPI communication. The MFRC522 RFID module operates at 13.56 MHz and communicates with the ESP8266/ESP32 through SPI (SDA, SCK, MOSI, MISO, RST).
Additional peripherals include:
16x2 LCD with I2C interface
Push button for mode selection
Buzzer for audio feedback
5V regulated power supply
The wiring configuration where RFID, LCD, Button, and Buzzer are clearly mapped to the ESP board pins.
Operating Modes
The device supports three main modes selectable via a single push button:
Inbound Mode – Register new tagged items into the system
Outbound Mode – Record item removal from inventory
Check Item Mode – Display item details without modifying stock
The LCD interface provides clear status feedback such as INBOUND, OUTBOUND, and CHECK ITEM, while the buzzer confirms successful tag detection.
Web Integration & Database
The system connects to a local or cloud-based web server. The backend can be deployed using XAMPP with Apache and MySQL.
Data flow sequence:
RFID tag scanned
UID captured by ESP
HTTP request sent to server (with device ID & token)
Database updated in real-time
Web dashboard displays transaction log
The web interface allows:
Device configuration
Item group management
Real-time inbound/outbound logs
Report export to Excel
Hardware Implementation
After successful breadboard prototyping, the circuit was assembled onto a perforated PCB and enclosed in a custom black panel box. The enclosure integrates:
Front LCD window
RFID scan area
Rear 5V adapter input
Power switch
The final device is compact, stable, and ready for industrial or laboratory environments.
#ESP32# #Embedded# #RFID# #inventory# #warehouse#
From Prototype to Production: PWM Generator & Servo Driver for Non-PWM PLC
In many industrial systems, not all PLC models provide native PWM output. When PWM expansion modules are available, they are often expensive and unnecessary for simple positioning tasks.
I needed to control a low-voltage servo (MG996R, 5–6V) using a standard 24V PLC digital output. Since the PLC did not support PWM, I decided to design a dedicated PWM Generator & Servo Driver board as a cost-effective solution.
Prototype Phase
The first version was built using a perforated prototype PCB.
The goal was to validate:
12V/24V PLC signal compatibility
Servo movement stability
After several adjustments, the prototype worked reliably. The servo response was smooth and consistent under normal load conditions. Once the concept was proven, I decided to redesign the circuit into a proper PCB.
PCB Design & Fabrication
The circuit was redesigned into a 2-layer PCB for:
Cleaner routing
Better power distribution
Reduced noise
More professional mechanical structure
The PCB was fabricated using JLCPCB. The board quality was excellent, with accurate drilling, clean copper traces, and clear silkscreen. The compact layout also improved reliability compared to the prototype version.
Small Batch Production
After testing the first PCB batch, I proceeded with small-scale production of 30 units. These boards were used for real application testing and market validation.
The system successfully enables standard PLC digital outputs (12V/24V) to control low-voltage servo motors without needing an expensive PLC PWM module.
Technical Overview
System flow:
PLC 12V/24V Digital Output
→ Signal Conditioning
→ PWM Generator
→ 5–6V Servo Driver
→ MG996R Servo
Main features:
12V/24V PLC compatible input
Stable 50Hz servo PWM
1–2ms adjustable pulse width
Compact 2-layer PCB
This project started from a simple prototype on a perforated board and evolved into a small production run using JLCPCB.
It demonstrates how custom PCB design can provide a practical and economical solution for PLC systems without built-in PWM functionality.
#PCB# #Module# #PWM# #PCBDesign# #SERVO# #PLC#