struct BoilerData {
int16_t tempSensor1;
int16_t tempSensor2;
int16_t tempSensor3;
};
constexpr size_t maxCycleCount = 10;
BoilerData historicalData[maxCycleCount];
size_t nextHistoricalEntry = 0;
bool HistoricalDataIsFull = false;
void addHistoricalData(int16_t sensor1, int16_t sensor2, int16_t sensor3) {
historicalData[nextHistoricalEntry].tempSensor1 = sensor1;
historicalData[nextHistoricalEntry].tempSensor2 = sensor2;
historicalData[nextHistoricalEntry].tempSensor3 = sensor3;
nextHistoricalEntry = (nextHistoricalEntry + 1) % maxCycleCount; // Move to the next index, cycling if necessary
if (nextHistoricalEntry == 0) HistoricalDataIsFull = true; // If nextHistoricalEntry is back to 0, then we kknow the array is full
}
void printHistoricalDataAtIndex(size_t idx) {
Serial.print(idx + 1); // for display start numbering at 1 (in C++ arrays starts at index 0)
Serial.write('\t');
Serial.print(historicalData[idx].tempSensor1);
Serial.write('\t');
Serial.print(historicalData[idx].tempSensor2);
Serial.write('\t');
Serial.println(historicalData[idx].tempSensor3);
}
void printHistoricalData() {
Serial.println(F("\n-----------------------------"));
// print the number of valid samples
if (HistoricalDataIsFull) Serial.print(maxCycleCount);
else Serial.print(nextHistoricalEntry);
Serial.println(F(" Historical Data sample(s)"));
Serial.println(F("-----------------------------"));
Serial.println(F("#\tsensor1\tsensor2\tsensor3"));
if (HistoricalDataIsFull) {
// the array has been fill up so we have to go through all entries
// because we use a circular buffer, the oldest entry is no longer at index 0
// but it is at nextHistoricalEntry (the one we should overwrite)
// so this is our start index, and we want to print maxCycleCount entries
// we use modulo so that our index stays within the bounds of our array
for (size_t i = nextHistoricalEntry; i < nextHistoricalEntry + maxCycleCount; ++i) {
printHistoricalDataAtIndex(i % maxCycleCount); // Ensure the index stays within bounds
}
} else {
for (size_t i = 0; i < nextHistoricalEntry; ++i) {
// the array is not full yet, so we print samples from index 0 to nextHistoricalEntry (not included)
printHistoricalDataAtIndex(i);
}
}
}
void setup() {
Serial.begin(115200);
}
void loop() {
addHistoricalData(random(200), random(200), random(200)); // add a new random entrty
printHistoricalData();
delay(1000);
}