class LongTermAverage {
private:
float* samples; // Array to store sensor samples
int sampleCount; // Number of samples stored
float sum; // Sum of samples
int maxSamples; // Maximum number of samples
public:
LongTermAverage() {
sampleCount = 0;
sum = 0.0;
maxSamples = 0;
samples = nullptr;
}
void setup(int maxSamples) {
// Clean up the previous state if needed
if (samples != nullptr) {
delete[] samples;
samples = nullptr;
}
// Set the new maxSamples value
this->maxSamples = maxSamples;
// Allocate memory for the samples array
samples = new float[maxSamples];
}
float calculateLongTermAverage(float* sensorValue) {
// Add the new sample to the sum
sum += *sensorValue;
// If the maximum number of samples is reached, subtract the oldest sample from the sum
if (sampleCount == maxSamples) {
sum -= samples[0];
// Shift the remaining samples to the left
for (int i = 0; i < maxSamples - 1; i++) {
samples[i] = samples[i + 1];
}
// Add the new sample to the end of the array
samples[maxSamples - 1] = *sensorValue;
} else {
// If the maximum number of samples is not reached yet, simply store the new sample
samples[sampleCount] = *sensorValue;
sampleCount++;
}
// Calculate and return the average
return sum / sampleCount;
}
~LongTermAverage() {
delete[] samples;
}
};
LongTermAverage avg_TC[11], avg_TC_AUX1[12],avg_TC_AUX2[12],avg_TC_AUX3[12],avg_TC_AUX4[12], avg_Volt[12], avg_Current[12], avg_Analog[8], avg_MUX_Analog[48]; // Create an instance of the LongTermAverageCalculator
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(35, INPUT);
pinMode(34, INPUT);
avg_TC[0].setup(100);
avg_TC[1].setup(5);
}
void loop() {
// put your main code here, to run repeatedly:
delay(50); // this speeds up the simulation
float raw = analogRead(35) + random(-40, 40) * 1.1f; //random(90,100)*1.1f;
float raw2 = analogRead(34) + random(-40, 40) * 1.1f;
float sensor_value1 = avg_TC[0].calculateLongTermAverage(&raw);
float sensor_value2 = avg_TC[1].calculateLongTermAverage(&raw2);
char buffer[80];
sprintf(buffer, "raw1: %.2f average1: %.2f average2: %.2f", raw, sensor_value1, sensor_value2);
Serial.println(buffer);
}