#include <LiquidCrystal_I2C.h>
#include <ArduinoJson.h>
#include <HttpClient.h> // Include the HttpClient library
const int potPin = A0;
const int chargingPin = 2;
const int fullyChargedPin = 3;
LiquidCrystal_I2C lcd(0x27, 16, 2);
int batteryPercentage = 1;
float electricPower = 0.0;
float timeRemaining = 0.0;
#define JSON_BUFFER_SIZE 200
StaticJsonDocument<JSON_BUFFER_SIZE> jsonDocument;
char jsonString[JSON_BUFFER_SIZE];
// Create an instance of the HttpClient class
HttpClient http;
void setup() {
pinMode(potPin, INPUT);
pinMode(chargingPin, OUTPUT);
pinMode(fullyChargedPin, OUTPUT);
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("EV Charging Sim");
}
void loop() {
// Simulate battery charging based on electric power applied
electricPower = map(analogRead(potPin), 0, 1023, 0, 10); // Scale potentiometer reading to a range of 0 to 10
// Calculate expected time remaining to complete charging
timeRemaining = (100 - batteryPercentage) / electricPower;
// Update battery percentage and check for fully charged
batteryPercentage += electricPower;
batteryPercentage = constrain(batteryPercentage, 0, 100);
// Update the JSON data
jsonDocument.clear();
jsonDocument["batteryPercentage"] = batteryPercentage;
jsonDocument["electricPower"] = electricPower;
jsonDocument["timeRemaining"] = timeRemaining;
// Serialize JSON data
serializeJson(jsonDocument, jsonString, sizeof(jsonString));
// Send JSON data via Serial
Serial.println(jsonString);
// Update the display
updateDisplay();
// Simulate charging completion
if (batteryPercentage >= 100) {
digitalWrite(chargingPin, LOW); // Turn off charging indicator
digitalWrite(fullyChargedPin, HIGH); // Turn on fully charged indicator
} else {
digitalWrite(chargingPin, HIGH); // Turn on charging indicator
digitalWrite(fullyChargedPin, LOW); // Turn off fully charged indicator
}
// Send data to server via HTTP POST
sendHttpPost(jsonString);
delay(1000); // Adjust this delay to control how often the values update (in milliseconds)
}
void updateDisplay() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Battery: ");
lcd.print(batteryPercentage);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Power: ");
lcd.print(electricPower);
lcd.print(" kW");
lcd.setCursor(10, 1);
lcd.print("ETA: ");
lcd.print(timeRemaining);
lcd.print(" hrs");
}
void sendHttpPost(const char* data) {
// Construct the HTTP POST request
http.beginRequest();
http.post("http://localhost:8080/api/data", "application/json", data);
http.endRequest();
// Read the response (optional)
String response = http.responseBody();
Serial.println("HTTP POST request sent.");
Serial.print("Response: ");
Serial.println(response);
}