Python Program 4: Interfacing Sensor Data to ThingSpeak through Raspberry Pi

Objective:

To interface temperature and humidity data from a DHT11 sensor to ThingSpeak using a Raspberry Pi.


Resources Required:

  • Raspberry Pi 2
  • DHT11 Sensor
  • Connectors
  • Sensor connecting wires
  • Computer system

Theory:

The DHT11 sensor is used to collect temperature and humidity data, which is then sent to the Raspberry Pi. The Raspberry Pi will transmit this data to a ThingSpeak channel, allowing users to remotely monitor the data through a cloud-based platform.

Setting Up ThingSpeak Account

Before we begin, you need to create an account on ThingSpeak:

  1. Visit the ThingSpeak website.

  2. After signing up or logging in, click on New Channel to create a new channel.

  3. Provide the required details for your channel:



    • Channel Name: Choose a suitable name.

    • Channel Description: Describe the purpose of your channel (e.g., "Temperature and Humidity Data").

    • You can configure up to 8 fields for different parameters. For this experiment, we’ll use:

      • Field 1: Temperature (°C)

      • Field 2: Humidity (%)

  4. After setting the fields, click Save.


Once saved, you will be redirected to the Private View tab. Here, you’ll find the Channel ID and API Keys that you will need for your project.

  • Write API Key: Required to send data to ThingSpeak.

  • Read API Key: Used to fetch data from the channel.

Make sure to copy and store these keys safely.


Circuit Diagram

For this experiment, the DHT11 sensor is connected to the Raspberry Pi GPIO pin (GPIO4 in this case). Here's how the connections should be made:

  • VCC pin of the DHT11 goes to 3.3V on the Raspberry Pi.
  • GND pin of the DHT11 goes to GND on the Raspberry Pi.
  • DATA pin of the DHT11 connects to GPIO4 on the Raspberry Pi.

Python Code:

The following Python code will read data from the DHT11 sensor and send it to your ThingSpeak channel.

import http.client import urllib import time import board import adafruit_dht import psutil # Replace with your Write API Key from ThingSpeak key = "KEY" # Initialize the DHT11 sensor sensor = adafruit_dht.DHT11(board.D4) # Function to send temperature and humidity to ThingSpeak def thermometer(): while True: try: temp = sensor.temperature # Read temperature from DHT11 humidity = sensor.humidity # Read humidity from DHT11 # Create a dictionary with the data to send params = urllib.parse.urlencode({'field1': temp, 'field2': humidity, 'key': key}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} # Set up the HTTP connection to ThingSpeak conn = http.client.HTTPConnection("api.thingspeak.com:80") conn.request("POST", "/update", params, headers) # Get the response from ThingSpeak response = conn.getresponse() print("Temperature: {}*C Humidity: {}%".format(temp, humidity)) print(response.status, response.reason) # Read and close the response data = response.read() conn.close() except Exception as e: print("Connection failed: ", e) break # Main loop to run the thermometer function if __name__ == "__main__": while True: thermometer()


Explanation of the Code:

  • Libraries Used:

    • http.client and urllib: These libraries are used to make HTTP requests to ThingSpeak.
    • adafruit_dht: This library allows interaction with the DHT11 sensor.
    • psutil: This library is used to check for conflicting processes and kill them before starting the script.
  • Sensor Setup: The DHT11 sensor is initialized, and the temperature and humidity are read in the thermometer() function.
  • Sending Data to ThingSpeak: The function then constructs a POST request containing the temperature and humidity data, along with the ThingSpeak API key. This data is sent to ThingSpeak using an HTTP connection.


Result:


After running the code, the temperature and humidity data should be successfully uploaded to your ThingSpeak channel. You can view the real-time data on your ThingSpeak dashboard, which will automatically update with new readings.

Conclusion:

This experiment demonstrates how to interface the DHT11 sensor with a Raspberry Pi to send temperature and humidity data to ThingSpeak. This project serves as a foundational step toward building IoT-based applications, where remote data monitoring is key.

By uploading sensor data to ThingSpeak, we can access it from anywhere and use the platform’s visualization tools to analyze trends and patterns in the data. 


✅ ðŸ‘‰ If you found this helpful, don’t forget to like, follow, comment, and share!

Let’s continue learning and building cool sensor projects. Team up with me and let’s complete this together! 💻✨

Comments

Popular posts from this blog

Fundamental of python : 1.Python Numbers