import machine
import network
import utime
import dht
import urequests
# Configure the sensor data pin
DATA_PIN = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
# Create an instance of the DHT22 sensor
sensor = dht.DHT22(DATA_PIN)
SERVER_URL = "YOUR_SERVER_URL"
# Connect with WiFi
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(WIFI_SSID,WIFI_PASSWORD)
if not wifi.isconnected():
print('connecting..')
timeout = 0
while (not wifi.isconnected() and timeout < 10):
print(10 - timeout)
timeout = timeout + 1
utime.sleep(1)
if(wifi.isconnected()):
print('connected')
else:
print('not connected')
sys.exit()
print('network config:', wifi.ifconfig())
connect_wifi() # Connecting to WiFi Router
def read_and_display_data():
# Function to read and display data from the DHT22 sensor
try:
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temp, humidity))
# print(f'Hello {humidity}')
# Prepare the payload
payload = {
"temperature": temp,
"humidity": humidity
}
print(payload)
response = urequests.put(SERVER_URL, json=payload)
# Print the response from the server
print("Response:", response.text)
response.close() # Close the connection
except Exception as e:
print("Error reading sensor data:", e)
# Main loop
while True:
read_and_display_data()
utime.sleep(1) # Wait for 1 seconds before reading the data again