Send Data to cloud Using Raspberry Pi || IoT Projects || Thingspeak || DHT22

Опубликовано: 04 Октябрь 2024
на канале: M Classes
575
5

In this tutorial, learn how to utilize the power of Raspberry Pi Pico and its MicroPython environment to send temperature and humidity data to ThingSpeak, a popular IoT platform.

🔧 Hardware Used:

Raspberry Pi Pico
DHT22 (AM2302) Temperature and Humidity Sensor
📝 Code:

Python
Copy code
import machine
import time
import urequests
import network
import ujson
import dht

ThingSpeak settings
THINGSPEAK_API_KEY = "TXD92FQJN6C8APJD"
THINGSPEAK_URL = "http://api.thingspeak.com/update"

Wi-Fi settings
WIFI_SSID = "Your_WiFi_SSID"
WIFI_PASSWORD = "Your_WiFi_Password"

DHT22 (AM2302) sensor on GPIO 4
dht_sensor = dht.DHT22(machine.Pin(4))

Function to read room temperature and humidity
def read_room_temperature_humidity():
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity

Function to send data to ThingSpeak
def send_data_to_thingspeak(temperature, humidity):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": temperature,
"field2": humidity,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()

Initialize the Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)

Wait for the Wi-Fi connection to establish
while not wifi.isconnected():
time.sleep(1)

print("Connected to Wi-Fi")

if __name__== "__main__":
try:
while True:
temperature, humidity = read_room_temperature_humidity()
send_data_to_thingspeak(temperature, humidity)
print("Data sent to ThingSpeak")
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass
🎥 Tutorial Highlights:

Introduction to Raspberry Pi Pico and MicroPython
Setting up Wi-Fi connectivity on Raspberry Pi Pico
Reading temperature and humidity data using DHT22 sensor
Sending data to ThingSpeak using MicroPython and urequests library
Tips for adjusting data sending intervals and handling exceptions
🔗 Useful Links:

ThingSpeak:https://thingspeak.com/
🚀 Don't forget to like, share, and subscribe for more Raspberry Pi and IoT tutorials! #RaspberryPi #IoT #ThingSpeak #MicroPython #Tutorial

Feel free to customize the Wi-Fi SSID and password in the code according to your network settings.