#include <LiquidCrystal_I2C.h>
#include <Arduino.h>
// Define constants
const int shuntVoltagePinPositive = A0; // Analog pin where the positive terminal voltage is connected
const int shuntVoltagePinNegative = A1; // Analog pin where the negative terminal voltage is connected
const float voltageReference = 3.3; // ESP32 voltage reference
const int adcMaxValue = 4095; // Maximum ADC value for 12-bit resolution
const float shuntResistance = 1.0; // Shunt resistor value in ohms
const float batteryCapacity = 10000.0; // Battery capacity in milliampere-hours (mAh)
// Variables for charge calculation and state of charge
float accumulatedCharge = 0.0; // Accumulated charge in Coulombs
float accumulatedCapacity = 0.0; // Accumulated capacity in milliampere-hours (mAh)
unsigned long lastTime = 0; // Last time the charge was calculated
const int chargeInterval = 1000; // Interval in milliseconds to calculate charge
void setup() {
// Start serial communication
Serial.begin(115200);
}
void loop() {
// Read the voltage values from the positive and negative terminals of the shunt resistor
int adcValuePositive = analogRead(shuntVoltagePinPositive);
int adcValueNegative = analogRead(shuntVoltagePinNegative);
// Convert ADC values to voltage
float voltagePositive = (adcValuePositive / static_cast<float>(adcMaxValue)) * voltageReference;
float voltageNegative = (adcValueNegative / static_cast<float>(adcMaxValue)) * voltageReference;
// Calculate the voltage drop across the shunt resistor
float voltageDrop = voltagePositive - voltageNegative;
// Calculate the current using Ohm's Law (I = V/R)
float current = voltageDrop / shuntResistance;
// Calculate the time since the last charge calculation
unsigned long currentTime = millis();
unsigned long elapsedTime = currentTime - lastTime;
// Update accumulated charge based on current and time
accumulatedCharge += (current * elapsedTime) / 1000.0; // Convert milliseconds to seconds
// Calculate the state of charge (SoC)
float soc = (accumulatedCharge / batteryCapacity) * 100.0;
// Update accumulated capacity based on current and time
accumulatedCapacity += (current * elapsedTime) / 3600000.0; // Convert milliseconds to hours
// Update the last time
lastTime = currentTime;
// Print the current, accumulated charge, and state of charge
Serial.print("Current: ");
Serial.print(current, 4); // Print with 4 decimal places
Serial.print(" A\tAccumulated Charge: ");
Serial.print(accumulatedCharge, 4); // Print with 4 decimal places
Serial.print(" C\tState of Charge: ");
Serial.print(soc, 2); // Print with 2 decimal places
Serial.println(" %");
// Wait for the next charge calculation interval
delay(chargeInterval);
}