MDM331AID/Experiment 6
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:
- 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.
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:
- 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.
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
- Switch off or disconnect the Raspberry Pi from its power supply before making the connections.
- Connect the DHT11 sensor to the Raspberry Pi according to the pin connection table.
- 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
- Boot the Raspberry Pi with Raspberry Pi OS.
- Connect the Raspberry Pi to a Wi-Fi network with Internet access.
- Open the terminal.
- Create and activate a Python virtual environment if required.
- Install the required Python libraries.
- Create a Python file, for example
edge_computing.py. - Enter the given program and save the file.
Step 3: ThingSpeak Setup
- Sign in to ThingSpeak.
- Create a new channel.
- Enable three fields in the channel.
- Name Field 1 as Average Temperature.
- Name Field 2 as Average Humidity.
- Name Field 3 as Temperature Alert.
- Save the channel.
- Open the API Keys section.
- Copy the channel's Write API Key.
- Replace
YOUR_API_KEY_HEREin the program with the actual Write API Key. - Save the Python program.
Step 4: Execute the Program
- 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"> python edge_computing.py </syntaxhighlight>
- Observe the raw temperature and humidity readings displayed in the terminal.
- Allow the program to collect 10 valid readings.
- Observe the calculated average temperature and average humidity.
- Observe the threshold status displayed by the program.
- Check the cloud upload status and ThingSpeak Entry ID.
Step 5: Verify Edge Processing
- 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 channel visualization page.
- Observe the value in Field 1 for average temperature.
- Observe the value in Field 2 for average humidity.
- 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
| 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
- What is edge computing?
- What is the difference between edge computing and cloud computing?
- Why is Raspberry Pi used as an edge device in this experiment?
- What is the role of the DHT11 sensor?
- Which GPIO pin is used to connect the DHT11 data pin?
- Why is GPIO4 used in this experiment?
- How many sensor readings are collected before calculating the average?
- What is the purpose of
SAMPLE_INTERVAL? - 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 are Field 1, Field 2 and Field 3 used for in ThingSpeak?
- What is a ThingSpeak Write API Key?
- Why should the API key not be publicly shared?
- What is the purpose of the
requestsPython library? - What is the difference between raw sensor data and processed sensor data?
- What are the advantages of processing sensor data at the edge?