Real-Time Temperature Monitoring & Alerts with Raspberry Pi, Python, Azure IoT Hub, Azure ML & Azure Communication Services

Diagram Explanation

1️⃣ Raspberry Pi with a DHT11/DHT22 sensor sends real-time temperature data to Azure IoT Hub.
2️⃣ Azure IoT Hub processes incoming data and triggers Azure Functions for further processing.
3️⃣ Azure ML Model analyzes data and detects temperature anomalies (e.g., overheating or cooling failures).
4️⃣ If an anomaly is detected, Azure Functions calls Azure Communication Services (ACS).
5️⃣ ACS sends an SMS/Email alert to the admin/user.
6️⃣ User/Admin monitors temperature data and receives alerts.


This guide will walk you through building a real-time temperature monitoring system using IoT sensors (Raspberry Pi) and Azure cloud services. The system will:
Collect temperature data from IoT sensors.
Analyze real-time temperature data for anomalies using Azure ML.
Trigger alerts (SMS/Email) via Azure Communication Services (ACS) when abnormal temperature conditions are detected.


🛠 Tech Stack

  • Hardware: Raspberry Pi, DHT11/DHT22 Temperature Sensor
  • Software & Services:
    • Python
    • Azure IoT Hub (Device Communication)
    • Azure Machine Learning (Anomaly Prediction)
    • Azure Functions (Processing & Alerts)
    • Azure Communication Services (ACS for SMS/Email Alerts)

🚀 Step 1: Setting Up Raspberry Pi & IoT Sensor

1️⃣ Install Dependencies on Raspberry Pi

Ensure your Raspberry Pi is up-to-date:

sudo apt update && sudo apt upgrade -y

Install required Python libraries:

pip install azure-iot-device Adafruit_DHT

2️⃣ Connect & Read Data from DHT11/DHT22 Sensor

Create a Python script sensor.py to read temperature data:

import Adafruit_DHT
import time

DHT_SENSOR = Adafruit_DHT.DHT11  # Use DHT22 if applicable
DHT_PIN = 4  # GPIO Pin

while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if temperature and humidity:
        print(f"Temp={temperature}°C  Humidity={humidity}%")
    else:
        print("Failed to read from sensor!")
    time.sleep(5)

🔗 Step 2: Sending Data to Azure IoT Hub

1️⃣ Create an IoT Hub in Azure

  • Go to Azure Portal → Create a new IoT Hub.
  • Note the Connection String & Device ID after registration.

2️⃣ Install Azure IoT SDK & Send Data

Modify sensor.py to send data to Azure IoT Hub:

from azure.iot.device import IoTHubDeviceClient, Message
import Adafruit_DHT
import time

CONNECTION_STRING = "Your IoT Hub Connection String"
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

def send_to_azure(temp, humidity):
    message = Message(f'{{"temperature": {temp}, "humidity": {humidity}}}')
    device_client.send_message(message)
    print("Message sent to Azure IoT Hub")

while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if temperature and humidity:
        send_to_azure(temperature, humidity)
    time.sleep(5)

🤖 Step 3: Setting Up Azure Machine Learning for Anomaly Detection

1️⃣ Create an Azure ML Workspace

  • Go to Azure Portal → Create Azure ML Workspace.
  • Use Jupyter Notebook or Azure ML Studio to train a model.

2️⃣ Train an Anomaly Detection Model

Create a Python script train_model.py to train an anomaly detection model:

import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
import joblib

# Generate synthetic data
data = {'temperature': np.random.normal(25, 5, 1000)}
df = pd.DataFrame(data)

# Train Anomaly Detection Model
model = IsolationForest(contamination=0.02)
model.fit(df[['temperature']])

# Save the model
joblib.dump(model, 'anomaly_model.pkl')

3️⃣ Deploy the Model in Azure ML

Upload anomaly_model.pkl to Azure ML Model Registry.


🔧 Step 4: Azure Function to Process Data & Trigger Alerts

1️⃣ Create an Azure Function

  • Go to Azure Portal → Azure Functions → Create a new function (Python)
  • Choose HTTP Trigger or IoT Hub Trigger

2️⃣ Install Dependencies

Inside Azure Function, install required packages:

pip install azure-iot-hub azure-ml azure-communication-email

3️⃣ Process Data & Trigger Alerts

Modify function_app.py in Azure Function:

import json
import joblib
import os
from azure.communication.email import EmailClient
from azure.iot.hub import IoTHubRegistryManager

MODEL_PATH = "anomaly_model.pkl"
ACS_CONNECTION_STRING = "Your ACS Connection String"
iot_hub_connection_string = "Your IoT Hub Connection String"

model = joblib.load(MODEL_PATH)
iot_client = IoTHubRegistryManager(iot_hub_connection_string)
email_client = EmailClient.from_connection_string(ACS_CONNECTION_STRING)

def send_alert_email(temp):
    message = {
        "sender": "alerts@yourdomain.com",
        "recipients": [{"email": "admin@yourdomain.com"}],
        "content": {"subject": "🔥 Overheating Alert!", "plainText": f"High temperature detected: {temp}°C"}
    }
    email_client.send(message)

def main(event: dict):
    data = json.loads(event.get_body().decode('utf-8'))
    temperature = data["temperature"]

    # Predict anomaly
    is_anomaly = model.predict([[temperature]])[0] == -1
    if is_anomaly:
        send_alert_email(temperature)

📩 Step 5: Sending SMS Alerts via Azure Communication Services (ACS)

1️⃣ Set Up Azure Communication Services

  • Go to Azure Portal → Azure Communication Services → Create a new resource
  • Copy the Connection String

2️⃣ Install ACS SDK

pip install azure-communication-sms

3️⃣ Send SMS Alert in Azure Function

Modify function_app.py to send SMS:

from azure.communication.sms import SmsClient

sms_client = SmsClient.from_connection_string(ACS_CONNECTION_STRING)

def send_alert_sms(temp):
    sms_client.send(from_="Your-ACS-Phone-Number", to=["+919XXXXXXXXX"], message=f"🔥 Temperature Alert! Current: {temp}°C")

📊 Step 6: Monitor & Visualize Data in Azure

  • Use Azure IoT Hub Metrics to track real-time sensor data.
  • Azure Monitor can visualize temperature trends.
  • Azure Log Analytics for logs & alert history.

🎯 Conclusion

With this setup, you now have a fully functional IoT-based real-time temperature monitoring system that:
Collects temperature data from Raspberry Pi sensors.
Sends data to Azure IoT Hub.
Uses Azure ML to detect anomalies.
Triggers SMS & Email Alerts via Azure Functions & ACS.

🚀 Next Steps: Extend this system by integrating a Web Dashboard or adding more ML models for predictive maintenance!

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete