import network
import socket
import time
import dht
from machine import Pin
# --- Configuration ---
WIFI_SSID = "Your_WiFi_Name"
WIFI_PASS = "Your_WiFi_Password"
DHT_PIN = 15 # GPIO pin connected to DHT22 data pin
# Initialize sensor
sensor = dht.DHT22(Pin(DHT_PIN))
# --- Connect to Wi-Fi ---
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
print("Connecting to WiFi...")
while not wlan.isconnected():
time.sleep(1)
print(f"Connected! IP Address: {wlan.ifconfig()[0]}")
# --- Setup TCP Server ---
# Create socket (IPv4, TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80)) # Bind to port 80
s.listen(5)
print("TCP Server is listening on port 80...")
while True:
try:
# Accept connection from client
client, addr = s.accept()
print(f"Client connected from {addr}")
# Receive the request (we can ignore content for a simple trigger)
request = client.recv(1024)
# Read DHT22 Data
try:
sensor.measure()
humidity = sensor.humidity()
response = f"Humidity: {humidity:.1f}%\n"
except Exception as e:
response = "Error reading sensor\n"
# Send response and close
client.send(response)
client.close()
except Exception as e:
print("Error:", e)