// After running the simulator, click on the DS18B20 chip to change the temperature
// Chip by bonnyr, source code: https://github.com/bonnyr/wokwi-ds1820-custom-chip/
#include <OneWire.h>
#include <DallasTemperature.h>
// Pin a cui è collegato il sensore DS18B20
#define ONE_WIRE_BUS 10
// Numero massimo di letture da mantenere nel buffer
#define BUFFER_SIZE 15
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// Buffer circolare
float buffer[BUFFER_SIZE];
int bufferIndex = 0; // Indice corrente
int bufferCount = 0; // Numero di valori nel buffer
void setup() {
Serial.begin(115200);
sensors.begin();
}
void loop() {
static uint32_t readTime = millis();
// Controlla se è il momento di eseguire una nuova lettura
if (millis() - readTime >= 1000) {
readTime = millis();
readSensor();
// Calcola e stampa la media
if (bufferCount > 0) {
Serial.print("Media: ");
Serial.println(calculateAverage());
}
}
}
void readSensor() {
// Richiede e legge la temperatura
sensors.requestTemperatures();
float tempC = sensors.getTempCByIndex(0);
// Scarta i valori non validi (-127)
if (tempC != -127.0) {
// Aggiungi al buffer
buffer[bufferIndex] = tempC;
// Incrementa indice circolare
bufferIndex = (bufferIndex + 1) % BUFFER_SIZE;
// Aggiorna il conteggio per avere una lettura valida anche quando il buffer non è pieno
bufferCount = min(bufferCount + 1, BUFFER_SIZE);
}
}
// Calcola la media dei valori nel buffer
float calculateAverage() {
float sum = 0;
for (int i = 0; i < bufferCount; i++) {
sum += buffer[i];
}
return sum / bufferCount;
}