Siddhant Kumar
Project 075 · Energy

Home Solar + Battery Optimizer.

Maximises how much of your own solar you actually use — shifting flexible loads into sunny hours and charging the battery smartly — so you buy less grid power and export less for a pittance.

Advanced 14–20 hours 30 min read SolarBatteryLogic
Jump to source Bill of materials
Home Solar + Battery Optimizer — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Advanced
Build time
14–20 hours
Indicative cost
₹5,000 – ₹9,000
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Energy
Last updated
28 July 2026
Contents — 26 sections

Project Overview

Maximises how much of your own solar you actually use — shifting flexible loads into sunny hours and charging the battery smartly — so you buy less grid power and export less for a pittance.

A home solar system with a battery is only as good as your ability to use your own generation. The economics are stark: power you consume yourself is worth the full retail price you would otherwise pay the grid, but power you export is usually bought back by the utility for a fraction of that. So every kilowatt-hour of solar that goes to the grid instead of running your own appliances is money left on the table. This project builds an optimiser that maximises self-consumption: it watches generation, home load and battery state, and orchestrates flexible loads and battery charging so that as much of your solar as possible does useful work in your own home.

It does this by understanding the whole picture in real time — how much the panels are generating, how much the house is drawing, how full the battery is, and what is being imported from or exported to the grid — and then acting on the flexible parts. Deferrable loads (a water heater, EV charging, a pool pump, a dishwasher) are shifted into the sunny hours so they run on surplus solar rather than grid power or evening battery. The battery is charged from midday surplus and discharged in the evening peak rather than dumped to the grid. And where time-of-use tariffs apply, the optimiser factors in when grid power is cheap or expensive, charging and running loads to minimise cost, not just to maximise raw self-consumption.

The result is a home that quietly rearranges its energy use to buy less and export less-for-a-pittance — often improving solar economics substantially — while staying comfortable. It reports generation, consumption, self-consumption fraction and savings so the benefit is visible. It is honest that it controls only flexible loads (it cannot move a load that must run now, and comfort/critical loads always take priority), that it needs correct measurement of generation/load/battery/grid to make good decisions, and that any control of real electrical loads must be done safely and within the inverter/battery system's own limits. But as a self-consumption optimiser that shifts flexible loads to solar hours and manages the battery intelligently, it extracts the value a solar-plus-battery system is capable of but rarely delivers on its own.

A photovoltaic solar panel in sunlight
A solar-plus-battery home is worth far more when you use your own generation instead of exporting it cheaply. Photograph sourced from Wikimedia Commons — Solar panel.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Measures generation, home load, battery state and grid import/export
  • Maximises self-consumption of your own solar
  • Shifts flexible loads (heater, EV, pump) into sunny hours
  • Charges the battery from surplus and discharges in the evening peak
  • Optimises for time-of-use tariffs where they apply
  • Reports self-consumption fraction and savings
  • Prioritises comfort/critical loads and stays within system limits

Real-World Applications

SettingHow it is used
Home solar + batteryMaximising self-consumption to cut grid import and low-value export.
Solar + EVCharging the EV from surplus solar rather than the grid.
Time-of-use tariff homesShifting loads/battery to minimise cost under variable tariffs.
Prosumer energy managementOrchestrating flexible loads around generation and price.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Whole-picture real-time energy awareness
  • Flexible-load shifting to solar surplus
  • Smart battery charge/discharge scheduling
  • Time-of-use tariff optimisation
  • Self-consumption and savings reporting
  • Comfort/critical-load priority
  • Safe control within inverter/battery limits

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelAdvanced
Estimated completion time14–20 hours
Indicative build cost₹5,000 – ₹9,000
Primary disciplineEnergy
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Whole-home energy measurement (generation/load/battery/grid)
  • Self-consumption optimisation and load shifting
  • Battery charge/discharge scheduling
  • Time-of-use tariff optimisation
  • Safe flexible-load control and prioritisation

Bill of Materials

Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.

ComponentKey specificationQtyApprox. cost
ESP32 DevKit V1 (ESP-WROOM-32)
Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC1₹450
PZEM-004T v3 AC energy meter (100 A CT)
The measurement side sits at mains potential — the opto-isolated UART is the only safe boundary.
80–260 VAC, 0–100 A, voltage/current/power/energy/PF/frequency, ±0.5 %1₹950
ACS712 hall-effect current sensor (20 A)
Zero-offset drifts with temperature — re-zero at boot with no load.
±20 A, 100 mV/A, 80 kHz bandwidth, 1.2 mΩ internal resistance, 2.1 kV isolation1₹180
4-channel opto-isolated relay board
All four coils energised draw ~280 mA — do not power from the MCU 5 V pin.
4 × SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel1₹280
0.96″ SSD1306 OLED display
Static images burn in — invert or scroll the screen periodically.
128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C1₹250
microSD card 32 GB A1 class
For 24/7 loggers buy a high-endurance card — normal cards die in months.
A1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended1₹450
5 V 3 A regulated SMPS adapter
Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A.
100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection1₹350
Generation + grid + battery metering
Correct measurement drives good decisions
CTs/meters on PV, grid tie and battery for the full picture1₹1,800
Flexible-load switching
Switch loads safely within ratings
Contactors/relays (or smart plugs) for heater/pump/EV control1₹900
Inverter/battery interface
Respect the system's own control and limits
API/Modbus link to the inverter/BMS for battery control where available1₹500
Tariff schedule / clockTime-of-use tariff data and accurate time1

Estimated total: ₹6,110, excluding tools, shipping and consumables.

Tools and consumables

  • Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
  • Digital multimeter — continuity, DC volts and current ranges
  • Wire strippers, flush cutters and a small set of precision screwdrivers
  • Heat-shrink tubing and a heat gun (or a lighter, carefully)
  • A laptop with a USB port and the toolchain listed above

Hardware Specifications

PartSpecificationSupplyInterfaceReference
ESP32 DevKit V1 (ESP-WROOM-32)Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
PZEM-004T v3 AC energy meter (100 A CT)80–260 VAC, 0–100 A, voltage/current/power/energy/PF/frequency, ±0.5 %5 V logic sideUART Modbus-RTU 9600Datasheet
ACS712 hall-effect current sensor (20 A)±20 A, 100 mV/A, 80 kHz bandwidth, 1.2 mΩ internal resistance, 2.1 kV isolation5 VAnalogueDatasheet
4-channel opto-isolated relay board4 × SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel5 V coil4× digitalDatasheet
0.96″ SSD1306 OLED display128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C3.3–5 VI²C (0x3C)Datasheet
microSD card 32 GB A1 classA1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended3.3 VSDIO / SPIDatasheet
5 V 3 A regulated SMPS adapter100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection5 VDC barrel / USBDatasheet

Consolidated electrical and interface specifications for every active part in the build.

Power Budget & Supply Sizing

Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
PZEM-004T v3 AC energy meter (100 A CT)5 V logic side20The measurement side sits at mains potential — the opto-isolated UART is the only safe boundary.
ACS712 hall-effect current sensor (20 A)5 V10Zero-offset drifts with temperature — re-zero at boot with no load.
4-channel opto-isolated relay board5 V coil280All four coils energised draw ~280 mA — do not power from the MCU 5 V pin.
0.96″ SSD1306 OLED display3.3–5 V20Static images burn in — invert or scroll the screen periodically.
microSD card 32 GB A1 class3.3 V100For 24/7 loggers buy a high-endurance card — normal cards die in months.
5 V 3 A regulated SMPS adapter5 V3000Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A.

Summed typical draw is 3590 mA. With a 1.5× design margin the supply should deliver at least 5400 mA continuously at the stated rail voltage.

Software Requirements & Development Environment

Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.

  • Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
  • Add https://espressif.github.io/arduino-esp32/package_esp32_index.json under File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager.
  • Set the correct port under Tools → Port. On Linux add yourself to the dialout group: sudo usermod -aG dialout $USER and log out and back in.
  • Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
  • Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.

Required libraries

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
ModbusMaster 2.0.1Modbus-RTU master framing for RS-485 meters and drives.Library Manager → "ModbusMaster" by Doc Walker
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager → "Adafruit SSD1306"
NTPClient / configTime bundledWall-clock time from an NTP server for timestamping.Bundled (`configTime()` on ESP32)
InfluxDB 2.x + Telegraf 2.7Time-series storage with retention policies and downsampling.docker run -p 8086:8086 influxdb:2.7
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon

Block Diagram

The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.

Home Solar + Battery Optimizer — system block diagramFunctional block diagram of the Home Solar + Battery Optimizer system. SenseGenerationPVLoadhomeBatterySoCGridimport/exportDecideESP32surplus/deficitTarifftime-of-useActShift loadsto solarBatterycharge/dischargeReportSelf-consumptionsavingsrightrightnone
Home Solar + Battery Optimizer — system block diagram

Circuit Diagram & Wiring

Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.

Home Solar + Battery Optimizer — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBPV meterGPIOGenerationGrid meterGPIOImport/exportBattery/BMSRS-485SoC / charge controlFlexible-load relaysGPIO 26/25/27/14Heater/EV/pump/etc.OLEDGPIO 21/22Flows/self-consumptionWi-FiDashboard/tariffRTCGPIO 21/22Tariff timing
Home Solar + Battery Optimizer — wiring schematic
PeripheralPeripheral pinController pinSignal
PV meterUART/AOUTGPIOGeneration
Grid meterUART/AOUTGPIOImport/export
Battery/BMSModbusRS-485SoC / charge control
Flexible-load relaysINGPIO 26/25/27/14Heater/EV/pump/etc.
OLEDSDA/SCLGPIO 21/22Flows/self-consumption
Wi-Fion-chipDashboard/tariff
RTCSDA/SCLGPIO 21/22Tariff timing

Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.

Wiring explanation

  • Meter generation, grid flow and battery so the optimiser knows surplus/deficit and battery state — the basis of every decision.
  • Switch flexible loads via correctly-rated relays/contactors (or smart plugs); never exceed ratings, and keep critical loads unswitched.
  • Interface the inverter/BMS (API/Modbus) for battery charge/discharge control where available, respecting the system's own limits.
  • Give the optimiser accurate time and the tariff schedule for time-of-use optimisation.
  • Any real-load control must be electrically safe and within the inverter/battery system's constraints.
An 18650 lithium-ion cell
ESP32 module measuring all four flows and shifting flexible loads into solar surplus. Photograph sourced from Wikimedia Commons — 18650 Li-ion battery.jpg. Reused under the licence stated on that page; please check it before republishing.

System Architecture

Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.

Home Solar + Battery Optimizer — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · ACS712 hall-effect current sensor (20 A)Driver layerwifi · pubsub · modbus · ssd1306Application logicsampling loop · filtering · thresholds · state machineTransport layerWi-Fi + MQTT → home energy dashboard · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Home Solar + Battery Optimizer — architecture stack

Working Principle

The economics of home solar make self-consumption the goal, and understanding why is the whole design. A unit of solar you consume yourself offsets a unit you would have bought from the grid at the full retail price; a unit you export is bought back by the utility at a much lower feed-in rate (often a small fraction of retail). So the same kilowatt-hour is worth several times more used at home than exported. A solar system left to its own devices exports its midday surplus for little and then buys expensive grid power in the evening — the optimiser's job is to rearrange that so the surplus does useful work in the home instead.

Making good decisions requires whole-picture measurement: generation (how much the panels are making), home load (how much the house is using), battery state of charge (how much storage headroom or reserve exists), and grid flow (import means deficit, export means surplus). From these the optimiser knows, moment to moment, whether there is surplus solar to absorb or a deficit to cover — and that surplus/deficit signal is what it acts on. Without accurate measurement of all four, it would be guessing; with it, it can precisely target zero export (use every spare watt) and minimal import.

It acts through the two flexible resources: deferrable loads and the battery. Load shifting moves discretionary consumption — heating water, charging the EV, running a pool pump or a dishwasher — into the hours of solar surplus, so those loads run on free self-generated power rather than grid power or the evening battery. The battery is scheduled deliberately: charge from midday surplus that would otherwise export cheaply, and discharge in the evening when the house would otherwise import expensively, rather than letting it charge and discharge dumbly. The crucial constraint is that only flexible loads can be moved — comfort and critical loads (lights, fridge, medical equipment) must run when needed and always take priority; the optimiser rearranges the discretionary energy around the fixed, never the other way round.

Where time-of-use tariffs apply, the objective sharpens from "maximise self-consumption" to "minimise cost", and the two can differ: if grid power is very cheap at night, it may be worth importing to charge the battery for an expensive evening peak, or running a flexible load then, even though it is not solar. So the optimiser folds the tariff schedule into its decisions — charging the battery and scheduling loads for the cheapest effective energy across solar surplus and tariff windows. Throughout, the design is honest about its scope and safety: it controls only flexible loads and prioritises comfort/critical ones; its decisions are only as good as its measurements; and any control of real electrical loads and of the battery must be electrically safe and stay within the inverter/battery system's own limits and control (it complements, not overrides, the BMS/inverter). Within that frame, it delivers what a solar-plus-battery home is capable of but rarely achieves alone — turning as much of your own generation as possible into value in your own home, and quietly cutting the bill.

The maths behind it

Self-consumption value

plainSelf-consumption value
Value of using vs exporting a unit of solar:

  save_self = retail_price   (avoided import)
  earn_export = feed_in_rate (<< retail)

Using your own solar is worth (retail − feed_in) more per
kWh than exporting → maximise self-consumption.

Surplus/deficit decision

plainSurplus/deficit decision
surplus = generation − load        (W)

  surplus > 0 → run flexible loads / charge battery
                (target ~zero export)
  surplus < 0 → discharge battery / defer flexible loads
                (minimise import)
Always serve critical loads first.

Tariff-aware cost minimisation

plainTariff-aware cost minimisation
Choose actions to minimise cost, not just maximise self-use:

  cost = Σ (import·price(t) − export·feed_in(t))

Under time-of-use, it can pay to charge the battery from
cheap off-peak grid for an expensive peak — optimise the
schedule across solar + tariff windows.

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Home Solar + Battery Optimizer — firmware flowchartControl flow through the main program loop. Read generation, load,battery, gridSurplus solar?Run flexible loads / charge batteryDeficit handlingRun flexible loads / chargebatteryDeficit handlingEvening peak / expensivetariff?Discharge battery / defer loadsHoldDischarge battery / deferloadsHoldReportself-consumption/savings
Home Solar + Battery Optimizer — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

  1. Set up whole-picture metering

    Meter generation, grid flow and battery state so the optimiser knows surplus/deficit and SoC. Interface the inverter/BMS for battery control where available.

  2. Set up flexible-load control

    Switch flexible loads via correctly-rated relays/contactors or smart plugs, leaving critical/comfort loads unswitched and prioritised.

  3. Set up tariff and reporting

    Provide the time-of-use tariff schedule and accurate time, and report self-consumption and savings.

Step-by-Step Implementation Guide

Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.

  1. Decide from surplus/deficit and tariff

    Compute surplus (generation − load), run flexible loads / charge the battery on surplus, discharge / defer on deficit, and fold in the tariff — always serving critical loads first.

    cppoptimiser.ino
    struct State { float gen, load, soc, gridW; };  // gridW>0 import
    
    // Decide flexible-load and battery actions to maximise self-consumption.
    void optimise(const State &s, float price, float feedIn){
      float surplus = s.gen - s.load;                 // >0 = spare solar
    
      if (surplus > FLEX_LOAD_W && s.soc > 0.5f){
        runFlexibleLoad(true);                         // soak surplus into a load
      } else if (surplus > 0 && s.soc < 0.95f){
        setBatteryCharge(surplus);                     // else store the surplus
      } else if (surplus < 0){                         // deficit
        if (isPeak(price) && s.soc > SOC_RESERVE)
          setBatteryDischarge(-surplus);               // cover peak from battery
        else
          deferFlexibleLoads();                        // avoid expensive import
      }
    
      // tariff opportunity: cheap grid to charge for an expensive peak
      if (isCheapOffPeak(price) && s.soc < SOC_TARGET && willPeakBeExpensive())
        setBatteryChargeFromGrid();
    
      runCriticalLoadsAlways();                         // comfort/critical priority
    }
    float surplus = s.gen - s.loadThe core signal is surplus solar — generation minus load — which the optimiser acts on to absorb spare generation or cover a deficit.
    runFlexibleLoad(true); // soak surplus into a loadSpare solar is directed into a flexible load so it does useful work at home rather than exporting for a pittance.
    setBatteryDischarge(-surplus); // cover peak from batteryIn an expensive peak with charge to spare, the battery covers the deficit instead of importing costly grid power.
    if (isCheapOffPeak(price) && ... willPeakBeExpensive())Under time-of-use tariffs it can pay to charge from cheap off-peak grid for an expensive peak — cost minimisation, not just raw self-consumption.
    runCriticalLoadsAlways(); // comfort/critical priorityCritical and comfort loads always run; the optimiser only ever rearranges the flexible, discretionary energy around them.
  2. Act safely, report and verify

    Switch flexible loads and command battery charge/discharge within the system's limits, report generation/load/battery/grid, self-consumption fraction and savings, and verify the benefit.

Complete Source Code

The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.

cppsolar-battery-optimizer.ino
/* ═══════════════════════════════════════════════════════════════
   Home Solar + Battery Optimizer — ESP32

   Maximises self-consumption: measures generation/load/battery/grid,
   shifts flexible loads into solar surplus, schedules the battery, and
   optimises for time-of-use tariffs. Critical loads always priority;
   control stays within the inverter/battery system's limits.
   ══════════════════════════════════════════════════════════════════ */

#include <WiFi.h>
#include <PubSubClient.h>
#include <PZEM004Tv30.h>

#define FLEX_LOAD_W 1500.0f   // e.g. water heater
#define SOC_RESERVE 0.20f
#define SOC_TARGET  0.90f
#define PIN_FLEX 26

PZEM004Tv30 pvMeter(Serial2, 16, 17);   // + grid/battery meters
WiFiClient net; PubSubClient mqtt(net);
double selfUsedWh=0, importWh=0, exportWh=0; uint32_t lastMs=0;

void runFlexibleLoad(bool on){ digitalWrite(PIN_FLEX, on?HIGH:LOW); }
void setBatteryCharge(float w){ /* command inverter/BMS within limits */ }
void setBatteryDischarge(float w){ /* command inverter/BMS within limits */ }

void setup(){
  Serial.begin(115200);
  pinMode(PIN_FLEX, OUTPUT);
  WiFi.begin(WIFI_SSID,WIFI_PASS); mqtt.setServer(MQTT_HOST,1883);
  lastMs=millis();
}

void loop(){
  if(!mqtt.connected()&&WiFi.status()==WL_CONNECTED) mqtt.connect("opt-1");
  mqtt.loop();
  uint32_t now=millis(); float dtHr=(now-lastMs)/3600000.0f; lastMs=now;

  float gen  = readGeneration();     // W
  float load = readHomeLoad();       // W
  float soc  = readBatterySoC();     // 0..1
  float grid = readGridFlow();       // W, >0 import
  float price = currentTariffPrice();

  float surplus = gen - load;

  if (surplus > FLEX_LOAD_W && soc > 0.5f){
    runFlexibleLoad(true);                       // use spare solar in a load
  } else if (surplus > 0 && soc < SOC_TARGET){
    runFlexibleLoad(false);
    setBatteryCharge(surplus);                    // store surplus
  } else if (surplus < 0){                        // deficit
    runFlexibleLoad(false);
    if (isPeak(price) && soc > SOC_RESERVE) setBatteryDischarge(-surplus);
    else deferFlexibleLoads();
  }
  if (isCheapOffPeak(price) && soc < SOC_TARGET && willPeakBeExpensive())
    setBatteryCharge(FLEX_LOAD_W);                // pre-charge from cheap grid

  // accounting for self-consumption/savings
  float used = fminf(gen, load);
  selfUsedWh += used*dtHr;
  if (grid > 0) importWh += grid*dtHr; else exportWh += -grid*dtHr;
  float selfFrac = gen>1 ? used/gen : 0;

  char m[240];
  snprintf(m,sizeof m,
    "{\"gen\":%.0f,\"load\":%.0f,\"soc\":%.2f,\"grid\":%.0f,"
    "\"self_frac\":%.2f,\"import_kWh\":%.2f,\"export_kWh\":%.2f}",
    gen, load, soc, grid, selfFrac, importWh/1000, exportWh/1000);
  mqtt.publish("energy/opt/status", m);

  delay(5000);
}
float surplus = gen - loadSurplus solar is computed from real generation and load — the signal the optimiser acts on to absorb spare generation.
runFlexibleLoad(true); // use spare solar in a loadSpare solar is soaked into a flexible load so it offsets a full-retail import instead of exporting cheaply.
if (isPeak(price) && soc > SOC_RESERVE) setBatteryDischarge(-surplus)An evening deficit at peak price is covered from the battery (above a reserve) rather than importing expensive grid power.
if (isCheapOffPeak(price) && ... willPeakBeExpensive())Time-of-use logic pre-charges from cheap off-peak grid for an expensive peak — minimising cost, not just maximising self-consumption.
float selfFrac = gen>1 ? used/gen : 0The self-consumption fraction and import/export tallies quantify and prove the optimiser's benefit.

Configuration & Calibration

Configuration steps

  • Configure generation/load/battery/grid metering and the inverter/BMS control interface and limits.
  • Define flexible loads and their ratings, and the critical/comfort loads to prioritise.
  • Set the time-of-use tariff schedule, SoC reserve/target and battery scheduling policy.
  • Configure reporting of self-consumption and savings.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. Metering

    Verify generation, load, battery SoC and grid flow against references so surplus/deficit is accurate.

  2. Load shifting

    Confirm flexible loads run on surplus and defer on deficit without disturbing critical loads.

  3. Tariff/battery

    Validate battery charge/discharge scheduling against the tariff and within system limits.

Network Architecture & Connectivity

Home Solar + Battery Optimizer — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsOptimiserESP32Inverter/BMSinterfaceWi-Fi/ModbusRouterto inverter/BMSMQTT 1883Energy dashboardflows + savingsDashboardself-consumptionPhonesummaries
Home Solar + Battery Optimizer — network topology

Communication protocol

Power flows, SoC, self-consumption and savings publish continuously; the optimiser controls flexible loads and battery locally within system limits.

Topic / endpointDirectionPayload
energy/opt/statusnode → dashboardgen, load, SoC, grid, self-consumption
energy/opt/actionnode → dashboardload-shift / battery actions
energy/opt/configapp → nodetariff, SoC targets, flexible loads

Message contract between the device and the broker.

Cloud platform configuration

A dashboard shows live flows and self-consumption, quantifies savings, and lets the owner set tariff/SoC/flexible-load policy.

Dashboard setup

Live PV/load/battery/grid flows, self-consumption fraction, import/export/savings, and action log.

Mobile app integration

Daily self-consumption/savings summaries and any action notifications.

Security considerations

  • Keep battery/load control local and within the inverter/BMS limits.
  • Authenticate config; secure energy data.
  • Never override critical-load priority.

Testing Procedure & Expected Output

Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.

TestWhat you should see
Midday surplusFlexible loads run / battery charges; export near zero
Evening deficit (peak)Battery discharges to cover load; import minimised
Cloudy periodFlexible loads defer; critical loads unaffected
Cheap off-peak with expensive peak aheadBattery pre-charges from cheap grid
Critical load demandAlways served; optimiser rearranges only flexible loads
Over a dayHigher self-consumption fraction and lower cost quantified

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

The dashboard shows live power flows (PV/load/battery/grid), self-consumption fraction, and import/export/savings, with the flexible-load and battery actions.

jsonenergy-opt.json
{
  "gen": 3200,
  "load": 1400,
  "soc": 0.62,
  "grid": -100,
  "self_frac": 0.94,
  "export_kWh": 2.1
}

With 3.2 kW generating and 1.4 kW of load, the optimiser has soaked the surplus into a flexible load and the battery so export is near zero and 94% of generation is self-consumed — the value a solar-plus-battery home is capable of.

A Grafana time-series dashboard
A dashboard shows the self-consumption fraction and the savings the optimiser delivers. Photograph sourced from Wikimedia Commons — Grafana dashboard.png. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Lots of low-value export

Likely cause. Surplus not soaked into loads/battery

Fix. Shift flexible loads and charge the battery on surplus; target near-zero export

Expensive evening import

Likely cause. Battery not scheduled for peak

Fix. Discharge the battery in the evening peak; pre-charge if cheaper off-peak

Critical loads disturbed

Likely cause. Switching non-flexible loads

Fix. Only control flexible loads; always prioritise critical/comfort

Bad decisions

Likely cause. Inaccurate metering

Fix. Calibrate generation/load/battery/grid measurement

Battery/inverter conflict

Likely cause. Exceeding system limits

Fix. Command within the inverter/BMS limits; respect its own control

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

An I²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an I²C scanner sketch first — it should print the device address. Most breakout boards include 4.7 kΩ pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

Performance Optimisation

  • Decide on a few-second cadence; flows change but not instantaneously.
  • Meter all four (gen/load/battery/grid) accurately for good decisions.
  • Command the battery/loads within system limits; complement the inverter/BMS.
  • Report self-consumption/savings to prove and tune the benefit.
  • Replace every delay() with a millis() comparison — blocking delays are the single most common cause of dropped readings.
  • Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
  • Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
  • Use uint8_t / uint16_t where the range allows; on an 8-bit AVR a 32-bit add costs four times as much.
  • Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
  • Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
  • For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.

Safety Precautions

  • Only control flexible loads; comfort/critical loads take priority and must not be forced to wait.
  • Any control of real electrical loads and the battery must be safe and within the inverter/battery system's own limits and control.
  • Decisions depend on correct measurement — calibrate metering.
  • Complement, do not override, the inverter/BMS protection.
  • Mains voltage kills. Anything on the load side of the relay is at 230 V. Do not work on a powered circuit, and never leave exposed mains wiring on a bench where someone could touch it.
  • Keep at least 6 mm of creepage between the mains and low-voltage sides of any board you make, and never route mains tracks under the microcontroller.
  • Have a qualified electrician do the final installation into a consumer unit or wall fitting. In most jurisdictions this is a legal requirement, not a suggestion.
  • Fit an RCD/RCBO upstream and fuse the load appropriately for its rating.
  • Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
  • Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
  • Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.

Maintenance

  • Verify metering calibration and control interfaces periodically.
  • Update tariff schedules and flexible-load definitions as they change.
  • Review self-consumption/savings and tune policy.
  • Confirm battery scheduling stays within limits as the pack ages.
  • Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
  • Rotate the microSD card annually and keep an image of the working system. Cards used as loggers wear out silently.
  • Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
  • Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
  • Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.

Future Improvements & Upgrades

A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.

  • Add solar/load forecasting to schedule proactively.
  • Add EV smart-charging integration (charge from surplus).
  • Add grid-service/VPP participation where available.
  • Add appliance-level control for finer load shifting.
  • Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
  • Add over-the-air firmware updates so you never have to physically reach a deployed node again.
  • Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
  • Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
  • Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
  • Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.

Frequently Asked Questions

Why maximise self-consumption?

Because a unit of solar you use yourself offsets a full-retail import, while a unit you export is bought back for a fraction of that. Using your own solar is worth several times more than exporting it.

What loads can it actually move?

Only flexible, deferrable ones — a water heater, EV charging, a pool pump, a dishwasher. Comfort and critical loads always take priority and run when needed; the optimiser rearranges the discretionary energy around them.

How does the battery help?

By storing midday surplus that would otherwise export cheaply and discharging it in the evening peak instead of importing expensively — scheduled deliberately rather than charging and discharging dumbly.

What about time-of-use tariffs?

The optimiser folds them in, minimising cost rather than just maximising raw self-consumption — for example pre-charging the battery from cheap off-peak grid for an expensive evening peak.

Is it safe to control my loads and battery?

It only switches flexible loads within their ratings and commands the battery within the inverter/BMS limits — complementing, not overriding, the system's own protection. Correct measurement and safe control are prerequisites.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. Solar self-consumptionReference
  2. Feed-in tariff vs retailReference
  3. Home battery storage and load shiftingReference
  4. Time-of-use tariffs / demand responseReference
  5. Home energy management systemsReference