Firebase + ESP32 Limitations and Fast Setup Guide

Why it works for prototypes, but not for large-scale IoT systems

Firebase is often a fast and convenient choice for connecting ESP32 devices to the cloud, especially in early prototypes and proof-of-concept systems. However, its architecture introduces limitations that become clear when the system starts scaling.

Firebase Realtime Database stores data in a JSON tree structure rather than a time-series optimized format. This makes it flexible for simple applications, but less efficient when dealing with continuous sensor streams. Without careful data modeling, retrieving historical data or performing time-based analysis can become inefficient.

Another key limitation is the communication model. Firebase relies on persistent WebSocket connections for real-time updates. While this is useful for instant synchronization, it does not provide messaging features like QoS levels, message queuing, or guaranteed delivery that are typically found in IoT-focused protocols like MQTT. This makes it less reliable in unstable network conditions or distributed systems with many devices.

In practice:

  • Works well for small to medium prototypes and dashboards
  • Starts to struggle with large-scale deployments and high-frequency telemetry

Key takeaway:

Firebase is excellent for fast development and validation, but MQTT-based architectures are generally better suited for scalable, production-grade IoT systems where reliability and efficiency are critical.

Wireless & IOT
ESP Connectivity Strategy: The Hidden Cost of Wi-Fi

After optimizing sleep modes and securing OTA updates, there is one remaining system-level problem that silently destroys battery life and user experience: connectivity behavior. Most ESP systems do not fail because Wi-Fi does not work. They fail because Wi-Fi is used inefficiently.

Wi-Fi reconnect is not free. On ESP32, a full scan and authentication cycle can cost hundreds of milliseconds of CPU time and several hundred milliamps of current draw. If your device wakes every minute, reconnecting from scratch every time is more expensive than the sensor reading itself.

The key optimization is state retention. Store the last connected BSSID, channel, and IP configuration in RTC memory. On wake, bypass scanning and reconnect directly using cached parameters. This reduces reconnect time dramatically and stabilizes power consumption across cycles.

Another important technique is exponential backoff for failed connections. If a network is unavailable, retrying aggressively only drains battery and increases thermal load. Instead, progressively increase the retry interval to avoid wasted wake cycles.

For advanced systems, consider hybrid connectivity strategies. BLE can be used for provisioning and fallback communication, while Wi-Fi handles bulk data transfer only when needed. This reduces radio usage significantly in intermittent reporting devices.

Finally, always align connectivity events with your sleep schedule. Waking the chip just to attempt a Wi-Fi reconnection is often worse than delaying transmission until multiple sensor samples are aggregated.

In real IoT systems, power is not saved by sleep alone. It is saved by how intelligently the device decides to talk to the network.

Wireless & IOT
ESP OTA Updates: Ship Once, Update Forever

The day you ship a product without OTA updates is the day you commit to never fixing bugs or adding features without physically retrieving every device. That's fine for a breadboard. It's a business problem at any scale. Here's how OTA works on ESP, from the simplest version to what production systems need.

How OTA Works Under the Hood

The ESP's flash is divided into partitions defined by a CSV file. For OTA, you need at least two app partitions: ota_0 and ota_1. Your current running firmware resides in one of them. During an OTA update, the new firmware writes to the other, the inactive one. When writing is complete and the SHA256 hash verifies, the bootloader checks it on reboot, and the device restarts into the new firmware.**

If the new firmware fails to boot correctly, for example if it crashes repeatedly or never calls esp_ota_mark_app_valid_cancel_rollback(), the bootloader automatically marks the update as invalid and reverts to the previous working firmware on the next power cycle. This rollback mechanism prevents bricks and is a critical production safety net.

Three OTA Methods, Pick Your Level

ArduinoOTA, for development

Install the library, add four lines to setup(), and your board appears in the Arduino IDE port list over the network. Upload new firmware exactly like USB over Wi-Fi. No authentication by default, so add a password at minimum. Not for production, but for rapid development iteration it is extremely convenient.

HTTP OTA, the production standard

Your device polls an HTTPS endpoint every N hours, or on command from the server. The endpoint returns either a 304 Not Modified response, meaning nothing to update, or a new firmware binary. The device downloads it to the inactive partition, verifies integrity, optionally checks signature, then reboots. ESP-IDF's esp_https_ota() handles most of this in a few lines of code.

Wireless & IOT
ESP Sleep Modes: Light Sleep and Choosing the Right Mode

ESP Sleep Modes: The Practical Guide to Not Killing Your Battery

In the previous post, we covered the five power states of the ESP32 family and took a deep dive into deep sleep, the go-to mode for battery-powered sensor nodes. Now we turn to light sleep, a mode that offers sub-milliampere current consumption while preserving RAM state and enabling fast wake-up.

Light Sleep: The Overlooked Middle Ground

Light sleep pauses the CPU while keeping RAM powered, typically around ~0.8 mA depending on configuration. When a wake source fires, execution resumes exactly where it stopped, no reboot, no re-initialization required. If your device needs to respond quickly to GPIO events but does not need to stay fully active all the time, light sleep is often the right choice.

The tradeoff is power. While ~0.8 mA is significantly lower than active mode, it is still much higher than deep sleep (~10 µA). At scale, this difference has a major impact on battery lifetime.

For devices that wake frequently, light sleep can be more energy-efficient overall because it avoids the repeated cost of system reboots and Wi-Fi reconnections. However, for longer sleep intervals measured in minutes or hours, deep sleep remains the clear winner.

Wake sources for light sleep include timers, GPIO interrupts, UART activity, and capacitive touch sensors. These are configured similarly to deep sleep using APIs such as esp_sleep_enable_timer_wakeup() and esp_sleep_enable_gpio_wakeup().

Wireless & IOT
Deep Sleep: The Right Tool for Battery Sensors

For a device that wakes up periodically to send data and then sleeps, which covers most of the battery IoT nodes, deep sleep is what you want. You call esp_deep_sleep_start() and the chip powers down to approximately 10 µA, keeping only the RTC oscillator ticking. Your specified wakeup source brings the chip back.

The GPIO16 trick for ESP8266: On the original ESP8266, you must wire GPIO16 to RST to wake from deep sleep via timer. The RTC fires a low pulse on GPIO16 which resets the chip. Forget this wire and your device sleeps forever.

On the ESP32, the timer wakeup is cleaner, no external wire needed. Call esp_sleep_enable_timer_wakeup(duration_in_microseconds) before esp_deep_sleep_start() and you're done.

Surviving Deep Sleep: RTC Memory

 Here's the subtle part: deep sleep kills your chip's state. All RAM is wiped. Your variables are gone. To preserve data across sleep cycles, use RTC memory, a small (16 KB) memory region powered by the RTC that survives deep sleep.

In Arduino: RTC_DATA_ATTR int bootCount = 0; that RTC_DATA_ATTR prefix stores the variable in RTC SLOW memory. Use it for boot counters, cached Wi-Fi credentials, last sensor value, or anything you need to remember between wakes.

 Cache your Wi-Fi BSSID and channel in RTC\_DATA\_ATTR variables. On subsequent wakes, pass them to WiFi.begin() explicitly to skip the channel scan. This alone cuts reconnect time from 3–5 seconds to under 1 second, a significant battery saving at scale.
Wireless & IOT
Relay vs Solid State Relay (SSR): Which One to Use in Automation Systems?

Relays are widely used in automation systems to control electrical loads such as motors, lamps, and industrial equipment. Two common types are mechanical relays and solid state relays (SSR). While both serve the same purpose, their working principles and performance characteristics are significantly different.

This article compares both relay types to help engineers choose the right solution for their application.

Working Principle

Mechanical Relay

A mechanical relay uses an electromagnetic coil to physically switch contacts.

Key characteristics:

  • Uses moving parts
  • Provides electrical isolation
  • Produces clicking sound during operation

Solid State Relay (SSR)

An SSR uses semiconductor components (triac, MOSFET, or optocoupler) to switch loads without moving parts.

Key characteristics:

  • No mechanical movement
  • Silent operation
  • Faster switching

image.png

Performance Comparison

Feature Mechanical Relay SSR
Switching Speed Slow (ms) Fast (µs)
Lifespan Limited (wear) Very long
Noise Audible click Silent
Heat Generation Low Higher
Power Consumption Coil required Low control power
Isolation High High (optical)

Load Handling

Mechanical Relay

  • Suitable for AC and DC loads
  • Handles high current surge
  • Better for inductive loads

SSR

  • Ideal for frequent switching
  • Best for resistive loads
  • Some types limited to AC only (triac-based)

image.png

Advantages and Limitations

Mechanical Relay Advantages

  • Low cost
  • Handles high current
  • Good isolation

Mechanical Relay Limitations

  • Contact wear over time
  • Slower switching
  • Mechanical noise

SSR Advantages

  • Long lifespan
  • Fast switching
  • No mechanical noise

SSR Limitations

  • Heat dissipation required
  • Higher cost
  • Leakage current (important for low-load systems)

Engineering Considerations

Choose based on application:

  • Use mechanical relay for:
    • Motor control
    • High current switching
    • Low-frequency operation
  • Use SSR for:
    • High-speed switching
    • Silent operation
    • Long-term reliability

Thermal management is critical when using SSR, especially in high-current applications.

Both mechanical relays and SSRs are essential components in automation systems. Mechanical relays are robust and cost-effective for general-purpose switching, while SSRs provide faster, quieter, and more reliable operation for high-frequency switching applications.

Selecting the right relay depends on load type, switching frequency, and system requirements.

#Automation#
#Relay#
#SSR#
#EmbeddedSystem#
#PowerElectronics#
#ControlSystem#

Automation & Control
Measuring Motorcycle Speed Using Hall Effect Sensor and Interrupt-Based Pulse Counting

Accurate speed measurement is essential in vehicle monitoring and safety systems. In this project, motorcycle speed is measured using a Hall Effect sensor combined with interrupt-based pulse counting on a microcontroller.

A magnet attached to the wheel generates pulses as the wheel rotates. These pulses are detected by the sensor and converted into speed using wheel dimension parameters.

System Overview

The system uses a Hall Effect sensor mounted near the rotating wheel. Each time the magnet passes the sensor, a pulse is generated.

image.png

Hardware Architecture

Main components:

  • Hall Effect sensor (NJK-5002C)
  • ESP32 microcontroller
  • LCD display
  • Power supply (battery + step-down)
  • Additional sensors (distance monitoring system)

The wiring configuration is shown in the system diagram.

image.png

Interrupt-Based Pulse Detection

To ensure accurate measurement, pulse detection is handled using interrupts.

Each pulse corresponds to one wheel rotation (or fraction, depending on magnet count).

Basic logic:

  1. Sensor detects magnet → generates pulse
  2. Interrupt triggers on rising/falling edge
  3. Pulse counter increments
  4. Speed calculated over time interval

This approach ensures no pulses are missed, even at high speeds.

Speed Calculation Method

Speed is calculated using wheel circumference.

From the configuration procedure:

  • Tire width
  • Tire height
  • Wheel diameter

These parameters are used to calculate effective wheel circumference.

Formula:

image.png

Where:

image.png

Final output is converted to km/h.

System Calibration

Accurate speed depends on proper calibration.

Key parameters:

  • Tire width and aspect ratio
  • Wheel diameter
  • Unit system (metric or imperial)

Incorrect values will result in inaccurate speed readings.

Integration with Safety System

This speed measurement is integrated into a safe distance warning system.

Based on system logic:

  • Speed affects warning level
  • Distance sensors monitor front and rear
  • System outputs:
    • SAFE
    • WARNING
    • DANGER

image.png


Engineering Considerations

Important design factors:

  • Sensor alignment affects detection accuracy
  • Noise filtering may be required
  • Debouncing needed for stable pulse detection
  • Interrupt handling must be efficient

Using interrupt-based detection significantly improves reliability compared to polling methods.

Conclusion

The implementation demonstrates how Hall Effect sensors and interrupt-based pulse counting can be used for accurate real-time speed measurement in vehicles.

By combining mechanical calibration, embedded processing, and system integration, the design provides a reliable foundation for advanced automotive monitoring systems.

#TestAndMeasurement#
#HallEffectSensor#
#RPMMeasurement#
#EmbeddedSystem#
#ESP32#
#Automation#

Test & Measurement
How to Measure AC Current Using CT Sensors: A Practical Guide

Current Transformer (CT) sensors are widely used for measuring AC current in industrial and embedded systems. They provide electrical isolation and allow high current measurement without direct electrical contact with the conductor.

This guide explains how to properly use CT sensors with microcontrollers for accurate current measurement.

How CT Sensors Work

A CT sensor operates based on electromagnetic induction. When AC current flows through the primary conductor, it induces a proportional current in the secondary coil.

Key points:

  • Output is current (not voltage)
  • Requires burden resistor to convert to voltage
  • Only works with AC signals

image.png

Basic Connection to Microcontroller

A CT sensor cannot be connected directly to an ADC input. The output must be conditioned.

Required components:

  • Burden resistor
  • RC low-pass filter (optional)
  • Voltage divider / biasing (for ADC protection)

Basic flow:

CT Sensor → Burden Resistor → Filter → ADC Input

image.png

Burden Resistor Selection

The burden resistor converts CT output current into measurable voltage.

Formula:

image.png

Where:

image.png

Selection considerations:

  • Output voltage must stay within ADC range (0–3.3V / 5V)
  • Too large → saturation
  • Too small → low resolution

Proper selection is critical for measurement accuracy.

Signal Conditioning and Offset

Because CT output is AC (positive & negative), ADC input must be adjusted.

Common approach:

  • Add DC offset (bias) to shift signal into positive range
  • Use capacitor filtering to stabilize waveform

This ensures safe and stable ADC readings.

image.png

RMS Calculation Implementation

After signal acquisition:

  1. Sample ADC values continuously
  2. Convert to voltage/current
  3. Apply RMS calculation
  4. Display or log results

To improve accuracy:

  • Use multiple sampling cycles
  • Apply filtering
  • Calibrate scaling factor

Common Mistakes

Avoid these common issues:

  • ❌ No burden resistor (dangerous for CT)
  • ❌ Direct connection to ADC
  • ❌ Incorrect resistor value
  • ❌ Ignoring signal offset
  • ❌ Low sampling rate

These mistakes can cause inaccurate readings or hardware damage.

Practical Applications

CT sensors are commonly used in:

  • Energy monitoring systems
  • Industrial load measurement
  • Smart meters
  • Motor current monitoring
  • Data logging systems

Conclusion

CT sensors provide a safe and effective method for measuring AC current in embedded systems. With proper signal conditioning, correct burden resistor selection, and accurate RMS calculation, reliable current measurement can be achieved for both industrial and IoT applications.

#Sensors#
#CTSensor#
#CurrentMeasurement#
#EmbeddedSystem#
#AnalogSignal#
#TestAndMeasurement#

Test & Measurement