Monitoring system for electric vehicles (log various sensors, such as consumed power, solar production, speed, slope, apparent wind, etc.)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.5 KiB

#include <Arduino.h>
#include <WiFi.h>
#include <FS.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include "wifi-credentials.h"
AsyncWebServer server(80);
float averageBatteryVoltage = 0.0f;
int16_t batteryVoltage = -1; //in mV
struct ADC_CalibrationValue
{
float Measure;
int16_t ADC_Value;
};
const ADC_CalibrationValue calibration[] = {
{ 0.118f, 1 },
{ 0.343f, 253 },
{ 0.791f, 801 },
{ 1.512f, 1705 },
{ 2.013f, 2306 },
{ 2.406f, 2796 },
{ 2.606f, 3058 },
{ 2.839f, 3423 },
{ 2.996f, 3726 },
{ 3.16f, 4094 }
};
const int8_t calibrationNumValues = sizeof(calibration)/sizeof(calibration[0]);
float getCalibratedVoltage(int16_t adcOutput)
{
for(int8_t i = 1; i < calibrationNumValues; ++i)
{
if(i == calibrationNumValues - 1 || calibration[i].ADC_Value >= adcOutput)
{
const auto& p = calibration[i - 1];
const auto& n = calibration[i];
return (float)(adcOutput - p.ADC_Value) / (float)(n.ADC_Value - p.ADC_Value) * (n.Measure - p.Measure) + p.Measure;
}
}
return -1.0f;
}
void setup()
{
Serial.begin(115200);
if(!SPIFFS.begin(false)){
Serial.println("SPIFFS Mount Failed");
return;
}
// Connect to Wi-Fi
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to Wifi...");
}
// Print ESP Local IP Address
Serial.print("Wifi connected, ip=");
Serial.println(WiFi.localIP());
server.on("/api/status", HTTP_GET, [](AsyncWebServerRequest *request){
int v = batteryVoltage;
char json[128];
sprintf(json, "{\"v\":%d,\"c\":1000}", v);
request->send(200, "text/json", json);
});
// Special case to send index.html without caching
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(SPIFFS, "/www/index.html", "text/html"); });
server.serveStatic("/index.html", SPIFFS, "/www/index.html");
// Other static files are cached (index.html knows whether to ignore caching or not for each file)
server.serveStatic("/", SPIFFS, "/www/").setCacheControl("max-age=5184000");
server.begin();
Serial.println("HTTP server started");
}
float avgAnalogV = 0.0f;
void loop()
{
const int potPin = 34;
const float minV = 0.14f; // 1
const float maxV = 3.16f; // 4094
delay(10);
int16_t analogV = analogRead(potPin);
float v = getCalibratedVoltage(analogV);
averageBatteryVoltage = averageBatteryVoltage * 0.95f + v * 0.05f;
batteryVoltage = (int16_t)(averageBatteryVoltage * 1000.0f + 0.5f);
//avgAnalogV = avgAnalogV * 0.9f + (float)analogV * 0.1f;
//batteryVoltage = (int16_t)(avgAnalogV + 0.5f);
}