import network # For Wi-Fi connectivity
import time # For delays and timing
import urequests # For making HTTP requests
import dht # For interfacing with DHT sensors
from machine import Pin # For controlling GPIO pins
# Wi-Fi credentials
ssid = 'Wokwi-GUEST' # SSID of the Wi-Fi network
password = '' # Password (empty for open networks like Wokwi-GUEST)
# url azure
SERVER_URL = 'https://server-temp-g2d3a9g8ewf2cxad.canadacentral-01.azurewebsites.net/api/data'
# Set up Wi-Fi in station mode
wlan = network.WLAN(network.STA_IF) # Create a WLAN object in station mode, the device connects to a Wi-Fi network as a client.
wlan.active(True) # Activate the Wi-Fi interface
wlan.connect(ssid, password) # Connect to the specified Wi-Fi network
# Wait until connected
print("Connecting to Wi-Fi...", end="")
while not wlan.isconnected():
print(".", end="") # Print dots while waiting
time.sleep(0.5) # Wait half a second before retrying
# Once connected, print confirmation and IP address
print("\nConnected!")
print("IP address:", wlan.ifconfig()[0]) # Display the assigned IP address
# Initialize the DHT22 sensor on GPIO pin 15
sensor = dht.DHT22(Pin(15))
def send_to_server(temp, hum):
if temp is None or hum is None:
print("No data to send.")
return
try:
data = {
"temperature": temp,
"humidity": hum
}
response = urequests.post(SERVER_URL, json=data)
print("Server response:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", e)
# Main loop: read sensor and send data every 15 seconds
while True:
try:
sensor.measure() # Trigger sensor measurement
temperature = sensor.temperature() # Read temperature in Celsius
humidity = sensor.humidity()
print("Temperature:", temperature, "°C") # Display temperature
print("Humidity:", humidity, "%")
send_to_server(temperature, humidity) # Send data to server
except Exception as e:
print("Error reading sensor or sending data:", e) # Handle errors
time.sleep(15)