Building a WiFi-Connected (ThingSpeak) Temperature and Humidity Monitor with Raspberry Pi Pico W and DHT11

 In this tutorial, we'll build a simple WiFi-enabled temperature and humidity monitor using the Raspberry Pi Pico W and a DHT11 sensor. We'll use Python-based MicroPython to program the Pico and send sensor data to ThingSpeak, a cloud platform that provides easy data logging and visualization.

What You’ll Need:

  1. Raspberry Pi Pico W (with MicroPython firmware installed)
  2. DHT11 Temperature & Humidity Sensor
  3. Jumper wires for connections
  4. WiFi network credentials
  5. ThingSpeak account (to obtain your API key)

Steps:

1. Setup Your Raspberry Pi Pico W

First, make sure you have MicroPython installed on your Pico W. If not, follow these simple steps:

  • Download and install Thonny IDE.
  • Select the correct board (Raspberry Pi Pico) and install MicroPython firmware using Tools > Options > Interpreter.
  • Write and save your MicroPython code using Thonny, directly onto your Pico.

2. Connect the DHT11 Sensor to Raspberry Pi Pico W

We'll connect the DHT11 sensor to the Pico W:

  • VCC to the 3.3V pin on the Pico.
  • GND to any GND pin.
  • DATA pin to GPIO16 on the Pico.




3. Set Up ThingSpeak

  • Create a ThingSpeak account at ThingSpeak.
  • Create a new channel to store temperature and humidity data. The two fields in your channel will represent:
    • Field1: Temperature (in °C)
    • Field2: Humidity (in %)
  • Obtain your Write API Key from your channel settings. This key allows you to send data to ThingSpeak.

4. Code Explanation

Now let's dive into the code. Below is the complete Python code, which connects to your WiFi, reads temperature and humidity from the DHT11 sensor, and sends the data to ThingSpeak every 15 seconds.

Code :
import machine
import urequests
import network
import uos
import utime
from machine import Pin
from dht import DHT11

# Configuration
HTTP_HEADERS = {'Content-Type': 'application/json'}
THINGSPEAK_WRITE_API_KEY = 'Your-API-Key'  # Replace with your ThingSpeak API key
SSID = 'Your-SSID'
PASSWORD = 'WiFi -Password'
WIFI_TIMEOUT = 10000  # Timeout for WiFi connection in milliseconds

# Initialize the DHT11 sensor
sensor_pin = Pin(16, Pin.OUT, Pin.PULL_DOWN)
sensor = DHT11(sensor_pin)

# Configure Pico W as Station
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

def connect_wifi(ssid, password, timeout):
    """Connect to WiFi network."""
    print('Connecting to network...')
    sta_if.connect(ssid, password)
    start_time = utime.ticks_ms()
    while not sta_if.isconnected():
        if utime.ticks_diff(utime.ticks_ms(), start_time) > timeout:
            print('Failed to connect to WiFi.')
            return False
        utime.sleep(1)
    print('Connected to network:', sta_if.ifconfig())
    return True

def read_sensor_data():
    """Read temperature and humidity from the DHT11 sensor."""
    sensor.measure()
    temperature = sensor.temperature()
    humidity = sensor.humidity()
    return temperature, humidity

def send_to_thingspeak(temperature, humidity):
    """Send the temperature and humidity data to ThingSpeak."""
    dht_readings = {'field1': temperature, 'field2': humidity}
    url = 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY
    try:
        response = urequests.post(url, json=dht_readings, headers=HTTP_HEADERS)
        print('Response from ThingSpeak:', response.text)
        response.close()
    except Exception as e:
        print('Error sending data to ThingSpeak:', e)

# Connect to WiFi
if not connect_wifi(SSID, PASSWORD, WIFI_TIMEOUT):
    raise RuntimeError('Could not connect to WiFi')

# Main loop
while True:
    # Read sensor data
    temperature, humidity = read_sensor_data()
    print("Temperature: {} C".format(temperature))
    print("Humidity: {} %".format(humidity))
    
    # Send data to ThingSpeak
    send_to_thingspeak(temperature, humidity)
    
    # Wait before the next reading
    utime.sleep(15)  # Adjust the delay as needed



5. Code Breakdown

  1. WiFi Connection:

    • The connect_wifi() function connects the Pico W to your specified WiFi network. It retries until a connection is successful or the timeout is reached.
  2. DHT11 Sensor Readings:

    • The read_sensor_data() function reads the temperature and humidity from the DHT11 sensor. The sensor's temperature() method returns the temperature in Celsius, while humidity() returns the humidity percentage.
  3. Sending Data to ThingSpeak:

    • The send_to_thingspeak() function posts the temperature and humidity data to ThingSpeak via an HTTP POST request. We send the values to field1 (temperature) and field2 (humidity).
  4. Main Loop:

    • Every 15 seconds, the code reads the sensor data and sends it to ThingSpeak. You can adjust the delay by changing the utime.sleep(15) value.

6. Running the Code

  1. Ensure your WiFi is on and the Pico is powered.
  2. Upload the code using Thonny IDE.
  3. Open the ThingSpeak channel to watch the live data feed.

Once the code is running, the sensor will periodically send temperature and humidity data to ThingSpeak, and you'll see the graphs updating in real-time.

7. Conclusion

With this setup, you can easily monitor your room's temperature and humidity online, thanks to the Pico W's WiFi capabilities and the simplicity of ThingSpeak. This project is an excellent starting point for more advanced IoT projects using MicroPython and the Raspberry Pi Pico W.


Further Ideas:

  • Add more sensors to measure light, air quality, or motion.
  • Create notifications or alerts when temperature/humidity reaches a certain threshold.

Feel free to share your thoughts and improvements in the comments below!


Comments

Popular posts from this blog

Tutorial: Using Raspberry Pi as an OpenVPN Client Router with Ethernet Sharing

How to Use a Raspberry Pi 4 as a Firewall to Block Adult Content and Protect Your Family

Tutorial: Using Raspberry Pi Pico and HW-488 Infrared Obstacle Avoidance Sensor to Play/Pause a Video on Your PC via USB