import urequests
import network
import time
from machine import Pin
from dht import DHT22
# WiFi configuration
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Django server URL (replace with your actual URL)
SERVER_URL = "http://127.0.0.1:8000/api/receive/receive_data"
# Pin configuration for the DHT sensor
DHT_PIN = 3 # Change this to your pin number
# Connect to WiFi
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to WiFi...")
while not wlan.isconnected():
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
# Read data from the DHT sensor
def read_sensor():
print("Initializing DHT sensor...")
dht = DHT22(Pin(DHT_PIN))
try:
print("Measuring data from DHT sensor...")
dht.measure()
temperature = dht.temperature()
humidity = dht.humidity()
print(f"Temperature: {temperature}, Humidity: {humidity}")
return {"temperature": temperature, "humidity": humidity}
except Exception as e:
print("Error during measurement:", e)
return None
# Send data to the server
def send_data_to_server(data):
try:
headers = {"Content-Type": "application/json"}
response = urequests.post(SERVER_URL, json=data, headers=headers)
print("Server response:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", e)
# Main loop
def main():
connect_to_wifi()
while True:
sensor_data = read_sensor()
if sensor_data:
print("Sending data:", sensor_data)
send_data_to_server(sensor_data)
time.sleep(10) # Send data every 10 seconds
if __name__ == "__main__":
main()