Maker Pro

Integrating IoT and SMS Alerts in Home Battery Monitoring: A DIY Guide with NodeMCU and MongoDB

January 29, 2024 by Ryan Susman

The Arduino Battery Backup Monitor is a DIY IoT project using NodeMCU and ADS1115 for real-time battery monitoring. Features SMS alerts via Twilio for critical battery status, uploads data to MongoDB for analysis, and is customizable for various home setups. This scalable and cost-effective solution enhances home automation and energy management.

Harnessing IoT for Home Battery Health: Building a NodeMCU-Based Monitor with SMS Alerts

In an era where home automation and energy management are increasingly crucial, the Arduino Battery Backup Monitor stands out as a beacon for DIY enthusiasts. This project encapsulates the ingenuity of combining Internet of Things (IoT) technology with practical home energy solutions. Utilizing a NodeMCU microcontroller and an ADS1115 ADC, it offers real-time monitoring of battery health, seamlessly integrating with MongoDB for data analysis and employing Twilio for timely SMS alerts. This article delves into the journey of creating a scalable, cost-effective system that not only enhances home automation but also fosters a deeper understanding of energy management through hands-on experience.


Hello, I'm Ryan Susman, and I'd like to share with you an exciting update on my Arduino Battery Backup Monitor project. In my journey, I've managed to source batteries from a Facebook listing, aiming to enhance the system for better cloud connectivity. In this video, I focus on using a NodeMCU microcontroller and an ADS1115 ADC. These components are crucial for accurately measuring voltage drops across a shunt and uploading data to MongoDB for thorough analysis. To get a detailed insight into how this system works, check out my full video:

I've found immense value in this battery project, particularly in how it's evolved. Initially, I acquired several batteries from a Facebook listing and upgraded them for cloud connectivity. The real game-changer was opting for a NodeMCU microcontroller with Wi-Fi and an ADS1115 ADC, rather than expensive pre-built units. This setup not only proved cost-effective but also enhanced precision in measuring voltage drops across a shunt resistor. The ability to upload data to MongoDB and analyze it offers a new level of monitoring efficiency and accuracy for battery systems. This project underscores the potential of DIY solutions in home automation and energy management.

In the Arduino Battery Backup Monitor project, the code plays a pivotal role in its functionality and efficiency. The main loop is the heart of the system, where crucial operations occur, such as taking voltage measurements from the ADS1115, calculating the rolling average, and determining the current draw. This loop also updates the remaining battery capacity and interacts with external systems like MongoDB for data uploading and Twilio for sending SMS alerts. The way the loop handles these tasks, with careful consideration for accuracy and responsiveness, showcases a well-thought-out approach to real-time monitoring and data management. This code structure not only makes the project functional but also adaptable for various home automation applications.


// Includes
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
#include <Adafruit_ADS1X15.h>
#include <Chrono.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h"

Function Prototypes

// Function Prototypes
// Connects to a WiFi network using the provided SSID and password
void connectToWiFi(const char* ssid, const char* password);

// Retrieves battery configuration data from a database using the MAC address
void getBatteryConfig(const String& macAddress);

// Initializes the ADS1115 Analog-to-Digital Converter (ADC)
void initializeADS1115();

// Takes a voltage measurement from a specified ADC pin
float takeMeasurement(int adcPin);

// Writes battery data to a database, including voltage, amperage, remaining capacity, and other details
void writeToDB(float voltage, float amperage, float remainingAh, const String& remainingTime, const String& state, const String& macAddress, const String& ipAddress, float remainingPercent);

// Calculates a rolling average for a given sample and current average over a specified number of samples
float calculateRollingAverage(float currentAverage, float newSample, int sampleCount);

// Formats a given time in seconds into a string in the format "HH:MM:SS"
String formatTime(long seconds);

// Function to send a text message using Twilio API
void sendTextMessage(const String& messageBody);


void setup() {
    // Serial output
    // Connect to WiFi (SSID and Password in arduino_secrets.h)
    // using the mac_address, pull the configurations for this deployment from MongoDB
    // Set up ADC (ADS1115)
    pinMode(kLedPin, OUTPUT);

    // Setup complete!

Main Loop

void loop() {
    digitalWrite(kLedPin, HIGH);

    float measurementInterval = myChrono.elapsed();
    float voltage = takeMeasurement(kAdcPin);

    voltageAverage = calculateRollingAverage(voltageAverage, voltage, rollingAvgDistance);

    if (startup_loop < rollingAvgDistance) {
    } else if (startup_loop == rollingAvgDistance) {

    // Calculate the current in amperes by dividing the average voltage by the shunt resistance
    float current = voltageAverage / shuntOhms;
    // Convert the measurement interval from milliseconds to hours for capacity calculation
    float timeHours = measurementInterval / 3600000.0;
    // Calculate the amount of capacity (in ampere-hours) used in this measurement interval
    float usedCapacity = current * timeHours;
    // Subtract the used capacity from the remaining battery capacity to update its value
    remainingCapacityAh -= usedCapacity;
    // Constrain the remaining capacity to be within the range of 0 to the maximum battery capacity
    remainingCapacityAh = constrain(remainingCapacityAh, 0.0, batteryCapacityAh);
    // Calculate the remaining battery capacity as a percentage of the total capacity
    float remainingBatteryPercent = (remainingCapacityAh * 100) / batteryCapacityAh;
    // Calculate remaining battery life in hours
    float remainingBatteryLifeHours = (current != 0) ? (remainingCapacityAh / current) : 0;
    // Convert remaining battery life from hours to seconds
    long remainingBatteryLifeSeconds = static_cast<long>(remainingBatteryLifeHours * 3600);
    // Format the remaining battery life in HH:MM:SS format
    String formattedRemainingBatteryLife = formatTime(remainingBatteryLifeSeconds);

    // Check if the SMS alert feature is enabled and if the current measurement conditions warrant an SMS alert.
    if (smsEnabled) {
        // Check if the current exceeds the threshold of 0.2 amps.
        if (current > 0.2) {
            currentExceeded = true; // Set a flag indicating that the current has exceeded the threshold.

            // Check if an SMS has not been sent yet or if it has been more than 2 hours since the last SMS.
            if (!smsSent || smsTimer.hasPassed(7200000)) { // 7200000 milliseconds = 2 hours
                // Send an SMS message to alert that the current has exceeded 0.2 amps. Customize the message and recipient.
                sendTextMessage("Battery:" + batteryName + " Current exceeds 0.2 Amps");
                smsSent = true; // Set the flag to indicate that an SMS has been sent.
                smsTimer.restart(); // Restart the timer to track the interval for the next SMS alert.
        // Check if the current has dropped below 0.2 amps after having previously exceeded it.
        else if (currentExceeded && current <= 0.2) {
            currentExceeded = false; // Reset the flag as the current is now below the threshold.

            // Check if an SMS was sent when the current exceeded the threshold.
            if (smsSent) {
                // Send an SMS message to alert that the current has dropped back below 0.2 amps. Customize the message and recipient.
                sendTextMessage("Battery:" + batteryName + " Current has dropped below 0.2 Amps");
                smsSent = false; // Reset the flag to allow a new SMS to be sent when the current goes above 0.2 amps again.
                smsTimer.restart(); // Restart the timer for timing the next SMS alert.

    Serial.print("V:          "); Serial.println(String(voltage, 7));
    Serial.print("Avg V:      "); Serial.println(String(voltageAverage, 7));
    Serial.print("I:          "); Serial.println(String(current, 7));
    Serial.print("Remain Ah:  "); Serial.println(String(remainingCapacityAh, 7));
    Serial.print("Remain %:   "); Serial.println(String(remainingBatteryPercent, 2));
    Serial.print("Remain Time:"); Serial.println(formattedRemainingBatteryLife);

    writeToDB(voltage, current, remainingCapacityAh, formattedRemainingBatteryLife, "", macAddress, ipAddress, remainingBatteryPercent);

    digitalWrite(kLedPin, LOW);

MongoDB Cloud Monitoring

Uploading data to MongoDB in the Arduino Battery Backup Monitor project is a crucial aspect that enables detailed tracking and analysis. This feature allows the system to store real-time measurements of voltage, current, and battery capacity in a structured format. MongoDB's robustness and flexibility in handling this data facilitate complex queries and aggregations. Furthermore, the integration with MongoDB Charts offers a powerful tool for visualizing this data. Through these charts, users can easily interpret the battery's performance and health over time, making it an invaluable resource for monitoring and decision-making in home energy management.


In conclusion, the Arduino Battery Backup Monitor project is a testament to the power and potential of DIY home automation. Combining the precision of hardware like the NodeMCU and ADS1115 with the advanced data handling capabilities of MongoDB, this project not only offers real-time battery monitoring but also paves the way for innovative energy management solutions. With the added functionality of SMS alerts, it ensures immediate response to critical battery conditions. This project serves as an inspiring blueprint for enthusiasts looking to delve into the world of IoT and smart home technology.

Related Content


You May Also Like