Jump to content

MDM331AID/Experiment 6

From cognifront

Experiment: Edge Computing Using Raspberry Pi for Local Sensor Data Processing

Aim

To implement an edge computing model using a Raspberry Pi in which sensor data is processed locally before being transmitted to the cloud, thereby reducing unnecessary data transmission, bandwidth usage, and response latency.

Objectives

  • To understand the concept and architecture of edge computing.
  • To interface a DHT11 temperature and humidity sensor with Raspberry Pi.
  • To process sensor readings locally using Python.
  • To implement threshold-based event detection at the edge.
  • To transmit processed sensor data to a cloud platform.
  • To understand how edge computing can reduce network traffic and improve response time.

Components Required

Sr. No. Component Quantity
1 Raspberry Pi 4 (4 GB) (COG-RPI4) 1
2 DHT11 Temperature and Humidity Sensor (COG-MSBA) 1
3 MicroSD card with Raspberry Pi OS 1
4 Raspberry Pi power supply 1
5 Patch cords As required
6 Computer with internet access 1
7 Wi-Fi network 1

Theory

Edge Computing

Edge computing is a distributed computing approach in which data is processed close to the source where it is generated rather than sending all raw data to a remote cloud server.

In a conventional cloud-based model, sensor data is transmitted to the cloud for processing. In an edge computing model, a local device such as a Raspberry Pi performs data processing and sends only relevant information to the cloud.

Need for Edge Computing

  • Reduced latency: Local processing avoids waiting for a remote server for immediate decisions.
  • Reduced bandwidth usage: Only selected or processed data is transmitted instead of every raw sensor reading.
  • Improved reliability: Local processing can continue even during temporary internet disconnections.
  • Better scalability: Reducing unnecessary cloud traffic can help support larger deployments.
  • Local decision-making: Threshold detection and other control operations can be performed directly on the edge device.

Role of Raspberry Pi as an Edge Device

The Raspberry Pi acts as an edge computing device in this experiment. It reads sensor data, processes the readings locally, detects abnormal conditions, and prepares summarized data for cloud transmission.

DHT11 Sensor

The DHT11 is a digital sensor used to measure temperature and relative humidity.

Typical operating measurement ranges are:

  • Temperature: 0°C to 50°C.
  • Relative humidity: 20% to 90%.

The sensor provides digital readings through a single data interface.

Local Data Processing

In this experiment, the Raspberry Pi reads temperature and humidity values at regular intervals.

The following processing operations are performed locally:

  • Calculate average temperature and humidity over a group of readings.
  • Compare the average temperature with a predefined threshold.
  • Generate a local alert if the threshold is exceeded.
  • Transmit processed values and alert status to the cloud rather than uploading every individual reading.

Cloud Communication

A cloud platform can store and visualize the processed sensor information. In this experiment, ThingSpeak is used as an example cloud service.

The Raspberry Pi sends processed data using an HTTP request. The cloud platform stores the submitted values for visualization and further analysis.

System Architecture

       DHT11 Sensor
            |
            v
     +------------------+
     |   Raspberry Pi   |
     |   Edge Device    |
     |                  |
     | Sensor Reading   |
     | Local Processing |
     | Threshold Check  |
     | Data Aggregation |
     +------------------+
            |
       Processed Data
            |
            v
        Wi-Fi Network
            |
            v
     +------------------+
     | Cloud Platform   |
     |   ThingSpeak     |
     |                  |
     | Data Storage     |
     | Visualization    |
     +------------------+

Pin Connections

Raspberry Pi Pin DHT11 Pin Description
Physical Pin 1 (3.3V) VCC Sensor power supply
Physical Pin 7 (GPIO4) DATA Digital data interface
Physical Pin 6 (GND) GND Common ground

Note: These connections assume a DHT11 module with compatible 3.3V logic levels and the indicated pin labels. Verify the actual sensor-board pinout before connecting. Raspberry Pi GPIO pins are not 5V tolerant.

Software Requirements

  • Raspberry Pi OS
  • Python 3
  • Adafruit CircuitPython DHT library
  • Adafruit Blinka library
  • Requests Python library
  • ThingSpeak account and channel

Install Required Libraries

If using a Python virtual environment, activate it first. Install the required packages using:

<syntaxhighlight lang="bash"> pip install adafruit-circuitpython-dht pip install adafruit-blinka pip install requests </syntaxhighlight>

If the DHT library requires additional system dependencies, install them according to the library's installation instructions for your Raspberry Pi OS version.


Program

The following Python program performs local sensor data aggregation and threshold detection on the Raspberry Pi. It uploads the processed data to ThingSpeak every 20 seconds.

Create a ThingSpeak channel with the following fields:

  • Field 1: Average Temperature
  • Field 2: Average Humidity
  • Field 3: Temperature Alert

Replace the API key with the channel's Write API Key.

import time
import board
import adafruit_dht
import requests

# Sensor configuration
dht = adafruit_dht.DHT11(board.D4)

# Cloud configuration
API_KEY = "YOUR_THINGSPEAK_WRITE_API_KEY"
THINGSPEAK_URL = "https://api.thingspeak.com/update"

# Edge processing configuration
SAMPLE_INTERVAL = 2
SAMPLES_PER_BATCH = 10
TEMP_THRESHOLD = 30.0

temperature_samples = []
humidity_samples = []

def upload_to_cloud(avg_temp, avg_humidity, alert):
    payload = {
        "api_key": API_KEY,
        "field1": avg_temp,
        "field2": avg_humidity,
        "field3": int(alert)
    }

    try:
        response = requests.post(
            THINGSPEAK_URL,
            data=payload,
            timeout=10
        )

        if response.status_code == 200 and response.text != "0":
            print("Cloud upload successful")
            print("Entry ID:", response.text)
        else:
            print("Cloud upload failed:", response.text)

    except requests.RequestException as error:
        print("Network error:", error)

try:
    print("Raspberry Pi Edge Computing System Started")

    while True:
        try:
            temperature = dht.temperature
            humidity = dht.humidity

            if temperature is not None and humidity is not None:
                temperature_samples.append(temperature)
                humidity_samples.append(humidity)

                print("Raw Temperature:", temperature, "°C")
                print("Raw Humidity:", humidity, "%")

            if len(temperature_samples) >= SAMPLES_PER_BATCH:
                # Local data aggregation
                avg_temp = sum(temperature_samples) / len(temperature_samples)
                avg_humidity = sum(humidity_samples) / len(humidity_samples)

                # Local threshold-based decision
                alert = avg_temp >= TEMP_THRESHOLD

                print("\n--- Edge Processing Result ---")
                print("Average Temperature:", round(avg_temp, 2), "°C")
                print("Average Humidity:", round(avg_humidity, 2), "%")

                if alert:
                    print("ALERT: Temperature threshold exceeded")
                else:
                    print("Status: Normal")

                # Send processed data to cloud
                upload_to_cloud(
                    round(avg_temp, 2),
                    round(avg_humidity, 2),
                    alert
                )

                # Clear batch for next aggregation
                temperature_samples.clear()
                humidity_samples.clear()

                print("------------------------------\n")

        except RuntimeError as error:
            # Temporary DHT11 reading errors
            print("Sensor reading error:", error)

        time.sleep(SAMPLE_INTERVAL)

except KeyboardInterrupt:
    print("Program stopped by user")

finally:
    dht.exit()

Code Explanation

Statement Description
import board Provides board pin definitions for Raspberry Pi.
import adafruit_dht Provides functions to read the DHT11 sensor.
import requests Provides HTTP communication with the cloud.
dht = adafruit_dht.DHT11(board.D4) Initializes the DHT11 sensor using GPIO4.
SAMPLE_INTERVAL = 2 Defines a two-second interval between sensor-reading attempts.
SAMPLES_PER_BATCH = 10 Defines the number of readings collected before local aggregation.
TEMP_THRESHOLD = 30.0 Defines the demonstration temperature threshold.
temperature_samples.append(temperature) Stores the latest valid temperature reading locally.
sum(temperature_samples) / len(temperature_samples) Calculates the average temperature for the current batch.
avg_temp >= TEMP_THRESHOLD Performs local threshold-based event detection.
requests.post() Transmits the processed sensor data to the cloud using HTTP.
temperature_samples.clear() Clears the current batch after processing.
dht.exit() Releases the DHT sensor resources when the program ends.

Procedure

Step 1: Hardware Setup

  1. Connect the DHT11 sensor to the Raspberry Pi using the specified pin connections.
  2. Connect the Raspberry Pi to its power supply.
  3. Ensure the sensor is powered using a compatible voltage and logic interface.

Step 2: Software Setup

  1. Boot Raspberry Pi OS.
  2. Connect the Raspberry Pi to a Wi-Fi network with internet access.
  3. Open the terminal.
  4. Create and activate a Python virtual environment if required.
  5. Install the required Python libraries.
  6. Create a Python file named edge_computing.py.
  7. Enter the given program and save it.

Step 3: Cloud Setup

  1. Sign in to ThingSpeak.
  2. Create a new channel.
  3. Enable Field 1, Field 2, and Field 3.
  4. Name the fields as Average Temperature, Average Humidity, and Temperature Alert.
  5. Save the channel.
  6. Open the API Keys tab.
  7. Copy the Write API Key.
  8. Replace YOUR_THINGSPEAK_WRITE_API_KEY in the program with the actual key.

Step 4: Execute the Program

  1. Run the program using the command:

<syntaxhighlight lang="bash"> python edge_computing.py </syntaxhighlight>

  1. Observe the raw sensor readings in the Raspberry Pi terminal.
  2. Observe the locally calculated average temperature and humidity.
  3. Check the local threshold detection output.
  4. Observe the cloud upload status.

Step 5: Verify Cloud Data

  1. Open the ThingSpeak channel.
  2. View the private channel's visualization page.
  3. Observe the uploaded average temperature and humidity.
  4. Observe the temperature alert field.
  5. Compare the local processing output with the cloud values.

Observations

Sr. No. Processing Stage Expected Observation
1 Sensor reading Raw temperature and humidity readings displayed locally
2 Data aggregation Average of ten valid readings calculated locally
3 Threshold detection Local alert generated when average temperature reaches or exceeds 30°C
4 Cloud transmission Processed readings and alert status sent to ThingSpeak
5 Cloud visualization Processed values displayed in the ThingSpeak channel

Comparison: Cloud-Based vs Edge-Based Processing

Parameter Cloud-Based Processing Edge-Based Processing
Data processing Performed on a remote cloud server Performed locally on Raspberry Pi
Data transmission Raw readings may be transmitted continuously Aggregated readings and alert status are transmitted
Bandwidth usage Can be higher when all raw data is uploaded Can be reduced by local aggregation and selective transmission
Response latency Depends on network and cloud processing Local decisions can be made without waiting for cloud processing
Internet dependency Remote processing requires connectivity Local processing can continue during internet outages
Scalability More raw data can increase cloud traffic and processing requirements Local filtering can reduce cloud traffic as deployments grow

Result

An edge computing application was implemented using a Raspberry Pi and a DHT11 sensor. Sensor data was aggregated and processed locally. Temperature threshold detection was performed on the Raspberry Pi, and processed sensor values and alert status were transmitted to the ThingSpeak cloud platform.

The experiment demonstrates how local processing can reduce unnecessary data transmission and support low-latency decision-making.

Viva Questions

  1. What is edge computing?
  2. What is the difference between edge computing and cloud computing?
  3. Why is Raspberry Pi suitable for edge computing applications?
  4. What is data aggregation?
  5. How does local processing reduce bandwidth usage?
  6. What is latency in an IoT system?
  7. What is the role of the DHT11 sensor in this experiment?
  8. Why is threshold detection performed locally?
  9. What is the purpose of the HTTP POST request?
  10. What is the difference between raw and processed sensor data?
  11. Can edge computing work without an internet connection?
  12. What are the limitations of this edge computing application?