Jump to content

MDM331AID/Experiment 10

From cognifront

Experiment: Real-Time IoT Temperature Data Collection and Machine Learning-Based Prediction

Aim

To implement an IoT application to collect temperature data using a DHT11 sensor and ESP32, and apply a machine learning model to predict future temperature values.

Objectives

  • To understand the integration of IoT sensor data with machine learning.
  • To collect temperature data from a DHT11 sensor using an ESP32.
  • To transmit the sensor data to a cloud platform using Wi-Fi.
  • To obtain the collected temperature dataset in CSV format.
  • To preprocess the IoT temperature dataset for machine learning.
  • To train a machine learning model using historical temperature data.
  • To predict future temperature values using the trained model.
  • To visualize the actual and predicted temperature values.

Components Required

Sr. No. Component / Software Quantity
1 ESP32 development board 1
2 DHT11 temperature and humidity sensor 1
3 USB cable 1
4 Patch cords / jumper wires As required
5 Wi-Fi network / Internet connection 1
6 Computer or laptop 1
7 Cognifront Cloud platform 1
8 Python 1
9 Jupyter Notebook / Google Colab / VS Code 1
10 Pandas, NumPy, Matplotlib and Scikit-learn libraries 1

Theory

Internet of Things (IoT) is a technology in which physical devices equipped with sensors, processing units and communication capabilities collect and exchange data over a network. In an IoT system, sensor data can be transmitted to a cloud platform for storage and further processing.

In this experiment, a DHT11 sensor is connected to an ESP32 development board. The DHT11 measures the temperature of the surrounding environment and provides the sensor reading to the ESP32. The ESP32 uses its built-in Wi-Fi capability to transmit the collected temperature data to the Cognifront Cloud platform.

The collected temperature readings are stored on the cloud platform and can be exported as a CSV file. The historical temperature data is then used as input for a machine learning model.

Machine Learning (ML) is a branch of artificial intelligence in which computer systems learn patterns from data and use those patterns to make predictions or decisions without being explicitly programmed for every individual case.

For temperature prediction, historical sensor readings can be used to train a machine learning model. The model learns the relationship between the input data and the corresponding temperature values. After training, the model can be given a future time value and can estimate the corresponding temperature.

In this experiment, Linear Regression is used as the machine learning model. Linear Regression is a supervised machine learning algorithm used to model the relationship between an independent variable and a dependent variable.

The basic equation of Linear Regression is:

y = mx + c

where:

  • y is the predicted temperature.
  • x is the input time or time index.
  • m is the slope of the regression line.
  • c is the intercept.

For this experiment, the timestamp of each temperature reading is converted into a numerical time representation or time index. The machine learning model uses the historical time and temperature relationship to predict future temperature values.

The overall system consists of two major stages:

Stage 1 — IoT Data Collection

DHT11 Sensor
      ↓
    ESP32
      ↓
    Wi-Fi
      ↓
Cognifront Cloud
      ↓
 Temperature CSV

Stage 2 — Machine Learning Prediction

Historical Temperature CSV
          ↓
     Data Preprocessing
          ↓
   Feature Preparation
          ↓
   Train-Test Split
          ↓
   Linear Regression
          ↓
   Future Prediction
          ↓
Actual vs Predicted Graph

The accuracy of the prediction depends on the amount and quality of historical sensor data and the behavior of the temperature during the data-collection period. A simple Linear Regression model is suitable for demonstrating the machine learning workflow, but more advanced models may be required for complex temperature patterns.

DHT11 and ESP32 Pin Connections

DHT11 Pin ESP32 Pin Description
VCC 3.3V Power supply
DATA GPIO 4 Digital temperature and humidity data
GND GND Ground connection

Note: The DATA pin can be connected to another suitable ESP32 GPIO if the program is modified accordingly.

IoT Data Collection Program

The ESP32 is programmed to read the temperature from the DHT11 and transmit the sensor data to the Cognifront Cloud platform.

A typical data collection program follows the same cloud communication mechanism used in the previous experiment.

#include "cogcloudesp.h"
#include "DHT.h"

#define DHT_PIN 4
#define DHT_TYPE DHT11

DHT dht(DHT_PIN, DHT_TYPE);

String ssid = "********";
String pass = "********";
String apikey = "YOUR_API_KEY_HERE";

void setup()
{
    Serial.begin(115200);

    dht.begin();

    cogInitCloud(ssid, pass, apikey);
}

void loop()
{
    cogAppLoop();

    float temperature = dht.readTemperature();

    if (isnan(temperature))
    {
        Serial.println("Failed to read temperature");
        delay(2000);
        return;
    }

    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");

    cogStoreCloudVariable(
        "DHT-Temp",
        String(temperature, 2)
    );

    delay(2000);
}

Machine Learning Program

The following Python program loads the temperature dataset exported from the Cognifront Cloud platform, preprocesses the data, trains a Linear Regression model and predicts future temperature values.

Install the required libraries if they are not already available:

pip install pandas numpy matplotlib scikit-learn

The following program can be executed using Jupyter Notebook, Google Colab or VS Code.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

# Load the IoT temperature dataset
df = pd.read_csv("dht11-data-logger-dht-temp.csv")

print("Original Dataset")
print(df.head())

# Convert Date column to datetime
df["Date"] = pd.to_datetime(
    df["Date"],
    errors="coerce"
)

# Convert temperature values to numeric
df["Value"] = pd.to_numeric(
    df["Value"],
    errors="coerce"
)

# Remove invalid records
df = df.dropna(
    subset=["Date", "Value"]
)

# Sort data according to time
df = df.sort_values("Date")

# Create a time index
df["Time_Index"] = np.arange(len(df))

# Input and output variables
X = df[["Time_Index"]]
y = df["Value"]

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42
)

# Create Linear Regression model
model = LinearRegression()

# Train the model
model.fit(X_train, y_train)

# Predict test values
y_pred = model.predict(X_test)

# Calculate evaluation metrics
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)

print("\nModel Evaluation")
print("MAE:", mae)
print("MSE:", mse)
print("RMSE:", rmse)
print("R2 Score:", r2)

# Predict future temperature values
future_steps = 10

last_index = df["Time_Index"].max()

future_index = np.arange(
    last_index + 1,
    last_index + 1 + future_steps
)

future_df = pd.DataFrame({
    "Time_Index": future_index
})

future_predictions = model.predict(
    future_df[["Time_Index"]]
)

future_df["Predicted_Temperature"] = future_predictions

print("\nFuture Temperature Predictions")
print(future_df)

# Plot actual temperature data
plt.figure(figsize=(10, 5))

plt.plot(
    df["Time_Index"],
    df["Value"],
    label="Actual Temperature"
)

# Plot regression prediction
plt.plot(
    X_test["Time_Index"],
    y_pred,
    label="Predicted Temperature"
)

plt.xlabel("Time Index")
plt.ylabel("Temperature (°C)")
plt.title("Actual vs Predicted Temperature")
plt.legend()
plt.tight_layout()
plt.show()

# Plot future predictions
plt.figure(figsize=(10, 5))

plt.plot(
    df["Time_Index"],
    df["Value"],
    label="Historical Temperature"
)

plt.plot(
    future_df["Time_Index"],
    future_df["Predicted_Temperature"],
    label="Future Prediction"
)

plt.xlabel("Time Index")
plt.ylabel("Temperature (°C)")
plt.title("Future Temperature Prediction")
plt.legend()
plt.tight_layout()
plt.show()

Code Explanation

  • pd.read_csv(): Loads the historical IoT temperature dataset from the CSV file.
  • pd.to_datetime(): Converts the Date column into a date-time format.
  • pd.to_numeric(): Converts the temperature values into numerical data.
  • dropna(): Removes records with invalid or missing date or temperature values.
  • sort_values(): Arranges the sensor readings chronologically.
  • Time_Index: Creates a numerical representation of the sequence of temperature readings.
  • train_test_split(): Divides the dataset into training and testing subsets.
  • LinearRegression(): Creates the Linear Regression machine learning model.
  • fit(): Trains the model using the training data.
  • predict(): Generates temperature predictions using the trained model.
  • MAE: Measures the average absolute difference between actual and predicted temperature values.
  • MSE: Measures the average squared difference between actual and predicted values.
  • RMSE: Represents the square root of the Mean Squared Error and indicates the typical prediction error in the same unit as temperature.
  • R² Score: Indicates how well the model explains the variation in the target temperature values.
  • future_index: Generates future time-index values for prediction.
  • future_predictions: Contains the temperature values predicted by the trained model.
  • plt.plot(): Creates graphs showing the actual, predicted and future temperature values.

Procedure

  1. Connect the DHT11 sensor to the ESP32 according to the pin connection table.
  2. Connect the ESP32 to the computer using a USB cable.
  3. Configure the Wi-Fi network and Cognifront Cloud API key in the ESP32 program.
  4. Upload the IoT data collection program to the ESP32.
  5. Allow the ESP32 to collect temperature readings from the DHT11 sensor.
  6. Verify that the temperature readings are being transmitted to the Cognifront Cloud platform.
  7. Collect a sufficient number of temperature readings.
  8. Export the collected sensor data from the cloud platform as a CSV file.
  9. Open Jupyter Notebook, Google Colab or VS Code.
  10. Install the required Python libraries.
  11. Load the exported temperature dataset using Pandas.
  12. Convert the Date and Value columns into suitable data types.
  13. Remove invalid or missing records.
  14. Sort the dataset according to the timestamp.
  15. Create a numerical time index for the machine learning model.
  16. Divide the dataset into training and testing subsets.
  17. Create and train the Linear Regression model.
  18. Predict the temperature values for the testing dataset.
  19. Calculate the MAE, MSE, RMSE and R² evaluation metrics.
  20. Generate future time-index values.
  21. Use the trained model to predict future temperature values.
  22. Plot the actual and predicted temperature values.
  23. Plot the future temperature predictions.
  24. Observe the performance of the machine learning model.

Observations and Output

The following observations can be recorded during the experiment:

Sr. No. Parameter Observation
1 Sensor DHT11
2 IoT device ESP32
3 Communication Wi-Fi
4 Cloud platform Cognifront Cloud
5 Dataset DHT11 temperature CSV dataset
6 Machine learning model Linear Regression
7 Training data Record the number of training samples
8 Testing data Record the number of testing samples
9 MAE Record the calculated value
10 RMSE Record the calculated value
11 R² Score Record the calculated value
12 Future temperature Record the predicted values

An illustrative output may appear as:

Model Evaluation
MAE: [calculated value]
MSE: [calculated value]
RMSE: [calculated value]
R2 Score: [calculated value]

Future Temperature Predictions

   Time_Index   Predicted_Temperature
0        ...             ...
1        ...             ...
2        ...             ...

The actual values depend on the temperature dataset collected from the IoT sensor.

Result

The IoT application successfully collected temperature data from the DHT11 sensor using the ESP32 and transmitted the data to the Cognifront Cloud platform. The collected sensor data was exported as a CSV dataset and used to train a Linear Regression machine learning model. The trained model was used to predict future temperature values, and the actual and predicted temperature values were visualized.

Viva Questions

  1. What is an IoT system?
  2. What is the role of the DHT11 sensor in this experiment?
  3. Why is an ESP32 used as the IoT device?
  4. How is the sensor data transmitted to the cloud?
  5. What is machine learning?
  6. What is supervised learning?
  7. What is Linear Regression?
  8. What are the independent and dependent variables in this experiment?
  9. Why is the timestamp converted into a numerical time index?
  10. What is the purpose of splitting the dataset into training and testing data?
  11. What is the purpose of the training dataset?
  12. What is the purpose of the testing dataset?
  13. What is MAE?
  14. What is MSE?
  15. What is RMSE?
  16. What does the R² score represent?
  17. What is the difference between prediction and actual sensor measurement?
  18. Why is historical sensor data required for machine learning?
  19. What factors can affect the accuracy of temperature prediction?
  20. Why might Linear Regression not perform well for rapidly changing temperature data?
  21. How could the prediction system be improved using another machine learning model?