import network
import dht
import time
import urequests
from machine import Pin
# Wi-Fi Configuration (Wokwi Virtual Wi-Fi)
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = "" # No password for Wokwi-GUEST
# DHT22 Sensor Setup
dht_pin = Pin(23, Pin.IN) # DHT22 on pin 23
sensor = dht.DHT22(dht_pin)
# Server URL to send data (This is the IP address of your Flask server on your local network)
SERVER_URL = "http://127.0.0.1:5000/update" # Use the correct server URL from Flask
# Connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
print("IP Address: ", wlan.ifconfig()[0])
# Function to send data to the external server
def send_data_to_server(temperature, humidity):
try:
# Prepare the data
data = {
'temperature': temperature,
'humidity': humidity
}
# Send HTTP POST request to external server
response = urequests.post(SERVER_URL, json=data)
# Print response from server (for debugging purposes)
print(response.text)
# Close the response to free memory
response.close()
except Exception as e:
print(f"Error sending data to server: {e}")
# Main function to read sensor data and send it
def main():
connect_wifi()
while True:
# Read sensor data
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
print("Temperature: {}°C, Humidity: {}%".format(temperature, humidity))
# Send data to external server
send_data_to_server(temperature, humidity)
# Wait before sending the next reading (e.g., every 10 seconds)
time.sleep(10)
# Run the main loop
if __name__ == '__main__':
main()