import dht
import machine
import time
import network
import socket
import ujson
# Khởi tạo cảm biến DHT22 (GPIO 15)
sensor = dht.DHT22(machine.Pin(15))
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print(wlan.ifconfig())
# Hàm lấy dữ liệu từ cảm biến DHT22
def get_dht22_data():
try:
sensor.measure()
temp = sensor.temperature() # Đọc nhiệt độ
hum = sensor.humidity() # Đọc độ ẩm
return temp, hum
except Exception as e:
print('Error reading sensor:', e)
return None, None
# Tạo server HTTP đơn giản
def serve():
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('Listening on', addr)
while True:
cl, addr = s.accept()
print('Client connected from', addr)
request = cl.recv(1024)
print('Request:', request)
# Lấy dữ liệu từ DHT22
temp, hum = get_dht22_data()
# Tạo JSON response
response_data = {
'temperature': temp,
'humidity': hum
}
# Gửi response JSON
response = ujson.dumps(response_data)
cl.send('HTTP/1.1 200 OK\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Connection: close\r\n\r\n')
cl.send(response)
cl.close()
# Khởi động server
serve()