# Logging DHT11 temperature and humidity readings to ThingSpeak using Python's requests module.

Here's a complete guide to **logging DHT11 temperature and humidity readings to ThingSpeak** using Python's `requests` module. This will assume you're using a Raspberry Pi with a DHT sensor (like DHT11 or DHT22) connected.

---

## 🔧 What You Need

* Raspberry Pi with internet access
    
* DHT11 or DHT22 sensor
    
* Python installed (`requests`, `Adafruit_DHT`)
    
* ThingSpeak account with a channel and **Write API Key**
    

---

## ✅ Step-by-Step Implementation

### 1\. **Install Required Libraries on environment**

```bash
pip install requests
pip install Adafruit_DHT
```

---

### 2\. **ThingSpeak Setup**

* Go to [ThingSpeak](https://thingspeak.com/)
    
* Create a channel
    
* Enable `field1` (Temperature) and `field2` (Humidity)
    
* Copy the **Write API Key** (found in API Keys tab)
    

---

### 3\. **Python Script to Read and Upload**

```python
import Adafruit_DHT
import requests
import time

# Sensor details
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4  # GPIO4 (change if needed)

# ThingSpeak API details
THINGSPEAK_WRITE_API = "YOUR_WRITE_API_KEY_HERE"
THINGSPEAK_URL = "https://api.thingspeak.com/update"

# Logging loop
while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        print(f"Temp={temperature:.1f}C  Humidity={humidity:.1f}%")

        # Send data to ThingSpeak
        payload = {
            'api_key': THINGSPEAK_WRITE_API,
            'field1': temperature,
            'field2': humidity
        }

        try:
            response = requests.get(THINGSPEAK_URL, params=payload)
            if response.status_code == 200:
                print("Data sent to ThingSpeak.")
            else:
                print("Failed to send data, HTTP:", response.status_code)
        except Exception as e:
            print("Request failed:", e)
    else:
        print("Failed to retrieve data from DHT sensor")

    # Wait 15 seconds (ThingSpeak limit)
    time.sleep(15)
```

---

## 📝 Notes

* Replace `YOUR_WRITE_API_KEY_HERE` with your actual ThingSpeak Write API Key.
    
* ThingSpeak accepts **1 update every 15 seconds** on free plans.
    
* You can run this script using:
    

```bash
python3 thingspeak_logger.py
```

---

Would you like this to run as a **background service** (systemd) on boot?
