Jump to content

MDM331AID/Experiment 6: Difference between revisions

From cognifront
CogWikiEditor (talk | contribs)
CogWikiEditor (talk | contribs)
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Experiment: Edge Computing Using Raspberry Pi for Local Sensor Data Processing =
= Experiment: Edge Computing Using Raspberry Pi for Local Sensor Data Processing =


Line 9: Line 8:


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


== Components Required ==
== Components Required ==
Line 40: Line 40:
|-
|-
| 5
| 5
| Patch cords
| Patch cords / jumper wires
| As required
| As required
|-
|-
Line 48: Line 48:
|-
|-
| 7
| 7
| Wi-Fi network
| Wi-Fi network with Internet access
| 1
| 1
|}
|}
Line 56: Line 56:
=== Edge Computing ===
=== 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.
'''Edge computing''' is a distributed computing approach in which data is processed close to the source where it is generated instead of sending all raw data to a remote cloud server for processing.


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.
In a conventional cloud-based IoT system, sensor data may be transmitted continuously to a remote server where processing and decision-making are performed. In an edge computing system, a local device such as a Raspberry Pi performs some of the processing near the sensor. Only the required or processed information is then transmitted to the cloud.
 
In this experiment, the Raspberry Pi acts as the '''edge device'''. It reads temperature and humidity data from the DHT11 sensor, collects multiple readings, calculates their averages, performs a temperature threshold check, and sends the processed results to ThingSpeak.


=== Need for Edge Computing ===
=== Need for Edge Computing ===


* '''Reduced latency:''' Local processing avoids waiting for a remote server for immediate decisions.
The major advantages of edge computing include:
* '''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.
* '''Reduced latency:''' Local processing allows decisions to be made without waiting for remote cloud processing.
* '''Better scalability:''' Reducing unnecessary cloud traffic can help support larger deployments.
* '''Reduced bandwidth usage:''' Processed or aggregated data can be transmitted instead of every raw sensor reading.
* '''Local decision-making:''' Threshold detection and other control operations can be performed directly on the edge device.
* '''Reduced cloud workload:''' Unnecessary raw data processing at the cloud can be reduced.
* '''Local decision-making:''' Conditions such as temperature thresholds can be checked directly on the edge device.
* '''Improved scalability:''' Reducing unnecessary network traffic can be beneficial when many IoT devices are deployed.


=== Role of Raspberry Pi as an 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.
The Raspberry Pi acts as the local processing unit in this experiment. It receives temperature and humidity readings from the DHT11 sensor through GPIO4.


=== DHT11 Sensor ===
The Raspberry Pi collects '''10 valid sensor readings''' and calculates the average temperature and average humidity locally. It then compares the average temperature with a predefined threshold of '''30°C'''.


The DHT11 is a digital sensor used to measure temperature and relative humidity.
If the average temperature is greater than or equal to 30°C, an alert condition is generated. The processed temperature, humidity and alert status are then transmitted to ThingSpeak.


Typical operating measurement ranges are:
=== DHT11 Temperature and Humidity Sensor ===


* Temperature: 0°C to 50°C.
The '''DHT11''' is a digital sensor capable of measuring temperature and relative humidity.
* Relative humidity: 20% to 90%.


The sensor provides digital readings through a single data interface.
The sensor provides temperature and humidity readings through a digital data interface. In this experiment, the DHT11 is connected to the Raspberry Pi and is read using the Adafruit CircuitPython DHT library.
 
The DHT11 is suitable for basic environmental monitoring and IoT demonstrations because it provides both temperature and humidity measurements using a single data connection.


=== Local Data Processing ===
=== Local Data Processing ===


In this experiment, the Raspberry Pi reads temperature and humidity values at regular intervals.
In this experiment, sensor data is processed locally on the Raspberry Pi before being transmitted to the cloud.
 
The processing sequence is:
 
# The Raspberry Pi reads temperature and humidity from the DHT11.
# Valid readings are stored in local lists.
# The process continues until 10 valid readings are collected.
# The average temperature is calculated from the collected readings.
# The average humidity is calculated from the collected readings.
# The average temperature is compared with the threshold value of 30°C.
# An alert status is generated based on the threshold condition.
# The processed values are transmitted to ThingSpeak.
# The local data lists are cleared and the next batch of readings is collected.
 
This approach demonstrates how edge computing can reduce the amount of raw sensor data that needs to be transmitted to the cloud.
 
=== Threshold-Based Event Detection ===
 
A threshold is a predefined value used to determine whether a measured parameter has reached a specified condition.


The following processing operations are performed locally:
In this experiment, the temperature threshold is:


* Calculate average temperature and humidity over a group of readings.
<pre>
* Compare the average temperature with a predefined threshold.
Temperature Threshold = 30°C
* Generate a local alert if the threshold is exceeded.
</pre>
* Transmit processed values and alert status to the cloud rather than uploading every individual reading.
 
The Raspberry Pi performs the following check:
 
<pre>
Average Temperature >= 30°C
        |
        +---- Yes ----> Temperature Alert
        |
        +---- No -----> Normal Status
</pre>
 
The resulting alert status is converted into a numerical value before transmission to ThingSpeak:
 
{| class="wikitable"
|-
! Condition
! Alert Value
|-
| Average temperature < 30°C
| 0
|-
| Average temperature >= 30°C
| 1
|}


=== Cloud Communication ===
=== Cloud Communication ===


A cloud platform can store and visualize the processed sensor information. In this experiment, ThingSpeak is used as an example cloud service.
'''ThingSpeak''' is a cloud-based IoT platform that can be used to collect, store and visualize sensor data.


The Raspberry Pi sends processed data using an HTTP request. The cloud platform stores the submitted values for visualization and further analysis.
In this experiment, the Raspberry Pi communicates with ThingSpeak using an '''HTTP POST request'''. The Python '''Requests''' library is used to send the processed sensor values to the ThingSpeak update API.
 
The three transmitted values are:
 
* '''Field 1:''' Average Temperature
* '''Field 2:''' Average Humidity
* '''Field 3:''' Temperature Alert
 
The ThingSpeak channel stores the received values and provides visualization of the uploaded sensor data.


=== System Architecture ===
=== System Architecture ===
Line 106: Line 160:
             |
             |
             v
             v
     +------------------+
     +----------------------+
     |   Raspberry Pi   |
     |   Raspberry Pi     |
     |   Edge Device   |
     |     Edge Device     |
     |                 |
     |                     |
     | Sensor Reading   |
     | Sensor Reading     |
     | Local Processing |
    |        ↓            |
     | Threshold Check |
    |  Data Collection    |
     | Data Aggregation |
     |       ↓            |
     +------------------+
     |  Average Calculation |
            |
     |       ↓            |
      Processed Data
    |  Threshold Detection |
     +----------------------+
             |
             |
            | Processed Data
             v
             v
        Wi-Fi Network
      Wi-Fi Network
             |
             |
            | HTTP POST
             v
             v
     +------------------+
     +----------------------+
     | Cloud Platform  |
     |     ThingSpeak      |
     |   ThingSpeak    |
     |   Cloud Platform    |
     |                 |
     |                     |
     | Data Storage     |
     |   Data Storage       |
     | Visualization   |
     |   Visualization     |
     +------------------+
     +----------------------+
</pre>
</pre>


== Pin Connections ==
== Pin Connections ==
The DHT11 sensor is connected to the Raspberry Pi using the following connections. The program initializes the sensor using '''board.D4''', corresponding to '''GPIO4'''.


{| class="wikitable"
{| class="wikitable"
Line 145: Line 204:
| Physical Pin 7 (GPIO4)
| Physical Pin 7 (GPIO4)
| DATA
| DATA
| Digital data interface
| Digital sensor data
|-
|-
| Physical Pin 6 (GND)
| Physical Pin 6 (GND)
Line 152: Line 211:
|}
|}


'''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.
'''Important:''' Raspberry Pi GPIO pins operate at 3.3 V logic and are '''not 5 V tolerant'''. Do not apply 5 V signals directly to Raspberry Pi GPIO pins. Verify the DHT11 module pinout before making connections.


== Software Requirements ==
== Software Requirements ==
Line 161: Line 220:
* Adafruit Blinka library
* Adafruit Blinka library
* Requests Python library
* Requests Python library
* ThingSpeak account and channel
* ThingSpeak account
* ThingSpeak channel with three fields
* Wi-Fi connection with Internet access


=== Install Required Libraries ===
=== Install Required Libraries ===


If using a Python virtual environment, activate it first. Install the required packages using:
If a Python virtual environment is being used, activate it before installing the required packages.
 
Install the required Python libraries using:


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 173: Line 236:
</syntaxhighlight>
</syntaxhighlight>


If the DHT library requires additional system dependencies, install them according to the library's installation instructions for your Raspberry Pi OS version.
The required libraries provide the following functionality:
 
* '''Adafruit CircuitPython DHT:''' Interfaces with the DHT11 sensor.
* '''Adafruit Blinka:''' Provides compatibility between CircuitPython libraries and Raspberry Pi hardware.
* '''Requests:''' Allows the Raspberry Pi to communicate with the ThingSpeak server using HTTP requests.
 
== ThingSpeak Cloud Setup ==
 
Create a ThingSpeak channel before running the program.


Configure the channel with the following fields:


== Program ==
{| class="wikitable"
|-
! Field
! Name
! Data
|-
| Field 1
| Average Temperature
| Average temperature in °C
|-
| Field 2
| Average Humidity
| Average relative humidity in %
|-
| Field 3
| Temperature Alert
| 0 = Normal, 1 = Alert
|}


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.
After creating the channel:


Create a ThingSpeak channel with the following fields:
# Open the '''API Keys''' section of the ThingSpeak channel.
# Copy the channel's '''Write API Key'''.
# Replace the placeholder API key in the program with the actual Write API Key.
# Save the Python program.


* Field 1: Average Temperature
'''Security Note:''' Do not publish or share the actual ThingSpeak Write API Key in publicly accessible code or documentation.
* Field 2: Average Humidity
* Field 3: Temperature Alert


Replace the API key with the channel's Write API Key.
== Program ==
 
The following Python program performs local sensor data aggregation and threshold detection on the Raspberry Pi. It uploads the processed data to ThingSpeak after every batch of 10 valid sensor readings.


<pre>
<pre>
# 2026, Cognifront. Member of the IoT Kits family.
import time
import time
import board
import board
Line 195: Line 288:


# Sensor configuration
# Sensor configuration
# board.D4 sets the pin configuration to BOARD, and uses pin 4
dht = adafruit_dht.DHT11(board.D4)
dht = adafruit_dht.DHT11(board.D4)


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


Line 289: Line 383:
finally:
finally:
     dht.exit()
     dht.exit()
</pre>
</pre>


Line 298: Line 394:
! Description
! Description
|-
|-
| import board
| <code>import time</code>
| Provides board pin definitions for Raspberry Pi.
| Provides timing functions used to control the sensor reading interval.
|-
| <code>import board</code>
| Provides Raspberry Pi board pin definitions used by the sensor library.
|-
| <code>import adafruit_dht</code>
| Provides functions for interfacing with the DHT11 sensor.
|-
| <code>import requests</code>
| Provides HTTP communication with the ThingSpeak cloud server.
|-
| <code>dht = adafruit_dht.DHT11(board.D4)</code>
| Initializes the DHT11 sensor on GPIO4.
|-
| <code>API_KEY</code>
| Stores the ThingSpeak channel Write API Key used for authentication.
|-
| <code>THINGSPEAK_URL</code>
| Specifies the ThingSpeak update API endpoint.
|-
| <code>SAMPLE_INTERVAL = 2</code>
| Sets the delay between sensor-reading attempts to two seconds.
|-
| <code>SAMPLES_PER_BATCH = 10</code>
| Specifies that 10 valid sensor readings are collected before local processing.
|-
| <code>TEMP_THRESHOLD = 30.0</code>
| Sets the temperature threshold to 30°C.
|-
|-
| import adafruit_dht
| <code>temperature_samples.append(temperature)</code>
| Provides functions to read the DHT11 sensor.
| Stores a valid temperature reading locally.
|-
|-
| import requests
| <code>humidity_samples.append(humidity)</code>
| Provides HTTP communication with the cloud.
| Stores a valid humidity reading locally.
|-
|-
| dht = adafruit_dht.DHT11(board.D4)
| <code>sum(temperature_samples) / len(temperature_samples)</code>
| Initializes the DHT11 sensor using GPIO4.
| Calculates the average temperature of the current batch.
|-
|-
| SAMPLE_INTERVAL = 2
| <code>sum(humidity_samples) / len(humidity_samples)</code>
| Defines a two-second interval between sensor-reading attempts.
| Calculates the average humidity of the current batch.
|-
|-
| SAMPLES_PER_BATCH = 10
| <code>avg_temp >= TEMP_THRESHOLD</code>
| Defines the number of readings collected before local aggregation.
| Performs the local threshold-based temperature check.
|-
|-
| TEMP_THRESHOLD = 30.0
| <code>requests.post()</code>
| Defines the demonstration temperature threshold.
| Sends the processed sensor values to ThingSpeak using an HTTP POST request.
|-
|-
| temperature_samples.append(temperature)
| <code>field1</code>
| Stores the latest valid temperature reading locally.
| Stores the average temperature in ThingSpeak.
|-
|-
| sum(temperature_samples) / len(temperature_samples)
| <code>field2</code>
| Calculates the average temperature for the current batch.
| Stores the average humidity in ThingSpeak.
|-
|-
| avg_temp >= TEMP_THRESHOLD
| <code>field3</code>
| Performs local threshold-based event detection.
| Stores the temperature alert status as 0 or 1.
|-
|-
| requests.post()
| <code>temperature_samples.clear()</code>
| Transmits the processed sensor data to the cloud using HTTP.
| Clears the collected temperature readings after processing the batch.
|-
|-
| temperature_samples.clear()
| <code>humidity_samples.clear()</code>
| Clears the current batch after processing.
| Clears the collected humidity readings after processing the batch.
|-
|-
| dht.exit()
| <code>dht.exit()</code>
| Releases the DHT sensor resources when the program ends.
| Releases the DHT sensor resources when the program terminates.
|}
|}


Line 342: Line 465:
=== Step 1: Hardware Setup ===
=== Step 1: Hardware Setup ===


# Connect the DHT11 sensor to the Raspberry Pi using the specified pin connections.
# Switch off or disconnect the Raspberry Pi from its power supply before making the connections.
# Connect the Raspberry Pi to its power supply.
# Connect the DHT11 sensor to the Raspberry Pi according to the pin connection table.
# Ensure the sensor is powered using a compatible voltage and logic interface.
# Connect DHT11 VCC to Raspberry Pi 3.3V.
# Connect DHT11 DATA to Raspberry Pi GPIO4 (Physical Pin 7).
# Connect DHT11 GND to Raspberry Pi GND (Physical Pin 6).
# Verify all connections before powering the Raspberry Pi.


=== Step 2: Software Setup ===
=== Step 2: Software Setup ===


# Boot Raspberry Pi OS.
# Boot the Raspberry Pi with Raspberry Pi OS.
# Connect the Raspberry Pi to a Wi-Fi network with internet access.
# Connect the Raspberry Pi to a Wi-Fi network with Internet access.
# Open the terminal.
# Open the terminal.
# Create and activate a Python virtual environment if required.
# Create and activate a Python virtual environment if required.
# Install the required Python libraries.
# Install the required Python libraries.
# Create a Python file named edge_computing.py.
# Create a Python file, for example <code>edge_computing.py</code>.
# Enter the given program and save it.
# Enter the given program and save the file.


=== Step 3: Cloud Setup ===
=== Step 3: ThingSpeak Setup ===


# Sign in to ThingSpeak.
# Sign in to ThingSpeak.
# Create a new channel.
# Create a new channel.
# Enable Field 1, Field 2, and Field 3.
# Enable three fields in the channel.
# Name the fields as Average Temperature, Average Humidity, and Temperature Alert.
# Name Field 1 as '''Average Temperature'''.
# Name Field 2 as '''Average Humidity'''.
# Name Field 3 as '''Temperature Alert'''.
# Save the channel.
# Save the channel.
# Open the API Keys tab.
# Open the '''API Keys''' section.
# Copy the Write API Key.
# Copy the channel's '''Write API Key'''.
# Replace YOUR_THINGSPEAK_WRITE_API_KEY in the program with the actual key.
# Replace <code>YOUR_API_KEY_HERE</code> in the program with the actual Write API Key.
# Save the Python program.


=== Step 4: Execute the Program ===
=== Step 4: Execute the Program ===


# Run the program using the command:
# Open the terminal on the Raspberry Pi.
# Navigate to the directory containing the Python program.
# Activate the Python virtual environment if one is being used.
# Run the program using:


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 375: Line 507:
</syntaxhighlight>
</syntaxhighlight>


# Observe the raw sensor readings in the Raspberry Pi terminal.
# Observe the raw temperature and humidity readings displayed in the terminal.
# Observe the locally calculated average temperature and humidity.
# Allow the program to collect 10 valid readings.
# Check the local threshold detection output.
# Observe the calculated average temperature and average humidity.
# Observe the cloud upload status.
# Observe the threshold status displayed by the program.
# Check the cloud upload status and ThingSpeak Entry ID.
 
=== Step 5: Verify Edge Processing ===


=== Step 5: Verify Cloud Data ===
# Observe that sensor readings are first stored locally on the Raspberry Pi.
# Verify that an average is calculated after 10 valid readings.
# Check whether the average temperature is below or equal to the threshold condition.
# If the average temperature is 30°C or higher, observe the temperature alert message.
# If the average temperature is below 30°C, observe the normal status message.
 
=== Step 6: Verify ThingSpeak Data ===


# Open the ThingSpeak channel.
# Open the ThingSpeak channel.
# View the private channel's visualization page.
# Open the channel visualization page.
# Observe the uploaded average temperature and humidity.
# Observe the value in '''Field 1''' for average temperature.
# Observe the temperature alert field.
# Observe the value in '''Field 2''' for average humidity.
# Compare the local processing output with the cloud values.
# Observe the value in '''Field 3''' for the temperature alert.
# Compare the values displayed on ThingSpeak with the processed values shown in the Raspberry Pi terminal.


== Observations ==
== Observations ==
Line 397: Line 539:
|-
|-
| 1
| 1
| Sensor reading
| Sensor Reading
| Raw temperature and humidity readings displayed locally
| Temperature and humidity readings from the DHT11 are displayed on the Raspberry Pi terminal.
|-
|-
| 2
| 2
| Data aggregation
| Local Data Collection
| Average of ten valid readings calculated locally
| Valid sensor readings are stored locally in the Raspberry Pi.
|-
|-
| 3
| 3
| Threshold detection
| Data Aggregation
| Local alert generated when average temperature reaches or exceeds 30°C
| Average temperature and average humidity are calculated after 10 valid readings.
|-
|-
| 4
| 4
| Cloud transmission
| Threshold Detection
| Processed readings and alert status sent to ThingSpeak
| Temperature alert is generated when the average temperature is greater than or equal to 30°C.
|-
|-
| 5
| 5
| Cloud visualization
| Cloud Transmission
| Processed values displayed in the ThingSpeak channel
| Average temperature, average humidity and alert status are transmitted to ThingSpeak using HTTP.
|-
| 6
| Cloud Visualization
| Processed sensor values are stored and displayed in the ThingSpeak channel.
|}
|}
=== Sample Serial Output ===
The following is an illustrative example. Actual temperature and humidity values will depend on the environment.
<pre>
Raspberry Pi Edge Computing System Started
Raw Temperature: 27.0 °C
Raw Humidity: 61.0 %
Raw Temperature: 27.0 °C
Raw Humidity: 62.0 %
...
--- Edge Processing Result ---
Average Temperature: 27.2 °C
Average Humidity: 61.7 %
Status: Normal
Cloud upload successful
Entry ID: 12345
------------------------------
</pre>
'''Note:''' The Entry ID shown above is only an example. The actual Entry ID is generated by ThingSpeak.


== Comparison: Cloud-Based vs Edge-Based Processing ==
== Comparison: Cloud-Based vs Edge-Based Processing ==
Line 426: Line 598:
|-
|-
| Data processing
| Data processing
| Performed on a remote cloud server
| Performed primarily on a remote cloud server.
| Performed locally on Raspberry Pi
| Performed locally on the Raspberry Pi.
|-
|-
| Data transmission
| Data transmission
| Raw readings may be transmitted continuously
| Raw sensor readings may be transmitted continuously.
| Aggregated readings and alert status are transmitted
| Sensor readings are processed locally before transmission.
|-
|-
| Bandwidth usage
| Bandwidth usage
| Can be higher when all raw data is uploaded
| Can be higher when raw readings are continuously transmitted.
| Can be reduced by local aggregation and selective transmission
| Can be reduced by aggregating readings locally.
|-
|-
| Response latency
| Response latency
| Depends on network and cloud processing
| Depends on network communication and cloud processing.
| Local decisions can be made without waiting for cloud processing
| Local threshold decisions can be made directly on the Raspberry Pi.
|-
|-
| Internet dependency
| Local decision-making
| Remote processing requires connectivity
| Requires communication with the cloud when processing is remote.
| Local processing can continue during internet outages
| Threshold detection is performed locally.
|-
|-
| Scalability
| Cloud workload
| More raw data can increase cloud traffic and processing requirements
| Can increase when large amounts of raw data are uploaded.
| Local filtering can reduce cloud traffic as deployments grow
| Reduced because processed values are transmitted.
|}
|}


== Result ==
== 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.
An edge computing application was successfully implemented using a Raspberry Pi and DHT11 temperature and humidity sensor. The Raspberry Pi collected sensor readings and processed them locally by calculating the average temperature and humidity over a batch of 10 valid readings.
 
A threshold-based temperature detection mechanism was implemented locally, using 30°C as the threshold. The processed temperature, humidity and alert status were then transmitted to the ThingSpeak cloud platform using HTTP.
 
Thus, the experiment demonstrates how edge computing can perform local data processing and decision-making before transmitting relevant information to the cloud, thereby reducing unnecessary data transmission and supporting faster local responses.
 
== Real-Life Applications ==


The experiment demonstrates how local processing can reduce unnecessary data transmission and support low-latency decision-making.
* '''Industrial condition monitoring:''' Temperature and humidity sensors can monitor machinery and industrial environments.
* '''Smart agriculture:''' Edge devices can locally process environmental sensor readings and transmit only important information to the cloud.
* '''Environmental monitoring:''' Local processing can be used to detect abnormal temperature or humidity conditions.
* '''Smart buildings:''' Edge devices can monitor environmental conditions and trigger local decisions.
* '''Predictive maintenance:''' Sensor data can be processed locally to detect abnormal operating conditions before transmitting summarized information to a cloud platform.


== Viva Questions ==
== Viva Questions ==
Line 460: Line 642:
# What is edge computing?
# What is edge computing?
# What is the difference between edge computing and cloud computing?
# What is the difference between edge computing and cloud computing?
# Why is Raspberry Pi suitable for edge computing applications?
# Why is Raspberry Pi used as an edge device in this experiment?
# What is data aggregation?
# What is the role of the DHT11 sensor?
# How does local processing reduce bandwidth usage?
# Which GPIO pin is used to connect the DHT11 data pin?
# What is latency in an IoT system?
# Why is GPIO4 used in this experiment?
# What is the role of the DHT11 sensor in this experiment?
# How many sensor readings are collected before calculating the average?
# Why is threshold detection performed locally?
# What is the purpose of <code>SAMPLE_INTERVAL</code>?
# What is the value of the temperature threshold used in this experiment?
# What happens when the average temperature reaches or exceeds 30°C?
# What is the purpose of local data aggregation?
# How does edge computing reduce bandwidth usage?
# Which communication protocol is used to transmit data to ThingSpeak?
# What is the purpose of the HTTP POST request?
# What is the purpose of the HTTP POST request?
# What is the difference between raw and processed sensor data?
# What are Field 1, Field 2 and Field 3 used for in ThingSpeak?
# Can edge computing work without an internet connection?
# What is a ThingSpeak Write API Key?
# What are the limitations of this edge computing application?
# Why should the API key not be publicly shared?
# What is the purpose of the <code>requests</code> Python library?
# What is the difference between raw sensor data and processed sensor data?
# What are the advantages of processing sensor data at the edge?

Latest revision as of 02:39, 8 October 2026

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 a Raspberry Pi.
  • To read temperature and humidity data from the DHT11 sensor using Python.
  • To process and aggregate sensor readings locally on the Raspberry Pi.
  • To implement threshold-based temperature event detection at the edge.
  • To transmit processed sensor data to the ThingSpeak cloud platform using HTTP.
  • To understand how edge processing can reduce unnecessary 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 / jumper wires As required
6 Computer with internet access 1
7 Wi-Fi network with Internet access 1

Theory

Edge Computing

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

In a conventional cloud-based IoT system, sensor data may be transmitted continuously to a remote server where processing and decision-making are performed. In an edge computing system, a local device such as a Raspberry Pi performs some of the processing near the sensor. Only the required or processed information is then transmitted to the cloud.

In this experiment, the Raspberry Pi acts as the edge device. It reads temperature and humidity data from the DHT11 sensor, collects multiple readings, calculates their averages, performs a temperature threshold check, and sends the processed results to ThingSpeak.

Need for Edge Computing

The major advantages of edge computing include:

  • Reduced latency: Local processing allows decisions to be made without waiting for remote cloud processing.
  • Reduced bandwidth usage: Processed or aggregated data can be transmitted instead of every raw sensor reading.
  • Reduced cloud workload: Unnecessary raw data processing at the cloud can be reduced.
  • Local decision-making: Conditions such as temperature thresholds can be checked directly on the edge device.
  • Improved scalability: Reducing unnecessary network traffic can be beneficial when many IoT devices are deployed.

Role of Raspberry Pi as an Edge Device

The Raspberry Pi acts as the local processing unit in this experiment. It receives temperature and humidity readings from the DHT11 sensor through GPIO4.

The Raspberry Pi collects 10 valid sensor readings and calculates the average temperature and average humidity locally. It then compares the average temperature with a predefined threshold of 30°C.

If the average temperature is greater than or equal to 30°C, an alert condition is generated. The processed temperature, humidity and alert status are then transmitted to ThingSpeak.

DHT11 Temperature and Humidity Sensor

The DHT11 is a digital sensor capable of measuring temperature and relative humidity.

The sensor provides temperature and humidity readings through a digital data interface. In this experiment, the DHT11 is connected to the Raspberry Pi and is read using the Adafruit CircuitPython DHT library.

The DHT11 is suitable for basic environmental monitoring and IoT demonstrations because it provides both temperature and humidity measurements using a single data connection.

Local Data Processing

In this experiment, sensor data is processed locally on the Raspberry Pi before being transmitted to the cloud.

The processing sequence is:

  1. The Raspberry Pi reads temperature and humidity from the DHT11.
  2. Valid readings are stored in local lists.
  3. The process continues until 10 valid readings are collected.
  4. The average temperature is calculated from the collected readings.
  5. The average humidity is calculated from the collected readings.
  6. The average temperature is compared with the threshold value of 30°C.
  7. An alert status is generated based on the threshold condition.
  8. The processed values are transmitted to ThingSpeak.
  9. The local data lists are cleared and the next batch of readings is collected.

This approach demonstrates how edge computing can reduce the amount of raw sensor data that needs to be transmitted to the cloud.

Threshold-Based Event Detection

A threshold is a predefined value used to determine whether a measured parameter has reached a specified condition.

In this experiment, the temperature threshold is:

Temperature Threshold = 30°C

The Raspberry Pi performs the following check:

Average Temperature >= 30°C
        |
        +---- Yes ----> Temperature Alert
        |
        +---- No -----> Normal Status

The resulting alert status is converted into a numerical value before transmission to ThingSpeak:

Condition Alert Value
Average temperature < 30°C 0
Average temperature >= 30°C 1

Cloud Communication

ThingSpeak is a cloud-based IoT platform that can be used to collect, store and visualize sensor data.

In this experiment, the Raspberry Pi communicates with ThingSpeak using an HTTP POST request. The Python Requests library is used to send the processed sensor values to the ThingSpeak update API.

The three transmitted values are:

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

The ThingSpeak channel stores the received values and provides visualization of the uploaded sensor data.

System Architecture

       DHT11 Sensor
            |
            v
     +----------------------+
     |    Raspberry Pi      |
     |     Edge Device      |
     |                      |
     |  Sensor Reading      |
     |        ↓             |
     |  Data Collection     |
     |        ↓             |
     |  Average Calculation |
     |        ↓             |
     |  Threshold Detection |
     +----------------------+
            |
            | Processed Data
            v
       Wi-Fi Network
            |
            | HTTP POST
            v
     +----------------------+
     |      ThingSpeak      |
     |    Cloud Platform    |
     |                      |
     |   Data Storage       |
     |   Visualization      |
     +----------------------+

Pin Connections

The DHT11 sensor is connected to the Raspberry Pi using the following connections. The program initializes the sensor using board.D4, corresponding to GPIO4.

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

Important: Raspberry Pi GPIO pins operate at 3.3 V logic and are not 5 V tolerant. Do not apply 5 V signals directly to Raspberry Pi GPIO pins. Verify the DHT11 module pinout before making connections.

Software Requirements

  • Raspberry Pi OS
  • Python 3
  • Adafruit CircuitPython DHT library
  • Adafruit Blinka library
  • Requests Python library
  • ThingSpeak account
  • ThingSpeak channel with three fields
  • Wi-Fi connection with Internet access

Install Required Libraries

If a Python virtual environment is being used, activate it before installing the required packages.

Install the required Python libraries using:

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

The required libraries provide the following functionality:

  • Adafruit CircuitPython DHT: Interfaces with the DHT11 sensor.
  • Adafruit Blinka: Provides compatibility between CircuitPython libraries and Raspberry Pi hardware.
  • Requests: Allows the Raspberry Pi to communicate with the ThingSpeak server using HTTP requests.

ThingSpeak Cloud Setup

Create a ThingSpeak channel before running the program.

Configure the channel with the following fields:

Field Name Data
Field 1 Average Temperature Average temperature in °C
Field 2 Average Humidity Average relative humidity in %
Field 3 Temperature Alert 0 = Normal, 1 = Alert

After creating the channel:

  1. Open the API Keys section of the ThingSpeak channel.
  2. Copy the channel's Write API Key.
  3. Replace the placeholder API key in the program with the actual Write API Key.
  4. Save the Python program.

Security Note: Do not publish or share the actual ThingSpeak Write API Key in publicly accessible code or documentation.

Program

The following Python program performs local sensor data aggregation and threshold detection on the Raspberry Pi. It uploads the processed data to ThingSpeak after every batch of 10 valid sensor readings.

# 2026, Cognifront. Member of the IoT Kits family.
import time
import board
import adafruit_dht
import requests

# Sensor configuration
# board.D4 sets the pin configuration to BOARD, and uses pin 4
dht = adafruit_dht.DHT11(board.D4)

# Cloud configuration
API_KEY = "YOUR_API_KEY_HERE"
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 time Provides timing functions used to control the sensor reading interval.
import board Provides Raspberry Pi board pin definitions used by the sensor library.
import adafruit_dht Provides functions for interfacing with the DHT11 sensor.
import requests Provides HTTP communication with the ThingSpeak cloud server.
dht = adafruit_dht.DHT11(board.D4) Initializes the DHT11 sensor on GPIO4.
API_KEY Stores the ThingSpeak channel Write API Key used for authentication.
THINGSPEAK_URL Specifies the ThingSpeak update API endpoint.
SAMPLE_INTERVAL = 2 Sets the delay between sensor-reading attempts to two seconds.
SAMPLES_PER_BATCH = 10 Specifies that 10 valid sensor readings are collected before local processing.
TEMP_THRESHOLD = 30.0 Sets the temperature threshold to 30°C.
temperature_samples.append(temperature) Stores a valid temperature reading locally.
humidity_samples.append(humidity) Stores a valid humidity reading locally.
sum(temperature_samples) / len(temperature_samples) Calculates the average temperature of the current batch.
sum(humidity_samples) / len(humidity_samples) Calculates the average humidity of the current batch.
avg_temp >= TEMP_THRESHOLD Performs the local threshold-based temperature check.
requests.post() Sends the processed sensor values to ThingSpeak using an HTTP POST request.
field1 Stores the average temperature in ThingSpeak.
field2 Stores the average humidity in ThingSpeak.
field3 Stores the temperature alert status as 0 or 1.
temperature_samples.clear() Clears the collected temperature readings after processing the batch.
humidity_samples.clear() Clears the collected humidity readings after processing the batch.
dht.exit() Releases the DHT sensor resources when the program terminates.

Procedure

Step 1: Hardware Setup

  1. Switch off or disconnect the Raspberry Pi from its power supply before making the connections.
  2. Connect the DHT11 sensor to the Raspberry Pi according to the pin connection table.
  3. Connect DHT11 VCC to Raspberry Pi 3.3V.
  4. Connect DHT11 DATA to Raspberry Pi GPIO4 (Physical Pin 7).
  5. Connect DHT11 GND to Raspberry Pi GND (Physical Pin 6).
  6. Verify all connections before powering the Raspberry Pi.

Step 2: Software Setup

  1. Boot the Raspberry Pi with 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, for example edge_computing.py.
  7. Enter the given program and save the file.

Step 3: ThingSpeak Setup

  1. Sign in to ThingSpeak.
  2. Create a new channel.
  3. Enable three fields in the channel.
  4. Name Field 1 as Average Temperature.
  5. Name Field 2 as Average Humidity.
  6. Name Field 3 as Temperature Alert.
  7. Save the channel.
  8. Open the API Keys section.
  9. Copy the channel's Write API Key.
  10. Replace YOUR_API_KEY_HERE in the program with the actual Write API Key.
  11. Save the Python program.

Step 4: Execute the Program

  1. Open the terminal on the Raspberry Pi.
  2. Navigate to the directory containing the Python program.
  3. Activate the Python virtual environment if one is being used.
  4. Run the program using:

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

  1. Observe the raw temperature and humidity readings displayed in the terminal.
  2. Allow the program to collect 10 valid readings.
  3. Observe the calculated average temperature and average humidity.
  4. Observe the threshold status displayed by the program.
  5. Check the cloud upload status and ThingSpeak Entry ID.

Step 5: Verify Edge Processing

  1. Observe that sensor readings are first stored locally on the Raspberry Pi.
  2. Verify that an average is calculated after 10 valid readings.
  3. Check whether the average temperature is below or equal to the threshold condition.
  4. If the average temperature is 30°C or higher, observe the temperature alert message.
  5. If the average temperature is below 30°C, observe the normal status message.

Step 6: Verify ThingSpeak Data

  1. Open the ThingSpeak channel.
  2. Open the channel visualization page.
  3. Observe the value in Field 1 for average temperature.
  4. Observe the value in Field 2 for average humidity.
  5. Observe the value in Field 3 for the temperature alert.
  6. Compare the values displayed on ThingSpeak with the processed values shown in the Raspberry Pi terminal.

Observations

Sr. No. Processing Stage Expected Observation
1 Sensor Reading Temperature and humidity readings from the DHT11 are displayed on the Raspberry Pi terminal.
2 Local Data Collection Valid sensor readings are stored locally in the Raspberry Pi.
3 Data Aggregation Average temperature and average humidity are calculated after 10 valid readings.
4 Threshold Detection Temperature alert is generated when the average temperature is greater than or equal to 30°C.
5 Cloud Transmission Average temperature, average humidity and alert status are transmitted to ThingSpeak using HTTP.
6 Cloud Visualization Processed sensor values are stored and displayed in the ThingSpeak channel.

Sample Serial Output

The following is an illustrative example. Actual temperature and humidity values will depend on the environment.

Raspberry Pi Edge Computing System Started

Raw Temperature: 27.0 °C
Raw Humidity: 61.0 %

Raw Temperature: 27.0 °C
Raw Humidity: 62.0 %

...

--- Edge Processing Result ---
Average Temperature: 27.2 °C
Average Humidity: 61.7 %
Status: Normal
Cloud upload successful
Entry ID: 12345
------------------------------

Note: The Entry ID shown above is only an example. The actual Entry ID is generated by ThingSpeak.

Comparison: Cloud-Based vs Edge-Based Processing

Parameter Cloud-Based Processing Edge-Based Processing
Data processing Performed primarily on a remote cloud server. Performed locally on the Raspberry Pi.
Data transmission Raw sensor readings may be transmitted continuously. Sensor readings are processed locally before transmission.
Bandwidth usage Can be higher when raw readings are continuously transmitted. Can be reduced by aggregating readings locally.
Response latency Depends on network communication and cloud processing. Local threshold decisions can be made directly on the Raspberry Pi.
Local decision-making Requires communication with the cloud when processing is remote. Threshold detection is performed locally.
Cloud workload Can increase when large amounts of raw data are uploaded. Reduced because processed values are transmitted.

Result

An edge computing application was successfully implemented using a Raspberry Pi and DHT11 temperature and humidity sensor. The Raspberry Pi collected sensor readings and processed them locally by calculating the average temperature and humidity over a batch of 10 valid readings.

A threshold-based temperature detection mechanism was implemented locally, using 30°C as the threshold. The processed temperature, humidity and alert status were then transmitted to the ThingSpeak cloud platform using HTTP.

Thus, the experiment demonstrates how edge computing can perform local data processing and decision-making before transmitting relevant information to the cloud, thereby reducing unnecessary data transmission and supporting faster local responses.

Real-Life Applications

  • Industrial condition monitoring: Temperature and humidity sensors can monitor machinery and industrial environments.
  • Smart agriculture: Edge devices can locally process environmental sensor readings and transmit only important information to the cloud.
  • Environmental monitoring: Local processing can be used to detect abnormal temperature or humidity conditions.
  • Smart buildings: Edge devices can monitor environmental conditions and trigger local decisions.
  • Predictive maintenance: Sensor data can be processed locally to detect abnormal operating conditions before transmitting summarized information to a cloud platform.

Viva Questions

  1. What is edge computing?
  2. What is the difference between edge computing and cloud computing?
  3. Why is Raspberry Pi used as an edge device in this experiment?
  4. What is the role of the DHT11 sensor?
  5. Which GPIO pin is used to connect the DHT11 data pin?
  6. Why is GPIO4 used in this experiment?
  7. How many sensor readings are collected before calculating the average?
  8. What is the purpose of SAMPLE_INTERVAL?
  9. What is the value of the temperature threshold used in this experiment?
  10. What happens when the average temperature reaches or exceeds 30°C?
  11. What is the purpose of local data aggregation?
  12. How does edge computing reduce bandwidth usage?
  13. Which communication protocol is used to transmit data to ThingSpeak?
  14. What is the purpose of the HTTP POST request?
  15. What are Field 1, Field 2 and Field 3 used for in ThingSpeak?
  16. What is a ThingSpeak Write API Key?
  17. Why should the API key not be publicly shared?
  18. What is the purpose of the requests Python library?
  19. What is the difference between raw sensor data and processed sensor data?
  20. What are the advantages of processing sensor data at the edge?