print("Started!")
import time
import dht
import machine
import urequests as requests
import network
from machine import Pin, I2C
import ssd1306
temperature_threshold = 30
humidity_threshold = 80
temperature_get = None
humidity_get = None
place = "None"
state_push = 0
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
d = dht.DHT22(machine.Pin(4 , machine.Pin.IN))
led_red = machine.Pin(5, machine.Pin.OUT)
led_blue = machine.Pin(18, machine.Pin.OUT)
push_button = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_UP)
def connectWifi():
print("Connecting to WIFI", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Connected!")
def fetchDataOpenWeather():
url = "https://api.openweathermap.org/data/2.5/weather?lat=9.916647&lon=105.144236&appid=f5d85ff8dd1b7224bbe0125b42819504"
try:
res = requests.get(url)
resJSON = res.json()
temperature_fetch = resJSON['main']['temp']
humidity_fetch = resJSON['main']['humidity']
place_fetch = resJSON['name']
return {
'temperature': temperature_fetch,
'humidity': humidity_fetch,
'place': place_fetch
}
except Exception as e:
print("Request error!", e)
return None
def actions():
if temperature_get is not None and humidity_get is not None: # Kiểm tra để tránh lỗi
if temperature_get > temperature_threshold or humidity_get > humidity_threshold:
led_red.on()
led_blue.off()
else:
led_red.off()
led_blue.on()
oled.fill(0)
oled.text(str(place), 5, 10)
oled.text("Temp: " + str(temperature_get) + " C", 5, 20)
oled.text("Hum : " + str(humidity_get) + " %", 5, 30)
oled.show()
print("Temperature =", temperature_get)
print("Humidity =", humidity_get)
time.sleep(5)
def button_handler(pin):
global state_push # Khai báo biến toàn cục
if push_button.value() == 0:
state_push += 1
# Connect wifi
connectWifi()
push_button.irq(trigger=machine.Pin.IRQ_FALLING, handler=button_handler)
while True:
if state_push % 2 == 0:
result = fetchDataOpenWeather()
if result:
temperature_get = result['temperature']
humidity_get = result['humidity']
place = result['place']
else:
temperature_get = 300
humidity_get = 300
place = "Kien Giang"
else:
d.measure()
temperature_get = d.temperature()
humidity_get = d.humidity()
place = "Kien Giang"
actions()