ESP8266 Voltage Monitor

I use this voltage monitor with my solar battery bank.

WemosD1 in action with set levels via a trim potentio meter switching an opto coupled relay which in turns switch/connect my IOT electric solar battery charger during bad light conditions and only to top up the solar battery bank when needed below a set level by using grid voltage source.


//Libraries

#include <ESP8266WiFi.h>

#include <ESP8266WebServer.h>


//#include <EEPROM.h>

//#define EEPROM_SIZE 5 // define the number of bytes you want to access


const char* ssid = "xxxxxxxxxxxx";

const char* password = "xxxxxxxxx";

char host[] = "api.thingspeak.com";

const char* writeAPIKey = "XXXXXXXXXXXXXXXXXXX";


int relayPin = D5;

int updatePeriod = 15;


unsigned int raw = 0;

float voltage = 0.0; // calculated voltage

float output = 0.0; //output value

const float battery_max = 13.7; //maximum voltage of battery

const float battery_min = 12.9; //minimum voltage of battery before shutdown


//---------------------------------------------------------------------------------------------------------------------------------

void setup() {

Serial.begin(115200);


pinMode(relayPin, OUTPUT);

digitalWrite(relayPin, LOW);


Serial.println("");

Serial.print("Connecting to ");

Serial.println(ssid);


WiFi.begin(ssid, password);

// Wait for connection

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(".");

}

Serial.println("");

Serial.print("Connected to ");

Serial.println(ssid);

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

}


//---------------------------------------------------------------------------------------------------------------------------------------------

void loop() {

battery_read();

//Cut of points for charging/non-charging

if (voltage <= 12.9) electricchargerON(); //12V Batterry bank voltage low cut off on lcd

if (voltage >= 13.3) electricchargerOFF(); //13.0 Batterry bank voltage higher cur off.on lcd


// make TCP connections

WiFiClient client;

const int httpPort = 80;

if (!client.connect(host, httpPort)) {

return;

}


String url = "/update?key=";

url += writeAPIKey;

url += "&field1=";

url += String(voltage);

url += "&field2=";

// url += String(output);

url += "\r\n";


// Request to the server

client.print(String("GET ") + url + " HTTP/1.1\r\n" +

"Host: " + host + "\r\n" +

"Connection: keep-alive\r\n\r\n");


delay(updatePeriod * 1000);

}


float battery_read() {

raw = analogRead(A0);

voltage = raw / 1023.0;

voltage = voltage * 40;

Serial.print("voltage: ");

Serial.println(voltage, 2);

output = ((voltage - battery_min) / (battery_max - battery_min)) * 100;

if (output < 100)

return output;

else

return 100.0f;

}


void electricchargerON() {

digitalWrite(relayPin, HIGH); //Relay switch AC cord off.

}


void electricchargerOFF() {

digitalWrite(relayPin, LOW); //Relay switch AC cord off.

}