#include <DHT.h> // Include the DHT sensor library
#define DHTPIN 15 // Define the GPIO pin where the DHT sensor is connected
#define DHTTYPE DHT22 // Define the type of DHT sensor (DHT22)
DHT dht(DHTPIN, DHTTYPE); // Initialize the DHT sensor
float temperature_c; // Variable to store the current temperature reading
#define ntemp 10 // Number of temperature readings to store
float temp[ntemp]; // Array to store temperature readings
static int measurement_counter = 0; // Counter to track number of measurements
// Function to get the minimum temperature from stored readings
float getMin() {
float result = temp[0];
for (int i = 1; i < ntemp; i++) {
if (temp[i] < result) {
result = temp[i];
}
}
return result;
}
// Function to get the maximum temperature from stored readings
float getMax() {
float result = temp[0];
for (int i = 1; i < ntemp; i++) {
if (temp[i] > result) {
result = temp[i];
}
}
return result;
}
// Function to calculate the average temperature
float getAvg() {
float result = 0.0;
for (int i = 0; i < ntemp; i++) {
result += temp[i];
}
return (result / ntemp);
}
// Function to calculate the standard deviation of temperature readings
float getStdv() {
float avg = getAvg();
float deviation = 0.0;
float sumsqr = 0.0;
for (int i = 0; i < ntemp; i++) {
deviation = temp[i] - avg;
sumsqr += sq(deviation);
}
float variance = sumsqr / ntemp;
return sqrt(variance);
}
// Function to initialize the temperature array with zeros
void initialisation() {
for (int i = 0; i < ntemp; i++) {
temp[i] = 0.0;
}
}
// Function to update the counter and process data when enough readings are collected
void addCounter() {
measurement_counter++;
if (measurement_counter >= ntemp) {
printProcessedData(); // Print calculated statistics
resetCounter(); // Reset the counter
}
}
// Function to reset the measurement counter
void resetCounter() {
measurement_counter = 0;
}
// Function to add a new temperature reading to the array
void addReading(float t) {
temp[measurement_counter] = t; // Store the temperature reading
addCounter(); // Update counter and check if processing is needed
}
// Function to print the processed temperature data (Min, Max, Avg, Std Dev)
void printProcessedData() {
Serial.print("Min: ");
Serial.print(getMin());
Serial.print(", Max: ");
Serial.print(getMax());
Serial.print(", Avg: ");
Serial.print(getAvg());
Serial.print(", Stdev: ");
Serial.println(getStdv());
}
void setup() {
Serial.begin(9600); // Start serial communication
dht.begin(); // Initialize the DHT sensor
initialisation(); // Initialize the temperature array
}
void loop() {
temperature_c = dht.readTemperature(false); // Read temperature in Celsius
addReading(temperature_c); // Store and process the reading
Serial.print("Current temperature: ");
Serial.println(temperature_c);
delay(1000); // Waits for 1 second before taking the next reading
}