Thursday, 18 September 2025

RSP1

import adafruit_dht

import board

import requests

import time


# DHT11 sensor configuration

dhtDevice = adafruit_dht.DHT11(board.D4)


# ThingSpeak configuration

THINGSPEAK_API_KEY = "218PQ4GZVW9P3NDS"  # Replace with your API key

THINGSPEAK_URL = "https://api.thingspeak.com/update"


def read_sensor_data():

    temperature = dhtDevice.temperature

    humidity = dhtDevice.humidity


    if humidity is not None and temperature is not None:

        return temperature, humidity

    else:

        print("Failed to retrieve data from DHT11 sensor.")

        return None, None


def send_to_thingspeak(temperature, humidity):

    payload = {

        "api_key": THINGSPEAK_API_KEY,

        "field1": temperature,

        "field2": humidity

    }

    response = requests.get(THINGSPEAK_URL, params=payload)


    if response.status_code == 200:

        print("Data sent to ThingSpeak successfully.")

    else:

        print("Failed to send data to ThingSpeak.")


def main():

    try:

        while True:

            temperature, humidity = read_sensor_data()

            if temperature is not None and humidity is not None:

                print(f"Temperature: {temperature} C, Humidity: {humidity}%")

                send_to_thingspeak(temperature, humidity)


            time.sleep(10)  # Wait 10 seconds before next reading

    finally:

        dhtDevice.exit()


if __name__ == "__main__":

    main()


No comments:

Post a Comment